import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; /** * DES加密解密模式:ecb * 填充:pkcs5padding * 密码:5SiKez2Y 输出格式HEX * 字符集Utf-8 * * @ClassName DesUtil * * @Description * * @createTime 2023/11/23 * */ public class DesUtil { private static String PASSWORD = "youPassword"; private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";//算法/模式/补码方式 public static final String ALGORITHM_NAME = "DES"; public static String encode(String data) throws Exception { SecretKeySpec key = new SecretKeySpec(PASSWORD.getBytes(StandardCharsets.UTF_8), ALGORITHM_NAME); // 加密 Cipher cipherForEncryption = Cipher.getInstance(CIPHER_ALGORITHM); cipherForEncryption.init(Cipher.ENCRYPT_MODE, key); byte[] encrypted = cipherForEncryption.doFinal(data.getBytes(StandardCharsets.UTF_8)); return bytesToHex(encrypted); // 输出HEX格式 } public static String decode(String data) throws Exception { // 将Base64编码的加密文本解码为字节数组 byte[] encryptedBytes = hexStringToByteArray(data); SecretKeySpec key = new SecretKeySpec(PASSWORD.getBytes(StandardCharsets.UTF_8), ALGORITHM_NAME); // 创建解密器 Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); // 解密 byte[] decryptedBytes = cipher.doFinal(encryptedBytes); // 将解密后的字节数组转换为UTF-8编码的字符串 String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8); return decryptedText; } private static String bytesToHex(byte[] bytes) { StringBuilder result = new StringBuilder(); for (byte b : bytes) { result.append(String.format("%02x", b)); } return result.toString(); } private static byte[] hexStringToByteArray(String hexString) { int len = hexString.length(); byte[] byteArray = new byte[len / 2]; for (int i = 0; i < len; i += 2) { byteArray[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i+1), 16)); } return byteArray; } public static void main(String[] args) throws Exception { String str = encode("{\"password\":\"9b2a6298a36606f3490ac0e0b8d9917d\",\"test\":\"3301063501\"}"); System.out.println(str); System.out.println(decode(str)); } }
des算法加密
最新推荐文章于 2024-09-06 10:38:06 发布