Example usage for java.security.cert X509Certificate getIssuerX500Principal

List of usage examples for java.security.cert X509Certificate getIssuerX500Principal

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getIssuerX500Principal.

Prototype

public X500Principal getIssuerX500Principal() 

Source Link

Document

Returns the issuer (issuer distinguished name) value from the certificate as an X500Principal .

Usage

From source file:org.apache.ws.security.handler.WSHandler.java

/**
 * Evaluate whether a given certificate should be trusted.
 * Hook to allow subclasses to implement custom validation methods however they see fit.
 * <p/>/*from www .j av a 2s.c o  m*/
 * Policy used in this implementation:
 * 1. Search the keystore for the transmitted certificate
 * 2. Search the keystore for a connection to the transmitted certificate
 * (that is, search for certificate(s) of the issuer of the transmitted certificate
 * 3. Verify the trust path for those certificates found because the search for the issuer 
 * might be fooled by a phony DN (String!)
 *
 * @param cert the certificate that should be validated against the keystore
 * @return true if the certificate is trusted, false if not (AxisFault is thrown for exceptions
 * during CertPathValidation)
 * @throws WSSecurityException
 */
protected boolean verifyTrust(X509Certificate cert, RequestData reqData) throws WSSecurityException {

    // If no certificate was transmitted, do not trust the signature
    if (cert == null) {
        return false;
    }

    String[] aliases = null;
    String alias = null;
    X509Certificate[] certs;

    String subjectString = cert.getSubjectX500Principal().getName();
    String issuerString = cert.getIssuerX500Principal().getName();
    BigInteger issuerSerial = cert.getSerialNumber();

    if (doDebug) {
        log.debug("WSHandler: Transmitted certificate has subject " + subjectString);
        log.debug("WSHandler: Transmitted certificate has issuer " + issuerString + " (serial " + issuerSerial
                + ")");
    }

    // FIRST step
    // Search the keystore for the transmitted certificate

    // Search the keystore for the alias of the transmitted certificate
    try {
        alias = reqData.getSigCrypto().getAliasForX509Cert(issuerString, issuerSerial);
    } catch (WSSecurityException ex) {
        throw new WSSecurityException("WSHandler: Could not get alias for certificate with " + subjectString,
                ex);
    }

    if (alias != null) {
        // Retrieve the certificate for the alias from the keystore
        try {
            certs = reqData.getSigCrypto().getCertificates(alias);
        } catch (WSSecurityException ex) {
            throw new WSSecurityException("WSHandler: Could not get certificates for alias " + alias, ex);
        }

        // If certificates have been found, the certificates must be compared
        // to ensure against phony DNs (compare encoded form including signature)
        if (certs != null && certs.length > 0 && cert.equals(certs[0])) {
            if (doDebug) {
                log.debug("Direct trust for certificate with " + subjectString);
            }
            return true;
        }
    } else {
        if (doDebug) {
            log.debug("No alias found for subject from issuer with " + issuerString + " (serial " + issuerSerial
                    + ")");
        }
    }

    // SECOND step
    // Search for the issuer of the transmitted certificate in the keystore

    // Search the keystore for the alias of the transmitted certificates issuer
    try {
        aliases = reqData.getSigCrypto().getAliasesForDN(issuerString);
    } catch (WSSecurityException ex) {
        throw new WSSecurityException("WSHandler: Could not get alias for certificate with " + issuerString,
                ex);
    }

    // If the alias has not been found, the issuer is not in the keystore
    // As a direct result, do not trust the transmitted certificate
    if (aliases == null || aliases.length < 1) {
        if (doDebug) {
            log.debug("No aliases found in keystore for issuer " + issuerString + " of certificate for "
                    + subjectString);
        }
        return false;
    }

    // THIRD step
    // Check the certificate trust path for every alias of the issuer found in the keystore
    for (int i = 0; i < aliases.length; i++) {
        alias = aliases[i];

        if (doDebug) {
            log.debug("Preparing to validate certificate path with alias " + alias + " for issuer "
                    + issuerString);
        }

        // Retrieve the certificate(s) for the alias from the keystore
        try {
            certs = reqData.getSigCrypto().getCertificates(alias);
        } catch (WSSecurityException ex) {
            throw new WSSecurityException("WSHandler: Could not get certificates for alias " + alias, ex);
        }

        // If no certificates have been found, there has to be an error:
        // The keystore can find an alias but no certificate(s)
        if (certs == null || certs.length < 1) {
            throw new WSSecurityException("WSHandler: Could not get certificates for alias " + alias);
        }

        // Form a certificate chain from the transmitted certificate
        // and the certificate(s) of the issuer from the keystore
        // First, create new array
        X509Certificate[] x509certs = new X509Certificate[certs.length + 1];
        // Then add the first certificate ...
        x509certs[0] = cert;
        // ... and the other certificates
        for (int j = 0; j < certs.length; j++) {
            x509certs[j + 1] = certs[j];
        }
        certs = x509certs;

        // Use the validation method from the crypto to check whether the subjects' 
        // certificate was really signed by the issuer stated in the certificate
        try {
            if (reqData.getSigCrypto().validateCertPath(certs)) {
                if (doDebug) {
                    log.debug("WSHandler: Certificate path has been verified for certificate " + "with subject "
                            + subjectString);
                }
                return true;
            }
        } catch (WSSecurityException ex) {
            throw new WSSecurityException("WSHandler: Certificate path verification failed for certificate "
                    + "with subject " + subjectString, ex);
        }
    }

    if (doDebug) {
        log.debug("WSHandler: Certificate path could not be verified for " + "certificate with subject "
                + subjectString);
    }
    return false;
}

From source file:org.texai.x509.X509Utils.java

/** Generates a signed end-use certificate that cannot be used to sign other certificates, but can be used for authentication
 * and for message signing.//ww  w . j av  a  2s  .c  o  m
 *
 * @param myPublicKey the public key for this certificate
 * @param issuerPrivateKey the issuer's private key
 * @param issuerCertificate the issuer's certificate
 * @param uid the subject UID
 * @param domainComponent the domain component, e.g. TexaiLauncher or NodeRuntime
 * @return a signed end-use certificate
 *
 * @throws CertificateParsingException when the certificate cannot be parsed
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 */
public static X509Certificate generateX509Certificate(final PublicKey myPublicKey,
        final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid,
        final String domainComponent)
        throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert myPublicKey != null : "myPublicKey must not be null";
    assert issuerPrivateKey != null : "issuerPrivateKey must not be null";
    assert issuerCertificate != null : "issuerCertificate must not be null";
    assert uid != null : "uid must not be null";

    final String x500PrincipalString;
    // provide items to X500Principal in reverse order
    if (domainComponent == null || domainComponent.isEmpty()) {
        x500PrincipalString = "UID=" + uid + ", CN=texai.org";
    } else {
        x500PrincipalString = "UID=" + uid + ", DC=" + domainComponent + " ,CN=texai.org";
    }
    final X500Principal x500Principal = new X500Principal(x500PrincipalString);

    LOGGER.info("issuer: " + issuerCertificate.getIssuerX500Principal().getName());

    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
            new X500Name(StringUtils
                    .reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())), // issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            new X500Name(x500Principal.getName()), // subject,
            new SubjectPublicKeyInfo(ASN1Sequence.getInstance(myPublicKey.getEncoded()))); // publicKeyInfo

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    // Add authority key identifier
    x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate));

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(false)); // is not a CA certificate

    // add key usage
    final KeyUsage keyUsage = new KeyUsage(
            // the digitalSignature usage indicates that the subject public key may be used with a digital signature
            // mechanism to support security services other than non-repudiation, certificate signing, or revocation
            // information signing
            KeyUsage.digitalSignature | // the nonRepudiation usage indicates that the subject public key may be used to verify digital signatures
                                        // used to provide a non-repudiation service which protects against the signing entity falsely denying some
                                        // action, excluding certificate or CRL signing
                    KeyUsage.nonRepudiation | // the keyEncipherment usage indicates that the subject public key may be used for key transport, e.g. the
                                              // exchange of efficient symmetric keys in SSL
                    KeyUsage.keyEncipherment | // the dataEncipherment usage indicates that the subject public key may be used for enciphering user data,
                                               // other than cryptographic keys
                    KeyUsage.dataEncipherment | // the keyAgreement usage indicates that the subject public key may be used for key agreement, e.g. when a
                                                // Diffie-Hellman key is to be used for key management
                    KeyUsage.keyAgreement | // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
                                            // certificates
                    KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                           // information
                    KeyUsage.cRLSign | // see http://www.docjar.com/html/api/sun/security/validator/EndEntityChecker.java.html - bit 0 needs to set for SSL
                                       // client authorization
                    KeyUsage.encipherOnly);
    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate x509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey);
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        x509Certificate = makeCanonicalX509Certificate(
                jcaX509CertificateConverter.getCertificate(x509CertificateHolder));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        x509Certificate.checkValidity();
        x509Certificate.verify(issuerCertificate.getPublicKey());
    } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new TexaiException(ex);
    }
    assert x509Certificate.getKeyUsage()[0] : "must have digital signature key usage";

    return x509Certificate;
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

