package com.ff.base.utils; import com.ff.base.exception.base.BaseException; import lombok.Data; import javax.crypto.*; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.Base64; /** * 解密有用 * * @author shi * @date 2025/03/24 */ public class DESEncryptUtils { /** * 给…解密 * * @param inString 字符串中 * @param key 钥匙 * @return {@link String } * @throws Exception 例外 */ public static String DESEncrypt(String inString, String key) { try { byte[] encryptKey = key.getBytes(); // encryptKey KeySpec keySpec = new DESKeySpec(encryptKey); SecretKey myDesKey = SecretKeyFactory.getInstance("DES").generateSecret(keySpec); IvParameterSpec iv = new IvParameterSpec(encryptKey); KeyGenerator keygenerator = KeyGenerator.getInstance("DES"); Cipher desCipher; // Create the cipher desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // Initialize the cipher for encryption desCipher.init(Cipher.ENCRYPT_MODE, myDesKey, iv); //sensitive information String source = inString; byte[] text = source.getBytes(); System.out.println("Text [Byte Format] : " + text); System.out.println("Text : " + new String(text)); // Encrypt the text byte[] textEncrypted = desCipher.doFinal(text); String t = Base64.getEncoder().encodeToString(textEncrypted); System.out.println("Text Encryted [Byte Format] : " + textEncrypted); System.out.println("Text Encryted : " + t); // Initialize the same cipher for decryption desCipher.init(Cipher.DECRYPT_MODE, myDesKey, iv); // Decrypt the text byte[] textDecrypted = desCipher.doFinal(textEncrypted); System.out.println("Text Decryted : " + new String(textDecrypted)); return t; } catch (Exception e) { throw new BaseException("解密失败"); } } }