Example usage for org.bouncycastle.cert X509CertificateHolder getExtensions

List of usage examples for org.bouncycastle.cert X509CertificateHolder getExtensions

Introduction

In this page you can find the example usage for org.bouncycastle.cert X509CertificateHolder getExtensions.

Prototype

public Extensions getExtensions() 

Source Link

Document

Return the extensions block associated with this certificate if there is one.

Usage

From source file:co.runrightfast.core.security.cert.impl.CertificateServiceImplTest.java

License:Apache License

private void checkAuthorityKeyIdentifierExtenstion(final X509Certificate cert, final CaCert caCert)
        throws CertificateEncodingException, IOException {
    final JcaX509ExtensionUtils extUtils = jcaX509ExtensionUtils();
    final byte[] extValue = cert.getExtensionValue(OID.AUTHORITY_KEY_IDENIFIER.oid.getId());
    assertThat(extValue, is(notNullValue()));
    final byte[] expectedExtValue = X509CertExtension.builder().oid(Extension.authorityKeyIdentifier)
            .value(extUtils.createAuthorityKeyIdentifier(caCert.getCert())).critical(false).build()
            .toExtension().getExtnValue().getEncoded(DER.name());
    assertThat(Arrays.areEqual(extValue, expectedExtValue), is(true));

    final X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert);
    final Extension ext = certHolder.getExtensions().getExtension(OID.AUTHORITY_KEY_IDENIFIER.oid);
    assertThat(ext, is(notNullValue()));
    assertThat(Arrays.areEqual(ext.getExtnValue().getEncoded(DER.name()), expectedExtValue), is(true));
}

From source file:co.runrightfast.core.security.cert.impl.CertificateServiceImplTest.java

License:Apache License

private void checkSubjectKeyIdentifierExtenstion(final X509Certificate cert)
        throws CertificateEncodingException, IOException {
    final JcaX509ExtensionUtils extUtils = jcaX509ExtensionUtils();
    final byte[] extValue = cert.getExtensionValue(OID.SUBJECT_KEY_IDENIFIER.oid.getId());
    assertThat(extValue, is(notNullValue()));
    final byte[] expectedExtValue = X509CertExtension.builder().oid(Extension.subjectKeyIdentifier)
            .value(extUtils.createSubjectKeyIdentifier(cert.getPublicKey())).critical(false).build()
            .toExtension().getExtnValue().getEncoded(DER.name());
    assertThat(Arrays.areEqual(extValue, expectedExtValue), is(true));

    final X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert);
    final Extension ext = certHolder.getExtensions().getExtension(OID.SUBJECT_KEY_IDENIFIER.oid);
    assertThat(ext, is(notNullValue()));
    assertThat(Arrays.areEqual(ext.getExtnValue().getEncoded(DER.name()), expectedExtValue), is(true));
}

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  w w w .j  a v a 2 s. co m
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:edu.nps.moves.mmowgli.CACManager.java

License:Open Source License

