AES加解密算法怎么实现
这篇文章主要介绍“AES加解密算法怎么实现”,在日常操作中,相信很多人在AES加解密算法怎么实现问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”AES加解密算法怎么实现”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
/** * base 64 encode * @param bytes 待编码的byte[] * @return 编码后的base 64 code */ public static String base64Encode(byte[] bytes){ return Base64.encodeBase64String(bytes); } /** * base 64 decode * @param base64Code 待解码的base 64 code * @return 解码后的byte[] * @throws Exception */ public static byte[] base64Decode(String base64Code) throws Exception{ return StringUtils.isEmpty(base64Code) ? null : Base64.decodeBase64(base64Code); } public static byte[] aesEncryptToBytes(String content, byte[] encryptKey) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgenInit(kgen, encryptKey); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES")); return cipher.doFinal(content.getBytes("utf-8")); } /** * AES加密为base 64 code * @param content 待加密的内容 * @param encryptKey 加密密钥 * @return 加密后的base 64 code * @throws Exception */ public static String aesEncrypt(String content, String encryptKey) throws Exception { return base64Encode(aesEncryptToBytes(content, getAESKey(encryptKey))); } public static String aesDecryptByBytes(byte[] encryptBytes, byte[] decryptKey) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgenInit(kgen, decryptKey); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES")); byte[] decryptBytes = cipher.doFinal(encryptBytes); return new String(decryptBytes,"utf-8"); } /** * 将base 64 code AES解密 * @param encryptStr 待解密的base 64 code * @param decryptKey 解密密钥 * @return 解密后的string * @throws Exception */ public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception { return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), getAESKey(decryptKey)); } public static byte[] getAESKey(String encodingAESKey){ byte[] array = Base64.decodeBase64(encodingAESKey+"="); return array; } /** **防止在linux下随机生成key * @param kgen * @param bytes * @throws NoSuchAlgorithmException */ public static void kgenInit(KeyGenerator kgen, byte[] bytes) throws NoSuchAlgorithmException { //1.防止linux下 随机生成key SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" ); secureRandom.setSeed(bytes); //2.根据密钥初始化密钥生成器 kgen.init(128, secureRandom); } public static void main(String[] args) throws Exception { /** 测试线secret_key */ String encoding_aes_key="88assadsfsdfsffsf6dsfsdfd"; /** 参数加密 */ String encrypt = aesEncrypt(content, encoding_aes_key); System.out.println("加密后:" + encrypt); /** 参数解密 */ String decrypt = aesDecrypt(encrypt, encoding_aes_key); System.out.println("解密后:" + decrypt); }
到此,关于“AES加解密算法怎么实现”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!