最近有个新项目用java做的,老项目是asp.net,接口传输需要des加解密,网上查了些资料,大多数不能拿来就用,自己经过调试加工了一下,具体代码如下:
**一定是8位
/// <summary>
/// 利用DES加密算法加密字符串(可解密)
/// </summary>
/// <param name="pToEncrypt">被加密的字符串</param>
/// <param name="key">**(只支持8个字节的**)</param>
/// <returns>加密后的字符串</returns>
public static string DESEnCode(string pToEncrypt, string key)
{
try
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(pToEncrypt);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
stream2.Write(bytes, 0, bytes.Length);
stream2.FlushFinalBlock();
StringBuilder builder = new StringBuilder();
foreach (byte num in stream.ToArray())
{
builder.AppendFormat("{0:X2}", num);
}
stream.Close();
return builder.ToString();
}
catch (Exception) { return "xxxx"; }
}
/// <summary>
/// 解密
/// </summary>
/// <param name="plaintext">加密后的字符串</param>
/// <param name="key">**(只支持8个字节的**)</param>
/// <returns>解密后的字符串</returns>
public static string Decode(string str, string key, string encLangue)
{
try
{
//str=Ruijie.Pcfg.Utils.DESEncrypt.HexTostring(str);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] buffer = new byte[str.Length / 2];
for (int i = 0; i < (str.Length / 2); i++)
{
int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
buffer[i] = (byte)num2;
}
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
stream.Close();
if (encLangue == "java")
{
return Encoding.GetEncoding("utf-8").GetString(stream.ToArray());
}
else
{
return Encoding.GetEncoding("gb2312").GetString(stream.ToArray());
}
}
catch (Exception) { return ""; }
}
对应java的方法如下:
package com.testspring;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class DesHelper {
/**
* 加密
*
*
* **/
public String encrypt(String message,String key)
{
return toHexString(encryptByte(message,key)).toUpperCase();
}
/**
* 明文加密后的数组
*
*
* **/
public byte[] encryptByte(String message, String key) {
byte[] s={};
try
{
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return cipher.doFinal(message.getBytes("UTF-8"));
}
catch (Exception ex) {
}
return s;
}
/**
* 数组转化成16进制
*
*
* **/
public static String toHexString(byte b[]) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String plainText = Integer.toHexString(0xff & b[i]);
if (plainText.length() < 2)
plainText = "0" + plainText;
hexString.append(plainText);
}
return hexString.toString();
}
/**
* 解密
*ciphertext 加密字符串,key **,encLangue 加密语言
*
* **/
public String decrypt(String ciphertext, String key,String encLangue) {
try {
byte[] bytesrc = convertHexString(ciphertext);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(bytesrc);
if(encLangue=="java")
{
return new String(retByte,"utf-8");
}
else
{
return new String(retByte);
}
}
catch (Exception ex)
{
}
return "";
}
/**
* 转化16进制字符串为byte数组
*
* **/
public static byte[] convertHexString(String ss) {
byte digest[] = new byte[ss.length() / 2];
for (int i = 0; i < digest.length; i++) {
String byteString = ss.substring(2 * i, 2 * i + 2);
int byteValue = Integer.parseInt(byteString, 16);
digest[i] = (byte) byteValue;
}
return digest;
}
}