Skip to content

Instantly share code, notes, and snippets.

@henryx
Created May 19, 2020 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henryx/27b747d627ec5cda89db78e013be6c34 to your computer and use it in GitHub Desktop.
Save henryx/27b747d627ec5cda89db78e013be6c34 to your computer and use it in GitHub Desktop.
Read PKCS#8 RSA key
public class ReadPKCS8 {
/**
Read PKCS#8 RSA key, with or without passphrase. It requires Bouncycastle library
*/
public static void main(String[] args) throws IOException, PKCSException, OperatorCreationException {
var file = "a_pkcs8_rsa_key.p8";
var password = "passphrase";
Security.addProvider(new BouncyCastleProvider());
PEMParser pemParser = new PEMParser(new FileReader(file));
Object object = pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
PrivateKey privateKey;
if (object instanceof PEMEncryptedKeyPair) {
// Encrypted key - we will use provided password
PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) object;
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
KeyPair kp = converter.getKeyPair(ckp.decryptKeyPair(decProv));
privateKey = kp.getPrivate();
} else if (object instanceof org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) {
PKCS8EncryptedPrivateKeyInfo keyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
PrivateKeyInfo privateKeyInfo = keyInfo.decryptPrivateKeyInfo(pkcs8Prov);
privateKey = converter.getPrivateKey(privateKeyInfo);
} else {
PEMKeyPair ukp = (PEMKeyPair) object;
KeyPair kp = converter.getKeyPair(ukp);
privateKey = kp.getPrivate();
}
System.out.println(privateKey.getAlgorithm())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment