Click to See Complete Forum and Search --> : DES converstion from Java to c#


danrocks
September 28th, 2009, 10:49 PM
Hi,

I am trying to convert DES with added salt to c# code. I am using the below code for the converstion

public static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
// Get the key from config file
string key = "Secret Key";

byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[0x10];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);

DESCryptoServiceProvider tdes = new DESCryptoServiceProvider();
tdes.Key = keyBytes;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.Zeros;

ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

This code gives me following error "Specified key is not a valid size for this algorithm." Can you please let me know if I need do anything specific to convert java code to c#.

Thanks,
Dan

MadHatter
September 29th, 2009, 06:31 PM
string key = "Secret K";

just like it said. the key was too long. it needs to be 8 bytes long. Not sure whether using UTF8 encoding will prefix the resultant bytes w/ the BOM of UTF8, but if so, the above string will not work either.

either do not use a string or use ascii encoding for your key, and keep it 8 bytes long.