private static void parseCert(String cert, CACData data) {
    cert = cert.replace(' ', '\r');
    cert = cert.replace("BEGIN\rCERTIFICATE", "BEGIN CERTIFICATE");
    cert = cert.replace("END\rCERTIFICATE", "END CERTIFICATE");
    PEMParser pr = new PEMParser(new StringReader(cert));
    try {//from ww w.j a v a 2 s.co  m
        Object o = pr.readObject();
        pr.close();
        if (o instanceof X509CertificateHolder) {
            X509CertificateHolder x509 = (X509CertificateHolder) o;
            X500Name x500name = x509.getSubject();
            RDN cnRdns[] = x500name.getRDNs(BCStyle.CN);

            String cn = IETFUtils.valueToString(cnRdns[0].getFirst().getValue());
            parseCN(cn, data);

            GeneralNames gns = GeneralNames.fromExtensions(x509.getExtensions(),
                    Extension.subjectAlternativeName);
            if (gns != null) {
                GeneralName[] subjectAltNames = gns.getNames();
                for (GeneralName gn : subjectAltNames) {
                    if (gn.getTagNo() == GeneralName.rfc822Name) { // check for email
                        String s = DERIA5String.getInstance(gn.getName()).getString();
                        if (s.contains("@")) {
                            data.userEmail = s;
                            break;
                        }
                    }
                }
            }

            // Create the unique card identifier (issuer+serial) which when hashed goes into the database for quick login
            String uniqueCertId = x509.getIssuer().toString() + " " + x509.getSerialNumber().toString();

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(uniqueCertId.getBytes("UTF-8")); // or UTF-16
            byte[] digest = md.digest();
            data.cacId = Hex.encodeHexString(digest);

            /* Alternatively, this will do a salted hash, but the output is not the same for the same input; better security
             * but the login performance would be bad since the user list has to be polled instead of indexed
             try {
               data.cacId = PasswordHash.createHash(uniqueCertId);
             }
             catch(Exception ex) {
               MSysOut.println(MmowgliConstants.SYSTEM_LOGS,"Program error, could not create CAC hash; auto-login disabled");
               data.cacId = null;
             }
             System.out.println("data cacId: "+data.cacId); */

        }
    } catch (IOException | NoSuchAlgorithmException ex) {
        MSysOut.println(MmowgliConstants.SYSTEM_LOGS,
                ex.getClass().getSimpleName() + ": Program error, could not parse CAC");
        data.cacId = null;
        data.isCACPresent = false;
    }

    // Some informational stuff
    /* this gives same info as the x509 methods below  
         RDN rdns[] = x500name.getRDNs();
         for(RDN rdn : rdns) {
            AttributeTypeAndValue[] tandV = rdn.getTypesAndValues();
            for(AttributeTypeAndValue tv : tandV) {
     System.out.println(tv.getType());
     System.out.println(IETFUtils.valueToString(tv.getType()));
     System.out.println(tv.getValue());
     System.out.println(IETFUtils.valueToString(tv.getValue()));
            }
         }
         */
    /*
    System.out.println("X509 version: "+x509.getVersionNumber());
    System.out.println("X509 Serial num: "+x509.getSerialNumber());
    System.out.println("X509 Sig algo: "+x509.getSignatureAlgorithm().getAlgorithm().toASN1Primitive());
    System.out.println("X509 Issuer: "+x509.getIssuer());
    System.out.println("X509 Not before: "+x509.getNotBefore());
    System.out.println("X509 Not after: "+x509.getNotAfter());
    System.out.println("X509 Subject: "+x509.getSubject());
    System.out.println("X509 Subject Public Key Info: "+x509.getSubjectPublicKeyInfo().getAlgorithm().getAlgorithm());
    */
    /* 
     System.out.println("CriticalExtensionOIDs: ");
     Set<?> set = x509.getCriticalExtensionOIDs();
     Iterator<?> itr = set.iterator();
     while(itr.hasNext()) {
       ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)itr.next();
       System.out.println(oid.toString()+" : "+x509.getExtension(oid).getParsedValue());
     }
               
     System.out.println("NonCriticalExtensionOIDs: ");
     set = x509.getNonCriticalExtensionOIDs();
     itr = set.iterator();
     while(itr.hasNext()) {
       ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)itr.next();
       System.out.println(oid.toString()+" : "+x509.getExtension(oid).getParsedValue());
     }
             
     System.out.println("Other api: getExtensionOIDs");
     List<?> lis = x509.getExtensionOIDs();
     itr = lis.iterator();
     while(itr.hasNext()) {
       ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)itr.next();
       System.out.println(oid.toString()+" : "+x509.getExtension(oid).getParsedValue());
     }
            
     System.out.println("From the extensions \"block\"");
     Extensions exts = x509.getExtensions();
     ASN1ObjectIdentifier[] ids = exts.getExtensionOIDs();
     for(ASN1ObjectIdentifier oid : ids) {
       org.bouncycastle.asn1.x509.Extension ext = exts.getExtension(oid);
       System.out.println(oid.toString()+": "+IETFUtils.valueToString(ext.getParsedValue()));
     }
    //     */
}

