'How do I read this private key as an ECPrivateKey in Java?
I have the following private key, and am attempting to read it as an instance of ECPrivateKey using BouncyCaste with the following code. However, I'm getting a null pointer exception:
Key:
-----BEGIN EC PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgtqnvswtIdNxKy07B
D3Y9vvlpwvSDqWCvyWmWTNea2ImgCgYIKoZIzj0DAQehRANCAATa0LtPPOI+De/u
RY1vSxR7gFGSoyjaDZyif/sWujLZWEj6Rc2IEl62VfWQD3GeYCEEKP9qzpOGyO+b
HWR98kNd
-----END EC PRIVATE KEY-----
Parsing code:
private PrivateKey readPemAsPrivateKey(final String pem) throws IOException {
final PEMParser pemParser = new PEMParser(new StringReader(pem));
final Object parsedPem = pemParser.readObject();
if (!(parsedPem instanceof PEMKeyPair)) {
throw new IOException("Attempted to parse PEM string as a keypair, but it's actually a " + parsedPem.getClass());
}
Security.addProvider(new BouncyCastleProvider());
final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
return converter.getKeyPair((PEMKeyPair) parsedPem).getPrivate();
}
The exception:
! java.lang.NullPointerException: null
! ... 29 common frames omitted
! Causing: org.bouncycastle.openssl.PEMException: unable to convert key pair: null
! at org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter.getKeyPair(Unknown Source) ~
Does anyone know how I can read this key as an ECPrivateKey object?
Note:
When I run the following openssl command, it spits the key out in a format that Bouncycastle does accept. Unfortunately, in production I don't have the option to pre-process the key--I have to work with the key as-is and process it in code.
$ openssl ec -inform PKCS8 -in T5TK5598S7.p8
read EC key
writing EC key
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIGaopmcUKDBihelMJbKUyRmaR6F3Eo90EZaqZJ3/mBr0oAoGCCqGSM49
AwEHoUQDQgAEnYaxPG+o57xM5o/M5QNn0ocwlw12ZNVWFEo9tKDQ7Jz5Gz/0eMcP
mEhm5msFFpWgrY0/T92MfwByuaLws/rM3w==
-----END EC PRIVATE KEY-----
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
