在Java中,可以使用Java Cryptography Extension (JCE)库来实现API接口的数据加密和解密。以下是一个简单的示例,使用AES算法进行数据加密和解密。
首先,确保已经在项目中引入了JCE库。如果使用Maven,可以在pom.xml文件中添加以下依赖:
<dependency>
<groupId>javax.crypto</groupId>
<artifactId>javax.crypto-api</artifactId>
<version>1.3.1</version>
</dependency>
接下来,创建一个名为EncryptionUtil的工具类,用于实现加密和解密功能:
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 EncryptionUtil {
private static final String ALGORITHM = "AES";
private static final String KEY = "your-secret-key"; // 请替换为你自己的密钥
public static String encrypt(String data) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedData);
}
public static String decrypt(String encryptedData) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
byte[] decryptedData = cipher.doFinal(decodedData);
return new String(decryptedData, StandardCharsets.UTF_8);
}
}
现在,你可以在API接口中使用EncryptionUtil类进行数据加密和解密。例如:
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/encrypt")
public ResponseEntity<String> encryptData(@RequestParam("data") String data) {
try {
String encryptedData = EncryptionUtil.encrypt(data);
return ResponseEntity.ok(encryptedData);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("加密失败");
}
}
@GetMapping("/decrypt")
public ResponseEntity<String> decryptData(@RequestParam("encryptedData") String encryptedData) {
try {
String decryptedData = EncryptionUtil.decrypt(encryptedData);
return ResponseEntity.ok(decryptedData);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("解密失败");
}
}
}
这个示例中,我们使用了AES算法进行加密和解密。你可以根据需要选择其他加密算法。注意,为了保证数据安全,密钥应该是随机生成的,并且不要将其硬编码在代码中。在实际项目中,可以考虑使用环境变量或配置文件来存储密钥。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。