RSA Decrypt PKCS1v15 AES Key in Java: A Comprehensive Guide
This Java example demonstrates how to decrypt an AES key using an RSA private key with PKCS1v15 padding.
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class RSAExample {
public static void main(String[] args) throws Exception {
// RSA private key
String privateKeyStr = 'your_private_key';
// Encrypted AES key
String encryptedAESKey = 'encrypted_aes_key';
// Decode the private key
byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance('RSA');
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
// Decrypt the AES key using the RSA private key
Cipher cipher = Cipher.getInstance('RSA/ECB/PKCS1Padding');
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] aesKeyBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedAESKey));
// Create a SecretKeySpec from the decrypted AES key
SecretKeySpec secretKeySpec = new SecretKeySpec(aesKeyBytes, 'AES');
// Decrypt the data using the AES key
Cipher aesCipher = Cipher.getInstance('AES/ECB/PKCS5Padding');
aesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedData = aesCipher.doFinal(Base64.getDecoder().decode('data_to_decrypt'));
System.out.println(new String(decryptedData));
}
}
Replace 'your_private_key' with your actual RSA private key, 'encrypted_aes_key' with the AES key encrypted using the public key, and 'data_to_decrypt' with the data you want to decrypt.
This example utilizes the javax.crypto and java.security packages from the Java standard library for RSA and AES decryption.
This example demonstrates a common approach for decrypting data that was previously encrypted using AES with a key that was in turn encrypted using RSA. It combines both RSA and AES cryptography to provide a layered security approach. Remember to use strong and secure private keys, and be aware of best practices for secure key management.
原文地址: https://www.cveoy.top/t/topic/phha 著作权归作者所有。请勿转载和采集!