Example usage for org.bouncycastle.pkcs.jcajce JcePKCSPBEInputDecryptorProviderBuilder JcePKCSPBEInputDecryptorProviderBuilder

List of usage examples for org.bouncycastle.pkcs.jcajce JcePKCSPBEInputDecryptorProviderBuilder JcePKCSPBEInputDecryptorProviderBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs.jcajce JcePKCSPBEInputDecryptorProviderBuilder JcePKCSPBEInputDecryptorProviderBuilder.

Prototype

public JcePKCSPBEInputDecryptorProviderBuilder() 

Source Link

Usage

From source file:com.vvote.thirdparty.ximix.util.BLSKeyStore.java

License:Apache License

/**
 * Load the key store object from the passed in PKCS#12 encoding, using the passed in password.
 *
 * @param password the password to unlock the key store.
 * @param encoding the ASN.1 encoded bytes representing the PKCS#12 store.
 * @throws IOException on a parsing error.
 * @throws GeneralSecurityException if there's an exception decrypting the store.
 *//*from   ww  w  . ja va 2  s .  c om*/
public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException {
    try {
        PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding);
        InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
                .setProvider("BC").build(password);
        ContentInfo[] infos = pfx.getContentInfos();

        for (int i = 0; i != infos.length; i++) {
            if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();

                Attribute[] attributes = bags[0].getAttributes();

                X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue();

                String keyID = getKeyID(attributes);
                BLS01PublicKeyParameters publicKeyParameters = BLSPublicKeyFactory
                        .createKey(cert.getSubjectPublicKeyInfo());

                paramsMap.put(keyID, publicKeyParameters.getParameters());
                sequenceNoMap.put(keyID, ASN1Integer.getInstance(
                        cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue())
                        .getValue().intValue());
                sharedPublicKeyMap.put(keyID, publicKeyParameters.getPk());

                if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) {
                    signingKeys.add(keyID);
                }
            } else {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();
                String keyID = getKeyID(bags[0].getAttributes());

                PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
                PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);

                sharedPrivateKeyMap.put(keyID, ASN1Integer.getInstance(info.parsePrivateKey()).getValue());
            }
        }
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e);
    }
}

From source file:org.candlepin.pki.PrivateKeyReaderTest.java

License:Open Source License

/**
 * Currently fails due to a bug in OpenJDK: https://bugs.openjdk.java.net/browse/JDK-8076999
 *//*  ww  w  . jav a  2 s  . c om*/
@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);
    }
}

From source file:org.commonjava.util.jhttpc.INTERNAL.util.BouncyCastleUtils.java

License:Apache License

public static KeyStore readKeyAndCertFromPem(String pemContent, String keyPass)
        throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException, JHttpCException {
    Logger logger = LoggerFactory.getLogger(BouncyCastleUtils.class);

    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);//from  w  ww.ja v  a2 s .  c  o m

    //        final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
    //                KeyManagerFactory.getDefaultAlgorithm());
    //
    //        kmfactory.init(ks, keyPass.toCharArray());

    //        final CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" );

    //        Pattern keyTypePattern = Pattern.compile( KEY_TYPE_PATTERN );
    //        Matcher matcher = keyTypePattern.matcher( pemContent );

    //        String keyType = "RSA";
    //        if ( matcher.find() )
    //        {
    //            String type = matcher.group( 1 );
    //            if ( "ENCRYPTED".equals( type ) )
    //            {
    //                keyType = "PKCS8";
    //            }
    //            else
    //            {
    //                keyType = type;
    //            }
    //        }
    //
    //        logger.trace( "Using key factory for type: {}", keyType );
    //        final KeyFactory keyFactory = KeyFactory.getInstance( keyType );

    //        final List<String> lines = SSLUtils.readLines( pemContent );
    //
    //        String currentHeader = null;
    //        final StringBuilder current = new StringBuilder();

    int certIdx = 0;

    BouncyCastleProvider bcProvider = new BouncyCastleProvider();
    InputDecryptorProvider provider = new JcePKCSPBEInputDecryptorProviderBuilder().setProvider(bcProvider)
            .build(keyPass.toCharArray());

    final List<Certificate> certs = new ArrayList<Certificate>();
    PrivateKey key = null;

    PEMParser pemParser = new PEMParser(new StringReader(pemContent));
    Object pemObj = null;
    while ((pemObj = pemParser.readObject()) != null) {
        logger.trace("Got PEM object: {}", pemObj);
        if (pemObj instanceof X509CertificateHolder) {
            X509CertificateHolder holder = (X509CertificateHolder) pemObj;
            X509Certificate certificate = new JcaX509CertificateConverter().setProvider(bcProvider)
                    .getCertificate(holder);

            certs.add(certificate);

            Set<String> aliases = new HashSet<String>();
            aliases.add("certificate" + certIdx);

            extractAliases(certificate, aliases);

            KeyStore.TrustedCertificateEntry ksEntry = new KeyStore.TrustedCertificateEntry(certificate);
            for (String alias : aliases) {
                ks.setEntry(alias, ksEntry, null);
                logger.trace("Storing trusted cert under alias: {}\n  with DN: {}", alias,
                        certificate.getSubjectDN().getName());
            }

            certIdx++;
        } else if (pemObj instanceof PKCS8EncryptedPrivateKeyInfo) {
            PKCS8EncryptedPrivateKeyInfo keyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObj;
            PrivateKeyInfo privateKeyInfo = null;
            try {
                privateKeyInfo = keyInfo.decryptPrivateKeyInfo(provider);
            } catch (PKCSException e) {
                throw new JHttpCException("Failed to decrypt key/certificate: %s", e, e.getMessage());
            }
            key = new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
        } else if (pemObj instanceof PEMEncryptedKeyPair) {
            PEMEncryptedKeyPair keyPair = (PEMEncryptedKeyPair) pemObj;
            PEMKeyPair decryptedKeyPair = keyPair
                    .decryptKeyPair(new BcPEMDecryptorProvider(keyPass.toCharArray()));
            PrivateKeyInfo privateKeyInfo = decryptedKeyPair.getPrivateKeyInfo();
            key = new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
        } else {
            logger.trace("Got unrecognized PEM object: {} (class: {})", pemObj,
                    (pemObj == null ? "NULL" : pemObj.getClass().getName()));
        }

        logger.trace("Got private key:\n{}\n", key);
    }

    if (key != null && !certs.isEmpty()) {
        logger.trace("Setting key entry: {}", key);
        ks.setKeyEntry(MonolithicKeyStrategy.KEY, key, keyPass.toCharArray(),
                certs.toArray(new Certificate[certs.size()]));
    } else {
        logger.warn("No private key found in PEM!");
    }

    return ks;
}

