Java Examples for org.bouncycastle.pkcs.PKCSException

The following java examples will help you to understand the usage of org.bouncycastle.pkcs.PKCSException. These source code samples are taken from different open source projects.

Example 1
Project: jsign-master  File: PrivateKeyUtils.java View source code
/**
     * Load the private key from the specified file. Supported formats are PVK and PEM, encrypted or not.
     * 
     * @param file
     * @param password
     */
public static PrivateKey load(File file, String password) throws IOException, GeneralSecurityException, OperatorCreationException, PKCSException {
    if (file.getName().endsWith(".pvk")) {
        return PVK.parse(file, password);
    } else if (file.getName().endsWith(".pem")) {
        return readPrivateKeyPEM(file, password);
    } else {
        throw new IllegalArgumentException("Unsupported private key format (PEM or PVK file expected");
    }
}
Example 2
Project: xipki-master  File: PrivateKeyCryptor.java View source code
PrivateKey decrypt(final PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) throws P11TokenException {
    ParamUtil.requireNonNull("encryptedPrivateKeyInfo", encryptedPrivateKeyInfo);
    PrivateKeyInfo privateKeyInfo;
    synchronized (decryptorProvider) {
        try {
            privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decryptorProvider);
        } catch (PKCSException ex) {
            throw new P11TokenException(ex.getMessage(), ex);
        }
    }
    AlgorithmIdentifier keyAlg = privateKeyInfo.getPrivateKeyAlgorithm();
    ASN1ObjectIdentifier keyAlgOid = keyAlg.getAlgorithm();
    String algoName;
    if (PKCSObjectIdentifiers.rsaEncryption.equals(keyAlgOid)) {
        algoName = "RSA";
    } else if (X9ObjectIdentifiers.id_dsa.equals(keyAlgOid)) {
        algoName = "DSA";
    } else if (X9ObjectIdentifiers.id_ecPublicKey.equals(keyAlgOid)) {
        algoName = "EC";
    } else {
        throw new P11TokenException("unknown private key algorithm " + keyAlgOid.getId());
    }
    try {
        KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance(algoName, "BC");
        return keyFactory.generatePrivate(keySpec);
    } catch (IOExceptionNoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException |  ex) {
        throw new P11TokenException(ex.getClass().getName() + ": " + ex.getMessage(), ex);
    }
}
Example 3
Project: bc-java-master  File: PfxPduTest.java View source code
private PKCS12PfxPdu createPfx(PrivateKey privKey, PublicKey pubKey, X509Certificate[] chain) throws NoSuchAlgorithmException, IOException, PKCSException {
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[2]);
    taCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Primary Certificate"));
    PKCS12SafeBagBuilder caCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[1]);
    caCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Intermediate Certificate"));
    PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[0]);
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key"));
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey));
    PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey, new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwd));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key"));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey));
    //
    // construct the actual key store
    //
    PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder();
    PKCS12SafeBag[] certs = new PKCS12SafeBag[3];
    certs[0] = eeCertBagBuilder.build();
    certs[1] = caCertBagBuilder.build();
    certs[2] = taCertBagBuilder.build();
    pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(passwd), certs);
    pfxPduBuilder.addData(keyBagBuilder.build());
    return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwd);
}
Example 4
Project: BETaaS_Platform-Tools-master  File: PKCS12Utils.java View source code
/**
   * A method to load BcCredential (consists of certificate chain, end entity 
   * alias and private key of end entity credential) from the PKCS12 file
   * @param pkcs12FileName: the PKCS12 file name
   * @param keyPasswd: the password of the key credential
   * @return
   * @throws Exception
   */
