Example usage for java.security.cert X509Certificate getIssuerDN

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

Introduction

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

Prototype

public abstract Principal getIssuerDN();

Source Link

Document

Denigrated, replaced by #getIssuerX500Principal() .

Usage

From source file:com.thoughtworks.go.security.SelfSignedCertificateX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
 *//*from www.j ava2 s  .  c o  m*/
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if (LOG.isDebugEnabled() && certificates != null) {
        for (int c = 0; c < certificates.length; c++) {
            X509Certificate cert = certificates[c];
            LOG.info(" Server certificate " + (c + 1) + ":");
            LOG.info("  Subject DN: " + cert.getSubjectDN());
            LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
            LOG.info("  Valid from: " + cert.getNotBefore());
            LOG.info("  Valid until: " + cert.getNotAfter());
            LOG.info("  Issuer: " + cert.getIssuerDN());
        }
    }

    try {
        if ((certificates != null) && (certificates.length == 1) && !truststore.containsAlias(CRUISE_SERVER)) {
            certificates[0].checkValidity();
            updateKeystore(CRUISE_SERVER, certificates[0]);
        } else {
            defaultTrustManager.checkServerTrusted(certificates, authType);
        }
    } catch (KeyStoreException ke) {
        throw new RuntimeException("Couldn't access keystore while checking server's certificate", ke);
    }
}

From source file:netscape.security.pkcs.PKCS7.java

/**
 * Returns the X.509 certificate listed in this PKCS7 block
 * which has a matching serial number and Issuer name, or
 * null if one is not found./*from  ww w .jav a  2  s .  c o m*/
 *
 * @param serial the serial number of the certificate to retrieve.
 * @param name the Distinguished Name of the Issuer.
 */
public X509Certificate getCertificate(BigInt serial, X500Name name) {

    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        X500Name thisName = (X500Name) cert.getIssuerDN();
        BigInteger tmpSerial = cert.getSerialNumber();
        BigInt thisSerial = new BigInt(tmpSerial);
        if (serial.equals(thisSerial) && name.equals(thisName)) {
            return cert;
        }
    }
    return null;
}

From source file:br.gov.serpro.cert.AuthSSLX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
 *//* ww  w . j  ava  2s.  c o m*/
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if (LOG.isInfoEnabled() && certificates != null) {
        for (int c = 0; c < certificates.length; c++) {
            X509Certificate cert = certificates[c];
            LOG.info(" Server certificate " + (c + 1) + ":");
            LOG.info("  Subject DN: " + cert.getSubjectDN());
            LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
            LOG.info("  Valid from: " + cert.getNotBefore());
            LOG.info("  Valid until: " + cert.getNotAfter());
            LOG.info("  Issuer: " + cert.getIssuerDN());
        }
    }
    // TODO: Implementar uma caixa de dilogo que pergunta para o usurio se ele quer aceitar o certificado do site
    // Implementado com try/catch usando JOptionPanel

    try {
        defaultTrustManager.checkServerTrusted(certificates, authType);
    } catch (CertificateException e) {
        //Object[] options = {"Aceitar Certificado", "Aceitar Permanentemente", "Cancelar"};
        Object[] options = { "Aceitar Certificado", "Cancelar" };
        switch (JOptionPane.showOptionDialog(null,
                "Falha na validao do seguinte certificado:\n"
                        + certificates[0].getSubjectX500Principal().getName(),
                "\nO que voc quer fazer?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                options, options[0])) {
        case 2:
            // Rejeita certificado!
            throw e;
        case 1:
            // Aceita certificado permanentemente
            // TODO: Adicionar cdigo para inserir o certificado como um certificado confivel
            break;
        // Aceita certificado para esta sesso

        }
    }
}

From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeRequestTest.java

/**
 *      Find all certificates for a user and approve any outstanding revocation. 
 *//*  w  w w  .j av a  2  s.co  m*/
