最近有個新項目用java做的,老項目是asp.net,介面傳輸需要des加解密,網上查了些資料,大多數不能拿來就用,自己經過調試加工了一下,具體代碼如下: 密鑰一定是8位 對應java的方法如下: package com.testspring; import javax.crypto.Cipher; ...
最近有個新項目用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;
}
}