热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Java和.net加密解密互通DES

Java代码:publicstaticStringencrypt(Stringdata,Stringkey)throwsException{CiphercipherCiphe

Java代码:

public static String encrypt(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

DESKeySpec desKeySpec = new DESKeySpec(key.substring(0, 8).getBytes("UTF-8"));

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.substring(0, 8).getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

return new BASE64Encoder().encode(cipher.doFinal(data.getBytes("UTF-8")));
}

public static String decrypt(String data, String key) throws IOException,
Exception {
if (data == null)
return "";
BASE64Decoder decoder = new BASE64Decoder();

Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

DESKeySpec desKeySpec = new DESKeySpec(key.substring(0, 8).getBytes(
"UTF-8"));

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.substring(0, 8).getBytes(
"UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(decoder.decodeBuffer(data));
return new String(retByte);
}


.net代码:

public static string DESEncrypt(string data, string desKey)
{
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(data);
des.Key = Encoding.UTF8.GetBytes(desKey.Substring(0, 8));
des.IV = Encoding.UTF8.GetBytes(desKey.Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Convert.ToBase64String(ms.ToArray());
ms.Close();
return str;
}
}

public static string DESDecrypt(string encryedData, string desKey)
{
byte[] inputByteArray = Convert.FromBase64String(encryedData);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = Encoding.UTF8.GetBytes(desKey.Substring(0, 8));
des.IV = Encoding.UTF8.GetBytes(desKey.Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return str;
}
}

注意:1.Java密钥为8字节,或8的倍数。

    2.只支持加密字符串为128位以内的字符加密,如果超过128位要分段进行加密




推荐阅读
author-avatar
书友79086887
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有