C# DES Decryption Issue - c#

I've a problem implementing symmetric encryption algorithm,the problem is that: randomly the decrypted data is incorrect(rubbish) and only happening on the deployment environment(IIS8 on Win Server 2012 R2)
I started with an AES implementation,when the problem showed up i did a remote debugging on the server and confirmed same encrypted input with the same key/vector is giving different result(rubbish) from my development environment(visual studio on win10 x64)
I've converted to DES but still the same problem exists,below is my DES class for reference:
public class SimpleDES
{
// Change these keys
private byte[] Key = { x, x, x, x, x, x, x, x};
private byte[] Vector;
private string salt = "********";
private ICryptoTransform EncryptorTransform, DecryptorTransform;
private System.Text.UTF8Encoding UTFEncoder;
public SimpleDES(string iVector)
{
this.Vector = this.StrToByteArray(iVector);
Array.Resize(ref this.Vector, 16);
//This is our encryption method
DESCryptoServiceProvider ObjDES = new DESCryptoServiceProvider();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = ObjDES.CreateEncryptor(this.Key, this.Vector);
DecryptorTransform = ObjDES.CreateDecryptor(this.Key, this.Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// ----------- The commonly used methods ------------------------------
/// Encrypt some text and return a string suitable for passing in a URL.
public string EncryptToString(string TextValue)
{
return ByteArrToString(Encrypt(TextValue + salt));
}
/// Encrypt some text and return an encrypted byte array.
public byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);
return EncryptBin(bytes);
}
/// Encrypt some binary and return an encrypted byte array.
public byte[] EncryptBin(Byte[] bytes)
{
byte[] encrypted;
//Used to stream the data in and out of the CryptoStream.
using (MemoryStream memoryStream = new MemoryStream())
{
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
using (CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write))
{
#region Write the decrypted value to the encryption stream
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
}
memoryStream.Close();
}
return encrypted;
}
/// The other side: Decryption methods
public string DecryptString(string EncryptedString)
{
return Decrypt(StrToByteArray(EncryptedString)).Replace(salt, string.Empty);
}
/// Decryption when working with byte arrays.
public string Decrypt(byte[] EncryptedValue)
{
Byte[] decryptedBytes;
using (MemoryStream encryptedStream = new MemoryStream())
{
using (CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write))
{
#region Write the encrypted value to the decryption stream
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
#endregion
}
}
// remove trailing zero bytes
//int lastIndex = Array.FindLastIndex(decryptedBytes, b => b != 0);
//Array.Resize(ref decryptedBytes, lastIndex + 1);
return UTFEncoder.GetString(decryptedBytes);
}
public byte[] DecryptBin(byte[] EncryptedValue)
{
#region Write the encrypted value to the decryption stream
MemoryStream encryptedStream = new MemoryStream();
CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
Byte[] decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
encryptedStream.Close();
#endregion
return decryptedBytes;
}
/// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
// return encoding.GetBytes(str);
// However, this results in character values that cannot be passed in a URL. So, instead, I just
// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
public byte[] StrToByteArray(string str)
{
if (str.Length == 0)
throw new Exception("Invalid string value in StrToByteArray");
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
byte val;
byte[] byteArr = new byte[str.Length / 3];
int i = 0;
int j = 0;
do
{
val = byte.Parse(str.Substring(i, 3));
byteArr[j++] = val;
i += 3;
}
while (i < str.Length);
return byteArr;
}
// Same comment as above. Normally the conversion would use an ASCII encoding in the other direction:
// System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
// return enc.GetString(byteArr);
public string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
}
I hope somebody can have an explanation/suggestion
Edit : sample usage that i've remotely debugged:
byte[] binData;
SimpleDES AES = new SimpleDES("xxxxxxx");
long sz = objRdr.GetBytes(2, 0, null, 0, 0);
if (sz > 0)
{
binData = new byte[sz];
objRdr.GetBytes(2, 0, binData, 0, binData.Length);
string Name = AES.Decrypt(binData);
}
Clarification:-
The class might not be cleanly finalized i had issues with padding(AES implementation) but i had to include for reference
The Core of the problem lies in Decrypt method: same key,vector and input byte array resulted in different decrypted byte array

Related

How can i encrypt by postgres and decrypt by c#?