public int approveRevocation(Admin internalAdmin, Admin approvingAdmin, String username, int reason,
        int approvalType, CertificateStoreSessionRemote certificateStoreSession,
        ApprovalSessionRemote approvalSession, ApprovalExecutionSessionRemote approvalExecutionSession,
        int approvalCAID) throws Exception {
    Collection<java.security.cert.Certificate> userCerts = certificateStoreSession
            .findCertificatesByUsername(internalAdmin, username);
    Iterator<java.security.cert.Certificate> i = userCerts.iterator();
    int approvedRevocations = 0;
    while (i.hasNext()) {
        X509Certificate cert = (X509Certificate) i.next();
        String issuerDN = cert.getIssuerDN().toString();
        BigInteger serialNumber = cert.getSerialNumber();
        boolean isRevoked = certificateStoreSession.isRevoked(issuerDN, serialNumber);
        if ((reason != RevokedCertInfo.NOT_REVOKED && !isRevoked)
                || (reason == RevokedCertInfo.NOT_REVOKED && isRevoked)) {
            int approvalID;
            if (approvalType == ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE) {
                approvalID = RevocationApprovalRequest.generateApprovalId(approvalType, username, reason,
                        serialNumber, issuerDN);
            } else {
                approvalID = RevocationApprovalRequest.generateApprovalId(approvalType, username, reason, null,
                        null);
            }
            Query q = new Query(Query.TYPE_APPROVALQUERY);
            q.add(ApprovalMatch.MATCH_WITH_APPROVALID, BasicMatch.MATCH_TYPE_EQUALS,
                    Integer.toString(approvalID));
            ApprovalDataVO approvalData = (ApprovalDataVO) (approvalSession.query(internalAdmin, q, 0, 1,
                    "cAId=" + approvalCAID, "(endEntityProfileId=" + SecConst.EMPTY_ENDENTITYPROFILE + ")")
                    .get(0));
            Approval approval = new Approval("Approved during testing.");
            approvalExecutionSession.approve(approvingAdmin, approvalID, approval,
                    raAdminSession.getCachedGlobalConfiguration(new Admin(Admin.INTERNALCAID)));
            approvalData = (ApprovalDataVO) approvalSession.findApprovalDataVO(internalAdmin, approvalID)
                    .iterator().next();
            assertEquals(approvalData.getStatus(), ApprovalDataVO.STATUS_EXECUTED);
            CertificateStatus status = certificateStoreSession.getStatus(issuerDN, serialNumber);
            assertEquals(status.revocationReason, reason);
            approvalSession.removeApprovalRequest(internalAdmin, approvalData.getId());
            approvedRevocations++;
        }
    }
    return approvedRevocations;
}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

private void getCertificateForPartnership(byte[] cert, PropertyTree dom, String prefix) {
    if (cert != null) {
        try {/*from w  w w.  j a v  a  2 s. c o m*/
            ByteArrayInputStream bais = new ByteArrayInputStream(cert);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate verifyCert = (X509Certificate) cf.generateCertificate(bais);
            bais.close();
            dom.setProperty(prefix + "issuer", verifyCert.getIssuerDN().getName());
            dom.setProperty(prefix + "subject", verifyCert.getSubjectDN().getName());
            dom.setProperty(prefix + "thumbprint", getCertFingerPrint(verifyCert));
            dom.setProperty(prefix + "valid-from", StringUtilities.toGMTString(verifyCert.getNotBefore()));
            dom.setProperty(prefix + "valid-to", StringUtilities.toGMTString(verifyCert.getNotAfter()));
        } catch (Exception e) {
            dom.setProperty(prefix + "Error", e.toString());
        }
    } else {
        dom.setProperty(prefix, "");
    }
}

