DES加密算法
public class SymmetricalEncryptionDemo {
public static void main(String[] args) throws Exception { //要加密的内容 String content = "今晚6点 505 嘿嘿嘿!"; byte[] bytes = content.getBytes(); //对称AES或者DES算法。 SecretKey secretKey = (SecretKey) //加密 String encryptData = encrypt(content, secretKey); System.out.println(encryptData); //解密 String decryptData = decrypt(encryptData, secretKey); System.out.println(decryptData); } /** * 生成 * @return * @throws NoSuchAlgorithmException */ private static SecretKey createKey() throws NoSuchAlgorithmException { //生成秘钥 KeyGenerator generator = KeyGenerator.getInstance("DES");//得到了key生成者 SecretKey secretKey = generator.generateKey(); return secretKey; } /** * 解密方法 * @param encryptData * @param secretKey * @return */ public static String decrypt(String encryptData,SecretKey secretKey)throws Exception{ byte[] bytes = Base64.getDecoder().decode(encryptData); //得到cipher单例对象 Cipher cipher = Cipher.getInstance("DES"); //解密 //初始化,指定模式为解密模式,并传入秘钥 cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptBytes = cipher.doFinal(bytes); return new String(decryptBytes); } /** * 加密方法 * @param content * @param secretKey * @return */ public static String encrypt(String content,SecretKey secretKey)throws Exception{ byte[] bytes = content.getBytes(); //得到cipher单例对象 Cipher cipher = Cipher.getInstance("DES"); //初始化cipher cipher.init(Cipher.ENCRYPT_MODE, secretKey); //正式加密 //得到加密后的字节数组 byte[] encryptBytes = cipher.doFinal(bytes); return Base64.getEncoder().encodeToString(encryptBytes); }}