2

I am using AES 256 to encrypt/decrypt some plain text. But the algorithm uses only PKCS7 for padding, but I need to use PKCS5 to make it compatible to other platforms. How can I achieve this?

My source code is:

public string Encrypt(byte[] PlainTextBytes, byte[] KeyBytes, string InitialVector)
{
    byte[] InitialVectorBytes = Encoding.UTF8.GetBytes(InitialVector);
    RijndaelManaged SymmetricKey = new RijndaelManaged();
    SymmetricKey.Mode = CipherMode.CBC;
    SymmetricKey.Padding = PaddingMode.PKCS7;
    ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes);
    MemoryStream MemStream = new MemoryStream();
    CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write);
    CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
    CryptoStream.FlushFinalBlock();
    byte[] CipherTextBytes = MemStream.ToArray();
    MemStream.Close();
    CryptoStream.Close();
    return ByteToHexConversion(CipherTextBytes);
}
Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
Bhaskar
  • 10,537
  • 6
  • 53
  • 64

1 Answers1

4

PKCS#5-padding and PKCS#7-padding are different names for the same algorithm. It is also sometimes called PKCS-padding or RFC3852-padding.

Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189
  • Thanks a lot. But can you help me with the source of the problem, this is part of a huge enterpise implementation, which is using AES 256 for encryption of data. The hex output of the encryption in Unix (Oracle) and Windows is giving different result, even though we are using the same key and iv. – Bhaskar Jun 29 '09 at 11:09
  • Give us an example key, iv and inputdata as well as the output from your two systems. That might help troubleshooting your problem. You might also want to include the code that is used on your Unix system. – Rasmus Faber Jun 29 '09 at 11:33
  • Unix (Oracle): Key (hex) = "3D39DDFC9FEAD0C32333F744AFCC78157A06695C55FA2C206D96743849DC14D8 Input (plain) = "012345678901234" IV = "0123456789123456" Output (hex) = "00984BBED076541E051A239C02D97117" Windows: Key (hex) = "3D39DDFC9FEAD0C32333F744AFCC78157A06695C55FA2C206D96743849DC14D8 Input (plain) = "012345678901234" IV = "0123456789123456" Output (hex) = "127187969E6F08996662D62854121AF5" – Bhaskar Jun 29 '09 at 12:52
  • 1
    Your Unix(Oracle) values are encrypted using ECB-mode (basically ignoring the IV). Your Windows values are correct. – Rasmus Faber Jun 29 '09 at 13:45
  • Can i do my encryption in .NET by ignoring the IV (ECB mode). I guess, I will have to go with the Unix guys. – Bhaskar Jun 30 '09 at 07:35
  • Yes, just use SymmetricKey.Mode = CipherMode.ECB instead of CBC and use null for the IV (and tease the Unix guys about using ECB mode and still specifying an IV). – Rasmus Faber Jun 30 '09 at 07:59