Last post Sep 04, 2019 12:03 AM by TiredOldCat
Sep 03, 2019 01:34 PM|TiredOldCat|LINK
I have the following VB code for encrypting (works well) plain text.
Private Function AESEncryptStringToBase64(strPlainText As String, EncryptionKey As String) As String
Dim Algo As RijndaelManaged = RijndaelManaged.Create()
.BlockSize = 128
.FeedbackSize = 128
.KeySize = 256
.Mode = CipherMode.CBC
.IV = Guid.NewGuid().ToByteArray()
.Key = Encoding.ASCII.GetBytes(EncryptionKey)
Using Encryptor As ICryptoTransform = Algo.CreateEncryptor()
Using MemStream As New MemoryStream
Using CryptStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
Using Writer As New StreamWriter(CryptStream)
AESEncryptStringToBase64 = Convert.ToBase64String(Algo.IV.Concat(MemStream.ToArray()).ToArray())
I am trying to convert to C# and I think I have the code correct except for the highlighted line above. See the highlighted line below.
Thanks for any help.
My C# code follows.
protected string Encrypt(string strPlainText, string encryptionKey)
RijndaelManaged Algo = new RijndaelManaged();
Algo.BlockSize = 128;
Algo.FeedbackSize = 128;
Algo.KeySize = 256;
Algo.Mode = CipherMode.CBC;
Algo.IV = Guid.NewGuid().ToByteArray();
Algo.Key = Encoding.ASCII.GetBytes(encryptionKey);
using (ICryptoTransform Encryptor = Algo.CreateEncryptor())
using (MemoryStream MemStream = new MemoryStream())
using (CryptoStream CryptStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
using (StreamWriter Writer = new StreamWriter(CryptStream))
} //using (StreamWriter Writer = new StreamWriter(CryptStream))
byte  temp = MemStream.ToArray();
AESEncryptStringToBase64 = BitConverter.ToString(temp);
} //using (CryptoStream CryptStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
} //using (MemoryStream MemStream = new MemoryStream())
} //using (ICryptoTransform Encryptor = Algo.CreateEncryptor())
Sep 03, 2019 02:40 PM|mgebhard|LINK
The code looks correct. Is there any reason why you don't simply test the code?
Sep 04, 2019 12:03 AM|TiredOldCat|LINK
Code looked ok but did not work.
the VB line of code = AESEncryptStringToBase64 = Convert.ToBase64String(Algo.IV.Concat(MemStream.ToArray()).ToArray())
It was the Concat part that threw me. Eventually I figured that there are two arrays but the VB code did not explicitly state them.
So, I found the 2 byte arrays that were being combined and updated my code as follows.
byte temp1 = MemStream.ToArray();
byte temp2 = Algo.IV;
var result = temp2.Concat(temp1);
AESEncryptStringToBase64 = Convert.ToBase64String(result.ToArray());
Eventually, I will condense this code to a single line.