Java与C#交互DES算法加密解密数据

    要加密结果一样,其实很简单,只要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,容易让人产生误解。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值