Example usage for org.bouncycastle.asn1.x500 X500Name toString

List of usage examples for org.bouncycastle.asn1.x500 X500Name toString

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x500 X500Name toString.

Prototype

public String toString() 

Source Link

Usage

From source file:fi.laverca.Pkcs7.java

License:Apache License

/**
 * Read the Issuer from a SignedData/*from  w  w w. j a  va 2 s  . c om*/
 * @param si data
 * @return Issuer as String
 */
public static String readIssuer(final SignerInfo si) {
    if (si == null) {
        return null;
    }

    IssuerAndSerialNumber ias = si.getIssuerAndSerialNumber();
    X500Name issuerName = ias.getName();

    return issuerName.toString();
}

From source file:net.sf.keystore_explorer.crypto.x509.GeneralNameUtil.java

License:Open Source License

/**
 * Get string representation for General names that cannot cause a
 * IOException to be thrown. Unsupported are ediPartyName, otherName and
 * x400Address. Returns a blank string for these.
 *
 * @param generalName//from  ww  w.ja v a2s.co m
 *            General name
 * @param addLinkForURI
 *            If true, convert URI to a clickable link
 * @return String representation of general name
 */
public static String safeToString(GeneralName generalName, boolean addLinkForURI) {

    if (generalName == null) {
        return "";
    }

    switch (generalName.getTagNo()) {
    case GeneralName.directoryName: {
        X500Name directoryName = (X500Name) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.DirectoryGeneralName"),
                directoryName.toString());
    }
    case GeneralName.dNSName: {
        DERIA5String dnsName = (DERIA5String) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.DnsGeneralName"), dnsName.getString());
    }
    case GeneralName.iPAddress: {
        byte[] ipAddressBytes = ((ASN1OctetString) generalName.getName()).getOctets();

        String ipAddressString = "";
        try {
            ipAddressString = InetAddress.getByAddress(ipAddressBytes).getHostAddress();
        } catch (UnknownHostException e) {
            // ignore -> results in empty IP address string
        }

        return MessageFormat.format(res.getString("GeneralNameUtil.IpAddressGeneralName"), ipAddressString);
    }
    case GeneralName.registeredID: {
        ASN1ObjectIdentifier registeredId = (ASN1ObjectIdentifier) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.RegisteredIdGeneralName"),
                ObjectIdUtil.toString(registeredId));
    }
    case GeneralName.rfc822Name: {
        DERIA5String rfc822Name = (DERIA5String) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.Rfc822GeneralName"), rfc822Name.getString());
    }
    case GeneralName.uniformResourceIdentifier: {
        DERIA5String uri = (DERIA5String) generalName.getName();

        String link = addLinkForURI
                ? "<html><a href=\"" + uri.getString() + "\">" + uri.getString() + "</a></html>"
                : uri.getString();

        return MessageFormat.format(res.getString("GeneralNameUtil.UriGeneralName"), link);
    }
    case GeneralName.otherName: {
        // we currently only support UPN in otherName
        String upn = parseUPN(generalName);
        return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), "UPN", upn);
    }
    default: {
        return "";
    }
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

License:Open Source License

/**
 * Get short name for certificate. Common name if available, otherwise use
 * entire distinguished name./*  www .  j a  v  a  2  s . c o  m*/
 *
 * @param cert
 *            Certificate
 * @return Short name
 */
public static String getShortName(X509Certificate cert) {
    X500Name subject = X500NameUtils.x500PrincipalToX500Name(cert.getSubjectX500Principal());

    String shortName = extractCommonName(subject);

    if (shortName == null) {
        shortName = subject.toString();
    }

    return shortName;
}

From source file:net.sf.portecle.DViewCSR.java

License:Open Source License

/**
 * Populate the dialog with the currently selected certificate request's details.
 * //www .j  a  va  2  s  .  c  o  m
 * @throws CryptoException A problem was encountered getting the certificate request's details
 */
private void populateDialog() throws CryptoException {
    // Version
    m_jtfVersion
            .setText(m_req.toASN1Structure().getCertificationRequestInfo().getVersion().getValue().toString());
    m_jtfVersion.setCaretPosition(0);

    // Subject
    X500Name subject = m_req.getSubject();
    m_jtfSubject.setText(subject.toString());
    m_jtfSubject.setCaretPosition(0);

    m_basename = NameUtil.getCommonName(subject);

    // Public Key (algorithm and keysize)
    SubjectPublicKeyInfo keyInfo = m_req.getSubjectPublicKeyInfo();

    AsymmetricKeyParameter keyParams = null;
    try {
        keyParams = PublicKeyFactory.createKey(keyInfo);
    } catch (IOException e) {
        throw new CryptoException(RB.getString("DViewCSR.NoGetKeyInfo.exception.message"), e);
    }

    m_jtfPublicKey.setText(AlgorithmType.toString(keyInfo.getAlgorithm().getAlgorithm().toString()));

    int iKeySize = KeyPairUtil.getKeyLength(keyParams);
    if (iKeySize != KeyPairUtil.UNKNOWN_KEY_SIZE) {
        m_jtfPublicKey.setText(MessageFormat.format(RB.getString("DViewCSR.m_jtfPublicKey.text"),
                m_jtfPublicKey.getText(), iKeySize));
    }
    m_jtfPublicKey.setCaretPosition(0);

    // Signature Algorithm
    String sigAlgName = SignatureType.toString(m_req.getSignatureAlgorithm().getAlgorithm().toString());
    m_jtfSignatureAlgorithm.setText(sigAlgName);
    m_jtfSignatureAlgorithm.setCaretPosition(0);

    // TODO: attributes, requested extensions
}

