Récemment, il y a un nouveau projet réalisé en Java. L'ancien projet est asp.net. La transmission par interface nécessite un cryptage et un décryptage DES. J'ai vérifié certaines informations en ligne et j'ai constaté que la plupart d'entre elles ne pouvaient pas être déboguées et traitées immédiatement. le code spécifique Comme suit :
La clé doit être à 8 chiffres
/// <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 ""; } }
La méthode java correspondante est la suivante :
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; } }
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!