use of org.bouncycastle.operator.InputDecryptorProvider 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.operator.InputDecryptorProvider in project candlepin by candlepin.
the class PrivateKeyReaderTest method testReadEncryptedPKCS8.
/**
* Currently fails due to a bug in OpenJDK: https://bugs.openjdk.java.net/browse/JDK-8076999
*/
@Test
@Ignore
public void testReadEncryptedPKCS8() throws Exception {
String keyFile = "keys/pkcs8-aes256-encrypted.pem";
try (InputStream keyStream = cl.getResourceAsStream(keyFile);
Reader expectedReader = new InputStreamReader(cl.getResourceAsStream(keyFile))) {
PrivateKey actualKey = new PrivateKeyReader().read(keyStream, "password");
PKCS8EncryptedPrivateKeyInfo expected = (PKCS8EncryptedPrivateKeyInfo) new PEMParser(expectedReader).readObject();
// the PBE in JcePKCSPBEInputDecryptorProviderBuilder stands for "password based encryption"
InputDecryptorProvider provider = new JcePKCSPBEInputDecryptorProviderBuilder().setProvider(BC_PROVIDER).build(PASSWORD);
PrivateKeyInfo decryptedInfo = expected.decryptPrivateKeyInfo(provider);
PrivateKey expectedKey = new JcaPEMKeyConverter().setProvider(BC_PROVIDER).getPrivateKey(decryptedInfo);
assertEquals(actualKey, expectedKey);
}
}
use of org.bouncycastle.operator.InputDecryptorProvider in project certmgr by hdecarne.
the class DERCertReaderWriter method tryDecodeKey.
@Nullable
private static KeyPair tryDecodeKey(ASN1Primitive asn1Object, String resource, PasswordCallback password) throws IOException {
PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = null;
try {
encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.getInstance(asn1Object));
} catch (Exception e) {
Exceptions.ignore(e);
}
PrivateKeyInfo privateKeyInfo = null;
if (encryptedPrivateKeyInfo != null) {
Throwable passwordException = null;
while (privateKeyInfo == null) {
char[] passwordChars = password.queryPassword(resource);
if (passwordChars == null) {
throw new PasswordRequiredException(resource, passwordException);
}
InputDecryptorProvider inputDecryptorProvider = INPUT_DECRYPTOR_BUILDER.build(passwordChars);
try {
privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
} catch (PKCSException e) {
passwordException = e;
}
}
}
try {
privateKeyInfo = PrivateKeyInfo.getInstance(asn1Object);
} catch (Exception e) {
Exceptions.ignore(e);
}
KeyPair key = null;
if (privateKeyInfo != null) {
PrivateKey privateKey;
try {
String algorithmId = privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm().getId();
KeyFactory keyFactory = JCA_JCE_HELPER.createKeyFactory(algorithmId);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded());
privateKey = keyFactory.generatePrivate(keySpec);
} catch (GeneralSecurityException e) {
throw new CertProviderException(e);
}
key = KeyHelper.rebuildKeyPair(privateKey);
}
return key;
}
use of org.bouncycastle.operator.InputDecryptorProvider in project neo4j by neo4j.
the class PkiUtils method loadPrivateKey.
public static PrivateKey loadPrivateKey(Path privateKeyFile, String passPhrase) throws IOException {
if (passPhrase == null) {
passPhrase = "";
}
try (PEMParser r = new PEMParser(Files.newBufferedReader(privateKeyFile))) {
Object pemObject = r.readObject();
final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(PROVIDER);
if (// -----BEGIN RSA/DSA/EC PRIVATE KEY----- Proc-Type: 4,ENCRYPTED
pemObject instanceof PEMEncryptedKeyPair) {
final PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) pemObject;
final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passPhrase.toCharArray());
return converter.getKeyPair(ckp.decryptKeyPair(decProv)).getPrivate();
} else if (// -----BEGIN ENCRYPTED PRIVATE KEY-----
pemObject instanceof PKCS8EncryptedPrivateKeyInfo) {
try {
final PKCS8EncryptedPrivateKeyInfo encryptedInfo = (PKCS8EncryptedPrivateKeyInfo) pemObject;
final InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passPhrase.toCharArray());
final PrivateKeyInfo privateKeyInfo = encryptedInfo.decryptPrivateKeyInfo(provider);
return converter.getPrivateKey(privateKeyInfo);
} catch (PKCSException | OperatorCreationException e) {
throw new IOException("Unable to decrypt private key.", e);
}
} else if (// -----BEGIN PRIVATE KEY-----
pemObject instanceof PrivateKeyInfo) {
return converter.getPrivateKey((PrivateKeyInfo) pemObject);
} else if (// -----BEGIN RSA/DSA/EC PRIVATE KEY-----
pemObject instanceof PEMKeyPair) {
return converter.getKeyPair((PEMKeyPair) pemObject).getPrivate();
} else {
throw new IOException("Unrecognized private key format.");
}
}
}
use of org.bouncycastle.operator.InputDecryptorProvider in project athenz by yahoo.
the class Crypto method loadPrivateKey.
public static PrivateKey loadPrivateKey(Reader reader, String pwd) throws CryptoException {
try (PEMParser pemReader = new PEMParser(reader)) {
PrivateKey privKey = null;
X9ECParameters ecParam = null;
Object pemObj = pemReader.readObject();
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 Private 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();
}
if (pemObj instanceof PEMKeyPair) {
PrivateKeyInfo pKeyInfo = ((PEMKeyPair) pemObj).getPrivateKeyInfo();
JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
privKey = pemConverter.getPrivateKey(pKeyInfo);
// /CLOVER:OFF
} else if (pemObj instanceof PKCS8EncryptedPrivateKeyInfo) {
// /CLOVER:ON
PKCS8EncryptedPrivateKeyInfo pKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObj;
if (pwd == null) {
throw new CryptoException("No password specified to decrypt encrypted private key");
}
// Decrypt the private key with the specified password
InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider(BC_PROVIDER).build(pwd.toCharArray());
PrivateKeyInfo privateKeyInfo = pKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
privKey = pemConverter.getPrivateKey(privateKeyInfo);
}
if (ecParam != null && privKey != null && ECDSA.equals(privKey.getAlgorithm())) {
ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed());
KeyFactory keyFactory = KeyFactory.getInstance(getECDSAAlgo(), getKeyFactoryProvider());
ECPrivateKeySpec keySpec = new ECPrivateKeySpec(((BCECPrivateKey) privKey).getS(), ecSpec);
privKey = keyFactory.generatePrivate(keySpec);
}
return privKey;
// /CLOVER:OFF
} catch (PEMException e) {
LOG.error("loadPrivateKey: Caught PEMException, problem with format of key detected.");
throw new CryptoException(e);
} catch (NoSuchProviderException e) {
LOG.error("loadPrivateKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
throw new CryptoException(e);
} catch (NoSuchAlgorithmException e) {
LOG.error("loadPrivateKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
throw new CryptoException(e);
} catch (InvalidKeySpecException e) {
LOG.error("loadPrivateKey: Caught InvalidKeySpecException, invalid key spec is being used.");
throw new CryptoException(e);
} catch (OperatorCreationException e) {
LOG.error("loadPrivateKey: Caught OperatorCreationException when creating JceOpenSSLPKCS8DecryptorProviderBuilder.");
throw new CryptoException(e);
} catch (PKCSException e) {
LOG.error("loadPrivateKey: Caught PKCSException when decrypting private key.");
throw new CryptoException(e);
} catch (IOException e) {
LOG.error("loadPrivateKey: Caught IOException, while trying to read key.");
throw new CryptoException(e);
}
// /CLOVER:ON
}
Aggregations