I encrypt password in postgres
and i want to decrypt it in c#, but two ways can not matching
.How can i do that?
private static byte[] TruncateHash(string key, int length)
{
SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
// Hash the key.
byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(key);
byte[] hash = sha1.ComputeHash(keyBytes);
// Truncate or pad the hash.
Array.Resize(ref hash, length);
return hash;
}
public static string EncryptString(string plaintext, string Passphrase)
{
TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
// Initialize the crypto provider.
tripleDes.Key = TruncateHash(Passphrase, tripleDes.KeySize / 8);
tripleDes.IV = TruncateHash("", tripleDes.BlockSize / 8);
// Convert the plaintext string to a byte array.
byte[] plaintextBytes = System.Text.Encoding.Unicode.GetBytes(plaintext);
// Create the stream.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
// Create the encoder to write to the stream.
CryptoStream encStream = new CryptoStream(ms, tripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
// Use the crypto stream to write the byte array to the stream.
encStream.Write(plaintextBytes, 0, plaintextBytes.Length);
encStream.FlushFinalBlock();
// Convert the encrypted stream to a printable string.
return Convert.ToBase64String(ms.ToArray());
}
public static string DecryptString(string encryptedtext, string Passphrase)
{
TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
// Initialize the crypto provider.
tripleDes.Key = TruncateHash(Passphrase, tripleDes.KeySize / 8);
tripleDes.IV = TruncateHash("", tripleDes.BlockSize / 8);
// Convert the encrypted text string to a byte array.
byte[] encryptedBytes = Convert.FromBase64String(encryptedtext);
// Create the stream.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
// Create the decoder to write to the stream.
CryptoStream decStream = new CryptoStream(ms, tripleDes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
// Use the crypto stream to write the byte array to the stream.
decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
decStream.FlushFinalBlock();
// Convert the plaintext stream to a string.
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
I found a way to encrypt in postgres using pgcrypto.
And below is encrypt and decrypt in postgres.
SELECT encode(encrypt_iv('ABCDE121212','Key123', '','3des'), 'base64');
select decrypt_iv(decode('jEI4V5q6h5/p12NRJm666g==','base64'),'Key123','','3des')
What's wrong in my code, c# and postgres can't not matching.
I want to keep c# code and change postgres code to matching
Source Url
Encrypt function:
public static String AES_encrypt(String input, string key, string Iv, int keyLength)
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = keyLength;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = mkey(key,keyLength);
aes.IV = mkey(Iv,128);
var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] xBuff = null;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
{
byte[] xXml = Encoding.UTF8.GetBytes(input);
cs.Write(xXml, 0, xXml.Length);
cs.FlushFinalBlock();
}
xBuff = ms.ToArray();
}
return Convert.ToBase64String(xBuff,Base64FormattingOptions.None);
}
Decrypt function:
public static String AES_decrypt(String Input, string key, string Iv, int keyLength)
{
try
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = keyLength;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = mkey(key,keyLength);
aes.IV = mkey(Iv,128);
var decrypt = aes.CreateDecryptor();
byte[] encryptedStr = Convert.FromBase64String(Input);
string Plain_Text;
using (var ms = new MemoryStream(encryptedStr))
{
using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
Plain_Text = reader.ReadToEnd();
}
}
}
return Plain_Text;
}
catch (Exception ex)
{
return null;
}
}
Helper function:
private static byte[] mkey(string skey, int keyLength)
{
int length = keyLength / 8;
byte[] key = Encoding.UTF8.GetBytes(skey);
byte[] k = GenerateEmptyArray(length);
for (int i = 0; i < key.Length; i++)
{
//k[i % 16] = (byte)(k[i % 16] ^ key[i]);
k[i] = key[i];
if(i == length-1)
break;
}
return k;
}
Variables:
input = "Hello World"
key = "NBJ42RKQ2vQoYFZO"
Iv = "j1C83921vHExVhVp"
keyLength = 128
Info about variables:
input - string that is not encrypted or encrypted. If it's encrypted it will be in Base64 format
key - Any Unicode character that will match the AES key size(in this example it's 128). I have written a function that will extract the specific length of characters and add them to a byte array
Code:
public static string PasswordFixer(string skey,int keyLength)
{
int length = keyLength / 8;
byte[] key = Encoding.UTF8.GetBytes(skey);
byte[] k = GenerateEmptyArray(length);
for (int i = 0; i < key.Length; i++)
{
k[i] = key[i];
if(i == length-1)
break;
}
return Encoding.UTF8.GetString(k);
}
Iv - it's always 128bit long meaning 16bytes. you can ignore Iv if you want, in PostgreSQL if you planing to use `encrypt` function then you can ignore the Iv by hard coding like this `aes.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };`
keylength-
This is the AES key length in this example we use 128bit meaning 16 bytes. whatever the characters that you use as the Key need to match the length of 16 bytes.
PostgreSQL
The equivalent SQL statement for the encryption and decryption is this
encrypt_iv,decrypt_iv
select convert_from(decrypt_iv(decode(tbl1.encrypted,'base64')::bytea ,'NBJ42RKQ2vQoYFZO','j1C83921vHExVhVp', 'aes-cbc/pad:pkcs'), 'UTF-8') as decrypted,tbl1.encrypted from (select encode(encrypt_iv('Hello World', 'NBJ42RKQ2vQoYFZO','j1C83921vHExVhVp', 'aes-cbc/pad:pkcs'), 'base64') as encrypted) as tbl1
encrypt,decrypt
select convert_from(decrypt(decode(tbl1.encrypted,'base64')::bytea ,'NBJ42RKQ2vQoYFZO', 'aes-cbc/pad:pkcs'), 'UTF-8') as decrypted,tbl1.encrypted from (select encode(encrypt('Hello World', 'NBJ42RKQ2vQoYFZO', 'aes-cbc/pad:pkcs'), 'base64') as encrypted) as tbl1

AES decrypting non text files end up in corrupt data

I'm writing a Windows app in C# which has to interact with a Mac app (written in Cocoa). This app encrypts files in AES with CBC (IV, a key, salt, HMAC). I don't know a lot about encryption but I think that's what it does. The Cocoa library we use is RNCryptor. They have a C# version which is what I'm using on the Windows side (with a few modifications, mainly to use byte[] instead of Strings).
Now text files are decrypted correctly, but other files (for example, a PNG file), end up corrupted (the correct file on the right, and the corrupted on the left, using UTF8 encoding, you can see there's a lot of diamonds with ?s):
I believe this is due to the encoding of the file, but I tried UTF8, Default, Unicode, ASCII... and the output files are always corrupted with different file sizes, being ASCII and the default encoding (UTF16 I believe) the closest in size.
This is the RNCryptor modified code I used:
public byte[] Decrypt (byte[] encryptedBase64, string password)
{
PayloadComponents components = this.unpackEncryptedBase64Data (encryptedBase64);
if (!this.hmacIsValid (components, password)) {
return null;
}
byte[] key = this.generateKey (components.salt, password);
byte[] plaintextBytes = new byte[0];
switch (this.aesMode) {
case AesMode.CTR:
// Yes, we are "encrypting" here. CTR uses the same code in both directions.
plaintextBytes = this.encryptAesCtrLittleEndianNoPadding(components.ciphertext, key, components.iv);
break;
case AesMode.CBC:
plaintextBytes = this.decryptAesCbcPkcs7(components.ciphertext, key, components.iv);
break;
}
return plaintextBytes;
}
private byte[] decryptAesCbcPkcs7 (byte[] encrypted, byte[] key, byte[] iv)
{
var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
var decryptor = aes.CreateDecryptor(key, iv);
string plaintext;
using (MemoryStream msDecrypt = new MemoryStream(encrypted))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
return Encoding.UTF8.GetBytes(plaintext);
}
private PayloadComponents unpackEncryptedBase64Data (byte[] encryptedBase64)
{
List<byte> binaryBytes = new List<byte>();
binaryBytes.AddRange (encryptedBase64);
PayloadComponents components;
int offset = 0;
components.schema = binaryBytes.GetRange(0, 1).ToArray();
offset++;
this.configureSettings ((Schema)binaryBytes [0]);
components.options = binaryBytes.GetRange (1, 1).ToArray();
offset++;
components.salt = binaryBytes.GetRange (offset, Cryptor.saltLength).ToArray();
offset += components.salt.Length;
components.hmacSalt = binaryBytes.GetRange(offset, Cryptor.saltLength).ToArray();
offset += components.hmacSalt.Length;
components.iv = binaryBytes.GetRange(offset, Cryptor.ivLength).ToArray();
offset += components.iv.Length;
components.headerLength = offset;
components.ciphertext = binaryBytes.GetRange (offset, binaryBytes.Count - Cryptor.hmac_length - components.headerLength).ToArray();
offset += components.ciphertext.Length;
components.hmac = binaryBytes.GetRange (offset, Cryptor.hmac_length).ToArray();
return components;
}
private bool hmacIsValid (PayloadComponents components, string password)
{
byte[] generatedHmac = this.generateHmac (components, password);
if (generatedHmac.Length != components.hmac.Length) {
return false;
}
for (int i = 0; i < components.hmac.Length; i++) {
if (generatedHmac[i] != components.hmac[i]) {
return false;
}
}
return true;
}
And this is my code decrypting and writing the file:
byte[] decryptedFile = this.decryptor.Decrypt(File.ReadAllBytes(filePath), password);
File.WriteAllBytes(filePath, decryptedFile);
What can be wrong here? Thanks in advance.
The problem is in your use of StreamReader when decrypting. StreamReader reads text (UTF-8 here), not arbitrary binary data. One solution would be to read the data into a MemoryStream, and use its ToArray() method to get the resulting byte[].

AESManaged File Encryption and Decryption and prepending initiaization vector

I am trying to encrypt/decrypt bytes - I have done a lot of reading about the Key and IV for the AES algorithm using the AESManaged class in System.Security.Cryptography. I read James Johnson's answer to the following question http://www.techques.com/question/1-7025135/My-Length-of-the-data-to-decrypt-is-invalid-error where he suggests that you use a random IV in the encryption routine and prepend the IV to the encrypted message. The decrypt function strips off the random IV from the beginning of the encrypted message to initialize the decryption class and then decrypts the rest of the bytes. I have attempted to do this in the following code. But I keep getting the "Length of the data to decrypt is invalid." error message when I attempt the decrypt after the encryption. Could someone possibly shed some light on what might be wrong.
USAGE: (streamToEncrypt/streamToDecrypt are System.IO.Stream)
using (var cryptoHelper = new AESHelper())
{
var encryptedBytes = cryptoHelper.Encrypt(AESHelper.StreamToByteArray(streamToEncrypt));
}
using (var cryptoHelper = new AESHelper())
{
var decryptedBytes = cryptoHelper.Decrypt(AESHelper.StreamToByteArray(streamToDecrypt));
}
public class AESHelper : IDisposable
{
public AesManaged AESManaged;
internal ICryptoTransform Encryptor { get; set; }
internal ICryptoTransform Decryptor { get; set; }
private const string KEY = "2428GD19569F9B2C2341839416C8E87G";
private static readonly byte[] Salt = Encoding.ASCII.GetBytes("?pt1$8f]l4g80");
private const Int32 ITERATIONS = 1042;
internal AESHelper()
{
AESManaged = new AesManaged();
AESManaged.BlockSize = AESManaged.LegalBlockSizes[0].MaxSize;
AESManaged.KeySize = AESManaged.LegalKeySizes[0].MaxSize;
AESManaged.Mode= CipherMode.CBC;
}
public void KeyGenerator()
{
var key = new Rfc2898DeriveBytes(KEY, Salt, ITERATIONS);
AESManaged.Key = key.GetBytes(AESManaged.KeySize / 8);
}
public byte[] Encrypt(byte[] input)
{
KeyGenerator();
var ms = new MemoryStream();
//Random IV
Encryptor = AESManaged.CreateEncryptor(AESManaged.Key, AESManaged.IV);
//Add the IV to the beginning of the memory stream
ms.Write(BitConverter.GetBytes(AESManaged.IV.Length), 0, sizeof(int));
ms.Write(AESManaged.IV, 0, AESManaged.IV.Length);
var cs = new CryptoStream(ms,
Encryptor, CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();
return ms.ToArray();
}
public byte[] Decrypt(byte[] input)
{
KeyGenerator();
// Get the initialization vector from the encrypted stream
var ms = new MemoryStream(input);
AESManaged.IV = ReadByteArray(ms);
Decryptor = AESManaged.CreateDecryptor(AESManaged.Key, AESManaged.IV);
var cs = new CryptoStream(ms,
Decryptor, CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();//Error occurs here
return ms.ToArray();
}
internal static byte[] ReadByteArray(Stream s)
{
var rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
var buffer = new byte[16];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
internal static byte[] StreamToByteArray(Stream inputStream)
{
if (!inputStream.CanRead)
{
throw new ArgumentException();
}
// This is optional
if (inputStream.CanSeek)
{
inputStream.Seek(0, SeekOrigin.Begin);
}
var output = new byte[inputStream.Length];
var bytesRead = inputStream.Read(output, 0, output.Length);
Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
return output;
}
public void Dispose()
{
if (AESManaged != null)
((IDisposable) AESManaged).Dispose();
}}
Many Thanks in advance
Probably you have solved this already but I'll just put my answer for others who faces similar issue.
Error occurs due to the additional information present in the input array. In public byte[] Encrypt(byte[] input) method you are writing IV length and IV before the ciphered data is written. Lines:
ms.Write(BitConverter.GetBytes(AESManaged.IV.Length), 0, sizeof(int));
ms.Write(AESManaged.IV, 0, AESManaged.IV.Length);
In public byte[] Decrypt(byte[] input) method you are reading this information and using read IV as initialization vector for AES algorithm. All fine. Then you are constructing CryptoStream with CryptoStreamMode.Write and passing MemoryStream object ms which gets decrypted data. However the passed input array contains not only the encrypted message but also the IV that you wrote during the encryption process. That is why it fails to decrypt.
What you need to do to overcome this is either extract only cipher data from the input array and pass it to: cs.Write(cipherData, 0, cipherData.Length); or change mode into CryptoStreamMode.Read and use cs.Read(outputBuff, 0, outputBuff.Length);.
Also don't use the same MemoryStream object to read and write to because you'll have some garbage in it after CryptoStream will write in it.

Facing Memory Leaks in AES Encryption Method

Can anyone please identify is there any possible memory leaks in following code. I have tried with .Net Memory Profiler and it says "CreateEncryptor" and some other functions are leaving unmanaged memory leaks as I have confirmed this using Performance Monitors.
but there are already dispose, clear, close calls are placed wherever possible please advise me accordingly. its a been urgent.
public static string Encrypt(string plainText, string key)
{
//Set up the encryption objects
byte[] encryptedBytes = null;
using (AesCryptoServiceProvider acsp = GetProvider(Encoding.UTF8.GetBytes(key)))
{
byte[] sourceBytes = Encoding.UTF8.GetBytes(plainText);
using (ICryptoTransform ictE = acsp.CreateEncryptor())
{
//Set up stream to contain the encryption
using (MemoryStream msS = new MemoryStream())
{
//Perform the encrpytion, storing output into the stream
using (CryptoStream csS = new CryptoStream(msS, ictE, CryptoStreamMode.Write))
{
csS.Write(sourceBytes, 0, sourceBytes.Length);
csS.FlushFinalBlock();
//sourceBytes are now encrypted as an array of secure bytes
encryptedBytes = msS.ToArray(); //.ToArray() is important, don't mess with the buffer
csS.Close();
}
msS.Close();
}
}
acsp.Clear();
}
//return the encrypted bytes as a BASE64 encoded string
return Convert.ToBase64String(encryptedBytes);
}
private static AesCryptoServiceProvider GetProvider(byte[] key)
{
AesCryptoServiceProvider result = new AesCryptoServiceProvider();
result.BlockSize = 128;
result.KeySize = 256;
result.Mode = CipherMode.CBC;
result.Padding = PaddingMode.PKCS7;
result.GenerateIV();
result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] RealKey = GetKey(key, result);
result.Key = RealKey;
// result.IV = RealKey;
return result;
}
private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
{
byte[] kRaw = suggestedKey;
List<byte> kList = new List<byte>();
for (int i = 0; i < p.LegalKeySizes[0].MaxSize; i += 8)
{
kList.Add(kRaw[(i / 8) % kRaw.Length]);
}
byte[] k = kList.ToArray();
return k;
}
Update: After some more investigation I logged this as a bug on Microsoft connect. They have acknowledged the bug and have created a hotfix. (Obviously, this is a hotfix so the usual disclaimers apply. If you can, upgrading to .net 4.0 would probably be the preferred solution)
It seems that this code leaks in .net 3.5, but is works fine in .net 4.0.
I started in .net 4.0 and copied your code into a quick test app and called it 1,000,000 times, and the memory usage stayed constant at 22.4mb the whole time. I also tracked the GC heap sizes and handle counts, and they all stayed constant. As far as I can tell that code isn't leaking.
I then rebuilt the app under .net 3.5 and re-run the test and I got the exact leak you are describing. It started at around 24mb, and by the time it had made 100k calls, memory usage had doubled to over 50mb. Interestingly, it seemed to be the Gen2 heap that was increasing which suggests it is a managed memory leak rather than unmanaged handles/memory.
If possibly I would suggest you try to switch to .net 4.0.
My complete code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
String encryptedString;
for (int j = 0; j < 1000; j++)
{
for (int i = 0; i < 1000; i++)
{
encryptedString = Encrypt(String.Format("test string {0} {1}", j, i), "key");
}
Console.WriteLine("j = {0}", j);
}
Console.WriteLine("Finished");
Console.ReadLine();
}
public static string Encrypt(string plainText, string key)
{
//Set up the encryption objects
byte[] encryptedBytes = null;
using (AesCryptoServiceProvider acsp = GetProvider(Encoding.UTF8.GetBytes(key)))
{
byte[] sourceBytes = Encoding.UTF8.GetBytes(plainText);
using (ICryptoTransform ictE = acsp.CreateEncryptor())
{
//Set up stream to contain the encryption
using (MemoryStream msS = new MemoryStream())
{
//Perform the encrpytion, storing output into the stream
using (CryptoStream csS = new CryptoStream(msS, ictE, CryptoStreamMode.Write))
{
csS.Write(sourceBytes, 0, sourceBytes.Length);
csS.FlushFinalBlock();
//sourceBytes are now encrypted as an array of secure bytes
encryptedBytes = msS.ToArray(); //.ToArray() is important, don't mess with the buffer
csS.Close();
}
msS.Close();
}
}
acsp.Clear();
}
//return the encrypted bytes as a BASE64 encoded string
return Convert.ToBase64String(encryptedBytes);
}
private static AesCryptoServiceProvider GetProvider(byte[] key)
{
AesCryptoServiceProvider result = new AesCryptoServiceProvider();
result.BlockSize = 128;
result.KeySize = 256;
result.Mode = CipherMode.CBC;
result.Padding = PaddingMode.PKCS7;
result.GenerateIV();
result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] RealKey = GetKey(key, result);
result.Key = RealKey;
// result.IV = RealKey;
return result;
}
private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
{
byte[] kRaw = suggestedKey;
List<byte> kList = new List<byte>();
for (int i = 0; i < p.LegalKeySizes[0].MaxSize; i += 8)
{
kList.Add(kRaw[(i / 8) % kRaw.Length]);
}
byte[] k = kList.ToArray();
return k;
}
}
}
Not really trying to hijack a thread but what is the major difference between your encrypt and this one?
///
/// Encrypts a string
///
/// Text to be encrypted
/// Password to encrypt with
/// Salt to encrypt with
/// Can be either SHA1 or MD5
/// Number of iterations to do
/// Needs to be 16 ASCII characters long
/// Can be 128, 192, or 256
/// An encrypted string
public static string Encrypt(string PlainText, string Password,
string Salt, string HashAlgorithm,
int PasswordIterations, string InitialVector,
int KeySize)
{
try
{
if (string.IsNullOrEmpty(PlainText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] CipherTextBytes = null;
using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream())
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
{
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
CipherTextBytes = MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
CryptoStream.Dispose();
MemStream.Dispose();
}
}
Encryptor.Dispose();
}
SymmetricKey.Clear();
return Convert.ToBase64String(CipherTextBytes);
}
catch { throw; }
}
I ran this one under 3.5 and it didn't budge past 22mb. My crypto skills are a little thin but I'm just wondering overall why one is better than the other, or if it is. Seems alot of ways to do the same things.

Help decrypting in ColdFusion passwords created in .NET

I have a SQL db storing passwords that were encrypted through a .NET application, that I need to decrypt through a ColdFusion app. I just can't seem to get things set upproperly for the CF decryption to work. Any help would by appreciated. Thanks.
The .NET decryption code is:
public string Decrypt(string input)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int ZeroBasedByteCount = (input.Length / 2);
//Put the input string into the byte array
byte[] inputByteArray = new byte[ZeroBasedByteCount];
int i;
int x;
for (x = 0;x<ZeroBasedByteCount;x++)
{
i = (Convert.ToInt32(input.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
//Create the crypto objects
des.Key = ASCIIEncoding.ASCII.GetBytes(key);
des.IV = ASCIIEncoding.ASCII.GetBytes(key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
//Flush the data through the crypto stream into the memory stream
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
//Get the decrypted data back from the memory stream
StringBuilder ret = new StringBuilder();
foreach(byte b in ms.ToArray())
{
ret.Append((char)b);
}
return ret.ToString();
}
catch(Exception ex)
{
throw(ex);
return null;
}
}
Have you read the docs for the CF Decrypt function and determined what values you need for the encoding, IVorSalt, and/or iterations arguments? (It looks like the algorithm is DES.)

Categories

Resources