1

I need byte array as output after decryption byte array in C#. I am using below code. but i am getting "padding error". Is this below method is correct or i need to make any changes.

  static byte[] DecryptBytesToBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
    // Check arguments. 
    if (cipherText == null || cipherText.Length <= 0)
        throw new ArgumentNullException("cipherText");
    if (Key == null || Key.Length <= 0)
        throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
        throw new ArgumentNullException("Key");
    // Declare the string used to hold 
    // the decrypted text.
    byte[] encrypted = null;
    // Create an AesCryptoServiceProvider object 
    // with the specified key and IV. 
    using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
    {
        //aesAlg.Key = Key;
        //aesAlg.IV = IV;
        aesAlg.KeySize = 128;
        aesAlg.BlockSize = 128;
        aesAlg.Key = Key;
        aesAlg.IV = Key;
        aesAlg.Mode = CipherMode.CBC;
        aesAlg.Padding = PaddingMode.PKCS7;
        // Create a decrytor to perform the stream transform.
        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
        // Create the streams used for decryption. 
        using (MemoryStream msDecrypt = new MemoryStream(cipherText))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {
                    string encrypted_text = srDecrypt.ReadToEnd();
                    encrypted = new byte[encrypted_text.Length * sizeof(char)];
                    System.Buffer.BlockCopy(encrypted_text.ToCharArray(), 0, encrypted, 0, encrypted.Length);
                }
            }
        }
    }
    return encrypted;
}
trm nhcl
  • 17
  • 4
  • Why are you using a `StreamReader` at all if you're trying to get *bytes*? That seems like a very bad idea to me. – Jon Skeet Apr 21 '16 at 05:57
  • Possible duplicate of ["Padding is invalid and cannot be removed" using AesManaged](http://stackoverflow.com/questions/604210/padding-is-invalid-and-cannot-be-removed-using-aesmanaged) – mehrdad safa Apr 21 '16 at 06:01
  • @JonSkeet can you specify any other mehtod or code – trm nhcl Apr 21 '16 at 06:10
  • Well I would probably create a new MemoryStream and call `csDecrypt.CopyTo(target)` then return `target.ToByteArray()`... but if the problem is that it's unable to decrypt your data, that's not going to help. – Jon Skeet Apr 21 '16 at 06:12

0 Answers0