Basically, I have an encryption method written in Java (Actually it's a 3rd party one I need to use, it came with the provided key), it works fine and dandy, but trying to implement the same thing thing in C# I have run into a major issue, I can't figure out how to provide a key length larger then 8 characters to DESCryptoServiceProvider.
Here's my java code:
public static String EncryptUrl(String parameters){
try{
String encodedStr = "";
Cipher cipher;
DESKeySpec keySpec = new DESKeySpec(key.getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generateSecret(keySpec));
encodedStr = Base64.encodeBase64String(cipher.doFinal(parameters.getBytes("UTF8")));
try{
encodedStr = URLEncoder.encode(encodedStr, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is unknown");
}
return encodedStr;
}
catch(Exception ex){
return null;
}
}
And here's my attempt so far at a C# implementation:
public static string EncryptUrl(string originalString)
{
if (String.IsNullOrEmpty(originalString))
{
throw new ArgumentNullException
("The string which needs to be encrypted can not be null.");
}
byte[] tempKeyBytes = Encoding.ASCII.GetBytes("^op!l#ahD");
byte[] keyBytes = new byte[16];
Array.Copy(tempKeyBytes, keyBytes, tempKeyBytes.Length);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider()
{
Padding = PaddingMode.None,
KeySize = 128,
BlockSize = 128
};
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform encryptor = cryptoProvider.CreateWeakEncryptor(tempKeyBytes, tempKeyBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptoStream);
writer.Write(originalString);
cryptoStream.FlushFinalBlock();
writer.Flush();
string encryptedUrl = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
return Uri.EscapeDataString(encryptedUrl);
}
So long story short The key I was provided is 9 characters long (I HAVE to use this key and i HAVE to use DES and i HAVE to implement in C#), DESCryptoServiceProvider has an issue when using anything above 8 characters as a key, because of the fact the DES implementation in .NET only accepts a 64-bit key, so i'm wondering if there is a way to use a 9 character key for a DES encryption implementation