public class AesEncrypt { //实际的加密解密操作 public static final String key = "dreamsoft1234567"; private static byte[] Operation(byte[] src,String key,int mode) throws Exception{ if (key==null) { System.out.println("Key不能为空"); return null; } if (key.length()!=16) { System.out.println("Key需要16位长度"); return null; } byte[] raw=key.getBytes("utf-8"); SecretKeySpec keySpec=new SecretKeySpec(raw, "AES"); Cipher cipher=Cipher.getInstance("AES"); cipher.init(mode, keySpec); byte[] encrypted=cipher.doFinal(src); return encrypted; } public static byte[] encrypt(byte[] src, String key) throws Exception { return Operation(src, key, Cipher.ENCRYPT_MODE); } public static byte[] decrypt(byte[] src, String key) throws Exception { return Operation(src, key, Cipher.DECRYPT_MODE); } public static String encryptStr(String src, String key) throws Exception { byte[] resultByte = Operation(src.getBytes("utf-8"), key, Cipher.ENCRYPT_MODE); return new BASE64Encoder().encode(resultByte); } public static String decryptStr(String src, String key) throws Exception { byte[] base64Byte=new BASE64Decoder().decodeBuffer(src); byte[] base64ResultByte = Operation(base64Byte, key, Cipher.DECRYPT_MODE); return new String(base64ResultByte); } public static void main(String[] args) { try { //我是加密密钥 String key = "dreamsoft1234567"; String content = "110105198702111234"; System.out.println("加密前:" +content); System.out.println("密钥:" +key); try { String enCodeStr=encryptStr(content, key); System.out.println("\n加密后Base64的数据:"); System.out.println(enCodeStr); System.out.println("\nBase64解密后的数据:"); String deCodeStr=decryptStr(enCodeStr, key); System.out.println(deCodeStr); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } }
AES加密工具类
最新推荐文章于 2023-04-03 15:58:34 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)