Frage

I am getting length of the string wrong after using the following Decryption Method.

public static string DecryptRJ256(string prm_key, string prm_iv, string prm_text_to_decrypt) {
    string sEncryptedString = prm_text_to_decrypt;

    RijndaelManaged myRijndael = new RijndaelManaged();
    myRijndael.Padding = PaddingMode.Zeros;
    myRijndael.Mode = CipherMode.CBC;
    myRijndael.KeySize = 256;
    myRijndael.BlockSize = 256;

    byte[] key = Encoding.ASCII.GetBytes(prm_key);
    byte[] IV = Encoding.ASCII.GetBytes(prm_iv);

    ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

    byte[] sEncrypted = Convert.FromBase64String(sEncryptedString);

    byte[] fromEncrypt = new byte[sEncrypted.Length];

    MemoryStream msDecrypt = new MemoryStream(sEncrypted);
    CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

    csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

    return (Encoding.ASCII.GetString(fromEncrypt));
}

For example:

string ID = "yUFYhclPyPubnhMZ+SHJb1wrt44pao3B82jdbL1ierM=";
string finalID = DecryptRJ256(sKy, sIV, ID);
Response.Write(finalID); \\200905410 (**this is correct**)
Response.Write(finalID.Length); \\32 (**this should be 9**)

What am I doing wrong?

War es hilfreich?

Lösung

You are using zero padding. This pads the message with zero bytes until it reaches the block size (32 bytes in your case). Since zero padding is ambiguous (can't distinguish between an input that ended with zero bytes and the padding), .net doesn't remove it automatically.

So you have two choices:

  • Use PKCS7 padding for both encryption and decryption (that's what I recommend)
  • Manually strip all terminal zero bytes from the decrypted plaintext.

Your crypto isn't good either:

  1. Keys and IVs should be binary, not ASCII (use base64 encoding here)
  2. Using ASCII on the plaintext silently corrupts unicode characters - Use utf-8 instead
  3. You need a new random IV for each encryption call and need to read it back during decryption
  4. You should add a MAC, else active attacks (such as padding oracles) can often break it.
  5. Use TransformFinalBlock instead of those memory streams.
  6. Why use Rijndael256 over AES?

Andere Tipps

When I compiled this with symmetric decryptor object with the current Key, that is without key and IV, I get this as finalID.

???hV?9-2O?o?????}yl?????N?W

exactly 32 characters. Refining the key and IV would help. I am not sure, but hope this might help.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top