DeSede 3DES Encryption in .NET (Cryptography Issues) (2009-10-08)
private string SimpleStringEncrypt(string toEncrypt, string key, System.Text.Encoding encoding)
{
byte[] text = encoding.GetBytes(toEncrypt);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
tdes.Mode = System.Security.Cryptography.CipherMode.CBC;
tdes.Key = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key));
tdes.Padding = PaddingMode.PKCS7;
return Convert.ToBase64String(tdes.CreateEncryptor().TransformFinalBlock(text, 0, text.Length));
}
public string URLEncode(string s)
{
Encoding e = Encoding.UTF8;
return HttpUtility.UrlEncode(s, e);
}
The issue I am having however is around the passphrase. I am trying to use a key (A VALID sample passphrase is: XZ5n45Ej1byXRqGh73rfnc1FH2R/cKQy)
The issue i am running into is that it says that the keylength is invalid; however if I do the same thing in Java with this code:
private static KeySpec keySpec;
private static SecretKeyFactory keyFactory;
private static Cipher cipher;
public static String encrypt( String unencryptedString, String encryptionKey ) throws Exception
{
if ( unencryptedString == null || unencryptedString.trim().length() == 0 )
throw new IllegalArgumentException(
"unencrypted string was null or empty" );
if ( encryptionKey == null )
throw new IllegalArgumentException( "encryption key was null" );
if ( encryptionKey.trim().length() < 24 )
throw new IllegalArgumentException(
"encryption key was less than 24 characters" );
try
{
byte[] keyAsBytes = encryptionKey.getBytes("UTF-8");
keySpec = new DESedeKeySpec( keyAsBytes );
keyFactory = SecretKeyFactory.getInstance( "DESede" );
cipher = Cipher.getInstance( "DESede" );
SecretKey key = keyFactory.generateSecret( keySpec );
cipher.init( Cipher.ENCRYPT_MODE, key );
byte[] cleartext = unencryptedString.getBytes("UTF-8");
byte[] ciphertext = cipher.doFinal( cleartext );
BASE64Encoder base64encoder = new BASE64Encoder();
return base64encoder.encode( ciphertext );
//return new String(ciphertext,"UTF-8");
}
catch (InvalidKeyException e)
{
throw new Exception( e );
}
catch (NoSuchAlgorithmException e)
{
throw new Exception( e );
}
catch (UnsupportedEncodingException e)
{
throw new Exception( e );
}
catch (NoSuchPaddingException e)
{
throw new Exception( e );
}
catch (Exception e)
{
throw new Exception( e );
}
}
Everything I am running into is saying that .NET doesnt support 44-bit passphrases but I know there has to be a way. Can anyone help or shed any light on this? I'd like to finish this application in .net; but it's not looking good 
|