/**
 * Verifies the signature on an enveloped digital signature on a UDDI
 * entity, such as a business, service, tmodel or binding template.
 * <br><Br>/*from   w ww .ja v  a 2  s .  c  om*/
 * It is expected that either the public key of the signing certificate
 * is included within the signature keyinfo section OR that sufficient
 * information is provided in the signature to reference a public key
 * located within the Trust Store provided<br><Br> Optionally, this
 * function also validate the signing certificate using the options
 * provided to the configuration map.
 *
 * @param obj an enveloped signed JAXB object
 * @param OutErrorMessage a human readable error message explaining the
 * reason for failure
 * @return true if the validation passes the signature validation test,
 * and optionally any certificate validation or trust chain validation
 * @throws IllegalArgumentException for null input
 */
public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage)
        throws IllegalArgumentException {
    if (OutErrorMessage == null) {
        OutErrorMessage = new AtomicReference<String>();
        OutErrorMessage.set("");
    }
    if (obj == null) {
        throw new IllegalArgumentException("obj");
    }
    try {
        DOMResult domResult = new DOMResult();
        JAXB.marshal(obj, domResult);

        Document doc = ((Document) domResult.getNode());
        Element docElement = doc.getDocumentElement(); //this is our signed node

        X509Certificate signingcert = getSigningCertificatePublicKey(docElement);

        if (signingcert != null) {
            logger.info(
                    "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString());
            if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) {
                signingcert.checkValidity();
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) {
                logger.info("verifying revocation status via OSCP for X509 public key "
                        + signingcert.getSubjectDN().toString());
                X500Principal issuerX500Principal = signingcert.getIssuerX500Principal();
                logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by "
                        + issuerX500Principal.getName() + ", attempting to retrieve certificate");
                Security.setProperty("ocsp.enable", "false");
                X509Certificate issuer = FindCertByDN(issuerX500Principal);
                if (issuer == null) {
                    OutErrorMessage.set(
                            "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. "
                                    + OutErrorMessage.get());
                    //throw new CertificateException("unable to locate the issuers certificate in the trust store");
                } else {
                    RevocationStatus check = OCSP.check(signingcert, issuer);
                    logger.info("certificate " + signingcert.getSubjectDN().toString()
                            + " revocation status is " + check.getCertStatus().toString() + " reason "
                            + check.getRevocationReason().toString());
                    if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) {
                        OutErrorMessage
                                .set("Certificate status is " + check.getCertStatus().toString() + " reason "
                                        + check.getRevocationReason().toString() + "." + OutErrorMessage.get());

                        //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString());
                    }
                }
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_CRL)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) {
                logger.info("verifying revokation status via CRL for X509 public key "
                        + signingcert.getSubjectDN().toString());

                Security.setProperty("ocsp.enable", "false");
                System.setProperty("com.sun.security.enableCRLDP", "true");

                X509CertSelector targetConstraints = new X509CertSelector();
                targetConstraints.setCertificate(signingcert);
                PKIXParameters params = new PKIXParameters(GetTrustStore());
                params.setRevocationEnabled(true);
                CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                CertPathValidator certPathValidator = CertPathValidator
                        .getInstance(CertPathValidator.getDefaultType());
                CertPathValidatorResult result = certPathValidator.validate(certPath, params);
                try {
                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
                    logger.info("revokation status via CRL PASSED for X509 public key "
                            + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            if (map.containsKey(CHECK_TRUST_CHAIN)
                    && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) {
                logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString());
                try {
                    PKIXParameters params = new PKIXParameters(GetTrustStore());
                    params.setRevocationEnabled(false);
                    CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                    CertPathValidator certPathValidator = CertPathValidator
                            .getInstance(CertPathValidator.getDefaultType());
                    CertPathValidatorResult result = certPathValidator.validate(certPath, params);

                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;

                    TrustAnchor ta = pkixResult.getTrustAnchor();
                    X509Certificate cert = ta.getTrustedCert();

                    logger.info(
                            "trust chain validated X509 public key " + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage);
            if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) {
                //no error message and its cryptographically valid
                return true;
            }
            return false;
        }

        //last chance validation
        logger.info(
                "signature did not have an embedded X509 public key. reverting to user specified certificate");
        //cert wasn't included in the signature, revert to some other means
        KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE));
        URL url = Thread.currentThread().getContextClassLoader()
                .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
        if (url == null) {
            try {
                url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL();
            } catch (Exception x) {
            }
        }
        if (url == null) {
            try {
                url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
            } catch (Exception x) {
            }
        }
        if (url == null) {
            logger.error("");
            OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and"
                    + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get());
            return false;
        }
        KeyStore.PrivateKeyEntry keyEntry = null;

        ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray());

        if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()));
        } else {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray()));
        }

        Certificate origCert = keyEntry.getCertificate();
        if (map.containsKey(CHECK_TIMESTAMPS)) {
            if (origCert.getPublicKey() instanceof X509Certificate) {
                X509Certificate x = (X509Certificate) origCert.getPublicKey();
                x.checkValidity();
            }
        }
        PublicKey validatingKey = origCert.getPublicKey();
        return verifySignature(docElement, validatingKey, OutErrorMessage);
    } catch (Exception e) {
        //throw new RuntimeException(e);
        logger.error("Error caught validating signature", e);
        OutErrorMessage.set(e.getMessage());
        return false;
    }
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public byte[] getPKIMessage(InputStream inputStream) throws KeystoreException {

    try {/*from ww  w.j  a  v  a2  s . com*/
        CMSSignedData signedData = new CMSSignedData(inputStream);
        Store reqStore = signedData.getCertificates();
        @SuppressWarnings("unchecked")
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        KeyStoreReader keyStoreReader = new KeyStoreReader();
        PrivateKey privateKeyRA = keyStoreReader.getRAPrivateKey();
        PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
        X509Certificate certRA = (X509Certificate) keyStoreReader.getRACertificate();
        X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();

        CertificateFactory certificateFactory = CertificateFactory
                .getInstance(CertificateManagementConstants.X_509);
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert = (X509Certificate) certificateFactory
                .generateCertificate(byteArrayInputStream);

        PkcsPkiEnvelopeDecoder envelopeDecoder = new PkcsPkiEnvelopeDecoder(certRA, privateKeyRA);
        PkiMessageDecoder messageDecoder = new PkiMessageDecoder(reqCert, envelopeDecoder);
        PkiMessage<?> pkiMessage = messageDecoder.decode(signedData);
        Object msgData = pkiMessage.getMessageData();

        Nonce senderNonce = Nonce.nextNonce();
        TransactionId transId = pkiMessage.getTransactionId();
        Nonce recipientNonce = pkiMessage.getSenderNonce();
        CertRep certRep;

        PKCS10CertificationRequest certRequest = (PKCS10CertificationRequest) msgData;
        X509Certificate generatedCert = generateCertificateFromCSR(privateKeyCA, certRequest,
                certCA.getIssuerX500Principal().getName());

        List<X509Certificate> issued = new ArrayList<X509Certificate>();
        issued.add(generatedCert);

        if (issued.size() == 0) {
            certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
        } else {
            CMSSignedData messageData = getMessageData(issued);
            certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
        }

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert,
                CertificateManagementConstants.DES_EDE);
        PkiMessageEncoder encoder = new PkiMessageEncoder(privateKeyRA, certRA, envEncoder);
        CMSSignedData cmsSignedData = encoder.encode(certRep);

        return cmsSignedData.getEncoded();

    } catch (CertificateException e) {
        String errorMsg = "Certificate issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (MessageEncodingException e) {
        String errorMsg = "Message encoding issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Input output issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (MessageDecodingException e) {
        String errorMsg = "Message decoding issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (CMSException e) {
        String errorMsg = "CMS issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    }
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

private void signDOM(Node node, PrivateKey privateKey, Certificate origCert) {
    XMLSignatureFactory fac = initXMLSigFactory();
    X509Certificate cert = (X509Certificate) origCert;
    // Create the KeyInfo containing the X509Data.

    KeyInfoFactory kif = fac.getKeyInfoFactory();

    List<Object> x509Content = null;//new ArrayList<Object>();
    List<X509Data> data = new ArrayList<X509Data>();
    if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_SUBJECTDN)) {
        x509Content = new ArrayList<Object>();

        x509Content.add(cert.getSubjectDN().getName());
        //  x509Content.add(cert);
        //x509Content.add(cert.getSubjectDN().getName());
        X509Data xd = kif.newX509Data(x509Content);
        data.add(xd);/*from  w  w w.  j a  v a  2  s.  c  o  m*/
    }

    //  if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_X500_PRINICPAL)) {
    // }
    if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_BASE64)) {
        x509Content = new ArrayList<Object>();
        x509Content.add(cert);
        //x509Content.add(cert.getSubjectX500Principal().getName());
        X509Data xd = kif.newX509Data(x509Content);
        data.add(xd);
    }
    if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_SERIAL)) {
        x509Content = new ArrayList<Object>();

        X509IssuerSerial issuer = kif.newX509IssuerSerial(cert.getIssuerX500Principal().getName(),
                cert.getSerialNumber());

        x509Content.add(issuer);
        X509Data xd = kif.newX509Data(x509Content);
        data.add(xd);
    }

    //  
    //x509Content.add(cert);
    KeyInfo ki = kif.newKeyInfo(data);

    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privateKey, node);
    dsc.putNamespacePrefix(XML_DIGSIG_NS, "ns2");

    // Create the XMLSignature, but don't sign it yet.
    try {
        SignedInfo si = initSignedInfo(fac);
        XMLSignature signature = fac.newXMLSignature(si, ki);

        // Marshal, generate, and sign the enveloped signature.
        signature.sign(dsc);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:test.be.fedict.eid.applet.PcscTest.java

@Test
public void displayCitizenCertificates() throws Exception {
    PcscEidSpi pcscEidSpi = new PcscEid(new TestView(), this.messages);
    if (false == pcscEidSpi.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEidSpi.waitForEidPresent();/*from   w w w .j  a  v  a  2s .c o m*/
    }

    byte[] authnCertData = pcscEidSpi.readFile(PcscEid.AUTHN_CERT_FILE_ID);
    byte[] signCertData = pcscEidSpi.readFile(PcscEid.SIGN_CERT_FILE_ID);
    byte[] citizenCaCertData = pcscEidSpi.readFile(PcscEid.CA_CERT_FILE_ID);
    byte[] rootCaCertData = pcscEidSpi.readFile(PcscEid.ROOT_CERT_FILE_ID);
    byte[] nationalRegitryCertData = pcscEidSpi.readFile(PcscEid.RRN_CERT_FILE_ID);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate authnCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(authnCertData));
    X509Certificate signCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(signCertData));
    X509Certificate citizenCaCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(citizenCaCertData));
    X509Certificate rootCaCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(rootCaCertData));
    X509Certificate nationalRegitryCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(nationalRegitryCertData));

    LOG.debug("authentication certificate: " + authnCert);
    LOG.debug("signature certificate: " + signCert);
    LOG.debug("national registry certificate: " + nationalRegitryCert);
    LOG.debug("authn cert size: " + authnCertData.length);
    LOG.debug("sign cert size: " + signCertData.length);
    LOG.debug("citizen CA certificate: " + citizenCaCert);
    LOG.debug("root CA certificate: " + rootCaCert);
    LOG.debug("authn cert serial number: " + authnCert.getSerialNumber());
    LOG.debug("authn certificate issuer: " + authnCert.getIssuerX500Principal());

    File rootCaFile = File.createTempFile("test-root-ca-", ".pem");
    FileWriter rootCaFileWriter = new FileWriter(rootCaFile);
    PEMWriter rootCaPemWriter = new PEMWriter(rootCaFileWriter);
    rootCaPemWriter.writeObject(rootCaCert);
    rootCaPemWriter.close();

    File citizenCaFile = File.createTempFile("test-citizen-ca-", ".pem");
    FileWriter citizenCaFileWriter = new FileWriter(citizenCaFile);
    PEMWriter citizenCaPemWriter = new PEMWriter(citizenCaFileWriter);
    citizenCaPemWriter.writeObject(citizenCaCert);
    citizenCaPemWriter.close();

    pcscEidSpi.close();
    LOG.debug("root ca file: " + rootCaFile.getAbsolutePath());
    LOG.debug("citizen CA file: " + citizenCaFile.getAbsolutePath());
}

