use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project gocd by gocd.
the class GoAgentServerClientBuilder method getPrivateKey.
private PrivateKey getPrivateKey() throws IOException {
PrivateKey privateKey;
try (PEMParser reader = new PEMParser(new FileReader(this.sslPrivateKey, StandardCharsets.UTF_8))) {
Object pemObject = reader.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider());
if (pemObject instanceof PEMEncryptedKeyPair) {
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase());
KeyPair keyPair = converter.getKeyPair(((PEMEncryptedKeyPair) pemObject).decryptKeyPair(decProv));
privateKey = keyPair.getPrivate();
} else if (pemObject instanceof PEMKeyPair) {
KeyPair keyPair = converter.getKeyPair((PEMKeyPair) pemObject);
privateKey = keyPair.getPrivate();
} else if (pemObject instanceof PrivateKeyInfo) {
PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemObject;
privateKey = converter.getPrivateKey(privateKeyInfo);
} else {
throw new RuntimeException("Unable to parse key of type " + pemObject.getClass());
}
return privateKey;
}
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project cas by apereo.
the class PrivateKeyFactoryBean method readPemPrivateKey.
private PrivateKey readPemPrivateKey() {
LOGGER.trace("Attempting to read as PEM [{}]", this.location);
try (val in = new InputStreamReader(this.location.getInputStream(), StandardCharsets.UTF_8);
val br = new BufferedReader(in);
val pp = new PEMParser(br)) {
val object = pp.readObject();
if (object instanceof PrivateKeyInfo) {
return new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) object);
}
if (object instanceof PEMKeyPair) {
val pemKeyPair = (PEMKeyPair) object;
val kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
return kp.getPrivate();
}
} catch (final Exception e) {
LOGGER.debug("Unable to read key", e);
}
return null;
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project ddf by codice.
the class KeystoreEditor method addToStore.
private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data, String type, String fileName, String path, String storepass, KeyStore store) throws KeystoreEditorException {
OutputStream fos = null;
try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
if (StringUtils.isBlank(alias)) {
throw new IllegalArgumentException(NULL_ALIAS_MSG);
}
Path storeFile = Paths.get(path);
// check the two most common key/cert stores first (pkcs12 and jks)
if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
// priv key + cert chain
KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
pkcs12Store.load(inputStream, storePassword.toCharArray());
Certificate[] chain = pkcs12Store.getCertificateChain(alias);
Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
if (key != null) {
store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
}
} else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
// java keystore file
KeyStore jks = KeyStore.getInstance("jks");
jks.load(inputStream, storePassword.toCharArray());
Enumeration<String> aliases = jks.aliases();
// we are going to store all entries from the jks regardless of the passed in alias
while (aliases.hasMoreElements()) {
String jksAlias = aliases.nextElement();
if (jks.isKeyEntry(jksAlias)) {
Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
} else {
Certificate certificate = jks.getCertificate(jksAlias);
store.setCertificateEntry(jksAlias, certificate);
}
}
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
// need to parse der separately from pem, der has the same mime type but is binary hence
// checking both
} else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
ASN1Primitive asn1Primitive = asn1InputStream.readObject();
X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, "BC");
Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
store.setCertificateEntry(cnStr, certificate);
}
store.setCertificateEntry(alias, certificate);
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
// if it isn't one of the stores we support, it might be a key or cert by itself
} else if (isPemParsable(type, fileName)) {
// This is the catch all case for PEM, P7B, etc. with common file extensions if the mime
// type isn't read correctly in the browser
Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
PEMParser pemParser = new PEMParser(reader);
Object object;
boolean setEntry = false;
while ((object = pemParser.readObject()) != null) {
if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
PEMKeyPair pemKeyPair;
if (object instanceof PEMEncryptedKeyPair) {
PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
} else {
pemKeyPair = (PEMKeyPair) object;
}
KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
PrivateKey privateKey = keyPair.getPrivate();
Certificate[] chain = store.getCertificateChain(alias);
if (chain == null) {
chain = buildCertChain(alias, store);
}
store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
setEntry = true;
} else if (object instanceof X509CertificateHolder) {
X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, "BC");
Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
store.setCertificateEntry(cnStr, certificate);
}
store.setCertificateEntry(alias, certificate);
setEntry = true;
} else if (object instanceof ContentInfo) {
ContentInfo contentInfo = (ContentInfo) object;
if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
ASN1Set certificates = originatorInfo.getCertificates();
setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
} else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
ASN1Set certificates = signedData.getCertificates();
setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
}
} else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
Certificate[] chain = store.getCertificateChain(alias);
if (chain == null) {
chain = buildCertChain(alias, store);
}
try {
store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
setEntry = true;
} catch (KeyStoreException keyEx) {
try {
PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(), keyPassword.toCharArray());
store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(), chain);
setEntry = true;
} catch (GeneralSecurityException e) {
LOGGER.info("Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.", e);
throw keyEx;
}
}
}
}
if (setEntry) {
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
}
}
} catch (Exception e) {
LOGGER.info("Unable to add entry {} to store", alias, e);
throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ignore) {
}
}
}
init();
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project athenz by yahoo.
the class Crypto method loadPublicKey.
public static PublicKey loadPublicKey(Reader r) throws CryptoException {
try (org.bouncycastle.openssl.PEMParser pemReader = new org.bouncycastle.openssl.PEMParser(r)) {
Object pemObj = pemReader.readObject();
JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
X9ECParameters ecParam = null;
if (pemObj instanceof ASN1ObjectIdentifier) {
// make sure this is EC Parameter we're handling. In which case
// we'll store it and read the next object which should be our
// EC Public Key
ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
ecParam = ECNamedCurveTable.getByOID(ecOID);
// /CLOVER:OFF
if (ecParam == null) {
throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId());
}
// /CLOVER:ON
pemObj = pemReader.readObject();
} else if (pemObj instanceof X9ECParameters) {
ecParam = (X9ECParameters) pemObj;
pemObj = pemReader.readObject();
}
SubjectPublicKeyInfo keyInfo;
if (pemObj instanceof org.bouncycastle.cert.X509CertificateHolder) {
keyInfo = ((org.bouncycastle.cert.X509CertificateHolder) pemObj).getSubjectPublicKeyInfo();
} else {
keyInfo = (SubjectPublicKeyInfo) pemObj;
}
PublicKey pubKey = pemConverter.getPublicKey(keyInfo);
if (ecParam != null && ECDSA.equals(pubKey.getAlgorithm())) {
ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed());
KeyFactory keyFactory = KeyFactory.getInstance(getECDSAAlgo(), getKeyFactoryProvider());
ECPublicKeySpec keySpec = new ECPublicKeySpec(((BCECPublicKey) pubKey).getQ(), ecSpec);
pubKey = keyFactory.generatePublic(keySpec);
}
return pubKey;
} catch (NoSuchProviderException e) {
LOG.error("loadPublicKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
throw new CryptoException(e);
} catch (NoSuchAlgorithmException e) {
LOG.error("loadPublicKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
throw new CryptoException(e);
// /CLOVER:OFF
} catch (InvalidKeySpecException e) {
LOG.error("loadPublicKey: Caught InvalidKeySpecException, invalid key spec is being used.");
throw new CryptoException("InvalidKeySpecException");
} catch (IOException e) {
throw new CryptoException(e);
}
// /CLOVER:ON
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project athenz by yahoo.
the class Crypto method extractX509CSRPublicKey.
public static String extractX509CSRPublicKey(PKCS10CertificationRequest certReq) {
JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
PublicKey publicKey;
try {
publicKey = pemConverter.getPublicKey(certReq.getSubjectPublicKeyInfo());
// /CLOVER:OFF
} catch (PEMException ex) {
LOG.error("extractX509CSRPublicKey: unable to get public key: {}", ex.getMessage());
return null;
}
// /CLOVER:ON
return convertToPEMFormat(publicKey);
}
Aggregations