2009-11-18 88 views
1

如何在.NET中使用DES如何在.NET中使用DES算法?

以下是我会做它在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; 
} 

是否有在.NET解密DES加密库?如果是这样,我该如何使用它?

回答

1

假设您输入流

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(); 

否则,你当然可以随便写的输入流。 对于ECB模式下,你还需要将DES对象的模式设置为ECB:

DES.Mode = CipherMode.ECB 
+0

我得到与上面的代码错误数据的异常公开打破了DES密钥。 – 2009-12-01 12:01:12

1

作为一个侧面说明,以补充其他的答案。如果可以,请勿使用它,请使用AESCryptoServiceProvider

对于许多应用程序,DES现在被认为是不安全的 。这主要是由于密钥大小为 小,因此主要是 ;在1999年1月, distributed.net和电子 前沿基金会合作,在 22小时 15分钟