From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java

protected void addCertificate(X509Certificate cert, Element signedCertificate, Document doc, int index,
        Input input) throws CertificateEncodingException, NoSuchAlgorithmException, XmlSignatureException {
    Element elCert = createElement("Cert", doc, input);
    signedCertificate.appendChild(elCert);

    String algorithm = getMessageDigestAlgorithm(getDigestAlgorithmForSigningCertificate(),
            "The digest algorithm '%s' for the signing certificate is invalid");
    String digest = calculateDigest(algorithm, cert.getEncoded());
    Element certDigest = createElement("CertDigest", doc, input);
    elCert.appendChild(certDigest);//from   ww w  .  j  ava  2 s .com
    Element digestMethod = createDigSigElement("DigestMethod", doc, input.getPrefixForXmlSignatureNamespace());
    certDigest.appendChild(digestMethod);
    setAttribute(digestMethod, "Algorithm", getDigestAlgorithmForSigningCertificate());
    Element digestValue = createDigSigElement("DigestValue", doc, input.getPrefixForXmlSignatureNamespace());
    certDigest.appendChild(digestValue);
    digestValue.setTextContent(digest);

    Element issuerSerial = createElement("IssuerSerial", doc, input);
    elCert.appendChild(issuerSerial);
    Element x509IssuerName = createDigSigElement("X509IssuerName", doc,
            input.getPrefixForXmlSignatureNamespace());
    issuerSerial.appendChild(x509IssuerName);
    x509IssuerName.setTextContent(cert.getIssuerX500Principal().getName(X500Principal.RFC2253));
    Element x509SerialNumber = createDigSigElement("X509SerialNumber", doc,
            input.getPrefixForXmlSignatureNamespace());
    issuerSerial.appendChild(x509SerialNumber);
    x509SerialNumber.setTextContent(cert.getSerialNumber().toString());

    List<String> uris = getSigningCertificateURIs();
    if (!uris.isEmpty() && uris.size() > index) {
        String uri = uris.get(index);
        if (uri != null && !uri.isEmpty()) {
            setAttribute(elCert, "URI", uri);
        }
    }
}