From source file:eu.betaas.taas.securitymanager.authentication.service.impl.GWEcmqvExtService.java

License:Apache License

public EcmqvMessage initEcmqv(byte[] ephPubX, byte[] ephPubY, byte[] certByte) {
    // decode the certificate
    X509CertificateHolder cert = null;
    try {//from w  w w. ja v  a 2  s .co  m
        cert = new X509CertificateHolder(certByte);
    } catch (IOException e1) {
        log.error("Error in decoding the submitted certificate!!");
        e1.printStackTrace();
    }

    // validate the certificate
    boolean isCertValid = false;

    try {
        isCertValid = validateCert(cert);
    } catch (Exception e) {
        log.error("Error in verifying the submitted certificate: " + e.getMessage());
        e.printStackTrace();
    }

    if (!isCertValid) {
        log.error("The submitted certificate is not valid!!");
        return null;
    }
    log.debug("Passed the certificate validation!!");

    // decode the ephemeral public key
    try {
        ephPub = ECKeyPairGen.generateECPublicKey192(new BigInteger(ephPubX), new BigInteger(ephPubY));
    } catch (Exception e) {
        log.error("Error in decoding the submitted ephemeral public key: " + e.getMessage());
        e.printStackTrace();
    }

    // perform embedded public key validation
    boolean pubValid = ECMQVUtils.validateEmbedPubKey(ephPub);
    if (!pubValid) {
        log.error("The submitted ephemeral public key is not valid!!");
        return null;
    }
    log.debug("Passed the embedded ephemeral public key validation!!");

    // generates its own ephemeral key pairs, we assume that in this stage the 
    // ephemeral key pairs were not generated
    AsymmetricCipherKeyPair myEphKp = ECKeyPairGen.generateECKeyPair192();

    myEphPub = (ECPublicKeyParameters) myEphKp.getPublic();
    myEphPriv = (ECPrivateKeyParameters) myEphKp.getPrivate();

    // computes the implicit signature --> the static private key was obtained
    // when we validate the certificate (upon loading the KeyStore)
    BigInteger implSig = ECMQVUtils.computeImplicitSig(myEphPub, myEphPriv, statPriv);

    // calculates the shared key K
    ECPoint K = null;
    try {
        K = ECMQVUtils.calculateSharedKey(ephPub,
                (ECPublicKeyParameters) PublicKeyFactory.createKey(cert.getSubjectPublicKeyInfo()),
                ephPub.getParameters().getH(), implSig);
    } catch (IOException e) {
        log.error("Error in calculating the shared key K: " + e.getMessage());
        e.printStackTrace();
    }

    // derive 2 symmetric keys from the shared key K
    byte[] Kx = K.normalize().getXCoord().toBigInteger().toByteArray();
    int Lx = K.normalize().getXCoord().toBigInteger().bitLength();
    double x = Math.log(Lx) / Math.log(2.0);
    double L = Math.pow(2, 1 + Math.ceil(x));

    byte[] deriveK = ECMQVUtils.deriveKeyHKDF(Kx, (int) L / 8);

    // k1 and k2 split from newKey --> k1: to be MACed, k2: the session key
    k1 = new byte[deriveK.length / 2];
    k2 = new byte[deriveK.length / 2];
    int c = 0;
    for (byte b : deriveK) {
        if (c < deriveK.length / 2) {
            k1[c] = b;
        } else {
            k2[c - deriveK.length / 2] = b;
        }
        c++;
    }

    // retrieving my user friendly name from the SubjectAlternativeNames in my 
    // certificate
    Extensions myExs = myCert.getExtensions();
    if (myExs != null) {
        GeneralNames gns = GeneralNames.fromExtensions(myExs, Extension.subjectAlternativeName);
        for (int i = 0; i < gns.getNames().length; i++) {
            myUFN = gns.getNames()[i].getName().toString();
        }
    }

    // retrieving other GW user friendly name from the SubjectAlternativeNames 
    // in the submitted certificate
    Extensions oExs = cert.getExtensions();
    if (oExs != null) {
        GeneralNames gns = GeneralNames.fromExtensions(oExs, Extension.subjectAlternativeName);
        for (int i = 0; i < gns.getNames().length; i++) {
            ufn = gns.getNames()[i].getName().toString();
        }
    }

    // compute the MAC to be sent to the other gateway
    byte[] myMac = ECMQVUtils.computeMAC("2", myUFN, ufn, myEphPub.getQ().getEncoded(),
            ephPub.getQ().getEncoded(), k1);

    EcmqvMessage eMsg = new EcmqvMessage();
    eMsg.setMyMac(myMac);
    try {
        eMsg.setMyCertificate(myCert.getEncoded());
    } catch (IOException e) {
        log.error("Error in encoding the certificate: " + e.getMessage());
        e.printStackTrace();
    }

    eMsg.setEphemeralPublicX(myEphPub.getQ().normalize().getXCoord().toBigInteger().toByteArray());
    eMsg.setEphemeralPublicY(myEphPub.getQ().normalize().getXCoord().toBigInteger().toByteArray());

    return eMsg;
}