public static BcCredential loadPKCS12Credential(String pkcs12FileName, char[] keyPasswd, int certType) {
    PKCS12PfxPdu pfxPdu = null;
    //  	if(certType == APPS_CERT){
    //  		log.info("Reading AppStoreCertInter.p12 file");
    //  		InputStream is = PKCS12Utils.class.getResourceAsStream(pkcs12FileName);
    //  		log.info("AppStoreCertInter.p12 file has been converted to InputStream");
    //  		pfxPdu = new PKCS12PfxPdu(Streams.readAll(is));
    //  		log.info("Read the PKCS12PfxPdu...");
    //  	}
    //  	else if(certType == GW_CERT){
    // Try to put the AppStoreCertInter.p12 in the karaf, so no need to read
    // from the resource, e.g. getResourceAsStream
    log.debug("will start loading PKCS12 file...");
    try {
        pfxPdu = new PKCS12PfxPdu(Streams.readAll(new FileInputStream(pkcs12FileName)));
    } catch (FileNotFoundException e) {
        log.error("PKCS12 file: " + pkcs12FileName + " is not found!!");
        e.printStackTrace();
    } catch (IOException e) {
        log.error("IOException in initializing PKCS12PfxPdu...");
        e.printStackTrace();
    }
    log.debug("Loading PKCS12 successfully...");
    //  	}
    try {
        if (!pfxPdu.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), keyPasswd)) {
            log.error("PKCS#12 MAC test failed!");
            return null;
        }
    } catch (PKCSException e) {
        e.printStackTrace();
    }
    ContentInfo[] infos = pfxPdu.getContentInfos();
    InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder().build(keyPasswd);
    String eeAlias = null;
    AsymmetricKeyParameter privCred = null;
    List<X509CertificateHolder> chainList = new ArrayList<X509CertificateHolder>();
    //    log.info("Start iterating over the ContentInfo...");
    for (int i = 0; i != infos.length; i++) {
        if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = null;
            try {
                dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);
            } catch (PKCSException e) {
                log.error("Error in initiating PKCS12SafeBagFactory...");
                e.printStackTrace();
            }
            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            for (int b = 0; b != bags.length; b++) {
                PKCS12SafeBag bag = bags[b];
                X509CertificateHolder certHldr = (X509CertificateHolder) bag.getBagValue();
                chainList.add(certHldr);
                log.debug("Found a certificate and add it to certificate chain...");
            }
        } else {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
            PrivateKeyInfo info;
            AsymmetricKeyParameter privKey = null;
            try {
                info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
                privKey = PrivateKeyFactory.createKey(info);
            } catch (PKCSException e) {
                log.error("Error in getting the decrypt private key info...");
                e.printStackTrace();
            } catch (IOException e) {
                log.error("Error in loading private key...");
                e.printStackTrace();
            }
            Attribute[] attributes = bags[0].getAttributes();
            for (int a = 0; a != attributes.length; a++) {
                Attribute attr = attributes[a];
                if (attr.getAttrType().equals(PKCS12SafeBag.friendlyNameAttribute)) {
                    eeAlias = ((DERBMPString) attr.getAttributeValues()[0]).getString();
                    privCred = privKey;
                    log.debug("Get end entity alias");
                    log.debug("Priv. credential D: " + ((ECPrivateKeyParameters) privCred).getD().toString());
                }
            }
        }
    }
    X509CertificateHolder[] chain = new X509CertificateHolder[chainList.size()];
    chain = (X509CertificateHolder[]) chainList.toArray(chain);
    BcCredential cred = new BcCredential(eeAlias, privCred, chain);
    log.debug("Credential has been loaded!!");
    return cred;
}
Example 5
Project: jruby-openssl-master  File: PKCS10Request.java View source code
// verify
public boolean verify(final PublicKey publicKey) throws InvalidKeyException {
    if (signedRequest == null) {
        if (true)
            throw new IllegalStateException("no signed request");
        return false;
    }
    try {
        ContentVerifierProvider verifier = new PKCS10VerifierProvider(publicKey);
        return signedRequest.isSignatureValid(verifier);
    } catch (PKCSException e) {
        throw new InvalidKeyException(e);
    }
}
Example 6
Project: box-java-sdk-master  File: BoxDeveloperEditionAPIConnection.java View source code
private PrivateKey decryptPrivateKey() {
    PrivateKey decryptedPrivateKey = null;
    try {
        PEMParser keyReader = new PEMParser(new StringReader(this.privateKey));
        Object keyPair = keyReader.readObject();
        keyReader.close();
        if (keyPair instanceof PEMEncryptedKeyPair) {
            JcePEMDecryptorProviderBuilder builder = new JcePEMDecryptorProviderBuilder();
            PEMDecryptorProvider decryptionProvider = builder.build(this.privateKeyPassword.toCharArray());
            keyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProvider);
            PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        } else if (keyPair instanceof PKCS8EncryptedPrivateKeyInfo) {
            InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider("BC").build(this.privateKeyPassword.toCharArray());
            PrivateKeyInfo keyInfo = ((PKCS8EncryptedPrivateKeyInfo) keyPair).decryptPrivateKeyInfo(pkcs8Prov);
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        } else {
            PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        }
    } catch (IOException e) {
        throw new BoxAPIException("Error parsing private key for Box Developer Edition.", e);
    } catch (OperatorCreationException e) {
        throw new BoxAPIException("Error parsing PKCS#8 private key for Box Developer Edition.", e);
    } catch (PKCSException e) {
        throw new BoxAPIException("Error parsing PKCS private key for Box Developer Edition.", e);
    }
    return decryptedPrivateKey;
}
Example 7
Project: canl-java-master  File: CertificateUtils.java View source code
private static PrivateKey convertToPrivateKey(Object pemObject, String type, PasswordSupplier pf) throws IOException {
    PrivateKeyInfo pki;
    try {
        pki = resolvePK(type, pemObject, pf);
    } catch (OperatorCreationException e) {
        throw new IOException("Can't initialize decryption infrastructure", e);
    } catch (PKCSException e) {
        throw new IOException("Error decrypting private key: the password is " + "incorrect or the " + type + " data is corrupted.", e);
    }
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
    return converter.getPrivateKey(pki);
}
Example 8
Project: irma_future_id-master  File: PfxPduTest.java View source code
private PKCS12PfxPdu createPfx(PrivateKey privKey, PublicKey pubKey, X509Certificate[] chain) throws NoSuchAlgorithmException, IOException, PKCSException {
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[2]);
    taCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Primary Certificate"));
    PKCS12SafeBagBuilder caCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[1]);
    caCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Intermediate Certificate"));
    PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[0]);
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key"));
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey));
    PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey, new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwd));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key"));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey));
    //
    // construct the actual key store
    //
    PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder();
    PKCS12SafeBag[] certs = new PKCS12SafeBag[3];
    certs[0] = eeCertBagBuilder.build();
    certs[1] = caCertBagBuilder.build();
    certs[2] = taCertBagBuilder.build();
    pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(passwd), certs);
    pfxPduBuilder.addData(keyBagBuilder.build());
    return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwd);
}