I am using this function to encrypt data in my UWP project:
public string Encrypt(string text, string key)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
byte[] sessionKey = Encoding.UTF8.GetBytes(key);
Aes myAes = Aes.Create();
myAes.Mode = CipherMode.ECB;
myAes.KeySize = 128;
myAes.Key = sessionKey;
myAes.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = myAes.CreateEncryptor();
buffer = encryptor.TransformFinalBlock(buffer, 0, buffer.Length);
return Convert.ToBase64String (buffer);
}
But upon decrypting the data returned from Encrypt() , I get a different result (not equal to the text parameter of Encrypt() ). I am using the following code:
public string Decrypt(string text, string key)
{
byte[] buffer = Convert.FromBase64String(text);
byte[] sessionKey = Encoding.UTF8.GetBytes(key);
Aes myAes = Aes.Create();
myAes.Mode = CipherMode.ECB;
myAes.KeySize = 128;
myAes.Key = sessionKey;
myAes.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = myAes.CreateDecryptor();
buffer = decryptor.TransformFinalBlock(buffer, 0, buffer.Length);
return Convert.ToBase64String(buffer);
}
I am using the same key for both encryption and decryption
UPDATE: text parameter passed to Encrypt() : 450131283::0300DC98050044C406000100040052C40100626B02007E810900660F
Return text from Encrypt(): "lzkPu35Hq7j52IiMWRYSS6j7Vg84abVmhXmNpSxHShJDTbOqkZRFtsPZkEzTsjgRT4MzRHCQUS6MCiq1e5JCune4bZZi1nxxwHtEjZLKZ9E="
the same (above) value I pass to the Decrypt() method and I get the following: "NDUwMTMxMjgzOjowMzAwREM5ODA1MDA0NEM0MDYwMDAxMDAwNDAwNTJDNDAxMDA2MjZCMDIwMDdFODEwOTAwNjYwRg=="
The problem is what you're doing with the end of the decryption:
return Convert.ToBase64String(buffer);
You actually want to convert the decrypted binary data back into a string in a way that mirrors the original way you converted it from a string into plaintext binary data, so you want:
return Encoding.UTF8.GetString(buffer);
This sort of problem is usually best addressed by looking at every step in the transformation chain each direction, and make sure that they're balanced. So it should look like this:
Text
(Encode with UTF-8)
Non-encrypted binary data
(Encrypt)
Encrypted binary data
(Convert to base64)
Encrypted data as base64 text
(Store or whatever...)
Encrypted data as base64 text
(Convert from base64)
Encrypted binary data
(Decrypt)
Non-encrypted binary data
(Decode with UTF-8)
Text
Where I've got "decode with UTF-8" you've got "Convert to base64" so the decoding steps don't match the encoding steps.
See more on this question at Stackoverflow