作者:书友79086887 | 来源:互联网 | 2023-01-03 14:01
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位要分段进行加密