BlackBerry TripleDESEncryption output convert to String - blackberry

I'm trying to encrypt a String using TripleDESEncryption and followed this example I found on the internet (link: http://www.blackberry.com/developers/docs/3.6api/net/rim/device/api/crypto/doc-files/CryptoTest.html#sampleMD5Digest):
// sampleTripleDESEncryption
private static int sampleTripleDESEncryption( byte[] secretKey, byte[] plainText, byte[] cipherText ) throws CryptoTokenException, CryptoUnsupportedOperationException
{
// Create a new Triple-DES key based on the 24 bytes in the secretKey array
TripleDESKey key = new TripleDESKey( secretKey );
// Create a new instance of the Triple-DES encryptor engine, passing in the newly
// created key
TripleDESEncryptorEngine engine = new TripleDESEncryptorEngine( key );
// Encrypt one block (8 bytes) of plainText into cipherText
engine.encrypt( plainText, 0, cipherText, 0 );
// Return the block size of the engine
return engine.getBlockLength();
}
However, I want to convert the encrypted data to String. I'm not sure if the cipherText variable is the one to be converted. Any help? How am I going to convert it?

You just don't expect that result will be returned through parameter.
So first of all allocate enough buffer in chiperText. Call the method and you will have result in chiperText buffer with returned length (return value).

Related

Converting object to an encodable object failed: Instance of 'Future<dynamic>'

I am trying to get base64 string from image file. When I am using following method
Future convertBase64(file) async{
List<int> imageBytes = fileImage.readAsBytesSync();
String base64Image = await 'data:image/png;base64,' + base64Encode(imageBytes);
// print('length of image bytes ${base64Image.length}');
return base64Image;
}
It shows me an error :
exception---- Converting object to an encodable object failed: Instance of 'Future<dynamic>'
If I use without future it directly pass to next step without converting to base64 String. It usually takes time to convert.
The variable fileImage doesn't seem to match the variable file passed to the function. Might this be the one causing the issue?
I'm curious on why the need to call await on a String - this seems to be unnecessary. The error might be caused on how convertBase64() was called. For async methods like Future<T>, I suggest calling it like:
convertBase64(imageFile).then((String base64Image) {
// Handle base64Image
});
Also, as previously recommended in the comments, it's better to use Uri.dataFromBytes() instead of parsing the encoded String on your own.
Future<String> convertBase64(File file) async{
List<int> imageBytes = file.readAsBytesSync();
return Uri.dataFromBytes(imageBytes, mimeType: "image/png").toString();
}

Google Tink: How to get raw key string from a KeysetHandle?

I am new to Tink and would like to extract the raw key data(in String form) from KeysetHandle which I generated like this:
keysetHandle = KeysetHandle.generateNew(
AeadKeyTemplates.AES128_GCM);
Or maybe some other API to get it.
How can I achieve this?
You can write the Keyset to disk with either KeysetHandle.write(), which requires encryption, other CleartextKeysetHandle.write(). Both require a BinaryKeysetWriter or JsonKeysetWriter.
Example will help. Here is how you would use CleartextKeysetHandle.write() to observe the key profile:
Try this for display:
// display key [Caveat: ONLY for observation]
public void display_key_profile_for_test_observation_only(KeysetHandle keysetHandle) throws IOException, GeneralSecurityException
{
System.out.println("\nDisplay key:");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CleartextKeysetHandle.write(keysetHandle, JsonKeysetWriter.withOutputStream(outputStream));
System.out.println("\n"+ new String(outputStream.toByteArray()));
}
As this belongs to a class, you may have to do some slight code modification. You see the keyword this denoting that the code snippets come from a class. Here is the test usage:
public void trial_usage_key_generation() throws IOException, GeneralSecurityException {
for (CIPHER_SYMMETRIC_ALGOS algo_type : CIPHER_SYMMETRIC_ALGOS.values()) {
System.out.println("Generating key for : " + algo_type);
KeysetHandle keysetHandle = this.generate_key_for_test_observation_only(algo_type);
this.display_key_profile_for_test_observation_only(keysetHandle);
}
}
You can use reflection to get the keyset as code below, or JsonKeysetWriter to get base64ed key bytestring (still needs to be unserialized to corresponding key object to get the raw key bytes).
KeysetHandle keysetHandle = KeysetHandle.generateNew(
AeadKeyTemplates.CHACHA20_POLY1305);
Method method = keysetHandle.getClass().getDeclaredMethod("getKeyset");
method.setAccessible(true);
Keyset keyset = (Keyset) method.invoke(keysetHandle);
ChaCha20Poly1305Key key = ChaCha20Poly1305Key.parseFrom(keyset.getKey(0).getKeyData().getValue());
byte[] keyBytes = key.getKeyValue().toByteArray();

