Archived Forum Post

Index of archived forum posts

Question:

AES Encryption and Decryption

Nov 11 '13 at 10:42

Please guys, forgive if i am asking this question in the wrong forum. i stumbled on ChilKat AES Cryptography API some times ago, and its really working good. Lately i have challenge in from of me. i am to decrypt a string in C# which was encrypted in PHP. I used Chilkat and everything seem good and working well. But i was ask to implement the code in pure C# for some reason best known to the boeard of directors. After some few test, i keep getting an exception (Lenght of data to decrypt is not valid) Please can anyone help out with this. Here is my code

public String inChargeEncrypt(String plaintext, byte[] encryptionKey, byte[] initializationVector) { byte[] encryptedText; using (RijndaelManaged rjManage = new RijndaelManaged()) { rjManage.Mode = CipherMode.CBC; rjManage.KeySize = 128; rjManage.Key = encryptionKey; rjManage.IV = initializationVector; rjManage.Padding = PaddingMode.None;

        ICryptoTransform iTransformer = rjManage.CreateEncryptor(rjManage.Key, rjManage.IV);
        using (MemoryStream memStream = new MemoryStream())
        {
            using (CryptoStream cEncryptStream = new CryptoStream(memStream, iTransformer, CryptoStreamMode.Write))
            {
                using (StreamWriter encryptStreamWriter = new StreamWriter(cEncryptStream))
                {
                    encryptStreamWriter.Write(plaintext);
                }
            }
            encryptedText = memStream.ToArray();
        }
    }
    return BitConverter.ToString(encryptedText);
}

public String inChargeDecrypt(String cipher, byte[] encryptionKey, byte[] initializationVector) { String decryptedText = null; using (RijndaelManaged rijManage = new RijndaelManaged()) { rijManage.Mode = CipherMode.CBC; rijManage.KeySize = 128; rijManage.Key = encryptionKey; rijManage.IV = initializationVector; rijManage.Padding = PaddingMode.None;

        ICryptoTransform iTranformation = rijManage.CreateDecryptor(rijManage.Key, rijManage.IV);
        using (MemoryStream memStream = new MemoryStream(Encoding.ASCII.GetBytes(cipher)))
        {
            using (CryptoStream cDecryptorStream = new CryptoStream(memStream, iTranformation, CryptoStreamMode.Read))
            {
                using (StreamReader decryptReader = new StreamReader(cDecryptorStream))
                {
                    decryptedText = decryptReader.ReadToEnd();
                }
            }
        }

    }
    return decryptedText;
}

Here is my Key and IV byte[] cypherKey = Encoding.ASCII.GetBytes("3174878857432116"); byte[] cypherIV = Encoding.ASCII.GetBytes("2301307412865135");