不能明文传证件号码后端加密解密最简单的方式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);

}

三:结果

相关推荐
geNE GENT9 小时前
Spring Boot 实战篇(四):实现用户登录与注册功能
java·spring boot·后端
FQNmxDG4S18 小时前
Java多线程编程:Thread与Runnable的并发控制
java·开发语言
青梅橘子皮18 小时前
Linux---基本指令
linux·运维·服务器
前端老石人18 小时前
HTML 字符引用完全指南
开发语言·前端·html
matlab_xiaowang18 小时前
Redux 入门:JavaScript 可预测状态管理库
开发语言·javascript·其他·ecmascript
虹科网络安全19 小时前
艾体宝干货|数据复制详解:类型、原理与适用场景
java·开发语言·数据库
axng pmje19 小时前
Java语法进阶
java·开发语言·jvm
rKWP8gKv719 小时前
Java微服务性能监控:Prometheus与Grafana集成方案
java·微服务·prometheus
老前端的功夫19 小时前
【Java从入门到入土】28:Stream API:告别for循环的新时代
java·开发语言·python
qq_4352879219 小时前
第9章 夸父逐日与后羿射日:死循环与进程终止?十个太阳同时值班的并行冲突
java·开发语言·git·死循环·进程终止·并行冲突·夸父逐日