要进行API管理加密和解密,可以使用以下解决方案:
Java示例:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class EncryptionUtils {
private static final String ALGORITHM = "AES";
private static final String KEY = "mysecretkey12345";
public static String encrypt(String plaintext) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
public static void main(String[] args) throws Exception {
String plaintext = "Hello, World!";
String encryptedText = encrypt(plaintext);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}
}
Python示例:
from cryptography.fernet import Fernet
KEY = b'mysecretkey12345'
def encrypt(plaintext):
cipher = Fernet(KEY)
encryptedBytes = cipher.encrypt(plaintext.encode())
return encryptedBytes.decode()
def decrypt(encryptedText):
cipher = Fernet(KEY)
decryptedBytes = cipher.decrypt(encryptedText.encode())
return decryptedBytes.decode()
plaintext = 'Hello, World!'
encryptedText = encrypt(plaintext)
print('Encrypted Text:', encryptedText)
decryptedText = decrypt(encryptedText)
print('Decrypted Text:', decryptedText)
无论你选择哪种方法,都需要在API管理平台或代码中配置密钥或密码,并确保在加密和解密过程中使用相同的密钥进行操作。另外,还需要确保合适的安全措施来保护密钥的安全性。