How can i decrypt the xml file in iOS with AES/CBC/PKCS5Padding standard,in android the file has been decrypted ,all keys like salt, IV

private static Cipher getCipher(int mode) throws Exception {
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
//a random Init. Vector. just for testing
byte[] iv = "e675f725e675f725".getBytes("UTF-8");
c.init(mode, generateKey(), new IvParameterSpec(iv));
return c;
}
private static String Decrypt(String encrypted) throws Exception {
byte[] decodedValue = new Base64().decode(encrypted.getBytes("UTF-8")); // new BASE64Decoder().decodeBuffer(encrypted);
Cipher c = getCipher(Cipher.DECRYPT_MODE);
byte[] decValue = c.doFinal(decodedValue);
return new String(decValue);
}
private static Key generateKey() throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
char[] password = "3x5FBNs!".toCharArray();
byte[] salt = "S#1tS#1t".getBytes("UTF-8");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
SecretKey tmp = factory.generateSecret(spec);
byte[] encoded = tmp.getEncoded();
return new SecretKeySpec(encoded, "AES");
}
I tried to use RNCryptor but could not decrypt. Can anybody help me which library should i use because i have got the encrypted file and don't know how it has been encrypted.
In order to use RNCryptor it is best to use it on both platforms.
From a previous question it seems that the encrypted data was bytes, not Base64 encoded.
The primitives supplied by Apple Common Crypto and are part of the Security.framework. The header to use is #import <CommonCrypto/CommonCrypto.h> and you will find the interfaces you need in CommonCryptor.h and CommonKeyDerivation.h.
Make an attempt for iOS and add the code along with hex dumps of all input and output parameters and data both for the Android and iOS code.

Getting Data from a Website using MVC 4 Web API

