本文主要是介绍加解密工具类CryptoAesUtils,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class CryptoAesUtils {private static final String AES = "AES";/*** 算法*/private static final String ALGORITHM = "AES/ECB/PKCS5Padding";/*** 将bytes转为各种进制的字符串** @param bytes byte[]* @param radix 可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制* @return String*/public static String binary(byte[] bytes, int radix) {//1代表正数return new BigInteger(1, bytes).toString(radix);}/*** base64编码** @param src 待编码的byte[]* @return 编码后的base64*/public static String base64Encode(byte[] src) {return Base64.getEncoder().encodeToString(src);}/*** base64解码** @param src 待解码的base64* @return 解码后的byte[]*/public static byte[] base64Decode(String src) {return Base64.getDecoder().decode(src);}/*** AES加密** @param content 加密内容* @param key 密钥* @return 加密后的byte[]*/public static byte[] encryptToBytes(String content, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);keyGenerator.init(128);Cipher cipher = Cipher.getInstance(ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), AES));return cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));}/*** AES加密** @param content 加密内容* @param key 密钥* @return 加密后的String*/public static String encrypt(String content, String key) throws NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeyException {return base64Encode(encryptToBytes(content, key));}/*** AES解密** @param bytes 解密的byte[]* @param key 密钥* @return 解密后的String*/public static String decryptByBytes(byte[] bytes, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);keyGenerator.init(128);Cipher cipher = Cipher.getInstance(ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), AES));byte[] decryptBytes = cipher.doFinal(bytes);return new String(decryptBytes);}/*** AES解密** @param encryptStr 解密内容* @param key 密钥* @return 解密后的String*/public static String decrypt(String encryptStr, String key) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {return StringUtils.isEmpty(encryptStr) ? null : decryptByBytes(base64Decode(encryptStr), key);}
这篇关于加解密工具类CryptoAesUtils的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!