October 21st, 2010 Java解密C#DES加密数据

本文介绍了一种确保Java与.NET平台间DES加密结果一致性的方法。通过设置相同的初始向量(IV),使得不同平台上的加密过程能够产生相同的结果。文章提供了具体的.NET与Java实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

早晨的时候,一个朋友在MSN上问我.NET的DES算法实现。我说,这不是很简单的,.NET Framework都有现成的封装直接用就可以了。仔细一问,原来他要和一个.NET实现的系统进行数据交换,他的DES的Java实现出来的结果和.NET的不一样。所以,他怀疑.NET那边的实现有问题。好吧,程序员们都是如此自负,自己从来都不会出问题的-_-||

DES算是相当成熟的算法了,就不再赘述了。要加密结果一样,其实很简单,只要IV值和密钥一样,出来的结果应该都是一样的。看到他那边的.NET实现之后,IV是一个空的byte数组,Java这边只要也把IV的值设为空的byte数组的,结果应该就是一样的。思路就是这样的,下面就是实现了。

.NET的DES算法实现

根据密钥加密字符串

public static string EncryptDES(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 DecryptDES(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算法实现

根据密钥加密字符串

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,容易让人产生误解。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值