views:

165

answers:

3

How do I use DES in .NET?

Here's how I'd do it in Java:

        public static String decrypt(byte[] pin, byte [] desKeyData ) throws Exception {
    //if (ISOConstantsLibrary.DEBUG) System.out.println("original: " + pin + " key: " + ISOUtil.bcd2str(desKeyData, 0, 2 * desKeyData.length, false) );
    String out = "";

    try {           
        SecretKeySpec desKey = new SecretKeySpec(desKeyData, "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");//DES/CBC/PKCS5Padding
        byte[] encrypted_password = pin;
        cipher.init(Cipher.DECRYPT_MODE, desKey);
        byte[] decrypted_password = cipher.doFinal(encrypted_password);
        out = new String(decrypted_password);
        //if (ISOConstantsLibrary.DEBUG) System.out.println("Decrypted Password " + out);
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return out;
}

Is there a library for decrypting DES encryption in .NET? If so, how do I use it?

+1  A: 

You can use the DESCryptoServiceProvider. See this article.

kgiannakakis
+1  A: 

Assuming your input is a stream

using System.Security.Cryptography

string key;
Stream input;
string output;
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//Set key and initialization vector for DES algorithm
DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
DES.IV = ASCIIEncoding.ASCII.GetBytes(key);

//Create CryptoStream layer to decrypt input on reading
CryptoStream decryptStream = new CryptoStream(input, DES.CreateDecryptor(), CryptoStreamMode.Read);
//return decrypted
return new StreamReader(decryptStream ).ReadToEnd();

otherwise you can of course easily write the input into a stream. For ECB mode you also need to set the Mode of the DES object to ECB:

DES.Mode = CipherMode.ECB
Grizzly
I am getting bad data exception with above code.
Maddy.Shik
+1  A: 

As a side note to complement the other answers. If you can, don't use it, use the AESCryptoServiceProvider.

DES is now considered to be insecure for many applications. This is chiefly due to the 56-bit key size being too small; in January, 1999, distributed.net and the Electronic Frontier Foundation collaborated to publicly break a DES key in 22 hours and 15 minutes

Jorge Córdoba