From source file:org.apache.jmeter.assertions.SMIMEAssertion.java

License:Apache License

private static AssertionResult verifySignature(SMIMEAssertionTestElement testElement, SMIMESignedParser s,
        String name) throws CMSException {
    AssertionResult res = new AssertionResult(name);

    try {//from   w  w  w  . j a v a  2  s . c om
        Store certs = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Iterator<?> signerIt = signers.getSigners().iterator();

        if (signerIt.hasNext()) {

            SignerInformation signer = (SignerInformation) signerIt.next();
            Iterator<?> certIt = certs.getMatches(signer.getSID()).iterator();

            if (certIt.hasNext()) {
                // the signer certificate
                X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

                if (testElement.isVerifySignature()) {

                    SignerInformationVerifier verifier = null;
                    try {
                        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert);
                    } catch (OperatorCreationException e) {
                        log.error("Can't create a provider", e);
                    }
                    if (verifier == null || !signer.verify(verifier)) {
                        res.setFailure(true);
                        res.setFailureMessage("Signature is invalid");
                    }
                }

                if (testElement.isSignerCheckConstraints()) {
                    StringBuilder failureMessage = new StringBuilder();

                    String serial = testElement.getSignerSerial();
                    if (!JOrphanUtils.isBlank(serial)) {
                        BigInteger serialNbr = readSerialNumber(serial);
                        if (!serialNbr.equals(cert.getSerialNumber())) {
                            res.setFailure(true);
                            failureMessage.append("Serial number ").append(serialNbr)
                                    .append(" does not match serial from signer certificate: ")
                                    .append(cert.getSerialNumber()).append("\n");
                        }
                    }

                    String email = testElement.getSignerEmail();
                    if (!JOrphanUtils.isBlank(email)) {
                        List<String> emailFromCert = getEmailFromCert(cert);
                        if (!emailFromCert.contains(email)) {
                            res.setFailure(true);
                            failureMessage.append("Email address \"").append(email)
                                    .append("\" not present in signer certificate\n");
                        }

                    }

                    String subject = testElement.getSignerDn();
                    if (subject.length() > 0) {
                        final X500Name certPrincipal = cert.getSubject();
                        log.debug("DN from cert: " + certPrincipal.toString());
                        X500Name principal = new X500Name(subject);
                        log.debug("DN from assertion: " + principal.toString());
                        if (!principal.equals(certPrincipal)) {
                            res.setFailure(true);
                            failureMessage.append("Distinguished name of signer certificate does not match \"")
                                    .append(subject).append("\"\n");
                        }
                    }

                    String issuer = testElement.getIssuerDn();
                    if (issuer.length() > 0) {
                        final X500Name issuerX500Name = cert.getIssuer();
                        log.debug("IssuerDN from cert: " + issuerX500Name.toString());
                        X500Name principal = new X500Name(issuer);
                        log.debug("IssuerDN from assertion: " + principal);
                        if (!principal.equals(issuerX500Name)) {
                            res.setFailure(true);
                            failureMessage
                                    .append("Issuer distinguished name of signer certificate does not match \"")
                                    .append(subject).append("\"\n");
                        }
                    }

                    if (failureMessage.length() > 0) {
                        res.setFailureMessage(failureMessage.toString());
                    }
                }

                if (testElement.isSignerCheckByFile()) {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    X509CertificateHolder certFromFile;
                    InputStream inStream = null;
                    try {
                        inStream = new BufferedInputStream(
                                new FileInputStream(testElement.getSignerCertFile()));
                        certFromFile = new JcaX509CertificateHolder(
                                (X509Certificate) cf.generateCertificate(inStream));
                    } finally {
                        IOUtils.closeQuietly(inStream);
                    }

                    if (!certFromFile.equals(cert)) {
                        res.setFailure(true);
                        res.setFailureMessage("Signer certificate does not match certificate "
                                + testElement.getSignerCertFile());
                    }
                }

            } else {
                res.setFailure(true);
                res.setFailureMessage("No signer certificate found in signature");
            }

        }

        // TODO support multiple signers
        if (signerIt.hasNext()) {
            log.warn("SMIME message contains multiple signers! Checking multiple signers is not supported.");
        }

    } catch (GeneralSecurityException e) {
        log.error(e.getMessage(), e);
        res.setError(true);
        res.setFailureMessage(e.getMessage());
    } catch (FileNotFoundException e) {
        res.setFailure(true);
        res.setFailureMessage("certificate file not found: " + e.getMessage());
    }

    return res;
}

From source file:org.apache.poi.poifs.crypt.dsig.facets.XAdESXLSignatureFacet.java

License:Apache License