From source file:org.ejbca.core.protocol.cmp.CmpResponseMessage.java

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    boolean ret = false;
    // Some general stuff, common for all types of messages
    String issuer = null;// w w  w  .  j  a  v  a  2 s. com
    String subject = null;
    if (cert != null) {
        X509Certificate x509cert = (X509Certificate) cert;
        issuer = x509cert.getIssuerDN().getName();
        subject = x509cert.getSubjectDN().getName();
    } else if ((signCertChain != null) && (signCertChain.size() > 0)) {
        issuer = ((X509Certificate) signCertChain.iterator().next()).getSubjectDN().getName();
        subject = "CN=fooSubject";
    } else {
        issuer = "CN=fooIssuer";
        subject = "CN=fooSubject";
    }

    final GeneralName issuerName = new GeneralName(new X500Name(issuer));
    final GeneralName subjectName = new GeneralName(new X500Name(subject));
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(issuerName, subjectName,
            senderNonce, recipientNonce, transactionId);
    PKIBody myPKIBody = null;
    final PKIMessage myPKIMessage;

    try {
        if (status.equals(ResponseStatus.SUCCESS)) {
            if (cert != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Creating a CertRepMessage 'accepted'");
                }
                PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
                ASN1InputStream certASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cert.getEncoded()));
                ASN1InputStream cacertASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cacert.getEncoded()));
                try {
                    try {
                        CMPCertificate cmpcert = CMPCertificate.getInstance(certASN1InputStream.readObject());
                        CertOrEncCert retCert = new CertOrEncCert(cmpcert);
                        CertifiedKeyPair myCertifiedKeyPair = new CertifiedKeyPair(retCert);
                        CertResponse myCertResponse = new CertResponse(new ASN1Integer(requestId),
                                myPKIStatusInfo, myCertifiedKeyPair, null);

                        CertResponse[] certRespos = { myCertResponse };
                        CMPCertificate[] caPubs = {
                                CMPCertificate.getInstance(cacertASN1InputStream.readObject()) };

                        CertRepMessage myCertRepMessage = new CertRepMessage(caPubs, certRespos);

                        int respType = requestType + 1; // 1 = intitialization response, 3 = certification response etc
                        if (log.isDebugEnabled()) {
                            log.debug("Creating response body of type " + respType);
                        }
                        myPKIBody = new PKIBody(respType, myCertRepMessage);
                    } finally {
                        certASN1InputStream.close();
                        cacertASN1InputStream.close();
                    }
                } catch (IOException e) {
                    throw new IllegalStateException("Unexpected IOException caught.", e);
                }
            }
        } else if (status.equals(ResponseStatus.FAILURE)) {
            if (log.isDebugEnabled()) {
                log.debug("Creating a CertRepMessage 'rejected'");
            }
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(ASN1Integer.getInstance(PKIStatus.rejection.toASN1Primitive()));
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo
                    .getInstance(ASN1Sequence.getInstance(new DERSequence(statusInfoV)));
            myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType);

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Creating a 'waiting' message?");
            }
            // Not supported, lets create a PKIError failure instead
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(PKIStatus.rejection); // 2 = rejection
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo.getInstance(new DERSequence(statusInfoV));

            ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo);
            myPKIBody = new PKIBody(23, myErrorContent); // 23 = error                
        }

        if ((pbeKeyId != null) && (pbeKey != null) && (pbeDigestAlg != null) && (pbeMacAlg != null)) {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, pbeKeyId, pbeKey,
                    pbeDigestAlg, pbeMacAlg, pbeIterationCount);
        } else {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digest));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digest,
                    provider);
        }

        ret = true;

    } catch (CertificateEncodingException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (InvalidKeyException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchProviderException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SecurityException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SignatureException e) {
        log.error("Error creating CertRepMessage: ", e);
    }

    return ret;
}

From source file:com.otterca.persistence.entity.X509CertificateEntity.java

/**
 * Cache values within certificate. They should never be set directly and
 * the actual values in the database should be created via triggers.
 * //from   w  w w .  ja  v a2s  .  c  o m
 * @param cert
 */
protected final void cacheAttributes(X509Certificate cert) throws CertificateEncodingException, IOException {
    serialNumber = cert.getSerialNumber();
    certificate = cert.getEncoded();
    subject = cert.getSubjectDN().getName();
    issuer = cert.getIssuerDN().getName();
    notBefore = cert.getNotBefore();
    notAfter = cert.getNotAfter();

    //name = x509CertUtil.getName(cert);
    //fingerprint = x509CertUtil.getFingerprint(cert);
    //certHash = x509CertUtil.getCertificateHash(cert);
    //iHash = x509CertUtil.getIHash(cert);
    //sHash = x509CertUtil.getSHash(cert);
    //akidHash = x509CertUtil.getAkidHash(cert);
    //skidHash = x509CertUtil.getSkidHash(cert);
}

