Posts

Showing posts from January, 2016

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 This will generate the private key alone  Certificates: ope

java.security.spec.InvalidKeySpecException: Only RSAPrivate(Crt)KeySpec and PKCS8EncodedKeySpec supported for RSA private keys

public PrivateKey getPrivateKey(String fileName) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { byte[] keyFileBytes = readKeyFile(fileName); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyFileBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } The reason is this line, This is used to read public key spec and not private key. The private key is read via PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec ( keyBytes ); So as the error says it needs to be in PKCS8 spec format for java to understand.