@Override
public void postSign(Document document) throws MarshalException {
    LOG.log(POILogger.DEBUG, "XAdES-X-L post sign phase");

    QualifyingPropertiesDocument qualDoc = null;
    QualifyingPropertiesType qualProps = null;

    // check for XAdES-BES
    NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties");
    if (qualNl.getLength() == 1) {
        try {//w  w  w  . ja  v  a2  s.c  om
            qualDoc = QualifyingPropertiesDocument.Factory.parse(qualNl.item(0));
        } catch (XmlException e) {
            throw new MarshalException(e);
        }
        qualProps = qualDoc.getQualifyingProperties();
    } else {
        throw new MarshalException("no XAdES-BES extension present");
    }

    // create basic XML container structure
    UnsignedPropertiesType unsignedProps = qualProps.getUnsignedProperties();
    if (unsignedProps == null) {
        unsignedProps = qualProps.addNewUnsignedProperties();
    }
    UnsignedSignaturePropertiesType unsignedSigProps = unsignedProps.getUnsignedSignatureProperties();
    if (unsignedSigProps == null) {
        unsignedSigProps = unsignedProps.addNewUnsignedSignatureProperties();
    }

    // create the XAdES-T time-stamp
    NodeList nlSigVal = document.getElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue");
    if (nlSigVal.getLength() != 1) {
        throw new IllegalArgumentException("SignatureValue is not set.");
    }

    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.log(POILogger.DEBUG, "creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(nlSigVal.item(0)),
            tsaRevocationDataXadesT);

    // marshal the XAdES-T extension
    unsignedSigProps.addNewSignatureTimeStamp().set(signatureTimeStamp);

    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        insertXChild(unsignedSigProps, validationData);
    }

    if (signatureConfig.getRevocationDataService() == null) {
        /*
         * Without revocation data service we cannot construct the XAdES-C
         * extension.
         */
        return;
    }

    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = unsignedSigProps.addNewCompleteCertificateRefs();

    CertIDListType certIdList = completeCertificateRefs.addNewCertRefs();
    /*
     * We skip the signing certificate itself according to section
     * 4.4.3.2 of the XAdES 1.4.1 specification.
     */
    List<X509Certificate> certChain = signatureConfig.getSigningCertificateChain();
    int chainSize = certChain.size();
    if (chainSize > 1) {
        for (X509Certificate cert : certChain.subList(1, chainSize)) {
            CertIDType certId = certIdList.addNewCert();
            XAdESSignatureFacet.setCertID(certId, signatureConfig, false, cert);
        }
    }

    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = unsignedSigProps.addNewCompleteRevocationRefs();
    RevocationData revocationData = signatureConfig.getRevocationDataService().getRevocationData(certChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = completeRevocationRefs.addNewCRLRefs();
        completeRevocationRefs.setCRLRefs(crlRefs);

        for (byte[] encodedCrl : revocationData.getCRLs()) {
            CRLRefType crlRef = crlRefs.addNewCRLRef();
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }

            CRLIdentifierType crlIdentifier = crlRef.addNewCRLIdentifier();
            String issuerName = crl.getIssuerDN().getName().replace(",", ", ");
            crlIdentifier.setIssuer(issuerName);
            Calendar cal = Calendar.getInstance();
            cal.setTime(crl.getThisUpdate());
            crlIdentifier.setIssueTime(cal);
            crlIdentifier.setNumber(getCrlNumber(crl));

            DigestAlgAndValueType digestAlgAndValue = crlRef.addNewDigestAlgAndValue();
            XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, encodedCrl,
                    signatureConfig.getDigestAlgo());
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = completeRevocationRefs.addNewOCSPRefs();
        for (byte[] ocsp : revocationData.getOCSPs()) {
            try {
                OCSPRefType ocspRef = ocspRefs.addNewOCSPRef();

                DigestAlgAndValueType digestAlgAndValue = ocspRef.addNewDigestAlgAndValue();
                XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, ocsp,
                        signatureConfig.getDigestAlgo());

                OCSPIdentifierType ocspIdentifier = ocspRef.addNewOCSPIdentifier();

                OCSPResp ocspResp = new OCSPResp(ocsp);

                BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResp.getResponseObject();

                Calendar cal = Calendar.getInstance();
                cal.setTime(basicOcspResp.getProducedAt());
                ocspIdentifier.setProducedAt(cal);

                ResponderIDType responderId = ocspIdentifier.addNewResponderID();

                RespID respId = basicOcspResp.getResponderId();
                ResponderID ocspResponderId = respId.toASN1Object();
                DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Primitive();
                if (2 == derTaggedObject.getTagNo()) {
                    ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                    byte key[] = keyHashOctetString.getOctets();
                    responderId.setByKey(key);
                } else {
                    X500Name name = X500Name.getInstance(derTaggedObject.getObject());
                    String nameStr = name.toString();
                    responderId.setByName(nameStr);
                }
            } catch (Exception e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
        }
    }

    // marshal XAdES-C

    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new ArrayList<Node>();
    timeStampNodesXadesX1.add(nlSigVal.item(0));
    timeStampNodesXadesX1.add(signatureTimeStamp.getDomNode());
    timeStampNodesXadesX1.add(completeCertificateRefs.getDomNode());
    timeStampNodesXadesX1.add(completeRevocationRefs.getDomNode());

    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.log(POILogger.DEBUG, "creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1);
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        ValidationDataType timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
        insertXChild(unsignedSigProps, timeStampXadesX1ValidationData);
    }

    // marshal XAdES-X
    unsignedSigProps.addNewSigAndRefsTimeStamp().set(timeStampXadesX1);

    // XAdES-X-L
    CertificateValuesType certificateValues = unsignedSigProps.addNewCertificateValues();
    for (X509Certificate certificate : certChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = certificateValues.addNewEncapsulatedX509Certificate();
        try {
            encapsulatedPKIDataType.setByteArrayValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
    }

    RevocationValuesType revocationValues = unsignedSigProps.addNewRevocationValues();
    createRevocationValues(revocationValues, revocationData);

    // marshal XAdES-X-L
    Node n = document.importNode(qualProps.getDomNode(), true);
    qualNl.item(0).getParentNode().replaceChild(n, qualNl.item(0));
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

/**
 * Sequence is ignored by X509CA. The ctParams argument will NOT be kept after the function call returns,
 * and is allowed to contain references to session beans.
 * //from ww w  .j  a va 2s  .com
 * @throws CAOfflineException if the CA wasn't active
 * @throws InvalidAlgorithmException if the signing algorithm in the certificate profile (or the CA Token if not found) was invalid.  
 * @throws IllegalValidityException if validity was invalid
 * @throws IllegalNameException if the name specified in the certificate request was invalid
 * @throws CertificateExtensionException if any of the certificate extensions were invalid
 * @throws OperatorCreationException if CA's private key contained an unknown algorithm or provider
 * @throws CertificateCreateException if an error occurred when trying to create a certificate. 
 * @throws SignatureException if the CA's certificate's and request's certificate's and signature algorithms differ
 */
private Certificate generateCertificate(final EndEntityInformation subject, final RequestMessage request,
        final PublicKey publicKey, final int keyusage, final Date notBefore, final Date notAfter,
        final CertificateProfile certProfile, final Extensions extensions, final String sequence,
        final PublicKey caPublicKey, final PrivateKey caPrivateKey, final String provider,
        CertificateGenerationParams certGenParams) throws CAOfflineException, InvalidAlgorithmException,
        IllegalValidityException, IllegalNameException, CertificateExtensionException,
        OperatorCreationException, CertificateCreateException, SignatureException {

    // We must only allow signing to take place if the CA itself is on line, even if the token is on-line.
    // We have to allow expired as well though, so we can renew expired CAs
    if ((getStatus() != CAConstants.CA_ACTIVE) && ((getStatus() != CAConstants.CA_EXPIRED))) {
        final String msg = intres.getLocalizedMessage("error.caoffline", getName(), getStatus());
        if (log.isDebugEnabled()) {
            log.debug(msg); // This is something we handle so no need to log with higher priority
        }
        throw new CAOfflineException(msg);
    }

    final String sigAlg;
    if (certProfile.getSignatureAlgorithm() == null) {
        sigAlg = getCAToken().getSignatureAlgorithm();
    } else {
        sigAlg = certProfile.getSignatureAlgorithm();
    }
    // Check that the signature algorithm is one of the allowed ones
    if (!ArrayUtils.contains(AlgorithmConstants.AVAILABLE_SIGALGS, sigAlg)) {
        final String msg = intres.getLocalizedMessage("createcert.invalidsignaturealg", sigAlg);
        throw new InvalidAlgorithmException(msg);
    }
    // Check if this is a root CA we are creating
    final boolean isRootCA = certProfile.getType() == CertificateConstants.CERTTYPE_ROOTCA;

    final X509Certificate cacert = (X509Certificate) getCACertificate();
    // Check CA certificate PrivateKeyUsagePeriod if it exists (throws CAOfflineException if it exists and is not within this time)
    CertificateValidity.checkPrivateKeyUsagePeriod(cacert);
    // Get certificate validity time notBefore and notAfter
    final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert,
            isRootCA);

    final BigInteger serno;
    {
        // Serialnumber is either random bits, where random generator is initialized by the serno generator.
        // Or a custom serial number defined in the end entity object
        final ExtendedInformation ei = subject.getExtendedinformation();
        if (certProfile.getAllowCertSerialNumberOverride()) {
            if (ei != null && ei.certificateSerialNumber() != null) {
                serno = ei.certificateSerialNumber();
            } else {
                serno = SernoGeneratorRandom.instance().getSerno();
            }
        } else {
            serno = SernoGeneratorRandom.instance().getSerno();
            if ((ei != null) && (ei.certificateSerialNumber() != null)) {
                final String msg = intres.getLocalizedMessage(
                        "createcert.certprof_not_allowing_cert_sn_override_using_normal",
                        ei.certificateSerialNumber().toString(16));
                log.info(msg);
            }
        }
    }

    // Make DNs
    String dn = subject.getCertificateDN();
    if (certProfile.getUseSubjectDNSubSet()) {
        dn = certProfile.createSubjectDNSubSet(dn);
    }

    final X500NameStyle nameStyle;
    if (getUsePrintableStringSubjectDN()) {
        nameStyle = PrintableStringNameStyle.INSTANCE;
    } else {
        nameStyle = CeSecoreNameStyle.INSTANCE;
    }

    if (certProfile.getUseCNPostfix()) {
        dn = CertTools.insertCNPostfix(dn, certProfile.getCNPostfix(), nameStyle);
    }

    // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN
    final boolean ldapdnorder;
    if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) {
        ldapdnorder = false;
    } else {
        ldapdnorder = true;
    }
    final X500Name subjectDNName;
    if (certProfile.getAllowDNOverride() && (request != null) && (request.getRequestX500Name() != null)) {
        subjectDNName = request.getRequestX500Name();
        if (log.isDebugEnabled()) {
            log.debug("Using X509Name from request instead of user's registered.");
        }
    } else {
        final ExtendedInformation ei = subject.getExtendedinformation();
        if (certProfile.getAllowDNOverrideByEndEntityInformation() && ei != null
                && ei.getRawSubjectDn() != null) {
            final String stripped = StringTools.strip(ei.getRawSubjectDn());
            final String escapedPluses = CertTools.handleUnescapedPlus(stripped);
            final String emptiesRemoved = DNFieldsUtil.removeAllEmpties(escapedPluses);
            final X500Name subjectDNNameFromEei = CertTools.stringToUnorderedX500Name(emptiesRemoved,
                    CeSecoreNameStyle.INSTANCE);
            if (subjectDNNameFromEei.toString().length() > 0) {
                subjectDNName = subjectDNNameFromEei;
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Using X500Name from end entity information instead of user's registered subject DN fields.");
                    log.debug("ExtendedInformation.getRawSubjectDn(): " + ei.getRawSubjectDn() + " will use: "
                            + CeSecoreNameStyle.INSTANCE.toString(subjectDNName));
                }
            } else {
                subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder);
            }
        } else {
            subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder);
        }
    }
    // Make sure the DN does not contain dangerous characters
    if (StringTools.hasStripChars(subjectDNName.toString())) {
        if (log.isTraceEnabled()) {
            log.trace("DN with illegal name: " + subjectDNName);
        }
        final String msg = intres.getLocalizedMessage("createcert.illegalname");
        throw new IllegalNameException(msg);
    }
    if (log.isDebugEnabled()) {
        log.debug("Using subjectDN: " + subjectDNName.toString());
    }

    // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN
    // which many applications do not like.
    X500Name issuerDNName;
    if (isRootCA) {
        // This will be an initial root CA, since no CA-certificate exists
        // Or it is a root CA, since the cert is self signed. If it is a root CA we want to use the same encoding for subject and issuer,
        // it might have changed over the years.
        if (log.isDebugEnabled()) {
            log.debug("Using subject DN also as issuer DN, because it is a root CA");
        }
        issuerDNName = subjectDNName;
    } else {
        issuerDNName = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded());
        if (log.isDebugEnabled()) {
            log.debug("Using issuer DN directly from the CA certificate: " + issuerDNName.toString());
        }
    }

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalStateException("Caught unexpected IOException.", e);
    }
    final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(issuerDNName, serno,
            val.getNotBefore(), val.getNotAfter(), subjectDNName, pkinfo);

    // Only created and used if Certificate Transparency is enabled
    final X509v3CertificateBuilder precertbuilder = certProfile.isUseCertificateTransparencyInCerts()
            ? new X509v3CertificateBuilder(issuerDNName, serno, val.getNotBefore(), val.getNotAfter(),
                    subjectDNName, pkinfo)
            : null;

    // Check that the certificate fulfills name constraints
    if (cacert instanceof X509Certificate) {
        GeneralNames altNameGNs = null;
        String altName = subject.getSubjectAltName();
        if (certProfile.getUseSubjectAltNameSubSet()) {
            altName = certProfile.createSubjectAltNameSubSet(altName);
        }
        if (altName != null && altName.length() > 0) {
            altNameGNs = CertTools.getGeneralNamesFromAltName(altName);
        }
        CertTools.checkNameConstraints((X509Certificate) cacert, subjectDNName, altNameGNs);
    }

    // If the subject has Name Constraints, then name constraints must be enabled in the certificate profile!
    if (subject.getExtendedinformation() != null) {
        final ExtendedInformation ei = subject.getExtendedinformation();
        final List<String> permittedNC = ei.getNameConstraintsPermitted();
        final List<String> excludedNC = ei.getNameConstraintsExcluded();
        if ((permittedNC != null && !permittedNC.isEmpty()) || (excludedNC != null && !excludedNC.isEmpty())) {
            if (!certProfile.getUseNameConstraints()) {
                throw new CertificateCreateException(
                        "Tried to issue a certificate with Name Constraints without having enabled NC in the certificate profile.");
            }
        }
    }

    //
    // X509 Certificate Extensions
    //

    // Extensions we will add to the certificate, later when we have filled the structure with
    // everything we want.
    final ExtensionsGenerator extgen = new ExtensionsGenerator();

    // First we check if there is general extension override, and add all extensions from
    // the request in that case
    if (certProfile.getAllowExtensionOverride() && extensions != null) {
        ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs();
        for (ASN1ObjectIdentifier oid : oids) {
            final Extension ext = extensions.getExtension(oid);
            if (log.isDebugEnabled()) {
                log.debug("Overriding extension with oid: " + oid);
            }
            try {
                extgen.addExtension(oid, ext.isCritical(), ext.getParsedValue());
            } catch (IOException e) {
                throw new IllegalStateException("Caught unexpected IOException.", e);
            }
        }
    }

    // Second we see if there is Key usage override
    Extensions overridenexts = extgen.generate();
    if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) {
        if (log.isDebugEnabled()) {
            log.debug("AllowKeyUsageOverride=true. Using KeyUsage from parameter: " + keyusage);
        }
        if ((certProfile.getUseKeyUsage() == true) && (keyusage >= 0)) {
            final KeyUsage ku = new KeyUsage(keyusage);
            // We don't want to try to add custom extensions with the same oid if we have already added them
            // from the request, if AllowExtensionOverride is enabled.
            // Two extensions with the same oid is not allowed in the standard.
            if (overridenexts.getExtension(Extension.keyUsage) == null) {
                try {
                    extgen.addExtension(Extension.keyUsage, certProfile.getKeyUsageCritical(), ku);
                } catch (IOException e) {
                    throw new IllegalStateException("Caught unexpected IOException.", e);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "KeyUsage was already overridden by an extension, not using KeyUsage from parameter.");
                }
            }
        }
    }

    // Third, check for standard Certificate Extensions that should be added.
    // Standard certificate extensions are defined in CertificateProfile and CertificateExtensionFactory
    // and implemented in package org.ejbca.core.model.certextensions.standard
    final CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance();
    final List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions();
    final Iterator<String> certStdExtIter = usedStdCertExt.iterator();
    overridenexts = extgen.generate();
    while (certStdExtIter.hasNext()) {
        final String oid = certStdExtIter.next();
        // We don't want to try to add standard extensions with the same oid if we have already added them
        // from the request, if AllowExtensionOverride is enabled.
        // Two extensions with the same oid is not allowed in the standard.
        if (overridenexts.getExtension(new ASN1ObjectIdentifier(oid)) == null) {
            final CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile);
            if (certExt != null) {
                final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey,
                        val);
                if (value != null) {
                    extgen.addExtension(new ASN1ObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(),
                            value);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Extension with oid " + oid
                        + " has been overridden, standard extension will not be added.");
            }
        }
    }

    // Fourth, check for custom Certificate Extensions that should be added.
    // Custom certificate extensions is defined in certextensions.properties
    final List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions();
    final Iterator<Integer> certExtIter = usedCertExt.iterator();
    while (certExtIter.hasNext()) {
        final Integer id = certExtIter.next();
        final CertificateExtension certExt = fact.getCertificateExtensions(id);
        if (certExt != null) {
            // We don't want to try to add custom extensions with the same oid if we have already added them
            // from the request, if AllowExtensionOverride is enabled.
            // Two extensions with the same oid is not allowed in the standard.
            if (overridenexts.getExtension(new ASN1ObjectIdentifier(certExt.getOID())) == null) {
                final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey,
                        val);
                if (value != null) {
                    extgen.addExtension(new ASN1ObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(),
                            value);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Extension with oid " + certExt.getOID()
                            + " has been overridden, custom extension will not be added.");
                }
            }
        }
    }

    // Finally add extensions to certificate generator
    final Extensions exts = extgen.generate();
    ASN1ObjectIdentifier[] oids = exts.getExtensionOIDs();
    try {
        for (ASN1ObjectIdentifier oid : oids) {
            final Extension extension = exts.getExtension(oid);
            if (oid.equals(Extension.subjectAlternativeName)) { // subjectAlternativeName extension value needs special handling
                ExtensionsGenerator sanExtGen = getSubjectAltNameExtensionForCert(extension,
                        precertbuilder != null);
                Extensions sanExts = sanExtGen.generate();
                Extension eext = sanExts.getExtension(oid);
                certbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjetAlternativeName extension to certbuilder
                if (precertbuilder != null) { // if a pre-certificate is to be published to a CTLog
                    eext = getSubjectAltNameExtensionForCTCert(extension).generate().getExtension(oid);
                    precertbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjectAlternativeName extension to precertbuilder

                    eext = sanExts.getExtension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.4.6"));
                    if (eext != null) {
                        certbuilder.addExtension(eext.getExtnId(), eext.isCritical(), eext.getParsedValue()); // adding nrOfRedactedLabels extension to certbuilder
                    }
                }
            } else { // if not a subjectAlternativeName extension, just add it to both certbuilder and precertbuilder 
                final boolean isCritical = extension.isCritical();
                // We must get the raw octets here in order to be able to create invalid extensions that is not constructed from proper ASN.1
                final byte[] value = extension.getExtnValue().getOctets();
                certbuilder.addExtension(extension.getExtnId(), isCritical, value);
                if (precertbuilder != null) {
                    precertbuilder.addExtension(extension.getExtnId(), isCritical, value);
                }
            }
        }

        // Add Certificate Transparency extension. It needs to access the certbuilder and
        // the CA key so it has to be processed here inside X509CA.
        if (ct != null && certProfile.isUseCertificateTransparencyInCerts()
                && certGenParams.getConfiguredCTLogs() != null
                && certGenParams.getCTAuditLogCallback() != null) {

            // Create pre-certificate
            // A critical extension is added to prevent this cert from being used
            ct.addPreCertPoison(precertbuilder);

            // Sign pre-certificate
            /*
             *  TODO: Should be able to use a special CT signing certificate.
             *  It should have CA=true and ExtKeyUsage=PRECERTIFICATE_SIGNING_OID,
             *  and should not have any other key usages.
             */
            final ContentSigner signer = new BufferingContentSigner(
                    new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480);
            final X509CertificateHolder certHolder = precertbuilder.build(signer);
            final X509Certificate cert = (X509Certificate) CertTools
                    .getCertfromByteArray(certHolder.getEncoded());

            // Get certificate chain
            final List<Certificate> chain = new ArrayList<Certificate>();
            chain.add(cert);
            chain.addAll(getCertificateChain());

            // Submit to logs and get signed timestamps
            byte[] sctlist = null;
            try {
                sctlist = ct.fetchSCTList(chain, certProfile, certGenParams.getConfiguredCTLogs());
            } finally {
                // Notify that pre-cert has been successfully or unsuccessfully submitted so it can be audit logged.
                certGenParams.getCTAuditLogCallback().logPreCertSubmission(this, subject, cert,
                        sctlist != null);
            }
            if (sctlist != null) { // can be null if the CTLog has been deleted from the configuration
                ASN1ObjectIdentifier sctOid = new ASN1ObjectIdentifier(CertificateTransparency.SCTLIST_OID);
                certbuilder.addExtension(sctOid, false, new DEROctetString(sctlist));
            }
        } else {
            if (log.isDebugEnabled()) {
                String cause = "";
                if (ct == null) {
                    cause += "CT is not available in this version of EJBCA.";
                } else {
                    if (!certProfile.isUseCertificateTransparencyInCerts()) {
                        cause += "CT is not enabled in the certificate profile. ";
                    }
                    if (certGenParams == null) {
                        cause += "Certificate generation parameters was null.";
                    } else if (certGenParams.getCTAuditLogCallback() == null) {
                        cause += "No CT audit logging callback was passed to X509CA.";
                    } else if (certGenParams.getConfiguredCTLogs() == null) {
                        cause += "There are no CT logs configured in System Configuration.";
                    }
                }
                log.debug("Not logging to CT. " + cause);
            }
        }
    } catch (CertificateException e) {
        throw new CertificateCreateException(
                "Could not process CA's private key when parsing Certificate Transparency extension.", e);
    } catch (IOException e) {
        throw new CertificateCreateException(
                "IOException was caught when parsing Certificate Transparency extension.", e);
    } catch (CTLogException e) {
        throw new CertificateCreateException(
                "An exception occurred because too many CT servers were down to satisfy the certificate profile.",
                e);
    }

    //
    // End of extensions
    //

    if (log.isTraceEnabled()) {
        log.trace(">certgen.generate");
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    X509Certificate cert;
    try {
        cert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());
    } catch (IOException e) {
        throw new IllegalStateException("Unexpected IOException caught when parsing certificate holder.", e);
    } catch (CertificateException e) {
        throw new CertificateCreateException("Could not create certificate from CA's private key,", e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<certgen.generate");
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued certificate using the CA certificate we don't want to issue this cert
    // because something is wrong...
    final PublicKey verifyKey;
    // We must use the configured public key if this is a rootCA, because then we can renew our own certificate, after changing
    // the keys. In this case the _new_ key will not match the current CA certificate.
    if ((cacert != null) && (!isRootCA)) {
        verifyKey = cacert.getPublicKey();
    } else {
        verifyKey = caPublicKey;
    }
    try {
        cert.verify(verifyKey);
    } catch (InvalidKeyException e) {
        throw new CertificateCreateException("CA's public key was invalid,", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateCreateException(e);
    } catch (NoSuchProviderException e) {
        throw new IllegalStateException("Provider was unknown", e);
    } catch (CertificateException e) {
        throw new CertificateCreateException(e);
    }

    // If we have a CA-certificate, verify that we have all path verification stuff correct
    if (cacert != null) {
        final byte[] aki = CertTools.getAuthorityKeyId(cert);
        final byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert);
        if ((aki != null) && (ski != null)) {
            final boolean eq = Arrays.equals(aki, ski);
            if (!eq) {
                final String akistr = new String(Hex.encode(aki));
                final String skistr = new String(Hex.encode(ski));
                final String msg = intres.getLocalizedMessage("createcert.errorpathverifykeyid", akistr,
                        skistr);
                log.error(msg);
                // This will differ if we create link certificates, NewWithOld, therefore we can not throw an exception here.
            }
        }
        final Principal issuerDN = cert.getIssuerX500Principal();
        final Principal caSubjectDN = cacert.getSubjectX500Principal();
        if ((issuerDN != null) && (caSubjectDN != null)) {
            final boolean eq = issuerDN.equals(caSubjectDN);
            if (!eq) {
                final String msg = intres.getLocalizedMessage("createcert.errorpathverifydn",
                        issuerDN.getName(), caSubjectDN.getName());
                log.error(msg);
                throw new CertificateCreateException(msg);
            }
        }
    }
    // Before returning from this method, we will set the private key and provider in the request message, in case the response  message needs to be signed
    if (request != null) {
        request.setResponseKeyInfo(caPrivateKey, provider);
    }
    if (log.isDebugEnabled()) {
        log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: "
                + subject.getCertificateDN());
    }
    return cert;
}

