how to encrypt and decrpyt files with adobe air ? (encrypt ok, but decrpyt isn't yet ) - air

i want to encrypt and decrpyt files with adobe air. and i am successfully encrypt files with code. but i dont yet decrpyt an encrypted file please help me, what can i do?
i am using this code for encrypt:
import com.hurlant.crypto.symmetric.AESKey;
import com.hurlant.crypto.symmetric.DESKey;
import com.hurlant.util.Hex;
import flash.filesystem.FileStream;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.filesystem.FileMode;
import flash.display.BitmapData;
import flash.display.Bitmap;
import com.hurlant.util.ArrayUtil;
stop();
var stream:FileStream;
var stream2:FileStream;
var file:File;
var fileToEncrypt:ByteArray;
encrypt();
function encrypt():void
{
file = File.applicationDirectory.resolvePath("logo_markatalog.png");
fileToEncrypt = new ByteArray;
stream = new FileStream();
stream.open( file, FileMode.READ );
stream.readBytes(fileToEncrypt);
stream.close();
var appDir:String = File.applicationDirectory.nativePath;
//file = File(appDir+"logo_markatalog_enc.png");
file = new File(appDir+"/logo_markatalog_enc.png");
var key:ByteArray = Hex.toArray("635232557");
var aes:AESKey = new AESKey(key);
aes.encrypt(fileToEncrypt);
stream2 = new FileStream();
stream2.open( file, FileMode.WRITE );
stream2.writeBytes(fileToEncrypt);
stream2.close();
}

I can't tell you what you're doing wrong but I can give you what I use to encrypt object into file and decrypt them back.
someKey var is your key used to encrypt and decrypt.
theFileWithEncryptedObject var is the file where I save my encrypted object in the first code part, from which I read the encrypted object in second code part.
I use an md5 hash on the key, that's not necessary.
Here's the way I encrypt object into file with hurlant.crypto :
var fileStream:FileStream = new FileStream();
fileStream.open(theFileWithEncryptedObject, FileMode.WRITE);
var bytes:ByteArray = new ByteArray();
bytes.writeObject(theObjectToEncrypt);
var key:ByteArray = Hex.toArray(someKey);
var md5:MD5 = new MD5();
key = md5.hash(key);
var pad:IPad = new PKCS5();
var aes:ICipher = Crypto.getCipher("simple-aes-128-cbc", key, pad);
pad.setBlockSize(aes.getBlockSize());
aes.encrypt(bytes);
fileStream.writeBytes(bytes);
fileStream.close();
And here how I decrypt and get back my object from the file :
var bytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(theFileWithEncryptedObject, FileMode.READ);
fileStream.readBytes(bytes);
fileStream.close();
var key:ByteArray = Hex.toArray(someKey);
var md5:MD5 = new MD5();
key = md5.hash(key);
var pad:IPad = new PKCS5;
var aes:ICipher = Crypto.getCipher("simple-aes-128-cbc", key, pad);
pad.setBlockSize(aes.getBlockSize());
aes.decrypt(bytes);
var theObjectDecrypted:Object;
bytes.position = 0;
theObjectDecrypted = bytes.readObject();
Hope this helps.

Related

Send Image to the API using image path that stored in local database

I am trying to send image to the API, I have multiple local storage image path which is stored in local
database sqlite and I have to upload these image on one click. in the
local database. replace _mediaFile = await CrossMedia.Current.TakePhotoAsync
with _mediaFile = Image_Path_From_Database
The datatobesync it contain multiple local storage image path from local dat
conn = await DependencyService.Get().GetConnection();
List datatobesync = new List();
datatobesync = (from c in conn.Table<CDCInfo>()
where c.SyncStatus == 0 && c.UserName == Settings.Username
select new CDCInfo
{
PhotoPath = c.PhotoPath,
}
I have a string image path but I am not sure about how
to use this
Using MediaPlugin for opening a gallery or camera. After selecting the
picture I set that picture to _mediafile and added to the content and send it to the API.
Detail Here
these lines of code gets image from the gallery or camra (using MediaPlugin) in a
mediaFile and send it to the API
private MediaFile _mediaFile;
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.
StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
AllowCropping = true,
PhotoSize = PhotoSize.Medium
});
var content = new MultipartFormDataContent();
content.Add(new StreamContent(_mediaFile.GetStream()),"\"Files\"", $"\"{_mediaFile.path}\"");
var httpClnt = new HttpClient();
result = await httpClnt.PostAsync(Urle, content);
How can I add image to the content using database path and send it to the API without using MediaPlugin.
I am trying to do something like
foreach (var item in datatobesync)
{
try
{
HttpClient client = new HttpClient();
MultipartFormDataContent content = new
MultipartFormDataContent();
content.Add(new
StreamContent("Here I want to user item.PhotoPath Image path from the database".GetStream()),"\"Files\"",
$"\"{item.PhotoPath}\"");
var httpClnt = new HttpClient();
result = await httpClnt.PostAsync(Urle, content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I dont know how to use image path at this line
content.Add(new StreamContent(How_to_User_ImagePath_Her.GetStream()),"\"Files\"",
$"\"{item.PhotoPath}\"");
How to get GetStram() of image path

CloudBlockBlob DownloadTextAsync Behavior Difference

I am using an azure function with event grid trigger and CloudBlockBlob as input binding. The content is getting downloaded from CloudBlockBob using DownloadTextAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
If the file being downloaded above is being generated using XmlDocument, DownloadTextAsync returns gibberish. However, if the file is generated by using FileStream, it works fine. PFB the implementations of generating the file-
Using XmlDocument
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(typeof(List<ContractName>), new XmlRootAttribute("RootAttributeName"));
serializer.Serialize(stringwriter, contractData);
var xmlString = stringwriter.ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
doc.PreserveWhitespace = true;
doc.Save(fileName);
Using FileStream
var serializer = new XmlSerializer(typeof(List<ContractName>), new XmlRootAttribute("RootAttributeName"));
var file = new FileStream(fileName, FileMode.OpenOrCreate);
serializer.Serialize(file, contractData);
file.Close();
Code being used to download the content-
Using DownloadTextAsync
private static async System.Threading.Tasks.Task<string> DownloadContentAsync_DownloadTextAsync(string storageAccountConnectionString, string containerName, string blobName)
{
CloudBlobContainer container = GetContainer(storageAccountConnectionString, containerName);
ICloudBlob blob = await container.GetBlobReferenceFromServerAsync(blobName);
// Download the blob content
string xmlBlobContent =
await (blob as CloudBlockBlob).DownloadTextAsync(
null,
new BlobRequestOptions { LocationMode = LocationMode.PrimaryThenSecondary },
new OperationContext());
return xmlBlobContent;
}
Using DownloadToStreamAsync
private static async System.Threading.Tasks.Task<string> DownloadContentAsync_DownloadToStreamAsync(string storageAccountConnectionString, string containerName, string blobName)
{
CloudBlobContainer container = GetContainer(storageAccountConnectionString, containerName);
ICloudBlob blob = await container.GetBlobReferenceFromServerAsync(blobName);
// Download the blob content
MemoryStream resultStream = new MemoryStream();
await (blob as CloudBlockBlob).DownloadToStreamAsync(
resultStream,
null,
new BlobRequestOptions { LocationMode = LocationMode.PrimaryThenSecondary },
new OperationContext());
string xmlBlobContent = System.Text.Encoding.UTF8.GetString(resultStream.ToArray());
return xmlBlobContent;
}
Why there is a difference in response from DownloadTextAsync.
Updated 0713:
Figured it out. The root cause is that when you're using XmlDocument to generate the xml file, the encoding is utf-16. But for FileStream, it generates the xml file with encoding utf-8.
So, the solution is that, when using XmlDocument, we can specify the encoding to utf-8(no code change for FileStream). Sample code as below:
Generate xml file using XmlDocument:
//2. Using XMLDoc
serializer.Serialize(stringwriter, contractData);
var xmlString = stringwriter.ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
doc.PreserveWhitespace = true;
string fileName = String.Format(#"C:\TestBlobDownloadContent\UsingXMLDoc" + count + ".xml");
//encoding as utf-8
using (TextWriter sw = new StreamWriter(fileName, false, Encoding.UTF8))
{
doc.Save(sw);
}
When read the xml file from blob storage via DownloadTextAsync() method, no need to specify the encoding option, like below:
// Download the blob content
string xmlBlobContent =
await (blob as CloudBlockBlob).DownloadTextAsync(
null,
new BlobRequestOptions { LocationMode = LocationMode.PrimaryThenSecondary },
new OperationContext());
Original answer:
This is due to the encode/decode issue.
Solution:
In the DownloadTextAsync() method, add parameter System.Text.Encoding.Unicode. Like below:
string xmlBlobContent =
await (blob as CloudBlockBlob).DownloadTextAsync(
System.Text.Encoding.Unicode,
null,
new BlobRequestOptions { LocationMode = LocationMode.PrimaryThenSecondary },
new OperationContext());
The test result:

How download binary files with pentaho?

The Http Client step of pentaho only allows download of text files.
How can I download binary files with Pentaho?
Add a Modified Java Script Value with the following code
var fileURL = "https://hp.imguol.com.br/c/home/b1/2018/05/26/mohamed-salah-chora-apos-se-machucar-em-lance-com-sergio-ramos-1527363329053_300x300.jpg";
var url = java.net.URL(fileURL);
var httpConn = url.openConnection();
// opens input stream from the HTTP connection
var inputStream = httpConn.getInputStream();
var saveFilePath = "d:/myfile10.jpg";
var bis = java.io.BufferedInputStream(inputStream);
var bos = java.io.BufferedOutputStream(java.io.FileOutputStream(java.io.File(saveFilePath)));
var inByte;
while((inByte = bis.read()) != -1) {
bos.write(inByte);
}
bis.close();
bos.close();

Amazon S3 .NET Core how to upload a file

I would like to upload a file with Amazon S3 inside a .NET Core project. Is there any reference on how to create and use an AmazonS3 client? All i can find in AmazonS3 documentation for .Net Core is this(http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-netcore.html) which is not very helpfull.
I did using IFormFile, like this:
(You need to install AWSSDK.S3)
public async Task UploadFileToS3(IFormFile file)
{
using (var client = new AmazonS3Client("yourAwsAccessKeyId", "yourAwsSecretAccessKey", RegionEndpoint.USEast1))
{
using (var newMemoryStream = new MemoryStream())
{
file.CopyTo(newMemoryStream);
var uploadRequest = new TransferUtilityUploadRequest
{
InputStream = newMemoryStream,
Key = file.FileName,
BucketName = "yourBucketName",
CannedACL = S3CannedACL.PublicRead
};
var fileTransferUtility = new TransferUtility(client);
await fileTransferUtility.UploadAsync(uploadRequest);
}
}
}
For simple file uploading in a .netcore project, I followed this link.
After finishing the simple file upload procedure, I followed the documentation on this and this links, which were very helpful. Following two links were also helpful for a quick start.
https://github.com/awslabs/aws-sdk-net-samples/blob/master/ConsoleSamples/AmazonS3Sample/AmazonS3Sample/S3Sample.cs
http://www.c-sharpcorner.com/article/fileupload-to-aws-s3-using-asp-net/
This was my final code snippets in the controller for file upload (I skipped the view part, which is elaborately explained in the link shared above).
[HttpPost("UploadFiles")]
public IActionResult UploadFiles(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
var filename = ContentDispositionHeaderValue
.Parse(formFile.ContentDisposition)
.FileName
.TrimStart().ToString();
filename = _hostingEnvironment.WebRootPath + $#"\uploads" + $#"\{formFile.FileName}";
size += formFile.Length;
using (var fs = System.IO.File.Create(filename))
{
formFile.CopyTo(fs);
fs.Flush();
}//these code snippets saves the uploaded files to the project directory
uploadToS3(filename);//this is the method to upload saved file to S3
}
}
return RedirectToAction("Index", "Library");
}
This is the method to upload files to Amazon S3:
private IHostingEnvironment _hostingEnvironment;
private AmazonS3Client _s3Client = new AmazonS3Client(RegionEndpoint.EUWest2);
private string _bucketName = "mis-pdf-library";//this is my Amazon Bucket name
private static string _bucketSubdirectory = String.Empty;
public UploadController(IHostingEnvironment environment)
{
_hostingEnvironment = environment;
}
public void uploadToS3(string filePath)
{
try
{
TransferUtility fileTransferUtility = new
TransferUtility(new AmazonS3Client(Amazon.RegionEndpoint.EUWest2));
string bucketName;
if (_bucketSubdirectory == "" || _bucketSubdirectory == null)
{
bucketName = _bucketName; //no subdirectory just bucket name
}
else
{ // subdirectory and bucket name
bucketName = _bucketName + #"/" + _bucketSubdirectory;
}
// 1. Upload a file, file name is used as the object key name.
fileTransferUtility.Upload(filePath, bucketName);
Console.WriteLine("Upload 1 completed");
}
catch (AmazonS3Exception s3Exception)
{
Console.WriteLine(s3Exception.Message,
s3Exception.InnerException);
}
}
This was all for uploading files in Amazon S3 bucket. I worked on .netcore 2.0 and also, don't forget to add necessary dependencies for using Amazon API. These were:
AWSSDK.Core
AWSSDK.Extensions.NETCore.Setup
AWSSDK.S3
Hope, this would help.
I wrote a complete sample for upload a file to Amazon AWS S3 with asp.net core mvc
you can see my sample project in github link:
https://github.com/NevitFeridi/AWS_Upload_Sample_ASPCoreMVC
There was a function for uploading file to S3 using Amazon.S3 SDK in the HomeController.
In this function " UploadFileToAWSAsync " you can find every things you need
// you must set your accessKey and secretKey
// for getting your accesskey and secretKey go to your Aws amazon console
string AWS_accessKey = "xxxxxxx";
string AWS_secretKey = "xxxxxxxxxxxxxx";
string AWS_bucketName = "my-uswest";
string AWS_defaultFolder = "MyTest_Folder";
protected async Task<string> UploadFileToAWSAsync(IFormFile myfile, string subFolder = "")
{
var result = "";
try
{
var s3Client = new AmazonS3Client(AWS_accessKey, AWS_secretKey, Amazon.RegionEndpoint.USWest2);
var bucketName = AWS_bucketName;
var keyName = AWS_defaultFolder;
if (!string.IsNullOrEmpty(subFolder))
keyName = keyName + "/" + subFolder.Trim();
keyName = keyName + "/" + myfile.FileName;
var fs = myfile.OpenReadStream();
var request = new Amazon.S3.Model.PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
InputStream = fs,
ContentType = myfile.ContentType,
CannedACL = S3CannedACL.PublicRead
};
await s3Client.PutObjectAsync(request);
result = string.Format("http://{0}.s3.amazonaws.com/{1}", bucketName, keyName);
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
Addition to #Tiago's answers, AWSS3 SDK is changed a bit, so here is the updated method:
public async Task UploadImage(IFormFile file)
{
var credentials = new BasicAWSCredentials("access", "secret key");
var config = new AmazonS3Config
{
RegionEndpoint = Amazon.RegionEndpoint.EUNorth1
};
using var client = new AmazonS3Client(credentials, config);
await using var newMemoryStream = new MemoryStream();
file.CopyTo(newMemoryStream);
var uploadRequest = new TransferUtilityUploadRequest
{
InputStream = newMemoryStream,
Key = file.FileName,
BucketName = "your-bucket-name",
CannedACL = S3CannedACL.PublicRead
};
var fileTransferUtility = new TransferUtility(client);
await fileTransferUtility.UploadAsync(uploadRequest);
}
Per AWS SDK docs, .Net Core support was added in late 2016.
https://aws.amazon.com/sdk-for-net/
So the instructions for uploading files to S3 should be identical to any other instructions for .Net.
The "getting started" guide for the AWS SDK for .Net is literally the case you describe of connecting and uploading a file to S3 - and included as a sample project ready for you to run if you've installed the "AWS Toolkit for Visual Studio" (which should be installed with the .Net AWS SDK).
So all you need to do is open visual studio, find their sample S3 project, or you can look at it here:
// simple object put
PutObjectRequest request = new PutObjectRequest()
{
ContentBody = "this is a test",
BucketName = bucketName,
Key = keyName
};
PutObjectResponse response = client.PutObject(request);
This assumes you have instantiated an Amazon.S3.AmazonS3Client after including the namespace, and configured it with your own credentials.
You first need to install in the Package Manager Console:
Install-package AWSSDK.Extensions.NETCORE.Setup
Install-package AWSSDK.S3
Then you need to have the credentials file in the directory:
C:\Users\username\.aws\credentials
The credential file should have this format:
[default]
aws_access_key_id=[Write your access key in here]
aws_secret_access_key=[Write your secret access key in here]
region=[Write your region here]
I uploaded in github an example of a basic CRUD in ASP.NET CORE for S3 buckets.
We came across an issue when implementing a High-Level API in a .net core solution. When clients had low bandwidth 3mb/s approx an error was thrown by Amazon S3 (The XML you provided was not well-formed). To resolve this issue we had to make an implementation using the low-level API.
https://docs.aws.amazon.com/en_us/AmazonS3/latest/dev/LLuploadFileDotNet.html
// Create list to store upload part responses.
List<UploadPartResponse> uploadResponses = new List<UploadPartResponse>();
// Setup information required to initiate the multipart upload.
InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest{
BucketName = bucketName,
Key = pathbucket
};
//Add metadata to file
string newDate = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
// Initiate the upload.
InitiateMultipartUploadResponse initResponse = await s3Client.InitiateMultipartUploadAsync(initiateRequest);
int uploadmb = 5;
// Upload parts.
long contentLength = new FileInfo(zippath).Length;
long partSize = uploadmb * (long)Math.Pow(2, 20); // 5 MB
try
{
long filePosition = 0;
for (int i = 1; filePosition < contentLength; i++) {
UploadPartRequest uploadRequest = new UploadPartRequest{
BucketName = bucketName,
Key = pathbucket,
UploadId = initResponse.UploadId,
PartNumber = i,
PartSize = partSize,
FilePosition = filePosition,
FilePath = zippath
};
// Track upload progress.
uploadRequest.StreamTransferProgress += new EventHandler<StreamTransferProgressArgs>(UploadPartProgressEventCallback);
// Upload a part and add the response to our list.
uploadResponses.Add(await s3Client.UploadPartAsync(uploadRequest));
filePosition += partSize;
}
// Setup to complete the upload.
CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest {
BucketName = bucketName,
Key = pathbucket,
UploadId = initResponse.UploadId
};
completeRequest.AddPartETags(uploadResponses);
// Complete the upload.
CompleteMultipartUploadResponse completeUploadResponse = await s3Client.CompleteMultipartUploadAsync(completeRequest);
}
catch (Exception exception)
{
Console.WriteLine("An AmazonS3Exception was thrown: { 0}", exception.Message);
// Abort the upload.
AbortMultipartUploadRequest abortMPURequest = new AbortMultipartUploadRequest {
BucketName = bucketName,
Key = keyName,
UploadId = initResponse.UploadId
};
}

WinRT No mapping for the Unicode character exists in the target multi-byte code page

I am trying to read a file in my Windows 8 Store App. Here is a fragment of code I use to achieve this:
if(file != null)
{
var stream = await file.OpenAsync(FileAccessMode.Read);
var size = stream.Size;
using(var inputStream = stream.GetInputStreamAt(0))
{
DataReader dataReader = new DataReader(inputStream);
uint numbytes = await dataReader.LoadAsync((uint)size);
string text = dataReader.ReadString(numbytes);
}
}
However, an exeption is thrown at line:
string text = dataReader.ReadString(numbytes);
Exeption message:
No mapping for the Unicode character exists in the target multi-byte code page.
How do I get by this?
I managed to read file correctly using similar approach to suggested by duDE:
if(file != null)
{
IBuffer buffer = await FileIO.ReadBufferAsync(file);
DataReader reader = DataReader.FromBuffer(buffer);
byte[] fileContent = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(fileContent);
string text = Encoding.UTF8.GetString(fileContent, 0, fileContent.Length);
}
Can somebody please elaborate, why my initial approach didn't work?
Try this instead of string text = dataReader.ReadString(numbytes):
dataReader.ReadBytes(stream);
string text = Convert.ToBase64String(stream);
If, like me, this was the top result when search for the same error regarding UWP, see the below:
The code I had which was throwing the error (no mapping for the unicode character exists..):
var storageFile = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(fileToken);
using (var stream = await storageFile.OpenAsync(FileAccessMode.Read))
{
using (var dataReader = new DataReader(stream))
{
await dataReader.LoadAsync((uint)stream.Size);
var json = dataReader.ReadString((uint)stream.Size);
return JsonConvert.DeserializeObject<T>(json);
}
}
What I changed it to so that it works correctly
var storageFile = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(fileToken);
using (var stream = await storageFile.OpenAsync(FileAccessMode.Read))
{
T data = default(T);
using (StreamReader astream = new StreamReader(stream.AsStreamForRead()))
using (JsonTextReader reader = new JsonTextReader(astream))
{
JsonSerializer serializer = new JsonSerializer();
data = (T)serializer.Deserialize(reader, typeof(T));
}
return data;
}