From source file:eu.betaas.taas.securitymanager.authentication.service.impl.GWEcmqvIntService.java

License:Apache License

public byte[] responseEcmqv(EcmqvMessage eMsg) throws Exception {
    // decode the certificate
    X509CertificateHolder cert = new X509CertificateHolder(eMsg.getMyCertificate());

    // decode the ECPublicKey
    ECPublicKeyParameters ephPub = ECKeyPairGen.generateECPublicKey192(
            new BigInteger(eMsg.getEphemeralPublicX()), new BigInteger(eMsg.getEphemeralPublicY()));
    // get the MAC 2
    byte[] mac2 = eMsg.getMyMac();

    // validate the certificate
    boolean isCertValid = false;
    isCertValid = validateCert(cert);/*from   w  w  w.ja  v  a2 s.  c om*/

    if (!isCertValid) {
        log.error("The submitted certificate is not valid!!");
        return null;
    }
    log.debug("Passed the certificate validation!!");

    // perform embedded public key validation
    boolean pubValid = ECMQVUtils.validateEmbedPubKey(ephPub);
    if (!pubValid) {
        log.error("The submitted ephemeral public key is not valid!!");
        return null;
    }
    log.debug("Passed the embedded ephemeral public key validation!!");
    // set the ephPub with this received ephPub
    this.ephPub = ephPub;

    // now, no need to generate my own ephemeral key here, because it is done
    // compute the implicit signature
    BigInteger implSig = ECMQVUtils.computeImplicitSig(myEphPub, myEphPriv, statPriv);

    // calculates the shared key K
    ECPublicKeyParameters statPub = (ECPublicKeyParameters) PublicKeyFactory
            .createKey(cert.getSubjectPublicKeyInfo());
    org.bouncycastle.math.ec.ECPoint K = ECMQVUtils.calculateSharedKey(this.ephPub, statPub,
            this.ephPub.getParameters().getH(), implSig);

    // derive 2 symmetric keys from the shared key K
    byte[] Kx = K.normalize().getXCoord().toBigInteger().toByteArray();
    int Lx = K.normalize().getXCoord().toBigInteger().bitLength();
    double x = Math.log(Lx) / Math.log(2.0);
    double L = Math.pow(2, 1 + Math.ceil(x));

    byte[] deriveK = ECMQVUtils.deriveKeyHKDF(Kx, (int) L / 8);

    // k1 and k2 split from newKey --> k1: to be MACed, k2: the session key
    k1 = new byte[deriveK.length / 2];
    k2 = new byte[deriveK.length / 2];
    int c = 0;
    for (byte b : deriveK) {
        if (c < deriveK.length / 2) {
            k1[c] = b;
        } else {
            k2[c - deriveK.length / 2] = b;
        }
        c++;
    }

    // retrieving my user friendly name from the SubjectAlternativeNames in my 
    // certificate
    Extensions myExs = myCert.getExtensions();
    if (myExs != null) {
        GeneralNames gns = GeneralNames.fromExtensions(myExs, Extension.subjectAlternativeName);
        for (int i = 0; i < gns.getNames().length; i++) {
            myUFN = gns.getNames()[i].getName().toString();
        }
    }

    // retrieving other GW user friendly name from the SubjectAlternativeNames 
    // in the submitted certificate
    Extensions oExs = cert.getExtensions();
    if (oExs != null) {
        GeneralNames gns = GeneralNames.fromExtensions(oExs, Extension.subjectAlternativeName);
        for (int i = 0; i < gns.getNames().length; i++) {
            ufn = gns.getNames()[i].getName().toString();
        }
    }

    // validate MAC 2, which is received from other GW
    boolean isMac2Valid = verifyMac2(mac2, ufn, myUFN, this.ephPub, myEphPub, k1);

    // compute the MAC to be sent to the other gateway
    if (!isMac2Valid) {
        log.error("Fails to verify the received MAC (2)!!");
        return null;
    }
    log.debug("Successfully verifies the received MAC (2)!!");

    byte[] mac3 = ECMQVUtils.computeMAC("3", myUFN, ufn, myEphPub.getQ().getEncoded(),
            ephPub.getQ().getEncoded(), k1);

    return mac3;
}

