I am trying to create decrypt function for 32-byte hex string representing 16-byte data this is what I tried so far (I found a working JS example here: http://www.hanewin.net/encrypt/aes/aes-test.htm ):
public static string DecryptString(string code)
{
string text = hex2s("0102030405060708090a0b0c0d0e0f11");
string key = hex2s("ed7c0c82daf513b81c32f6655e8fd4ee");
//Expected result: 260fe45846fb26dbb1d28d8166d4a89f
return BitConverter.ToString(Encoding.Default.GetBytes(decrypt(text, key)));
}
private static string hex2s(string hex)
{
var r = "";
if (hex.IndexOf("0x") == 0 || hex.IndexOf("0X") == 0) hex = hex.Substring(2);
if (hex.Length % 2 > 0) hex += '0';
for (var i = 0; i < hex.Length; i += 2)
{
int thisCharCode = hex[i];
char newCharCode = (char)(thisCharCode);
r = r + newCharCode;
}
return r;
}
public static String decrypt(String imput, String key)
{
byte[] data = Convert.FromBase64String(imput);
String decrypted;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Encoding.ASCII.GetBytes(key);
rijAlg.Mode = CipherMode.ECB;
rijAlg.BlockSize = 128;
rijAlg.Padding = PaddingMode.Zeros;
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, null);
using (MemoryStream msDecrypt = new MemoryStream(data))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
decrypted = srDecrypt.ReadToEnd();
}
}
}
}
return decrypted;
}
I am getting an error: "Length of the data to decrypt is invalid."
I will highly appreciated any suggestion.
stringeverywhere. Also, you're usingFromBase64Stringon a string that hasn't been generated by Base64 encoding. - Damien_The_Unbeliever