From source file:be.fedict.trust.service.bean.DownloaderMDB.java

private void processColdStartMessage(ColdStartMessage coldStartMessage) {
    if (null == coldStartMessage) {
        return;//from  w  w  w  .ja  v a 2 s . c om
    }

    String crlUrl = coldStartMessage.getCrlUrl();
    String certUrl = coldStartMessage.getCertUrl();
    LOG.debug("cold start CRL URL: " + crlUrl);
    LOG.debug("cold start CA URL: " + certUrl);

    File crlFile = download(crlUrl);
    File certFile = download(certUrl);

    // parsing
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        LOG.debug("certificate factory error: " + e.getMessage(), e);
        crlFile.delete();
        certFile.delete();
        return;
    }

    X509Certificate certificate = null;
    try {
        certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certFile));
    } catch (Exception e) {
        LOG.debug("error DER-parsing certificate");
        try {
            PEMReader pemReader = new PEMReader(new FileReader(certFile));
            certificate = (X509Certificate) pemReader.readObject();
            pemReader.close();
        } catch (Exception e2) {
            retry("error PEM-parsing certificate", e, certFile, crlFile);
        }
    }
    certFile.delete();

    X509CRL crl = null;
    try {
        crl = (X509CRL) certificateFactory.generateCRL(new FileInputStream(crlFile));
    } catch (Exception e) {
        retry("error parsing CRL", e, crlFile);
    }

    // first check whether the two correspond
    try {
        crl.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.error("no correspondence between CRL and CA");
        LOG.error("CRL issuer: " + crl.getIssuerX500Principal());
        LOG.debug("CA subject: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }
    LOG.debug("CRL matches CA: " + certificate.getSubjectX500Principal());

    // skip expired CAs
    Date now = new Date();
    Date notAfter = certificate.getNotAfter();
    if (now.after(notAfter)) {
        LOG.warn("CA already expired: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    // create database entitities
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(certificate);
    if (null != certificateAuthority) {
        LOG.debug("CA already in cache: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    /*
     * Lookup Root CA's trust point via parent certificates' CA entity.
     */
    LOG.debug(
            "Lookup Root CA's trust point via parent certificates' CA entity - Don't have Issuer's Serial Number??");
    String parentIssuerName = certificate.getIssuerX500Principal().toString();
    CertificateAuthorityEntity parentCertificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(parentIssuerName);
    if (null == parentCertificateAuthority) {
        LOG.error("CA not found for " + parentIssuerName + " ?!");
        crlFile.delete();
        return;
    }
    LOG.debug("parent CA: " + parentCertificateAuthority.getName());
    TrustPointEntity parentTrustPoint = parentCertificateAuthority.getTrustPoint();
    if (null != parentTrustPoint) {
        LOG.debug("trust point parent: " + parentTrustPoint.getName());
        LOG.debug("previous trust point fire data: " + parentTrustPoint.getFireDate());
    } else {
        LOG.debug("no parent trust point");
    }

    // create new CA
    certificateAuthority = this.certificateAuthorityDAO.addCertificateAuthority(certificate, crlUrl);

    // prepare harvesting
    certificateAuthority.setTrustPoint(parentTrustPoint);
    certificateAuthority.setStatus(Status.PROCESSING);
    if (null != certificateAuthority.getTrustPoint()
            && null == certificateAuthority.getTrustPoint().getFireDate()) {
        try {
            this.schedulingService.startTimer(certificateAuthority.getTrustPoint());
        } catch (InvalidCronExpressionException e) {
            LOG.error("invalid cron expression");
            crlFile.delete();
            return;
        }
    }

    // notify harvester
    String crlFilePath = crlFile.getAbsolutePath();
    try {
        this.notificationService.notifyHarvester(certificate.getSubjectX500Principal().toString(), crlFilePath,
                false);
    } catch (JMSException e) {
        crlFile.delete();
        throw new RuntimeException(e);
    }
}

From source file:be.fedict.eid.tsl.TrustServiceList.java

public void addXadesBes(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        X509Certificate signingCertificate, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    LOG.debug("preSign");

    // QualifyingProperties
    QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType();
    qualifyingProperties.setTarget("#" + signatureId);

    // SignedProperties
    SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType();
    String signedPropertiesId = signatureId + "-xades";
    signedProperties.setId(signedPropertiesId);
    qualifyingProperties.setSignedProperties(signedProperties);

    // SignedSignatureProperties
    SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory
            .createSignedSignaturePropertiesType();
    signedProperties.setSignedSignatureProperties(signedSignatureProperties);

    // SigningTime
    GregorianCalendar signingTime = new GregorianCalendar();
    signingTime.setTimeZone(TimeZone.getTimeZone("Z"));
    XMLGregorianCalendar xmlSigningTime = this.datatypeFactory.newXMLGregorianCalendar(signingTime);
    xmlSigningTime.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    signedSignatureProperties.setSigningTime(xmlSigningTime);

    // SigningCertificate
    CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType();
    CertIDType signingCertificateId = this.xadesObjectFactory.createCertIDType();

    X509IssuerSerialType issuerSerial = this.xmldsigObjectFactory.createX509IssuerSerialType();
    issuerSerial.setX509IssuerName(signingCertificate.getIssuerX500Principal().toString());
    issuerSerial.setX509SerialNumber(signingCertificate.getSerialNumber());
    signingCertificateId.setIssuerSerial(issuerSerial);

    DigestAlgAndValueType certDigest = this.xadesObjectFactory.createDigestAlgAndValueType();
    DigestMethodType jaxbDigestMethod = this.xmldsigObjectFactory.createDigestMethodType();
    jaxbDigestMethod.setAlgorithm(DigestMethod.SHA256);
    certDigest.setDigestMethod(jaxbDigestMethod);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digestValue;
    try {/*from   ww  w .  j  a  v  a 2s  .  co m*/
        digestValue = messageDigest.digest(signingCertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
    certDigest.setDigestValue(digestValue);
    signingCertificateId.setCertDigest(certDigest);

    signingCertificates.getCert().add(signingCertificateId);
    signedSignatureProperties.setSigningCertificate(signingCertificates);

    // marshall XAdES QualifyingProperties
    Node qualifyingPropertiesNode = marshallQualifyingProperties(document, qualifyingProperties);

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(qualifyingPropertiesNode));
    XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    // add XAdES ds:Reference
    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null);
    List<Transform> transforms = new LinkedList<Transform>();
    Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);
    Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms,
            XADES_TYPE, null);
    references.add(reference);
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

@Override
public RevocationResult getRevocationStatus(CertPath certPath, TrustAnchor trustAnchor, Date now)
        throws CRLException {
    Check.notNull(certPath, "certPath");
    Check.notNull(trustAnchor, "trustAnchor");

    List<? extends Certificate> certificates = certPath.getCertificates();

    RevocationResult revocationResult = new RevocationResultImpl(certificates.size());

    /* // w  ww  . j  av a 2 s . c  o  m
     * Step through all the certificates in the path and check the revocation status of all
     * the certificates in the path.
     */
    for (int i = 0; i < certificates.size(); i++) {
        X509Certificate certificate = toX509Certificate(certificates.get(i));

        PublicKey issuerPublicKey;
        X500Principal issuer;
        X509Certificate issuerCertificate;

        /*
         * we need to get the issuer of the current certificate
         * check if there is a next certificate in the path or that we must use the TrustAnchor
         */
        if ((i + 1) == certificates.size()) {
            /* this was the last entry from the path so we must use the trust anchor */
            if (trustAnchor.getTrustedCert() != null) {
                issuerCertificate = toX509Certificate(trustAnchor.getTrustedCert());
                issuerPublicKey = issuerCertificate.getPublicKey();
                issuer = issuerCertificate.getSubjectX500Principal();
            } else {
                /* the TrustAnchor does not contain a certificate but only an issuer and public key */
                issuerCertificate = null;
                issuerPublicKey = trustAnchor.getCAPublicKey();
                issuer = trustAnchor.getCA();
            }
        } else {
            /* get next entry from path ie. the issuer of the current certificate */
            issuerCertificate = toX509Certificate(certificates.get(i + 1));
            issuerPublicKey = issuerCertificate.getPublicKey();
            issuer = issuerCertificate.getSubjectX500Principal();
        }

        /*
         * sanity check to make sure the CertPath is ordered from end -> final CA
         * ie that the next certificate signed the previous certificate
         */
        verifyCertificate(certificate, issuerPublicKey);

        /* 
         * Sanity check. The issuer principal field of the certificate currently checked should 
         * normally be equal to the issuer principal.
         */
        if (!certificate.getIssuerX500Principal().equals(issuer)) {
            logger.warn("Certificate issuer field is not equal to issuer.");
        }

        if (issuerCertificate != null) {
            Set<KeyUsageType> keyUsage = X509CertificateInspector.getKeyUsage(issuerCertificate);

            /* 
             * check if issuer is allowed to issue CRLs (only when we have an issuerCertificate, and
             * a key usage extension) 
             */
            if (keyUsage != null && !keyUsage.contains(KeyUsageType.CRLSIGN)) {
                logger.debug("Issuer is not allowed to issue CRLs.");

                /*
                 * We will return UNKNOWN status.
                 */
                RevocationDetailImpl detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);

                revocationResult.getDetails()[i] = detail;

                /* there is no need to continue because issuer is not allowed to issue CRLs */
                break;
            }
        }

        X509CRLSelector crlSelector = new X509CRLSelector();

        /* create a selector to find all relevant CRLs that were issued to the same issuer as the certificate */
        crlSelector.addIssuer(issuer);

        try {
            List<X509CRL> crls = findCRLs(certificate, crlSelector, issuerPublicKey, now);

            RevocationDetail detail = getRevocationDetail(crls, certificate, issuerCertificate, issuerPublicKey,
                    now);

            revocationResult.getDetails()[i] = detail;

            if (detail.getStatus() == RevocationStatus.REVOKED) {
                logger.warn("Certificate is revoked.");

                if (logger.isDebugEnabled()) {
                    logger.debug("Revoked certificate: " + certificate);
                }

                /* there is no need to continue because the CRL is revoked */
                break;
            }
        } catch (NoSuchProviderException e) {
            throw new NoSuchProviderRuntimeException(e);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Revocation status for CertPath " + certPath + " and TrustAnchor " + trustAnchor + " is "
                + revocationResult);
    }

    return revocationResult;
}