Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I try to return the value in bytes in the decrypt after the encrytion is done, it gives an error as "length of the data to decrypt is invalid."or"Bad Data"

The code is as follows
C#
#region Decrypt

internal static byte[] Decrypt(string inFile)
{
    FileStream inFileStream = new FileStream(inFile, FileMode.Open, FileAccess.Read);
    MemoryStream outMemoryStream = new MemoryStream();
    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    Dictionary<string,> memDict = new Dictionary<string,>();
    CryptoStream cs = new CryptoStream(outMemoryStream, tdes.CreateDecryptor(Encoding.UTF8.GetBytes(sharedkey), sharedvector), CryptoStreamMode.Write);
    int bufferLen = 4096;
    byte[] buffer = new byte[bufferLen];
    //Convert.FromBase64String(buffer.Replace(" ", "+"));
    int bytesRead;
    do
    {
        // read a chunk of data from the input file
        bytesRead = inFileStream.Read(buffer, 0, bufferLen);
        // encrypt it
        cs.Write(buffer, 0, bytesRead);
    } while (bytesRead != 0);

    // close everything
    // this will also close the unrelying fsOut stream

    //byte[] cipherTextBytes = Convert.FromBase64String(cipherText.Replace(" ", "+"));
    //string strDecrypted = Decrypt(strToDecrypt.Replace(" ","+"),_privateKey);
    cs.FlushFinalBlock();
    cs.Close();
    inFileStream.Close();

    byte[] inByte = new byte[8192];
    inByte = outMemoryStream.ToArray();
    return inByte;
}

#endregion

#region Encrypt


public static byte[] Encrypt(string inFile)
{
    FileStream inFileStream = new FileStream(inFile, FileMode.Open, FileAccess.Read);
    MemoryStream outMemoryStream = new MemoryStream();
    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    Dictionary<string,> memDict = new Dictionary<string,>();
    CryptoStream cs = new CryptoStream(outMemoryStream, tdes.CreateEncryptor(Encoding.UTF8.GetBytes(sharedkey), sharedvector), CryptoStreamMode.Write);
    int bufferLen = 4096;
    byte[] buffer = new byte[bufferLen];
    int bytesRead;
    do
    {
        // read a chunk of data from the input file
        bytesRead = inFileStream.Read(buffer, 0, bufferLen);
        // encrypt it
        cs.Write(buffer, 0, bytesRead);
    } while (bytesRead != 0);

    // close everything
    // this will also close the unrelying fsOut stream

    cs.FlushFinalBlock();
    cs.Close();
    inFileStream.Close();

    byte[] inByte = new byte[8192];
    inByte = outMemoryStream.ToArray();
    return inByte;
}

#endregion
Posted
Updated 20-Sep-11 21:12pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900