From source file:net.maritimecloud.pki.ocsp.OCSPClient.java

License:Open Source License

public CertStatus getCertificateStatus() throws OCSPValidationException {
    try {//w w w.  j  a va 2 s.c o m
        if (null == url) {
            throw new OCSPValidationException("Certificate not validated by OCSP");
        }

        byte[] encodedOcspRequest = generateOCSPRequest(issuer, certificate.getSerialNumber()).getEncoded();

        HttpURLConnection httpConnection;
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestProperty("Content-Type", "application/ocsp-request");
        httpConnection.setRequestProperty("Accept", "application/ocsp-response");
        httpConnection.setDoOutput(true);

        try (DataOutputStream dataOut = new DataOutputStream(
                new BufferedOutputStream(httpConnection.getOutputStream()))) {
            dataOut.write(encodedOcspRequest);
            dataOut.flush();
        }

        InputStream in = (InputStream) httpConnection.getContent();

        if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new OCSPValidationException(
                    "Received HTTP code != 200 [" + httpConnection.getResponseCode() + "]");
        }

        OCSPResp ocspResponse = new OCSPResp(in);
        BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        byte[] receivedNonce = basicResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnId()
                .getEncoded();
        if (!Arrays.equals(receivedNonce, sentNonce)) {
            throw new OCSPValidationException("Nonce in ocsp response does not match nonce of ocsp request");
        }

        X509CertificateHolder certHolder = basicResponse.getCerts()[0];
        if (!basicResponse
                .isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) {
            if (!certHolder.isValidOn(Date.from(Instant.now()))) {
                throw new OCSPValidationException("Certificate is not valid today!");
            }
            // Certificate must have a Key Purpose ID for authorized responders
            if (!ExtendedKeyUsage.fromExtensions(certHolder.getExtensions())
                    .hasKeyPurposeId(KeyPurposeId.id_kp_OCSPSigning)) {
                throw new OCSPValidationException(
                        "Certificate does not contain required extension (id_kp_OCSPSigning)");
            }
            // Certificate must be issued by the same CA of the certificate that we are verifying
            if (!certHolder.isSignatureValid(
                    new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) {
                throw new OCSPValidationException("Certificate is not signed by the same issuer");
            }
            // Validate signature in OCSP response
            if (!basicResponse.isSignatureValid(
                    new JcaContentVerifierProviderBuilder().setProvider("BC").build(certHolder))) {
                throw new OCSPValidationException("Could not validate OCSP response!");
            }
        } else {
            if (!certHolder.isValidOn(Date.from(Instant.now()))) {
                throw new OCSPValidationException("Certificate is not valid today!");
            }
        }

        // SCEE Certificate Policy (?)
        /*if (null == certHolder.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck) || null == certHolder.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck).getExtnId()) {
        throw new OCSPValidationException("Extension id_pkix_ocsp_nocheck not found in certificate");
        }*/

        SingleResp[] responses = basicResponse.getResponses();
        if (responses[0].getCertID().getSerialNumber().equals(certificate.getSerialNumber())) {
            CertificateStatus status = responses[0].getCertStatus();
            if (status == CertificateStatus.GOOD) {
                return CertStatus.GOOD;
            } else {

                if (status instanceof RevokedStatus) {
                    revokedStatus = (RevokedStatus) status;
                    return CertStatus.REVOKED;
                } else {
                    return CertStatus.UNKNOWN;
                }
            }
        } else {
            throw new OCSPValidationException(
                    "Serial number of certificate in response ocsp does not match certificate serial number");
        }
    } catch (CertificateEncodingException | OperatorCreationException | OCSPException | IOException ex) {
        throw new OCSPValidationException("Unable to perform validation through OCSP ("
                + certificate.getSubjectX500Principal().getName() + ")", ex);
    } catch (CertException | CertificateException ex) {
        throw new OCSPValidationException("Unable to perform validation through OCSP ("
                + certificate.getSubjectX500Principal().getName() + ")", ex);
    }
}

