要解决AES加密和解密功能无法正常工作的问题,首先需要检查代码是否正确,并确定是否正确地使用了AES算法和相关库。
以下是一些解决方法的示例代码:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESExample {
private static final String AES_ALGORITHM = "AES";
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String data = "Hello, AES!";
String key = "1234567890123456"; // 密钥长度必须为16字节(128位)
String encryptedData = encrypt(data, key);
System.out.println("Encrypted data: " + encryptedData);
String decryptedData = decrypt(encryptedData, key);
System.out.println("Decrypted data: " + decryptedData);
}
}
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
def encrypt(data, key):
cipher = AES.new(key.encode(), AES.MODE_ECB)
encrypted_bytes = cipher.encrypt(pad(data.encode(), AES.block_size))
return base64.b64encode(encrypted_bytes).decode()
def decrypt(encrypted_data, key):
cipher = AES.new(key.encode(), AES.MODE_ECB)
decrypted_bytes = cipher.decrypt(base64.b64decode(encrypted_data))
return unpad(decrypted_bytes, AES.block_size).decode()
data = "Hello, AES!"
key = "1234567890123456" # 密钥长度必须为16字节(128位)
encrypted_data = encrypt(data, key)
print("Encrypted data:", encrypted_data)
decrypted_data = decrypt(encrypted_data, key)
print("Decrypted data:", decrypted_data)
请注意,这只是解决AES加密和解密问题的示例代码。具体解决方法可能因编程语言、库版本和环境而异。确保使用正确的算法和密钥长度,并遵循相关库的文档和最佳实践。另外,还要注意异常处理和数据的正确编码和解码。