From source file:org.viafirma.nucleo.validacion.OcspValidatorHandler.java

/**
 * Retorna el certificado de condianza.//  w  w  w  .  j av a2 s.  co m
 * 
 * @param certificadoX509
 * @return
 * @throws ExcepcionErrorInterno
 *             No se encuentra el certificado de confianza.
 */
private X509Certificate getIssuerX509(X509Certificate certificadoX509) throws ExcepcionErrorInterno {
    for (TrustAnchor trust : certificadosConfianza) {
        if (trust.getTrustedCert().getSubjectDN().getName().equals(certificadoX509.getIssuerDN().getName())) {
            return trust.getTrustedCert();
        }
    }
    log.warn(" No hemos encontrado el certificado de confianza.");
    throw new ExcepcionErrorInterno(CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA);
}

From source file:com.alfaariss.oa.engine.crypto.keystore.KeystoreSigningFactory.java

/**
 * Retrieve alias from the certificate store.
 * @see AbstractSigningFactory#getAliasForX509Cert(
 *  java.lang.String, java.math.BigInteger)
 *///from   www  .ja  v  a2s. co  m
@Override
public String getAliasForX509Cert(String issuer, BigInteger serialNumber) throws CryptoException {
    X500Principal issuerRDN = new X500Principal(issuer);
    Certificate cert = null;

    try {
        Enumeration<String> aliases = _certificatestore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            Certificate[] certs = _certificatestore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain
                cert = _certificatestore.getCertificate(alias);
                if (cert == null) {
                    return null;
                }
            } else {
                cert = certs[0];
            }

            if (cert instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) cert;
                if (serialNumber == null || x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
                    X500Principal certRDN = new X500Principal(x509cert.getIssuerDN().getName());
                    if (certRDN.equals(issuerRDN)) {
                        return alias;
                    }
                }
            }
        }
    } catch (KeyStoreException e) {
        _logger.error("Could not read alias from trust store", e);
        throw new CryptoException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
    }
    return null;
}

From source file:no.digipost.signature.client.asice.signature.CreateXAdESProperties.java

public Document createPropertiesToSign(final List<ASiCEAttachable> files, final X509Certificate certificate) {
    byte[] certificateDigestValue;
    try {//from  w  w w .  j a  v a2s.c o m
        certificateDigestValue = sha1(certificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new CertificateException("Unable to get encoded from of certificate", e);
    }

    DigestAlgAndValueType certificateDigest = new DigestAlgAndValueType(sha1DigestMethod,
            certificateDigestValue);
    X509IssuerSerialType certificateIssuer = new X509IssuerSerialType(certificate.getIssuerDN().getName(),
            certificate.getSerialNumber());
    SigningCertificate signingCertificate = new SigningCertificate(
            singletonList(new CertIDType(certificateDigest, certificateIssuer, null)));

    Date now = new Date();
    SignedSignatureProperties signedSignatureProperties = new SignedSignatureProperties(now, signingCertificate,
            null, null, null, null);
    SignedDataObjectProperties signedDataObjectProperties = new SignedDataObjectProperties(
            dataObjectFormats(files), null, null, null, null);
    SignedProperties signedProperties = new SignedProperties(signedSignatureProperties,
            signedDataObjectProperties, "SignedProperties");
    QualifyingProperties qualifyingProperties = new QualifyingProperties(signedProperties, null, "#Signature",
            null);

    DOMResult domResult = new DOMResult();
    marshaller.marshal(qualifyingProperties, domResult);
    Document document = (Document) domResult.getNode();

    // Explicitly mark the SignedProperties Id as an Document ID attribute, so that it will be eligble as a reference for signature.
    // If not, it will not be treated as something to sign.
    markAsIdProperty(document, "SignedProperties", "Id");

    return document;
}