如何使用Python中的AES库进行加密,然后用Java正确地解密该密文?
时间: 2024-11-04 09:16:09 浏览: 39
在Python中,你可以使用`cryptography`库中的`Fernet`模块进行AES(Advanced Encryption Standard)加密,而`java.util.Base64`可以帮助我们处理Base64编码的密文传输到Java中。以下是步骤:
1. **Python加密**:
```python
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
import base64
def encrypt(message, password):
salt = b'some_salt'
kdf = PBKDF2HMAC(algorithm=algorithms.HMAC(algorithm=algorithms.SHA256(), length=32),
length=32, salt=salt, iterations=100000, backend=default_backend())
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]), backend=default_backend())
encryptor = cipher.encryptor()
iv = encryptor.iv
ciphertext = encryptor.update(message.encode()) + encryptor.finalize()
return base64.urlsafe_b64encode(iv + ciphertext)
# 示例
message = "Hello, World!"
password = "your_secret_password"
encrypted_text = encrypt(message, password)
```
2. **Java解密** (假设你已经有了Base64解码后的密文、IV以及密码):
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESDecryption {
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String KEY = "your_secret_password"; // 对应Python中的密码
public static String decrypt(String encryptedText) throws Exception {
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] iv = new byte[16];
byte[] ciphertext = new byte[decodedBytes.length - 16];
System.arraycopy(decodedBytes, 0, iv, 0, 16);
System.arraycopy(decodedBytes, 16, ciphertext, 0, decodedBytes.length - 16);
SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
byte[] decryptedBytes = cipher.doFinal(ciphertext);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String decryptedMessage = decrypt("base64_encoded_encrypted_text_here");
System.out.println(decryptedMessage);
}
}
```
阅读全文