RSA Assymmetric Key Encryption
In addition to the standard X509 *.cer certificates there are also certificate files ending with *.PFX or *.P12.The later ones are X509 certs as well, but may in addition contain a private key, too. PFX was a Microsoft extension, while P12 was the Netscape one.
Generating from Scratch using OpenSSL
1. Generate a 2048-bit RSA private key
$ openssl genrsa -out private_key.pem 2048
This will generate a key file in traditional key format also called ssLeay private key format.
2. Convert private Key to PKCS#8 format (so Java can read it)
$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
3. Output public key portion in DER format (so Java can read it)
$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der
Generating from the .p12 File
- Private key:
openssl pkcs12 -in
yourP12File.pfx-nocerts -out
privateKey.pem - Certificates:
openssl pkcs12 -in
yourP12File.pfx-clcerts -nokeys -out
publicCert.pem
After this use the Steps 2 and 3 above to generate the certificate files.
Sample Code to Test
public class TestAssymmetric {
public static void main(String[] args) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
{
AssymmetricEncryptor encypter=new AssymmetricEncryptor();
PublicKey publicKey = encypter.getPublicKey("C:\\Users\\apillai\\Documents\\Assets\\public_key.der");
System.out.println(publicKey);
String clearText = "hello world";
System.out.println("Clear Text:" + clearText);
String encryptedString = encypter.encrypt(clearText,publicKey);
System.out.println("Encrypted String:" + encryptedString);
System.out.println("Encrypted String: Encoded" + Base64.encode(encryptedString.getBytes()));
PrivateKey privateKey = encypter.getPrivateKey("C:\\Users\\apillai\\Documents\\Assets\\private_key.der");
System.out.println(privateKey);
String decryptedString = encypter.decrypt(encryptedString,privateKey);
System.out.println(decryptedString);
}
}
Comments
Post a Comment