From source file:org.cesecore.certificates.certificate.CertificateCreateSessionTest.java

License:Open Source License

@Test
public void testDnOrder() throws Exception {
    final CertificateProfile certprof = new CertificateProfile(
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    assertTrue(certprof.getUseLdapDnOrder());
    String finger1 = null;/*from   w w  w .j  a  v  a2 s . c  o m*/
    String finger2 = null;
    try {
        int cpId = certProfileSession.addCertificateProfile(roleMgmgToken, "createCertTest", certprof);

        // EJBCA standard has SN means serialnumber, surname is SURNAME. Must be kept for backwards compatibility
        EndEntityInformation user = new EndEntityInformation("dnorder",
                "C=SE,O=PrimeKey,SN=12345,SURNAME=surname,CN=DnOrderTest", testx509ca.getCAId(), null,
                "dnoverride@anatom.se", new EndEntityType(EndEntityTypes.ENDUSER), 0, cpId,
                EndEntityConstants.TOKEN_USERGEN, 0, null);
        user.setStatus(EndEntityConstants.STATUS_NEW);
        user.setPassword("foo123");

        SimpleRequestMessage req = new SimpleRequestMessage(keys.getPublic(), "dnorder", "foo123");
        req.setIssuerDN(CertTools.getIssuerDN(testx509ca.getCACertificate()));
        req.setRequestDN("C=SE,O=Foo Company,SN=12345,SURNAME=surname,CN=DnOrderTest"); // This should not matter now

        // Make the call
        X509ResponseMessage resp = (X509ResponseMessage) certificateCreateSession.createCertificate(
                roleMgmgToken, user, req,
                org.cesecore.certificates.certificate.request.X509ResponseMessage.class,
                signSession.fetchCertGenParams());
        assertNotNull("Failed to get response", resp);
        Certificate cert = (X509Certificate) resp.getCertificate();
        finger1 = CertTools.getFingerprintAsString(cert);
        assertNotNull("Failed to create certificate", cert);
        X500Principal princ = ((X509Certificate) cert).getSubjectX500Principal();
        X500Name name = X500Name.getInstance(princ.getEncoded());
        assertEquals("CN=DnOrderTest,SERIALNUMBER=12345,SURNAME=surname,O=PrimeKey,C=SE", name.toString());
        // Get device serial number to check that it really is the correct stuff and that SerialNumber and SurName has not gotten mixed up
        RDN[] rdns = name.getRDNs(new ASN1ObjectIdentifier("2.5.4.5")); // Device serial number
        assertEquals(1, rdns.length);
        AttributeTypeAndValue value = rdns[0].getFirst();
        assertEquals("12345", value.getValue().toString());
        rdns = name.getRDNs(new ASN1ObjectIdentifier("2.5.4.4")); // Surname (last name)
        value = rdns[0].getFirst();
        assertEquals(1, rdns.length);
        assertEquals("surname", value.getValue().toString());

        // Test reversing DN, should make a lot of difference
        certprof.setUseLdapDnOrder(false);
        certProfileSession.changeCertificateProfile(roleMgmgToken, "createCertTest", certprof);

        resp = (X509ResponseMessage) certificateCreateSession.createCertificate(roleMgmgToken, user, req,
                org.cesecore.certificates.certificate.request.X509ResponseMessage.class,
                signSession.fetchCertGenParams());
        assertNotNull("Failed to get response", resp);
        cert = (X509Certificate) resp.getCertificate();
        finger2 = CertTools.getFingerprintAsString(cert);
        assertNotNull("Failed to create certificate", cert);
        princ = ((X509Certificate) cert).getSubjectX500Principal();
        name = X500Name.getInstance(princ.getEncoded());
        assertEquals("C=SE,O=PrimeKey,SURNAME=surname,SERIALNUMBER=12345,CN=DnOrderTest", name.toString());
        // Get device serial number to check that it really is the correct stuff and that SerialNumber and SurName has not gotten mixed up
        rdns = name.getRDNs(new ASN1ObjectIdentifier("2.5.4.5")); // Device serial number
        assertEquals(1, rdns.length);
        value = rdns[0].getFirst();
        assertEquals("12345", value.getValue().toString());
        rdns = name.getRDNs(new ASN1ObjectIdentifier("2.5.4.4")); // Surname (last name)
        value = rdns[0].getFirst();
        assertEquals(1, rdns.length);
        assertEquals("surname", value.getValue().toString());
    } finally {
        certProfileSession.removeCertificateProfile(roleMgmgToken, "createCertTest");
        internalCertStoreSession.removeCertificate(finger1);
        internalCertStoreSession.removeCertificate(finger2);
    }
}

From source file:org.cesecore.certificates.certificate.request.PKCS10RequestMessage.java

License:Open Source License

@Override
public String getUsername() {
    if (username != null) {
        return username;
    }//from   ww w.ja va  2s  .  co  m
    // Special if the DN contains unstructuredAddress where it becomes: 
    // CN=pix.primekey.se + unstructuredAddress=pix.primekey.se
    // We only want the CN and not the oid-part.
    // Luckily for us this is handles automatically by BC X500Name class
    X500Name xname = getRequestX500Name();
    String ret = null;
    if (xname == null) {
        log.info("No requestDN in request, probably we could not read/parse/decrypt request.");
    } else {
        RDN[] cnValues = xname.getRDNs(CeSecoreNameStyle.CN);
        if (cnValues.length == 0) {
            log.info("No CN in DN: " + xname.toString());
        } else {
            AttributeTypeAndValue[] tavs = cnValues[0].getTypesAndValues();
            for (AttributeTypeAndValue tav : tavs) {
                if (tav.getType().equals(CeSecoreNameStyle.CN)) {
                    ret = tav.getValue().toString();
                    break;
                }
            }
            // If we have a CN with a normal name like "Test Testsson" we only want to 
            // use the first part as the username
            int index = ret.indexOf(' ');
            if (index > 0) {
                ret = ret.substring(0, index);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("UserName='" + ret + "'");
    }
    return ret;
}

From source file:org.cesecore.certificates.certificate.request.PKCS10RequestMessage.java

License:Open Source License

@Override
public String getRequestDN() {
    String ret = null;/*from   ww w. j av a 2 s.  c om*/
    X500Name name = getRequestX500Name();
    if (name != null) {
        String dn = name.toString();
        // We have to make special handling again for Cisco devices. 
        // they will submit requests like: SN=FFFFFF+unstructuredName=Router
        // EJBCA does not handle this very well so we will change it to: SN=FFFFFF,unstructuredName=Router
        dn = dn.replace("+unstructuredName=", ",unstructuredName=");
        dn = dn.replace(" + unstructuredName=", ",unstructuredName=");
        dn = dn.replace("+unstructuredAddress=", ",unstructuredAddress=");
        dn = dn.replace(" + unstructuredAddress=", ",unstructuredAddress=");
        ret = dn;
    }
    if (log.isDebugEnabled()) {
        log.debug("getRequestDN: " + ret);
    }
    return ret;
}