From source file:org.cryptoworkshop.ximix.node.crypto.key.BLSKeyManager.java

License:Apache License

public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException {
    try {//from   w  w  w .j  a  v  a2s. c om
        PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding);
        InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
                .setProvider("BC").build(password);
        ContentInfo[] infos = pfx.getContentInfos();

        for (int i = 0; i != infos.length; i++) {
            if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();

                Attribute[] attributes = bags[0].getAttributes();

                X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue();

                String keyID = getKeyID(attributes);
                BLS01PublicKeyParameters publicKeyParameters = BLSPublicKeyFactory
                        .createKey(cert.getSubjectPublicKeyInfo());

                paramsMap.put(keyID, publicKeyParameters.getParameters());
                sharedPublicKeyMap.init(keyID, 1);
                sharedPublicKeyMap.addValue(keyID, new ElementShare(ASN1Integer.getInstance(
                        cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue())
                        .getValue().intValue(), publicKeyParameters.getPk()));

                if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) {
                    signingKeys.add(keyID);
                }
            } else {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();
                String keyID = getKeyID(bags[0].getAttributes());

                PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
                PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);

                sharedPrivateKeyMap.init(keyID, 1);
                sharedPrivateKeyMap.addValue(keyID,
                        new BigIntegerShare(sharedPublicKeyMap.getShare(keyID).getSequenceNo(),
                                ASN1Integer.getInstance(info.parsePrivateKey()).getValue()));
            }
        }
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e);
    }
}

From source file:org.cryptoworkshop.ximix.node.crypto.key.ECKeyManager.java

License:Apache License

public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException {
    try {/*w  ww  .j  a  va 2s.c om*/
        PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding);
        InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
                .setProvider("BC").build(password);
        ContentInfo[] infos = pfx.getContentInfos();

        for (int i = 0; i != infos.length; i++) {
            if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();

                Attribute[] attributes = bags[0].getAttributes();

                X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue();

                String keyID = getKeyID(attributes);
                ECPublicKeyParameters publicKeyParameters = (ECPublicKeyParameters) PublicKeyFactory
                        .createKey(cert.getSubjectPublicKeyInfo());

                paramsMap.put(keyID, publicKeyParameters.getParameters());
                sharedPublicKeyMap.init(keyID, 1);
                sharedPublicKeyMap.addValue(keyID, new ECPointShare(ASN1Integer.getInstance(
                        cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue())
                        .getValue().intValue(), publicKeyParameters.getQ()));

                if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) {
                    signingKeys.add(keyID);
                }
            } else {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();
                String keyID = getKeyID(bags[0].getAttributes());

                PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
                PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);

                sharedPrivateKeyMap.init(keyID, 1);
                sharedPrivateKeyMap.addValue(keyID,
                        new BigIntegerShare(sharedPublicKeyMap.getShare(keyID).getSequenceNo(),
                                ECPrivateKey.getInstance(info.parsePrivateKey()).getKey()));
            }
        }
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e);
    }
}

From source file:org.xipki.commons.security.pkcs11.emulator.PrivateKeyCryptor.java

License:Open Source License

PrivateKeyCryptor(final char[] password) throws P11TokenException {
    ParamUtil.requireNonNull("password", password);
    JcePKCSPBEOutputEncryptorBuilder eb = new JcePKCSPBEOutputEncryptorBuilder(ALGO);
    eb.setProvider("BC");
    eb.setIterationCount(ITERATION_COUNT);
    try {/*from   w w w . j  av  a2  s  .  c om*/
        encryptor = eb.build(password);
    } catch (OperatorCreationException ex) {
        throw new P11TokenException(ex.getMessage(), ex);
    }

    JcePKCSPBEInputDecryptorProviderBuilder db = new JcePKCSPBEInputDecryptorProviderBuilder();
    decryptorProvider = db.build(password);
}