Related
I'm trying to create methods for very strong Rijndael 256 string encryption that I can use for passwords but I get an error saying Padding is invalid and cannot be removed. when I read the CryptoStream and get the decrypted string. Here are my encrypt and decrypt methods:
private string AES256EncryptString(string key, string plainText)
{
try
{
using (RijndaelManaged rijndael = new RijndaelManaged())
{
rijndael.KeySize = 256;
rijndael.BlockSize = 128;
rijndael.Key = Encoding.UTF8.GetBytes(key);
rijndael.GenerateIV();
rijndael.Mode = CipherMode.CBC;
rijndael.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = rijndael.CreateEncryptor(rijndael.Key, rijndael.IV);
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(rijndael.IV, 0, rijndael.IV.Length);
CryptoStream crypoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
crypoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
crypoStream.FlushFinalBlock();
crypoStream.Close();
byte[] encryptedBytes = memoryStream.ToArray();
memoryStream.Close();
string encryptedText = Convert.ToBase64String(encryptedBytes);
return encryptedText;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
}
private string AES256DecryptString(string key, string encryptedText)
{
try
{
using (RijndaelManaged rijndael = new RijndaelManaged())
{
rijndael.KeySize = 256;
rijndael.BlockSize = 128;
rijndael.Key = Encoding.UTF8.GetBytes(key);
byte[] encryptedTextBytes = Encoding.UTF8.GetBytes(encryptedText);
byte[] iv = new byte[16];
Array.Copy(encryptedTextBytes, iv, iv.Length);
rijndael.IV = iv;
rijndael.Mode = CipherMode.CBC;
rijndael.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);
MemoryStream memoryStream = new MemoryStream();
byte[] encryptedTextWithoutIVBytes = new byte[encryptedTextBytes.Length - iv.Length];
Array.Copy(encryptedTextBytes, 16, encryptedTextWithoutIVBytes, 0, encryptedTextWithoutIVBytes.Length);
memoryStream.Write(encryptedTextWithoutIVBytes, 0, encryptedTextWithoutIVBytes.Length);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
StreamReader streamReader = new StreamReader(cryptoStream);
string decryptedText = streamReader.ReadToEnd();
cryptoStream.FlushFinalBlock();
cryptoStream.Close();
memoryStream.Close();
return decryptedText;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
}
As you can see I add the initialization vector before the encrypted string before adding the encrypted bit because I know that IVs should be random and I've seen this is a good strategy to use. I make sure to remove the IV before decrypting.
Is there a way to fix this without changing the padding mode (I've seen that PKCS7 padding is very secure)?
Problems:
You should use a proper password-based KDF for passwords and similar low-entropy keys. .NET has the Rfc2898DeriveBytes (PBKDF2) class to make this relatively easy.
You are not base64 decoding your ciphertext in your decryptor. Instead of
byte[] encryptedTextBytes = Encoding.UTF8.GetBytes(encryptedText);
you should have
byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText);
You need to reset the position of the MemoryStream after you populate it with ciphertext bytes. After
memoryStream.Write(encryptedTextWithoutIVBytes, 0, encryptedTextWithoutIVBytes.Length);
you need to insert
memoryStream.Seek(0, SeekOrigin.Begin);
I am having a problem with my code and cannot figure out the problem.
With fullMsg set to false it works.
If I change fullMsg to true it no longer works even if I set it back to false.
I have no idea what is going on as the byte[] array remains the same in all the cases.
private void sendIndividualMsg(string msg){
//Debug.Log (msg);
byte[] toSend = PackageMsg (msg);
byte[] decoded = UnPackageMsg (toSend);
Debug.Log( System.Text.Encoding.ASCII.GetString(decoded) );
}
private byte[] UnPackageMsg(byte[] msg){
var toDecrypt = msg;
if (fullMsg) {
toDecrypt = new byte[msg.Length - 16];
var decryptIV = new byte[16];
System.Buffer.BlockCopy (msg, 0, decryptIV, 0, 16);
System.Buffer.BlockCopy (msg, 16, toDecrypt, 0, (msg.Length - 16));
//myAes.IV = decryptIV;
}
PrintByteArray (toDecrypt, "ToDecrypt");
byte[] plaintext;
// Create the streams used for decryption.
{
ICryptoTransform decryptor = myAes.CreateDecryptor (myAes.Key, myAes.IV);
MemoryStream msDecrypt = new MemoryStream ();
CryptoStream csDecrypt = new CryptoStream (msDecrypt, decryptor, CryptoStreamMode.Write);
csDecrypt.Write(msg, 0, msg.Length);
csDecrypt.FlushFinalBlock();
csDecrypt.Close();
plaintext = msDecrypt.ToArray();
msDecrypt.Close ();
decryptor.Dispose();
}
if (plaintext.Length > 16) {
byte[] hash = new byte[16];
byte[] hashCalc = new byte[16];
byte[] payload = new byte[plaintext.Length - 16 ];
System.Buffer.BlockCopy (plaintext, 0, hash, 0, 16);
System.Buffer.BlockCopy (plaintext, 16, payload, 0, plaintext.Length - 16);
hashCalc = md5.ComputeHash(payload);
if(ByteArrayCompare(hash, hashCalc)){
return payload;
}else{
return new byte[0];
}
} else {
return new byte[0];
}
}
private byte[] PackageMsg(string msg){
System.Text.ASCIIEncoding ue = new System.Text.ASCIIEncoding();
byte[] bytes = ue.GetBytes(msg);
byte[] hashBytes = md5.ComputeHash(bytes);
byte[] toEncrypt = new byte[bytes.Length + hashBytes.Length];
System.Buffer.BlockCopy(hashBytes, 0, toEncrypt, 0, hashBytes.Length);
System.Buffer.BlockCopy(bytes, 0, toEncrypt, hashBytes.Length, bytes.Length);
//myAes.GenerateIV();
byte[] encrypted;
{
ICryptoTransform encryptor = myAes.CreateEncryptor (myAes.Key, myAes.IV);
MemoryStream msEncrypt = new MemoryStream ();
CryptoStream csEncrypt = new CryptoStream (msEncrypt, encryptor, CryptoStreamMode.Write);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
csEncrypt.Close();
encrypted = msEncrypt.ToArray();
msEncrypt.Close ();
encryptor.Dispose();
}
PrintByteArray (encrypted, "Encrypted");
//SessionBytes + IV + ENCRYPTED( hash + msg)
byte[] finalMsg = new byte[myAes.IV.Length + encrypted.Length ];
System.Buffer.BlockCopy(myAes.IV, 0, finalMsg, 0 , myAes.IV.Length);
System.Buffer.BlockCopy(encrypted, 0, finalMsg, myAes.IV.Length , encrypted.Length);
if (!fullMsg) {
finalMsg = encrypted;
}
return finalMsg;
}
(I want to send the IV through each message, but until I get this working their is no point.)
Basic explanation of the algorithm for encrypting:
If fullMsg is set the encryption is [session][iv][encryptedmsg]
If fullMsg is not set the encryption is [encryptedmsg]
For Decryption the first part of the code is too extract just the encryptedmsg part.
As show by the screenshot of the logs, in both modes the bytes are the same.
--
I have been looking everywhere for some sample code on how to encrypt a simple string with the encryption in the title using the Bouncy Castle Framework.
This code will run on a Windows Universal project.
My previous attempts to encrypt using the build in API's failed to decrypt on the server.
I tried this: which gives me a string like:
4pQUfomwVVsl68oQqWoWYNRmRM+Cp+vNFXBNdkN6dZPQ34VZ35vsKn9Q7QGTDVOj+w5mqVYHnGuAOFOgdgl8kA==
s = String.Format("{0}_{1}", s, DateTime.Now.ToString("ddMMyyyyHmmss"));
SymmetricKeyAlgorithmProvider algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
IBuffer keymaterial = CryptographicBuffer.ConvertStringToBinary("[Key]", BinaryStringEncoding.Utf8);
CryptographicKey KEY = algorithm.CreateSymmetricKey(keymaterial);
IBuffer IV = CryptographicBuffer.ConvertStringToBinary("[IV]", BinaryStringEncoding.Utf8);
IBuffer data = CryptographicBuffer.ConvertStringToBinary(s, BinaryStringEncoding.Utf8);
IBuffer output = CryptographicEngine.Encrypt(KEY, data, IV);
return CryptographicBuffer.EncodeToBase64String(output);
The server does encryption/decryption with
public static string Encrypt(string text, byte[] key, byte[] iv, int keysize = 128, int blocksize = 128, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = blocksize;
aes.KeySize = keysize;
aes.Mode = cipher;
aes.Padding = padding;
byte[] src = Encoding.UTF8.GetBytes(text);
using (ICryptoTransform encrypt = aes.CreateEncryptor(key, iv))
{
byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
encrypt.Dispose();
return Convert.ToBase64String(dest);
}
}
public static string Decrypt(string text, byte[] key, byte[] iv, int keysize = 128, int blocksize = 128, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = blocksize;
aes.KeySize = keysize;
aes.Mode = cipher;
aes.Padding = padding;
byte[] src = Convert.FromBase64String(text);
using (ICryptoTransform decrypt = aes.CreateDecryptor(key, iv))
{
byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
decrypt.Dispose();
return Encoding.UTF8.GetString(dest); //Padding is invalid and cannot be removed.
}
}
But it fails becasue:
Padding is invalid and cannot be removed.
That's why I want to try Bouncy Castle, but I can't find any suitable example code.
EDIT
I tried using Bouncy Castle with the code provided in the answer.
Now I'm getting the error:
initialisation vector must be the same length as block size
byte[] inputBytes = Encoding.UTF8.GetBytes(s);
byte[] IV = Encoding.UTF8.GetBytes("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
byte[] key = Encoding.UTF8.GetBytes("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
//Set up
AesEngine engine = new AesEngine();
CbcBlockCipher blockCipher = new CbcBlockCipher(engine);
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
Debug.WriteLine(IV.Length); //32
Debug.WriteLine(cipher.GetBlockSize()); //16
KeyParameter keyParam = new KeyParameter(key);
ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, IV);
cipher.Init(true, keyParamWithIv); //Error Message thrown
byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; //cip
int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
cipher.DoFinal(outputBytes, length); //Do the final block
string encryptedInput = Convert.ToBase64String(outputBytes);
The length on the server is 128. How can I force it to be equal and same length?
Here are snippets I use. It uses the default built-in System.Security.Cryptography. It doesn't need to be BC
/// <summary>
/// Encrypt a byte array using AES 128
/// </summary>
/// <param name="key">128 bit key</param>
/// <param name="secret">byte array that need to be encrypted</param>
/// <returns>Encrypted array</returns>
public static byte[] EncryptByteArray(byte[] key, byte[] secret)
{
using (MemoryStream ms = new MemoryStream())
{
using (AesManaged cryptor = new AesManaged())
{
cryptor.Mode = CipherMode.CBC;
cryptor.Padding = PaddingMode.PKCS7;
cryptor.KeySize = 128;
cryptor.BlockSize = 128;
//We use the random generated iv created by AesManaged
byte[] iv = cryptor.IV;
using (CryptoStream cs = new CryptoStream(ms, cryptor.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(secret, 0, secret.Length);
}
byte[] encryptedContent = ms.ToArray();
//Create new byte array that should contain both unencrypted iv and encrypted data
byte[] result = new byte[iv.Length + encryptedContent.Length];
//copy our 2 array into one
System.Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
System.Buffer.BlockCopy(encryptedContent, 0, result, iv.Length, encryptedContent.Length);
return result;
}
}
}
/// <summary>
/// Decrypt a byte array using AES 128
/// </summary>
/// <param name="key">key in bytes</param>
/// <param name="secret">the encrypted bytes</param>
/// <returns>decrypted bytes</returns>
public static byte[] DecryptByteArray(byte[] key, byte[] secret)
{
byte[] iv = new byte[16]; //initial vector is 16 bytes
byte[] encryptedContent = new byte[secret.Length - 16]; //the rest should be encryptedcontent
//Copy data to byte array
System.Buffer.BlockCopy(secret, 0, iv, 0, iv.Length);
System.Buffer.BlockCopy(secret, iv.Length, encryptedContent, 0, encryptedContent.Length);
using (MemoryStream ms = new MemoryStream())
{
using (AesManaged cryptor = new AesManaged())
{
cryptor.Mode = CipherMode.CBC;
cryptor.Padding = PaddingMode.PKCS7;
cryptor.KeySize = 128;
cryptor.BlockSize = 128;
using (CryptoStream cs = new CryptoStream(ms, cryptor.CreateDecryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(encryptedContent, 0, encryptedContent.Length);
}
return ms.ToArray();
}
}
}
If you really need BC, here is a quick test I manage to write based on the test suit from https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/crypto/test/AESFastTest.cs
You can tailor it for your need
private static void TestBC()
{
//Demo params
string keyString = "jDxESdRrcYKmSZi7IOW4lw==";
string input = "abc";
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] iv = new byte[16]; //for the sake of demo
//Set up
AesEngine engine = new AesEngine();
CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7
KeyParameter keyParam = new KeyParameter(Convert.FromBase64String(keyString));
ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);
// Encrypt
cipher.Init(true, keyParamWithIV);
byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
cipher.DoFinal(outputBytes, length); //Do the final block
string encryptedInput = Convert.ToBase64String(outputBytes);
Console.WriteLine("Encrypted string: {0}", encryptedInput);
//Decrypt
cipher.Init(false, keyParamWithIV);
byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)];
length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0);
cipher.DoFinal(comparisonBytes, length); //Do the final block
Console.WriteLine("Decrypted string: {0}",Encoding.UTF8.GetString(comparisonBytes)); //Should be abc
}
enter link description here
byte[] k; //32 byte
string para; // plaintext
string msgRefNo; // 16byte
byte[] inputBytes = Encoding.UTF8.GetBytes(para);
byte[] IV = Encoding.UTF8.GetBytes(msgRefNo);
byte[] key = k;
AesEngine engine = new AesEngine();
CbcBlockCipher blockCipher = new CbcBlockCipher(engine);
PaddedBufferedBlockCipher cipher1 = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
KeyParameter keyParam = new KeyParameter(key);
ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, IV);
cipher1.Init(true, keyParamWithIv); //Error Message thrown
byte[] outputBytes = new byte[cipher1.GetOutputSize(inputBytes.Length)]; //cip
int length = cipher1.ProcessBytes(inputBytes, outputBytes, 0);
cipher1.DoFinal(outputBytes, length); //Do the final block
string encryptedInput = Convert.ToBase64String(outputBytes);
return encryptedInput;
I have the following encryption method. I am not able to decrypt it. I have inherited the encryption algorithm so it cannot be changed.
public static string Encrypt(string plaintext)
{
byte[] rgbIV;
byte[] key;
RijndaelManaged rijndael = BuildRigndaelCommon(out rgbIV, out key);
//convert plaintext into a byte array
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
int BlockSize;
BlockSize = 16 * (1 + (plaintext.Length / 16));
Array.Resize(ref plaintextBytes, BlockSize);
// fill the remaining space with 0
for (int i = plaintext.Length; i < BlockSize; i++)
{
plaintextBytes[i] = 0;
}
byte[] cipherTextBytes = null;
//create uninitialized Rijndael encryption obj
using (RijndaelManaged symmetricKey = new RijndaelManaged())
{
//Call SymmetricAlgorithm.CreateEncryptor to create the Encryptor obj
var transform = rijndael.CreateEncryptor();
//Chaining mode
symmetricKey.Mode = CipherMode.CFB;
//create encryptor from the key and the IV value
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(key, rgbIV);
//define memory stream to hold encrypted data
using (MemoryStream ms = new MemoryStream())
{
//define cryptographic stream - contains the transformation key to be used and the mode
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
//encrypt contents of cryptostream
cs.Write(plaintextBytes, 0, BlockSize);
cs.FlushFinalBlock();
//convert encrypted data from a memory stream into a byte array
cipherTextBytes = ms.ToArray();
}
}
}
//store result as a hex value
string hexOutput = BitConverter.ToString(cipherTextBytes).Replace("-", "");
hexOutput = hexOutput.Substring(0, plaintext.Length * 2);
//finially return encrypted string
return hexOutput;
}
As you can see it's pretty standard except at the end it's converted to hex and substring is performed. I'm having great difficulty doing the opposite.
My decrypt method is like:
public static string Decrypt(string disguisedtext)
{
byte[] rgbIV;
byte[] key;
BuildRigndaelCommon(out rgbIV, out key);
byte[] disguishedtextBytes = FromHexString(disguisedtext);
string visiabletext = "";
//create uninitialized Rijndael encryption obj
using (var symmetricKey = new RijndaelManaged())
{
//Call SymmetricAlgorithm.CreateEncryptor to create the Encryptor obj
symmetricKey.Mode = CipherMode.CFB;
//create encryptor from the key and the IV value
// ICryptoTransform encryptor = symmetricKey.CreateEncryptor(key, rgbIV);
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(key, rgbIV);
//define memory stream to hold encrypted data
using (MemoryStream ms = new MemoryStream(disguishedtextBytes))
{
//define cryptographic stream - contains the transformation to be used and the mode
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
byte[] plaintextBytes = new Byte[disguishedtextBytes.Length];
cs.Write(disguishedtextBytes, 0, disguishedtextBytes.Length);
cs.FlushFinalBlock();
//convert decrypted data from a memory stream into a byte array
byte[] visiabletextBytes = ms.ToArray();
visiabletext = Encoding.UTF8.GetString(visiabletextBytes);
}
}
}
return visiabletext;
}
Helper Methods:
private static RijndaelManaged BuildRigndaelCommon(out byte[] rgbIV, out byte[] key)
{
rgbIV = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x8, 0xA, 0xB, 0xC, 0xD, 0xF, 0x10, 0x11, 0x12 };
key = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x8, 0xA, 0xB, 0xC, 0xD, 0xF, 0x10, 0x11, 0x12 };
//Specify the algorithms key & IV
RijndaelManaged rijndael = new RijndaelManaged{BlockSize = 128, IV = rgbIV, KeySize = 128, Key = key, Padding = PaddingMode.None};
return rijndael;
}
public static byte[] FromHexString(string hexString)
{
if (hexString == null)
{
return new byte[0];
}
var numberChars = hexString.Length;
var bytes = new byte[numberChars / 2];
for (var i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
}
return bytes;
}
I'm getting various errors regarding the length of the string and that the padding is invalid. Has anybody any ideas to get the decryption working. I've tried padding out the input string back to 32 bytes but no avail.
Your problem is a subtle error in your Encrypt method. You are losing data from your returned ciphertext by messing with the the hexOutput string. Instead of:
//store result as a hex value
string hexOutput = BitConverter.ToString(cipherTextBytes).Replace("-", "");
hexOutput = hexOutput.Substring(0, plaintext.Length * 2);
//finially return encrypted string
return hexOutput;
You should just return the output:
return BitConverter.ToString(cipherTextBytes).Replace("-", "");
You will also need to change the padding mode in your Decrypt method to None. Though this will now correctly decrypt it will also include the manual padding characters that you add in your encrypt method. As you don't know your plain text you have no GOOD way of removing them. You could always add a method to remove all bytes in your array that dont match your padding value of zero:
int endMarker = decryptedData.Length;
do { endMarker--; } while (decryptedData[endMarker] == 0);
Array.Resize(ref decryptedData, endMarker + 1);
However this isn't really a good idea as you're possibly discarding otherwise valid data. A better solution would be to update your encrypt and decrypt methods to let the cipher handle the padding. Putting it all together we get (showing only what i've changed):
private static RijndaelManaged BuildRigndaelCommon(out byte[] rgbIV, out byte[] key)
{
rgbIV = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x8, 0xA, 0xB, 0xC, 0xD, 0xF, 0x10, 0x11, 0x12 };
key = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x8, 0xA, 0xB, 0xC, 0xD, 0xF, 0x10, 0x11, 0x12 };
//Specify the algorithms key & IV
RijndaelManaged rijndael = new RijndaelManaged{BlockSize = 128, IV = rgbIV, KeySize = 128, Key = key, Padding = PaddingMode.PKCS7 };
return rijndael;
}
public static string Encrypt(string plaintext)
{
byte[] rgbIV;
byte[] key;
RijndaelManaged rijndael = BuildRigndaelCommon(out rgbIV, out key);
//convert plaintext into a byte array
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] cipherTextBytes = null;
//create uninitialized Rijndael encryption obj
using (RijndaelManaged symmetricKey = new RijndaelManaged())
{
//Call SymmetricAlgorithm.CreateEncryptor to create the Encryptor obj
var transform = rijndael.CreateEncryptor();
//Chaining mode
symmetricKey.Mode = CipherMode.CFB;
//create encryptor from the key and the IV value
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(key, rgbIV);
//define memory stream to hold encrypted data
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
//encrypt contents of cryptostream
cs.Write(plaintextBytes, 0, plaintextBytes.Length);
cs.Flush();
cs.FlushFinalBlock();
//convert encrypted data from a memory stream into a byte array
ms.Position = 0;
cipherTextBytes = ms.ToArray();
ms.Close();
cs.Close();
}
}
//store result as a hex value
return BitConverter.ToString(cipherTextBytes).Replace("-", "");
}
public static string Decrypt(string disguisedtext)
{
byte[] disguishedtextBytes = FromHexString(disguisedtext);
byte[] rgbIV;
byte[] key;
BuildRigndaelCommon(out rgbIV, out key);
string visiabletext = "";
//create uninitialized Rijndael encryption obj
using (var symmetricKey = new RijndaelManaged())
{
//Call SymmetricAlgorithm.CreateEncryptor to create the Encryptor obj
symmetricKey.Mode = CipherMode.CFB;
symmetricKey.BlockSize = 128;
//create encryptor from the key and the IV value
// ICryptoTransform encryptor = symmetricKey.CreateEncryptor(key, rgbIV);
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(key, rgbIV);
//define memory stream to hold encrypted data
using (MemoryStream ms = new MemoryStream(disguishedtextBytes))
{
//define cryptographic stream - contains the transformation to be used and the mode
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
byte[] decryptedData = new byte[disguishedtextBytes.Length];
int stringSize = cs.Read(decryptedData, 0, disguishedtextBytes.Length);
cs.Close();
//Trim the excess empty elements from the array and convert back to a string
byte[] trimmedData = new byte[stringSize];
Array.Copy(decryptedData, trimmedData, stringSize);
visiabletext = Encoding.UTF8.GetString(trimmedData);
}
}
}
return visiabletext;
}
Hope this helps point you on your way. As an aside I maintain a set of encryption utilities on Snipt that may be of use to you, particularly the SymmetricEncrypt and SymmetricDecrypt methods.
------ EDIT ------
As noted in the comment below, we are not allowed to alter the Encrypt method. I do like a good challenge! With appropriate byte mangling applied, here's a decrypt that honours the return coming form the Encrypt method:
public static string Decrypt(string disguisedtext)
{
byte[] disguishedtextBytes = FromHexString(disguisedtext);
var originalLength = disguishedtextBytes.Length;
int BlockSize;
BlockSize = 16 * (1 + (originalLength / 16));
Array.Resize(ref disguishedtextBytes, BlockSize);
// fill the remaining space with 0
for (int i = originalLength; i < BlockSize; i++)
{
disguishedtextBytes[i] = 0;
}
byte[] rgbIV;
byte[] key;
BuildRigndaelCommon(out rgbIV, out key);
string visiabletext = "";
//create uninitialized Rijndael encryption obj
using (var symmetricKey = new RijndaelManaged())
{
//Call SymmetricAlgorithm.CreateEncryptor to create the Encryptor obj
symmetricKey.Mode = CipherMode.CFB;
symmetricKey.BlockSize = 128;
symmetricKey.Padding = PaddingMode.None;
// ICryptoTransform encryptor = symmetricKey.CreateEncryptor(key, rgbIV);
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(key, rgbIV);
//define memory stream to hold encrypted data
using (MemoryStream ms = new MemoryStream(disguishedtextBytes))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
byte[] decryptedData = new byte[disguishedtextBytes.Length];
int stringSize = cs.Read(decryptedData, 0, disguishedtextBytes.Length);
cs.Close();
//Trim the excess empty elements from the array and convert back to a string
byte[] trimmedData = new byte[stringSize];
Array.Copy(decryptedData, trimmedData, originalLength);
Array.Resize(ref trimmedData, originalLength);
visiabletext = Encoding.UTF8.GetString(trimmedData);
}
}
return visiabletext;
}
It looks like your encryption method outputs a space separated hex string, representing a byte array: "OA FE 82 3B ...". It also makes assumptions about the plaintext and chops off any padding.
Your first step it to convert the hex string back into a byte array, which is pretty easy.
To deal with the lost padding just set decryption to NoPadding, as #Wolfwyrd suggests. You may have to check that your data is correctly terminated if the padding length was off.
If the assumptions about plaintext characters were wrong, then it is likely you will have to recover things by hand. If the plaintext is strict ASCII (7 bit characters only) then this should not be a problem. Anything outside that, such as accented letters: á, é etc. will break the assumption.
I'm trying to encrypt XML, and after decryption I end up with 1 byte too many - probably because of padding. This is my code. How can I change this to make it work?
public byte[] encryptData(byte[] source,string key)
{
byte[] btKeyInBytes = UTF8Encoding.UTF8.GetBytes(key);
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, btKeyInBytes);
AesManaged encryptor = new AesManaged();
encryptor.Padding = PaddingMode.Zeros;
using (MemoryStream encryptStream = new MemoryStream())
{
using (CryptoStream encStream = new CryptoStream(encryptStream, encryptor.CreateEncryptor(rfc.GetBytes(16), rfc.GetBytes(16)), CryptoStreamMode.Read))
{
//Read from the input stream, then encrypt and write to the output stream.
encStream.Write(source, 0, source.Length);
encStream.FlushFinalBlock();
encryptor.Clear();
}
encryptStream.Flush();
encryptedSource = encryptStream.ToArray();
}
return encryptedSource;
}
public byte[] decryptData(byte[] source, string key)
{
byte[] encryptedSource = null;
byte[] btKeyInBytes = UTF8Encoding.UTF8.GetBytes(key);
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, btKeyInBytes);
AesManaged encryptor = new AesManaged();
encryptor.Padding = PaddingMode.Zeros;
using (MemoryStream encryptStream = new MemoryStream())
{
using (CryptoStream encStream = new CryptoStream(encryptStream, encryptor.CreateDecryptor(rfc.GetBytes(16), rfc.GetBytes(16)), CryptoStreamMode.Write))
{
//Read from the input stream, then encrypt and write to the output stream.
encStream.Write(source, 0, source.Length);
encStream.FlushFinalBlock();
encryptor.Clear();
}
encryptStream.Flush();
encryptedSource = encryptStream.ToArray();
}
return encryptedSource;
}
It seems that the padding gives me 1 extra byte during decryption
If your problem is padding, then PaddingMode.Zeros is about the worst choice, since zeros cannot always be reliably removed. Better to use PKCS7 padding.
It is also possible that the encoding of end-of-line has changed between systems. Some systems use a single byte while other systems use two bytes. You really need to look at exactly what is in the decrypted file, byte by byte, as #Rup suggests.
I got it!
Now let's try to explain.
Let's say I have a file of 927 bytes.
What I do is to read this file and split it in pieces of 656 bytes. This byte array of 656 bytes is being encrypted. The second array will be 271 bytes.
In every block for encryption I used padding. When decrypting, you will not be able to know in which block padding was used because every block now can be divided by 16 (because of the padding in the encryption). Basically I only want padding used for the last block(271).
so this is my new code:
public byte[] encryptData(byte[] source, string key, bool padding)
{
byte[] encryptedSource = null;
byte[] btKeyInBytes = UTF8Encoding.UTF8.GetBytes(key);
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, btKeyInBytes);
AesManaged encryptor = new AesManaged();
//encryptor.Mode = CipherMode.CFB;
encryptor.KeySize = 128; // in bits
encryptor.Key = new byte[128 / 8]; // 16 bytes for 128 bit encryption
encryptor.IV = new byte[128 / 8];
if (padding) { encryptor.Padding = PaddingMode.PKCS7; }
else { encryptor.Padding = PaddingMode.None; }
using (MemoryStream encryptStream = new MemoryStream())
{
using (CryptoStream encStream =
new CryptoStream(encryptStream,
encryptor.CreateEncryptor(rfc.GetBytes(16),
rfc.GetBytes(16)),
CryptoStreamMode.Write))
{
//Read from the input stream, then encrypt and write to the output stream.
encStream.Write(source, 0, source.Length);
}
encryptStream.Flush();
encryptedSource = encryptStream.ToArray();
}
return encryptedSource;
}
public byte[] decryptData(byte[] source, string key,bool padding)
{
byte[] encryptedSource = null;
byte[] btKeyInBytes = UTF8Encoding.UTF8.GetBytes(key);
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, btKeyInBytes);
AesManaged encryptor = new AesManaged();
encryptor.Key = new byte[128 / 8]; // 16 bytes for 128 bit encryption
encryptor.IV = new byte[128 / 8];
if (padding) { encryptor.Padding = PaddingMode.PKCS7; }
else { encryptor.Padding = PaddingMode.None; }
using (MemoryStream encryptStream = new MemoryStream())
{
using (CryptoStream encStream =
new CryptoStream(encryptStream,
encryptor.CreateDecryptor(rfc.GetBytes(16),
rfc.GetBytes(16)),
CryptoStreamMode.Write))
{
//Read from the input stream, then encrypt and write to the output stream.
encStream.Write(source, 0, source.Length);
}
encryptStream.Flush();
encryptedSource = encryptStream.ToArray();
}
return encryptedSource;
}
I hope this helps!