From source file:org.cryptable.pki.communication.PKICMPMessages.java

License:Open Source License

/**
 * Update a certification request with local key generation
 *
 * @param certificate to be updated/*  w w  w.  j  ava  2 s  .c o m*/
 * @return return the binary ASN.1 message for a certification request
 * @throws CertificateEncodingException
 * @throws CMSException
 * @throws CRMFException
 * @throws OperatorCreationException
 * @throws CMPException
 * @throws IOException
 */
public byte[] createKeyUpdateMessageWithLocalKey(X509Certificate certificate, KeyPair keyPair)
        throws CertificateEncodingException, CMSException, CRMFException, OperatorCreationException,
        CMPException, IOException, PKICMPMessageException, NoSuchFieldException, IllegalAccessException {
    JcaCertificateRequestMessageBuilder certReqBuild = new JcaCertificateRequestMessageBuilder(BigInteger.ZERO);
    X509CertificateHolder x509CertificateHolder = new JcaX509CertificateHolder(certificate);

    certReqBuild.setSubject(x509CertificateHolder.getSubject());
    certReqBuild.setIssuer(x509CertificateHolder.getIssuer());
    certReqBuild.setSerialNumber(x509CertificateHolder.getSerialNumber());
    if (keyPair != null) {
        certReqBuild.setPublicKey(keyPair.getPublic());
        if (keyPair.getPrivate() != null) {
            certReqBuild.addControl(
                    new JcaPKIArchiveControlBuilder(keyPair.getPrivate(), x509CertificateHolder.getIssuer())
                            .addRecipientGenerator(
                                    new JceKeyTransRecipientInfoGenerator(pkiKeyStore.getRecipientCertificate())
                                            .setProvider(pkiKeyStore.getProvider()))
                            .build(new JceCMSContentEncryptorBuilder(
                                    new ASN1ObjectIdentifier(CMSEnvelopedDataGenerator.DES_EDE3_CBC))
                                            .setProvider(pkiKeyStore.getProvider()).build()));

        }
    } else
        certReqBuild.setPublicKey(x509CertificateHolder.getSubjectPublicKeyInfo());

    if (extensions != null) {
        for (Extension extension : extensions)
            certReqBuild.addExtension(extension.getExtnId(), extension.isCritical(),
                    extension.getParsedValue());
    } else {
        if (x509CertificateHolder.getExtensions() != null) {
            for (ASN1ObjectIdentifier oid : x509CertificateHolder.getExtensions().getExtensionOIDs()) {
                certReqBuild.addExtension(oid,
                        x509CertificateHolder.getExtensions().getExtension(oid).isCritical(),
                        x509CertificateHolder.getExtensions().getExtensionParsedValue(oid));
            }
        }
    }

    OptionalValidity tempOptionalValidity;
    if (optionalValidity != null) {
        tempOptionalValidity = optionalValidity;
    } else {
        tempOptionalValidity = new OptionalValidity(new Time(x509CertificateHolder.getNotBefore()),
                new Time(x509CertificateHolder.getNotAfter()));
    }
    Field field = certReqBuild.getClass().getSuperclass().getDeclaredField("templateBuilder");
    field.setAccessible(true);
    CertTemplateBuilder certTemplateBuilder = (CertTemplateBuilder) field.get(certReqBuild);
    certTemplateBuilder.setValidity(tempOptionalValidity);

    CertReqMessages certReqMsgs = new CertReqMessages(certReqBuild.build().toASN1Structure());

    return createProtectedPKIMessage(new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, certReqMsgs));
}

