首页 > 代码库 > JAVA中使用AES加密解密
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加密解密
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。