Spring Boot 接口加密解密:新姿势
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
@Service
public class EncryptionService {
private static final String ALGORITHM = "AES";
@Autowired
private EncryptionProperties properties;
public String encrypt(String data) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(properties.getSecretKey().getBytes(), ALGORITHM));
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public String decrypt(String encryptedData) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(properties.getSecretKey().getBytes(), ALGORITHM));
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes);
}
}
这段代码使用了AES算法进行数据加密和解密,其中EncryptionProperties
是一个自定义的配置类,用于从配置文件中读取加密的密钥。加密过程首先创建了一个Cipher
实例,然后用密钥初始化它,最后将数据加密。解密过程类似,但是使用了Cipher.DECRYPT_MODE
模式。这段代码提供了一个简洁的加密解密方法,并且可以很容易地集成到Spring Boot应用中。
评论已关闭