要加密结果一样,其实很简单,只要IV值和密钥一样,出来的结果应该都是一样的。
C#的DES加密解密算法:密钥长度为8
public static string Encode(string encryptString, string encryptKey)
{
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey);
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, new byte[8]), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
public static string Decode(string decryptString, string decryptKey)
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, new byte[8]), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
Java的DES算法,密钥长度为8
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
return new BASE64Encoder().encode(encryptedData);
}
public static String decryptDES(String decryptString, String decryptKey) throws Exception {
byte[] byteMi = new BASE64Decoder().decodeBuffer(decryptString);
IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
byte decryptedData[] = cipher.doFinal(byteMi);
return new String(decryptedData);
}
其实这个问题并不难解决,只是网上一些DES的算法的例子代码并没有用到IV,容易让人产生误解。