Spring Boot 使用 AES 加密详解
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
@Component
public class AesUtil {
@Value("${aes.key}")
private String aesKey;
public String encrypt(String data) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
byte[] keyBytes = new byte[16];
System.arraycopy(aesKey.getBytes(), 0, keyBytes, 0, Math.min(aesKey.getBytes().length, keyBytes.length));
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public String decrypt(String encryptedData) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
byte[] keyBytes = new byte[16];
System.arraycopy(aesKey.getBytes(), 0, keyBytes, 0, Math.min(aesKey.getBytes().length, keyBytes.length));
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(original);
}
}
这段代码提供了一个简单的AES加密和解密工具类,使用方法也很简单,只需要在Spring Boot项目中注入这个类,然后调用其encrypt
和decrypt
方法即可。在实际使用中,需要注意的是,aes.key
应该是一个安全的密钥,并且在配置文件中保护好,避免泄露。
评论已关闭