<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>
创建 AES 加密/解密工具类创建一个AesUtil的工具类来封装AES加密和解密的操作。如下所示。import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.util.Base64;public class AesUtil { private static final String ALGORITHM = "AES"; // 生成 AES Key public static String generateKey() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM); keyGen.init(256); SecretKey secretKey = keyGen.generateKey(); return Base64.getEncoder().encodeToString(secretKey.getEncoded()); } // 加密操作 public static String encrypt(String data, String key) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encryptedBytes = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } // 解密操作 public static String decrypt(String encryptedData, String key) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] decodedBytes = Base64.getDecoder().decode(encryptedData); byte[] decryptedBytes = cipher.doFinal(decodedBytes); return new String(decryptedBytes); }}
使用 AES 工具类通过一个Controller控制类来验证AES加密操作。import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/api")public class EncryptionController { private static final String SECRET_KEY = "12321kjdahfl"; // 这里你可以用 AesUtil.generateKey() 来生成一个密钥 @GetMapping("/encrypt") public String encrypt(@RequestParam String data) throws Exception { return AesUtil.encrypt(data, SECRET_KEY); } @GetMapping("/decrypt") public String decrypt(@RequestParam String encryptedData) throws Exception { return AesUtil.decrypt(encryptedData, SECRET_KEY); }}
测试加密和解密功能接下来我们就可以通过调用接口来实现数据加解密的操作了,如下所示。加密操作http://localhost:8080/api/encrypt?data=hello
解密操作http://localhost:8080/api/decrypt?encryptedData
到这里我们就完成了整合AES的加解密操作。AES 广泛应用于各种需要数据加密的场合,例如对于静态数据的保护,对于网络传输数据的保护,在移动物联网领域数据传输的加密保护等。(图片来源网络,侵删)
0 评论