Created
May 19, 2020 16:17
-
-
Save henryx/27b747d627ec5cda89db78e013be6c34 to your computer and use it in GitHub Desktop.
Read PKCS#8 RSA key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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