在Java中对接口进行加密通常涉及以下步骤:
选择加密算法
可以选择对称加密算法如AES,也可以选择非对称加密算法如RSA。
生成密钥
对于AES,需要生成一个密钥。
对于RSA,需要生成一对公钥和私钥。
加密数据
使用生成的密钥对数据进行加密。
签名验证
在发送请求前,对参数进行排序并加密,生成一个签名。
在接收请求后,对参数进行相同的处理,生成一个签名进行验证。
接口拦截器
可以创建一个拦截器来自动处理加密和解密过程。
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESDemo {
public static void main(String[] args) throws Exception {
// 生成密钥
SecretKey secretKey = generateKey();
String key = Base64.getEncoder().encodeToString(secretKey.getEncoded());
System.out.println("密钥: " + key);
// 加密
String plainText = "Hello, World!";
String encryptedText = encrypt(plainText, secretKey);
System.out.println("加密后的文本: " + encryptedText);
// 解密
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("解密后的文本: " + decryptedText);
}
public static SecretKey generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // 设置密钥长度
return keyGen.generateKey();
}
public static String encrypt(String plainText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
return new String(cipher.doFinal(decodedBytes), StandardCharsets.UTF_8);
}
}
对于更复杂的场景,如接口加密和签名验证,你可能需要结合使用AES和RSA算法,并使用过滤器或拦截器来自动处理这些过程。
请根据你的具体需求调整上述代码示例,并确保安全地存储和管理密钥。