locked
Problem while decrypting Data RRS feed

  • Question

  • I'm getting issue while decrypting Data. I'm using DES Encryption

    here's code

    for Encryption

     byte[] key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
                    byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
                    byte[] sourceData = System.Text.ASCIIEncoding.ASCII.GetBytes(source);
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    DESCryptoServiceProvider encryptor = new DESCryptoServiceProvider();
                    CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                    cs.Write(sourceData, 0, sourceData.Length);
                    cs.FlushFinalBlock();
                    return Convert.ToBase64String(ms.GetBuffer(), 0, ms.GetBuffer().Length);
    


    For Decrypting

      byte[] key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
                byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] encryptedDataBytes = Convert.FromBase64String(source);                
                    MemoryStream tempStream =new MemoryStream(encryptedDataBytes, 0, encryptedDataBytes.Length);                
                    DESCryptoServiceProvider decryptor = new DESCryptoServiceProvider();
                    CryptoStream decryptionStream = new CryptoStream(tempStream, decryptor.CreateDecryptor(key, iv), CryptoStreamMode.Read);                
                    StreamReader allDataReader =new StreamReader(decryptionStream);
                    return allDataReader.ReadToEnd();
    

    Exception is Bad Data Exception


    Regards Kumar Gaurav.
    Thursday, December 1, 2011 3:37 PM

Answers

  • When converting to base64 you're using ms.GetBuffer().Length. You should use the stream's Length instead because the buffer might be longer than the stream.

    return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

    • Marked as answer by urprob Friday, December 2, 2011 7:43 AM
    Thursday, December 1, 2011 3:52 PM