1
  1. I have encryption and decryption methods but the encryption method's output is wrong. The key is "u1S1t12vTeZtlRHd" and the output must be "kJtXKmIiP9f73IZJim16LA==" ( Please check decryiption method) but the encryption method is giving me this output "VmmB3k7hVoKF9/cAQedaYQ==". How can i fix it?
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] bytes = utf8Encoding.GetBytes("u1S1t12vTeZtlRHd");
RijndaelManaged rijndaelManaged = new RijndaelManaged
{
    Key = bytes,
    Mode = CipherMode.ECB,
    Padding = PaddingMode.PKCS7
};
byte[] bytes2 = utf8Encoding.GetBytes("FAILED");
rijndaelManaged.CreateEncryptor();
byte[] inArray;
try
{
    inArray = rijndaelManaged.CreateEncryptor().TransformFinalBlock(bytes2, 0, bytes2.Length);
}
finally
{
    rijndaelManaged.Clear();
}

Console.WriteLine(Convert.ToBase64String(inArray));
byte[] array = Convert.FromBase64String("kJtXKmIiP9f73IZJim16LA==");
byte[] bytes = Encoding.ASCII.GetBytes("u1S1t12vTeZtlRHd");
ICryptoTransform transform = new RijndaelManaged
{
    Mode = CipherMode.ECB,
    Padding = PaddingMode.None
}.CreateDecryptor(bytes, null);
MemoryStream memoryStream = new MemoryStream(array);
CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read);
byte[] array2 = new byte[checked(array.Length - 1 + 1)];
int count = cryptoStream.Read(array2, 0, array2.Length);
memoryStream.Close();
cryptoStream.Close();

Console.WriteLine(Encoding.UTF8.GetString(array2, 0, count));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • You never specify the key in your decryptor. That may not be all that's wrong, but it looks like a starting point... – Jon Skeet Aug 11 '21 at 19:37
  • u1S1t12vTeZtlRHd is the key , its specified in both methods. I'm trying to get this VmmB3k7hVoKF9/cAQedaYQ== as output from encryption method – pythonlearner11 Aug 11 '21 at 19:44
  • Ah, it's specified in `CreateDecryptor`. Right. In that case, I think it may well be the IV - you're specifying it as null in `CreateDecryptor`, but I *suspect* it needs to be the same as in the encryptor, where it's just generated randomly on construction. – Jon Skeet Aug 11 '21 at 19:48
  • Can you share an example about iv? I don't understand what you mean – pythonlearner11 Aug 11 '21 at 20:18
  • Basically, you need to use the same IV in the encryptor and decryptor, just like you need to use the same key. The difference is that the IV doesn't need to be secret. So just to get things working, you could hard-code that to the same IV, just like you're hard-coding it to be the same key. – Jon Skeet Aug 11 '21 at 20:25
  • "you could hard-code that to the same IV" As far as I know this is not recommended. You should always use a diffent IV, see https://crypto.stackexchange.com/a/54987/74702 – anion Jan 31 '23 at 11:57

0 Answers0