不能明文传证件号码后端加密解密最简单的方式AES

一:生成密钥

private static final String ALGORITHM = "AES";

// 生成密钥

public static String generateKey() throws Exception {

KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);

// 初始化128位密钥

keyGen.init(128);

SecretKey secretKey = keyGen.generateKey();

return Base64.getEncoder().encodeToString(secretKey.getEncoded());

}

二:利用生成的密钥加密解密

public class SimpleAesUtil {

private static final String ALGORITHM = "AES";

private static String key="LKrFJ0OA8bYDCjIsPRju+A==";

// 加密

public static String encrypt(String data) throws Exception {

byte\[\] keyBytes = Base64.getDecoder().decode(key);

SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, keySpec);

byte\[\] encryptedBytes = cipher.doFinal(data.getBytes());

return Base64.getEncoder().encodeToString(encryptedBytes);

}

// 解密

public static String decrypt(String encryptedData) throws Exception {

byte\[\] keyBytes = Base64.getDecoder().decode(key);

SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, keySpec);

byte\[\] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));

return new String(decryptedBytes);

}

public static void main(String\[\] args) throws Exception {

String originalText = "371502198906089802";

// 加密

String encrypted = encrypt(originalText);

System.out.println("加密结果: " + encrypted);

// 解密

String decrypted = decrypt(encrypted);

System.out.println("解密结果: " + decrypted);

}

三:结果

相关推荐
秋名RG1 分钟前
Java 基础语法
java·开发语言
java1234_小锋4 分钟前
MyBatis-Plus 3.5.15 已全面支持 Spring Boot 4.0 及 Jackson 3.0
java·spring boot·mybatis
码行山野赴时序归途6 分钟前
C 语言文件操作完全指南:从打开到关闭
c语言·开发语言
2501_9378609412 分钟前
Java 文件操作与IO(下):字节流、字符流实战IO读写
java·开发语言·python
xixingzhe214 分钟前
spring boot项目接口访问慢问题解决方案
java·数据库·spring boot
MetaLite16 分钟前
SpringBoot整合FastJson2数据脱敏-接口日志与失败降级
java·spring boot·后端
事圆则缓18 分钟前
Kotlin 高阶工程化与 Android 深入实践
android·开发语言·kotlin
驭渊的小故事25 分钟前
java抽奖项目-奖品上传中传递参数类型的错误
java·开发语言
名字还没想好☜28 分钟前
Go 时间格式化为什么用 2006-01-02:time.Format/Parse 的参考时间、时区与解析踩坑
开发语言·后端·golang·go
段一凡-华北理工大学30 分钟前
高炉智能布料技术与炉料分布优化~系列文章03:布料矩阵解码:环位、角度、圈数与料流的量化控制
java·网络·人工智能·矩阵·高炉智能化·高炉布料矩阵优化·高炉智能布料技术