use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project athenz by yahoo.
the class Utils method createKeyStore.
/**
* @param athensPublicKey the location on the public key file
* @param athensPrivateKey the location of the private key file
* @return a KeyStore with loaded key and certificate
* @throws Exception KeyStore generation can throw Exception for many reasons
*/
public static KeyStore createKeyStore(final String athensPublicKey, final String athensPrivateKey) throws Exception {
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
X509Certificate certificate;
PrivateKey privateKey = null;
final InputStream publicCertStream;
final InputStream privateKeyStream;
try {
if (Paths.get(athensPublicKey).isAbsolute() && Paths.get(athensPrivateKey).isAbsolute()) {
// Can not cover this branch in unit test. Can not refer any files by absolute paths
File certFile = new File(athensPublicKey);
File keyFile = new File(athensPrivateKey);
while (!certFile.exists() || !keyFile.exists()) {
LOG.error("Missing Athenz public or private key files");
Thread.sleep(1000);
}
publicCertStream = new FileInputStream(athensPublicKey);
privateKeyStream = new FileInputStream(athensPrivateKey);
} else {
publicCertStream = Resources.getResource(athensPublicKey).openStream();
privateKeyStream = Resources.getResource(athensPrivateKey).openStream();
}
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
try (PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream))) {
Object key = pemParser.readObject();
if (key instanceof PEMKeyPair) {
PrivateKeyInfo pKeyInfo = ((PEMKeyPair) key).getPrivateKeyInfo();
privateKey = pemConverter.getPrivateKey(pKeyInfo);
} else if (key instanceof PrivateKeyInfo) {
privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) key);
} else {
throw new IllegalStateException("Unknown object type: " + key.getClass().getName());
}
} catch (IOException e) {
throw new IllegalStateException("Unable to parse private key", e);
}
certificate = (X509Certificate) cf.generateCertificate(publicCertStream);
KeyStore keyStore = KeyStore.getInstance("JKS");
String alias = certificate.getSubjectX500Principal().getName();
keyStore.load(null);
keyStore.setKeyEntry(alias, privateKey, KEYSTORE_PASSWORD.toCharArray(), new X509Certificate[] { certificate });
return keyStore;
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project groovity by disney.
the class PublicKeyValueHandler method doLoad.
@Override
protected Object doLoad(InputStream stream, String contentType, @SuppressWarnings("rawtypes") Class valueClass, @SuppressWarnings("rawtypes") Map config) throws Exception {
Reader reader = new InputStreamReader(stream, getCharset(contentType));
PEMParser pemReader = new PEMParser(reader);
try {
Object o = pemReader.readObject();
if (o instanceof SubjectPublicKeyInfo) {
return new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo) o);
}
} finally {
pemReader.close();
}
return null;
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project keystore-explorer by kaikramer.
the class OpenSslPvkUtil method load.
/**
* Load an unencrypted OpenSSL private key from the stream. The encoding of
* the private key may be PEM or DER.
*
* @param is
* Stream to load the unencrypted private key from
* @return The private key
* @throws PrivateKeyEncryptedException
* If private key is encrypted
* @throws CryptoException
* Problem encountered while loading the private key
* @throws IOException
* An I/O error occurred
*/
public static PrivateKey load(InputStream is) throws CryptoException, IOException {
byte[] streamContents = ReadUtil.readFully(is);
EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
if (encType == null) {
throw new CryptoException(res.getString("NotValidOpenSsl.exception.message"));
}
if (encType == ENCRYPTED) {
throw new PrivateKeyEncryptedException(res.getString("OpenSslIsEncrypted.exception.message"));
}
// Check if stream is PEM encoded
PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
if (pemInfo != null) {
// It is - get DER from PEM
streamContents = pemInfo.getContent();
}
try {
// Read OpenSSL DER structure
ASN1InputStream asn1InputStream = new ASN1InputStream(streamContents);
ASN1Primitive openSsl = asn1InputStream.readObject();
asn1InputStream.close();
if (openSsl instanceof ASN1Sequence) {
ASN1Sequence seq = (ASN1Sequence) openSsl;
if (seq.size() == 9) {
// RSA private key
BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger modulus = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger publicExponent = ((ASN1Integer) seq.getObjectAt(2)).getValue();
BigInteger privateExponent = ((ASN1Integer) seq.getObjectAt(3)).getValue();
BigInteger primeP = ((ASN1Integer) seq.getObjectAt(4)).getValue();
BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(5)).getValue();
BigInteger primeExponentP = ((ASN1Integer) seq.getObjectAt(6)).getValue();
BigInteger primeExponenetQ = ((ASN1Integer) seq.getObjectAt(7)).getValue();
BigInteger crtCoefficient = ((ASN1Integer) seq.getObjectAt(8)).getValue();
if (!version.equals(VERSION)) {
throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
}
RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponenetQ, crtCoefficient);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(rsaPrivateCrtKeySpec);
} else if (seq.size() == 6) {
// DSA private key
BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger primeModulusP = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(2)).getValue();
BigInteger generatorG = ((ASN1Integer) seq.getObjectAt(3)).getValue();
// publicExponentY not req for pvk: sequence.getObjectAt(4);
BigInteger secretExponentX = ((ASN1Integer) seq.getObjectAt(5)).getValue();
if (!version.equals(VERSION)) {
throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
}
DSAPrivateKeySpec dsaPrivateKeySpec = new DSAPrivateKeySpec(secretExponentX, primeModulusP, primeQ, generatorG);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
return keyFactory.generatePrivate(dsaPrivateKeySpec);
} else if (seq.size() >= 2) {
// EC private key (RFC 5915)
org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey);
return new JcaPEMKeyConverter().getPrivateKey(privInfo);
} else {
throw new CryptoException(MessageFormat.format(res.getString("OpenSslSequenceIncorrectSize.exception.message"), "" + seq.size()));
}
} else {
throw new CryptoException(res.getString("OpenSslSequenceNotFound.exception.message"));
}
} catch (Exception ex) {
throw new CryptoException(res.getString("NoLoadOpenSslPrivateKey.exception.message"), ex);
}
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project keystore-explorer by kaikramer.
the class Pkcs8Util method loadEncrypted.
/**
* Load an encrypted PKCS #8 private key from the specified stream. The
* encoding of the private key may be PEM or DER.
*
* @param is
* Stream load the encrypted private key from
* @param password
* Password to decrypt
* @return The private key
* @throws PrivateKeyUnencryptedException
* If private key is unencrypted
* @throws PrivateKeyPbeNotSupportedException
* If private key PBE algorithm is not supported
* @throws CryptoException
* Problem encountered while loading the private key
* @throws IOException
* If an I/O error occurred
*/
public static PrivateKey loadEncrypted(InputStream is, Password password) throws CryptoException, IOException {
byte[] streamContents = ReadUtil.readFully(is);
// Check PKCS#8 is encrypted
EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
if (encType == null) {
// Not a valid PKCS #8 private key
throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
}
if (encType == UNENCRYPTED) {
throw new PrivateKeyUnencryptedException(res.getString("Pkcs8IsEncrypted.exception.message"));
}
// Check if stream is PEM encoded
PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
byte[] encPvk = null;
if (pemInfo != null) {
// It is - get DER from PEM
encPvk = pemInfo.getContent();
}
// If we haven't got the encrypted bytes via PEM then assume it is DER encoded
if (encPvk == null) {
encPvk = streamContents;
}
// try to read PKCS#8 info
PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = null;
try {
encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(encPvk));
} catch (Exception e) {
// Not a valid PKCS #8 private key
throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
}
// decrypt and create PrivateKey object from ASN.1 structure
try {
InputDecryptorProvider decProv = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider("BC").build(password.toCharArray());
PrivateKeyInfo privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decProv);
return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
} catch (Exception ex) {
throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
}
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project keystore-explorer by kaikramer.
the class OpenSslPvkUtilTest method checkCompatibilityWithBC.
@ParameterizedTest
@MethodSource("privateKeys")
public void checkCompatibilityWithBC(PrivateKey privateKey) throws Exception {
String key = OpenSslPvkUtil.getPem(privateKey);
try (PEMParser pemParser = new PEMParser(new StringReader(key))) {
Object obj = pemParser.readObject();
assertThat(obj).isInstanceOf(PEMKeyPair.class);
KeyPair keyPair = new JcaPEMKeyConverter().getKeyPair((PEMKeyPair) obj);
assertThat(keyPair.getPrivate()).isEqualTo(privateKey);
}
}
Aggregations