This is a follow-up to this post: New at MVC 4 Web API Confused about HTTPRequestMessage
Here is a summary of what I am trying to do: There is a web site that I want to interface with via MVC 4 Web API. At the site, users can log in with a user name and password, then go to a link called ‘Raw Data’ to query data from the site.
On the ‘Raw Data’ page, there is a dropdown list for ‘Device’, a text box for ‘From’ date, and a text box for ‘To’ date. Given these three parameters, the user can click the ‘Get Data’ button, and return a table of data to the page. What I have to do, is host a service on Azure that will programmatically provide values for these three parameters to the site, and return a CSV file from the site to Azure storage.
The company that hosts the site has provided documentation to programmatically interface with the site to retrieve this raw data. The document describes how requests are to be made against their cloud service. Requests must be authenticated using a custom HTTP authentication scheme. Here is how the authentication scheme works:
Calculate an MD5 hash from the user password.
Append the request line to the end of the value from step one.
Append the date header to the end of the value in step two.
Append the message body (if any) to the end of the value in step 3.
Calculate MD5 hash over the resulting value from step 4.
Append the value from step 5 to the user email using the “:” character as a delimiter.
Calculate Base64 over the value from step 6.
The code that I am going to list was done in Visual Studio 2012, C#, .NET Framework 4.5. All of the code in this post is in my 'FileDownloadController.cs' Controller class. The ‘getMd5Hash’ function takes a string, and returns an MD5 hash:
//Create MD5 Hash: Hash an input string and return the hash as a 32 character hexadecimal string.
static string getMd5Hash(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
This function takes a string, and returns BASE64:
//Convert to Base64
static string EncodeTo64(string input)
{
byte[] str1Byte = System.Text.Encoding.ASCII.GetBytes(input);
String plaintext = Convert.ToBase64String(str1Byte);
return plaintext;
}
The next function creates an HTTPClient, makes an HTTPRequestMessage, and returns the authorization. Note: The following is the URI that was returned from Fiddler when data was returned from the ‘Raw Data’ page: GET /rawdata/exportRawDataFromAPI/?devid=3188&fromDate=01-24-2013&toDate=01-25-2013 HTTP/1.1
Let me first walk through what is happening with this function:
The ‘WebSiteAuthorization’ function takes a ‘deviceID’, a ‘fromDate’, a ‘toDate’ and a ‘password’.
Next, I have three variables declared. I’m not clear on whether or not I need a ‘message body’, but I have a generic version of this set up. The other two variables hold the beginning and end of the URI.
I have a variable named ‘dateHeader’, which holds the data header.
Next, I attempt to create an HTTPClient, assign the URI with parameters to it, and then assign ‘application/json’ as the media type. I’m still not very clear on how this should be structured.
In the next step, the authorization is created, per the requirements of the API documentation, and then the result is returned.
public static string WebSiteAuthorization(Int32 deviceid, string fromDate, string toDate, string email, string password)
{
var messagebody = "messagebody"; // TODO: ??????????? Message body
var uriAddress = "GET/rawdata/exportRawDataFromAPI/?devid=";
var uriAddressSuffix = "HTTP/1.1";
//create a date header
DateTime dateHeader = DateTime.Today;
dateHeader.ToUniversalTime();
//create the HttpClient, and its BaseAddress
HttpClient ServiceHttpClient = new HttpClient();
ServiceHttpClient.BaseAddress = new Uri(uriAddress + deviceid.ToString() + " fromDate" + fromDate.ToString() + " toDate" + toDate.ToString() + uriAddressSuffix);
ServiceHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//create the authorization string
string authorizationString = getMd5Hash(password);
authorizationString = authorizationString + ServiceHttpClient + dateHeader + messagebody;
authorizationString = email + getMd5Hash(authorizationString);
authorizationString = EncodeTo64(authorizationString);
return authorizationString;
}
I haven’t tested this on Azure yet. I haven't completed the code that gets the file. One thing I know I need to do is to determine the correct way to create an HttpRequestMessage and use HttpClient to send it. In the documentation that I've read, and the examples that I've looked at, the following code fragments appear to be possible approaches to this:
Var serverAddress = http://my.website.com/;
//Create the http client, and give it the ‘serverAddress’:
Using(var httpClient = new HttpClient()
{BaseAddress = new Uri(serverAddress)))
Var requestMessage = new HttpRequestMessage();
Var objectcontent = requestMessage.CreateContent(base64Message, MediaTypeHeaderValue.Parse (“application/json”)
or----
var formatters = new MediaTypeFormatter[] { new jsonMediaTypeFormatter() };
HttpRequestMessage<string> request = new HttpRequestMessage<string>
("something", HttpMethod.Post, new Uri("http://my.website.com/"), formatters);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var httpClient = new HttpClient();
var response = httpClient.SendAsync(request);
or------
Client = new HttpClient();
var request = new HttpRequestMessage
{
RequestUri = "http://my.website.com/",
Method = HttpMethod.Post,
Content = new StringContent("ur message")
};
I'm not sure which approach to take with this part of the code.
Thank you for your help.
Read this step by step tutorial to understand the basic.

In C#, how can I know the file type from a byte[]?

I have a byte array filled from a file uploaded. But, in another part of the code, I need to know this file type uploaded from the byte[] so I can render the correct content-type to browser!
Thanks!!
As mentioned, MIME magic is the only way to do this. Many platforms provide up-to-date and robust MIME magic files and code to do this efficiently. The only way to do this in .NET without any 3rd party code is to use FindMimeFromData from urlmon.dll. Here's how:
public static int MimeSampleSize = 256;
public static string DefaultMimeType = "application/octet-stream";
[DllImport(#"urlmon.dll", CharSet = CharSet.Auto)]
private extern static uint FindMimeFromData(
uint pBC,
[MarshalAs(UnmanagedType.LPStr)] string pwzUrl,
[MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
uint cbSize,
[MarshalAs(UnmanagedType.LPStr)] string pwzMimeProposed,
uint dwMimeFlags,
out uint ppwzMimeOut,
uint dwReserverd
);
public static string GetMimeFromBytes(byte[] data) {
try {
uint mimeType;
FindMimeFromData(0, null, data, (uint)MimeSampleSize, null, 0, out mimeType, 0);
var mimePointer = new IntPtr(mimeType);
var mime = Marshal.PtrToStringUni(mimePointer);
Marshal.FreeCoTaskMem(mimePointer);
return mime ?? DefaultMimeType;
}
catch {
return DefaultMimeType;
}
}
This uses the Internet Explorer MIME detector. This is the same code used by IE to send a MIME type along with uploaded files. You can see the list of MIME types supported by urlmon.dll. One thing to watch out for is image/pjpeg and image/x-png which are non-standard. In my code I replace these with image/jpeg and image/png.
Not sure, but maybe you should investigate about magic numbers.
Update:
Reading about it, I don't think it's very reliable though.
If you know it's a System.Drawing.Image, you can do:
public static string GetMimeTypeFromImageByteArray(byte[] byteArray)
{
using (MemoryStream stream = new MemoryStream(byteArray))
using (Image image = Image.FromStream(stream))
{
return ImageCodecInfo.GetImageEncoders().First(codec => codec.FormatID == image.RawFormat.Guid).MimeType;
}
}
You can't know it from the byte stream, but you can store the MIME type when you initially populate the byte[].
Short answer: you can't
Longer answer: Usually, programs use the file extension to know what type of file they're dealing with. If you don't have that extension, you can only make guesses... for instance, you could look at the first few bytes and check if you recognize a well-known header (XML declaration tag for instance, or bitmap or JPEG header). But that will always be a guess in the end : without some metadata or information about the content, an array of bytes is just meaningless...
If you know extension of the file name, may be System.Web.MimeMapping will do the trick:
MimeMapping.GetMimeMapping(fileDisplayNameWithExtension)
I used it in MVC Action like this:
return File(fileDataByteArray, MimeMapping.GetMimeMapping(fileDisplayNameWithExtension), fileDisplayNameWithExtension);
Reminds me of back in the day we, er um "some people" used to share 50MB rar files on the early free image hosting sites, by just adding the .gif extension to the .rar filename.
Clearly if you are public facing and your are expecting a certain file type, and you have to be sure it is that file type, then you can't just trust the extension.
On the other hand, if your app would have no reason to distrust the the uploaded extension and or MIME type, then just get those when the file is uploaded like the answers you received from #rossfabircant and #RandolphPotter. create a type that has the byte[], as well as the original extension or mimetype, and pass that around.
If you need to verify that the file is actually a certain expected type like a valid .jpeg, or .png you can try to interpret the file as those types and see if it opens successfully. (System.Drawing.Imaging.ImageFormat)
If you are trying to classify the file only from the binary contents, and it could be any format in the whole wide world, that is really a tough, open-ended problem and there is no 100% reliable way to do it. You could invoke TrID against it, and there are likely similar forensics tools used by law enforcement investigators if you can find (and afford) them.
If you don't have to do it the hard way, don't.
You don't want to do it that way. Call Path.GetExtension when the file is uploaded, and pass the extension around with the byte[].
If you have a limited number of expected file types you want to support, magic numbers can be the way to go.
A simple way to check is to just open example files with a text/hex editor, and study the leading bytes to see if there is something there you can use to differentiate/discard files from the supported set.
If, on the other hand, you are looking to recognize any arbitrary file type, yeah, as everyone has stated already, tough.
Using the System.Drawing.Image 'RawFormat.Guid' Property you can detect MIME Type of Images.
but i am not sure how to find other File Types.
http://www.java2s.com/Code/CSharp/Network/GetImageMimeType.htm
UPDATE: you may try taking a look on this post
Using .NET, how can you find the mime type of a file based on the file signature not the extension
I got AccessViolationException while accessing memory using other answers, so I solved my problem using this code:
[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
private static extern int FindMimeFromData(IntPtr pBc,
[MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)]
byte[] pBuffer,
int cbSize,
[MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
int dwMimeFlags,
out IntPtr ppwzMimeOut,
int dwReserved
);
/**
* This function will detect mime type from provided byte array
* and if it fails, it will return default mime type
*/
private static string GetMimeFromBytes(byte[] dataBytes, string defaultMimeType)
{
if (dataBytes == null) throw new ArgumentNullException(nameof(dataBytes));
var mimeType = string.Empty;
IntPtr suggestPtr = IntPtr.Zero, filePtr = IntPtr.Zero;
try
{
var ret = FindMimeFromData(IntPtr.Zero, null, dataBytes, dataBytes.Length, null, 0, out var outPtr, 0);
if (ret == 0 && outPtr != IntPtr.Zero)
{
mimeType = Marshal.PtrToStringUni(outPtr);
Marshal.FreeCoTaskMem(outPtr);
}
}
catch
{
mimeType = defaultMimeType;
}
return mimeType;
}
How to call it:
string ContentType = GetMimeFromBytes(byteArray, "image/jpeg");
Hope this helps!

Resources