From source file:org.cryptable.pki.communication.PKICMPMessages.java

License:Open Source License

/**
 * Update a certification request with remote key generation
 *
 * @param certificate to be updated/* w  w  w. j av  a  2s  . c o m*/
 * @return return the binary ASN.1 message for a certification request
 * @throws CertificateEncodingException
 * @throws CMSException
 * @throws CRMFException
 * @throws OperatorCreationException
 * @throws CMPException
 * @throws IOException
 */
public byte[] createKeyUpdateMessageWithRemoteKey(X509Certificate certificate)
        throws CertificateEncodingException, CMSException, CRMFException, OperatorCreationException,
        CMPException, IOException, PKICMPMessageException, NoSuchFieldException, IllegalAccessException {
    JcaCertificateRequestMessageBuilder certReqBuild = new JcaCertificateRequestMessageBuilder(BigInteger.ZERO);
    X509CertificateHolder x509CertificateHolder = new JcaX509CertificateHolder(certificate);

    certReqBuild.setSubject(x509CertificateHolder.getSubject());
    certReqBuild.setIssuer(x509CertificateHolder.getIssuer());
    certReqBuild.setSerialNumber(x509CertificateHolder.getSerialNumber());

    if (extensions != null) {
        for (Extension extension : extensions)
            certReqBuild.addExtension(extension.getExtnId(), extension.isCritical(),
                    extension.getParsedValue());
    } else {
        if (x509CertificateHolder.getExtensions() != null) {
            for (ASN1ObjectIdentifier oid : x509CertificateHolder.getExtensions().getExtensionOIDs()) {
                certReqBuild.addExtension(oid,
                        x509CertificateHolder.getExtensions().getExtension(oid).isCritical(),
                        x509CertificateHolder.getExtensions().getExtensionParsedValue(oid));
            }
        }
    }

    OptionalValidity tempOptionalValidity;
    if (optionalValidity != null) {
        tempOptionalValidity = optionalValidity;
    } else {
        tempOptionalValidity = new OptionalValidity(new Time(x509CertificateHolder.getNotBefore()),
                new Time(x509CertificateHolder.getNotAfter()));
    }
    Field field = certReqBuild.getClass().getSuperclass().getDeclaredField("templateBuilder");
    field.setAccessible(true);
    CertTemplateBuilder certTemplateBuilder = (CertTemplateBuilder) field.get(certReqBuild);
    certTemplateBuilder.setValidity(tempOptionalValidity);

    CertReqMessages certReqMsgs = new CertReqMessages(certReqBuild.build().toASN1Structure());

    return createProtectedPKIMessage(new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, certReqMsgs));
}

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  ww w.  ja v a2s .c  o  m
        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);
    }
}