I work with SagePay forms and am currently converting the VB examples that they have for C #. I have achieved good results, so part of the encryption of my project works fine (SagePay can decrypt it).
The problem I am facing is that when I try to decrypt a string, it turns into garbage. If someone had done this before, I would really appreciate help in my decrypted code. I have included an encryption code that works, and the first two lines are setting up and calling another method.
I have not added VB code, but if necessary, I can add it. Didn't want a huge post if not required.
Useful methods:
public string byteArrayToHexString(byte[] ba) { return BitConverter.ToString(ba).Replace("-", ""); } public static byte[] StringToByteArray(string hex) { return Enumerable.Range(0, hex.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); }
The main encryption method with the first pair of lines, which is a call to it, extracted from a larger method.
string crypt = "blahblahblah" string EncryptAndEncode = "@" + byteArrayToHexString(aesEncrypt(crypt)); private byte[] aesEncrypt(string inputText) { RijndaelManaged AES = new RijndaelManaged();
Decoding and decoding methods
public string DecodeAndDecrypt(string strIn) { //** HEX decoding then AES decryption, CBC blocking with PKCS5 padding - DEFAULT ** string DecodeAndDecrypt = aesDecrypt(StringToByteArray(strIn.Substring(1))); return (DecodeAndDecrypt); } private string aesDecrypt(Byte[] inputBytes) { RijndaelManaged AES = new RijndaelManaged(); Byte[] keyAndIvBytes = UTF8Encoding.UTF8.GetBytes("tR7nR6wZHGjYMCuV"); Byte[] outputBytes = inputBytes;//Convert.FromBase64String(inputBytes); //set the mode, padding and block size AES.Padding = PaddingMode.PKCS7; AES.Mode = CipherMode.CBC; AES.KeySize = 128; AES.BlockSize = 128; //create streams and decryptor object MemoryStream memoryStream = new MemoryStream(outputBytes); CryptoStream cryptoStream = new CryptoStream(memoryStream, AES.CreateEncryptor(keyAndIvBytes, keyAndIvBytes), CryptoStreamMode.Read); //perform decryption cryptoStream.Read(outputBytes, 0, outputBytes.Length); Trace.WriteLine(outputBytes); //close streams memoryStream.Close(); cryptoStream.Close(); AES.Clear(); //return System.Text.Encoding.UTF8.GetString(outputBytes); string plainText = Encoding.UTF8.GetString(outputBytes, 0, outputBytes.Length); return plainText; }