• JAVA中使用AES加密解密


    技术交流群: 233513714

        /**
         * AES加密测试
         *
         * @param str 加密参数
         */
        public void aesTest(String str) {
            log.info("[rsaTest获取请求:{}]", str);
            try {
                String encryptResult = AESUtil.encrypt(str, "123456");
                log.info("[AES加密后的参数为:{}]", encryptResult);
                String decryptResult = AESUtil.decrypt(encryptResult, "123456");
                log.info("[AES解密后的参数为:{}]", decryptResult);
            } catch (Exception e) {
                log.info("[AES加密解密出现异常:{}]", e);
            }
        }
    
    
        /**
         * AES加密
         *
         * @param content  需要加密的内容
         * @param password 加密密码
         * @return
         */
        public static String encrypt(String content, String password) {
            try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                kgen.init(128, new SecureRandom(password.getBytes()));
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");
                byte[] byteContent = content.getBytes("utf-8");
                cipher.init(Cipher.ENCRYPT_MODE, key);
                byte[] result = cipher.doFinal(byteContent);
                Base64 base64 = new Base64();
                return base64.encodeToString(result);
            } catch (Exception e) {
                log.info("AES加密出现异常:{}", e);
            }
            return null;
        }
    
        /**
         * AES解密
         *
         * @param content  待解密内容
         * @param password 解密密钥
         * @return
         */
        public static String decrypt(String content, String password) {
            try {
                Base64 base64 = new Base64();
                byte[] text = base64.decode(content);
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                kgen.init(128, new SecureRandom(password.getBytes()));
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.DECRYPT_MODE, key);
                byte[] result = cipher.doFinal(text);
                return new String(result);
            } catch (Exception e) {
                log.info("AES解密出现异常:{}", e);
            }
            return null;
        }
  • 相关阅读:
    感想2
    感想1
    记录4
    记录3
    记录2
    记录1
    库存物资管理系统-测试
    开学测试
    大二下开学测试有感
    大二下周总结一
  • 原文地址:https://www.cnblogs.com/cnndevelop/p/7147027.html
Copyright © 2020-2023  润新知