JAVA中使用AES加密解密
Posted 大浪不惊涛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; }
以上是关于JAVA中使用AES加密解密的主要内容,如果未能解决你的问题,请参考以下文章