Example usage for java.security.cert X509Certificate getSerialNumber

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

Introduction

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

Prototype

public abstract BigInteger getSerialNumber();

Source Link

Document

Gets the serialNumber value from the certificate.

Usage

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

@Test
public void test02CrmfHttpOkUserKeyId1() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(this.issuerDN1, userDN1, this.keys, this.cacert1, nonce, transid, true, null,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId1", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);/*from   w w w. jav  a2  s  .  c  o  m*/
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN1, this.cacert1, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
    assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

    // Check key usage that it is digitalSignature for KeyId1 and
    // nonRepudiation for KeyId2
    boolean[] ku = cert.getKeyUsage();
    assertTrue(ku[0]);
    assertFalse(ku[1]);
    assertFalse(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    assertFalse(ku[8]);
    // Check DN that must be SE for KeyId1
    assertEquals("SE", CertTools.getPartFromDN(cert.getSubjectDN().getName(), "C"));

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN1, this.cacert1, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN1, this.cacert1, resp);

    // Now revoke the bastard!
    PKIMessage rev = genRevReq(this.issuerDN1, userDN1, cert.getSerialNumber(), this.cacert1, nonce, transid,
            true, null, null);
    PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
    assertNotNull(revReq);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(revReq);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpRevokeConfirmMessage(this.issuerDN1, userDN1, cert.getSerialNumber(), this.cacert1, resp, true);
    int reason = checkRevokeStatus(this.issuerDN1, cert.getSerialNumber());
    assertEquals(reason, RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION);

    // Create a revocation request for a non existing cert, chould fail!
    rev = genRevReq(this.issuerDN1, userDN1, new BigInteger("1"), this.cacert1, nonce, transid, true, null,
            null);
    revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
    assertNotNull(revReq);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(revReq);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpRevokeConfirmMessage(this.issuerDN1, userDN1, cert.getSerialNumber(), this.cacert1, resp, false);

}

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

@Test
public void test05CrmfHttpOkUserKeyId2() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, null,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId2", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);/*w w  w  .  ja va 2 s.  c o  m*/
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
    assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

    // Check key usage that it is digitalSignature for KeyId1 and
    // nonRepudiation for KeyId2
    boolean[] ku = cert.getKeyUsage();
    assertFalse(ku[0]);
    assertTrue(ku[1]);
    assertFalse(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    assertFalse(ku[8]);
    // Check DN that must be SE for KeyId1 and NO for KeyId2
    assertEquals("NO", CertTools.getPartFromDN(cert.getSubjectDN().getName(), "C"));

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN2, this.cacert2, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN2, this.cacert2, resp);

    // Now revoke the bastard!
    PKIMessage rev = genRevReq(this.issuerDN2, userDN2, cert.getSerialNumber(), this.cacert2, nonce, transid,
            true, null, null);
    PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
    assertNotNull(revReq);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(revReq);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpRevokeConfirmMessage(this.issuerDN2, userDN2, cert.getSerialNumber(), this.cacert2, resp, true);
    int reason = checkRevokeStatus(this.issuerDN2, cert.getSerialNumber());
    assertEquals(reason, RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION);
}

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   ww w . j  a v  a 2  s . 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.cesecore.util.CertTools.java

/**
 * Gets Serial number of the certificate as a string. For X509 Certificate this means a HEX encoded BigInteger, and for CVC certificate is means
 * the sequence field of the holder reference.
 * /*from ww  w.  j a v  a  2 s.c om*/
 * @param cert Certificate
 * 
 * @return String to be displayed
 */
public static String getSerialNumberAsString(Certificate cert) {
    String ret = null;
    if (cert == null) {
        throw new IllegalArgumentException("getSerialNumber: cert is null");
    }
    if (cert instanceof X509Certificate) {
        X509Certificate xcert = (X509Certificate) cert;
        ret = xcert.getSerialNumber().toString(16).toUpperCase();
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        // For CVC certificates the sequence field of the HolderReference is kind of a serial number,
        // but if can be alphanumeric which means it can not be made into a BigInteger
        CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        try {
            ret = cvccert.getCVCertificate().getCertificateBody().getHolderReference().getSequence();
        } catch (NoSuchFieldException e) {
            log.error("getSerialNumber: NoSuchFieldException: ", e);
            ret = "N/A";
        }
    } else {
        throw new IllegalArgumentException(
                "getSerialNumber: Certificate of type " + cert.getType() + " is not implemented");
    }
    return ret;
}

From source file:org.cesecore.util.CertTools.java

/**
 * Gets Serial number of the certificate.
 * //from   w  ww.j  a v  a  2s  .co  m
 * @param cert Certificate
 * 
 * @return BigInteger containing the certificate serial number. Can be 0 for CVC certificates with alphanumeric serial numbers if the sequence
 *         does not contain any number characters at all.
 * @throws IllegalArgumentException if null input of certificate type is not handled
 */
public static BigInteger getSerialNumber(Certificate cert) {
    if (cert == null) {
        throw new IllegalArgumentException("Null input");
    }
    BigInteger ret = null;
    if (cert instanceof X509Certificate) {
        X509Certificate xcert = (X509Certificate) cert;
        ret = xcert.getSerialNumber();
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        // For CVC certificates the sequence field of the HolderReference is kind of a serial number,
        // but if can be alphanumeric which means it can not be made into a BigInteger
        CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        try {
            String sequence = cvccert.getCVCertificate().getCertificateBody().getHolderReference()
                    .getSequence();
            ret = getSerialNumberFromString(sequence);
        } catch (NoSuchFieldException e) {
            log.error("getSerialNumber: NoSuchFieldException: ", e);
            ret = BigInteger.valueOf(0);
        }
    } else {
        throw new IllegalArgumentException(
                "getSerialNumber: Certificate of type " + cert.getType() + " is not implemented");
    }
    return ret;
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

/**
 * This method takes byte array and translates it onto a OCSPReq class.
 * /*w  w w .ja v a  2s .c om*/
 * @param request the byte array in question.
 * @param remoteAddress The remote address of the HttpRequest associated with this array.
 * @param transactionLogger A transaction logger.
 * @return
 * @throws MalformedRequestException
 * @throws SignRequestException thrown if an unsigned request was processed when system configuration requires that all requests be signed.
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws SignRequestSignatureException
 */
private OCSPReq translateRequestFromByteArray(byte[] request, String remoteAddress,
        TransactionLogger transactionLogger) throws MalformedRequestException, SignRequestException,
        SignRequestSignatureException, CertificateException, NoSuchAlgorithmException {
    final OCSPReq ocspRequest;
    try {
        ocspRequest = new OCSPReq(request);
    } catch (IOException e) {
        throw new MalformedRequestException("Could not form OCSP request", e);
    }
    if (ocspRequest.getRequestorName() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Requestor name is null");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Requestor name is: " + ocspRequest.getRequestorName().toString());
        }
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.REQ_NAME, ocspRequest.getRequestorName().toString());
        }
    }

    /**
     * check the signature if contained in request. if the request does not contain a signature and the servlet is configured in the way the a
     * signature is required we send back 'sigRequired' response.
     */
    if (log.isDebugEnabled()) {
        log.debug("Incoming OCSP request is signed : " + ocspRequest.isSigned());
    }
    if (ocspRequest.isSigned()) {
        final X509Certificate signercert = checkRequestSignature(remoteAddress, ocspRequest);
        final String signercertIssuerName = CertTools.getIssuerDN(signercert);
        final BigInteger signercertSerNo = CertTools.getSerialNumber(signercert);
        final String signercertSubjectName = CertTools.getSubjectDN(signercert);
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.SIGN_ISSUER_NAME_DN, signercertIssuerName);
            transactionLogger.paramPut(TransactionLogger.SIGN_SERIAL_NO,
                    signercert.getSerialNumber().toByteArray());
            transactionLogger.paramPut(TransactionLogger.SIGN_SUBJECT_NAME, signercertSubjectName);
            transactionLogger.paramPut(PatternLogger.REPLY_TIME, TransactionLogger.REPLY_TIME);
        }
        // Check if we have configured request verification using the old property file way..
        boolean enforceRequestSigning = OcspConfiguration.getEnforceRequestSigning();
        // Next, check if there is an OcspKeyBinding where signing is required and configured for this request
        // In the case where multiple requests are bundled together they all must be trusting the signer
        for (final Req req : ocspRequest.getRequestList()) {
            OcspSigningCacheEntry ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(req.getCertID());
            if (ocspSigningCacheEntry == null) {
                if (log.isTraceEnabled()) {
                    log.trace("Using default responder to check signature.");
                }
                ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getDefaultEntry();
            }
            if (ocspSigningCacheEntry != null
                    && ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                if (log.isTraceEnabled()) {
                    log.trace("ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate: "
                            + ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate());
                }
                final OcspKeyBinding ocspKeyBinding = ocspSigningCacheEntry.getOcspKeyBinding();
                if (log.isTraceEnabled()) {
                    log.trace("OcspKeyBinding " + ocspKeyBinding.getId() + ", RequireTrustedSignature: "
                            + ocspKeyBinding.getRequireTrustedSignature());
                }
                if (ocspKeyBinding.getRequireTrustedSignature()) {
                    enforceRequestSigning = true;
                    boolean isTrusted = false;
                    final List<InternalKeyBindingTrustEntry> trustedCertificateReferences = ocspKeyBinding
                            .getTrustedCertificateReferences();
                    if (trustedCertificateReferences.isEmpty()) {
                        // We trust ANY cert from a known CA
                        isTrusted = true;
                    } else {
                        for (final InternalKeyBindingTrustEntry trustEntry : trustedCertificateReferences) {
                            final int trustedCaId = trustEntry.getCaId();
                            final BigInteger trustedSerialNumber = trustEntry.fetchCertificateSerialNumber();
                            if (log.isTraceEnabled()) {
                                log.trace("Processing trustedCaId=" + trustedCaId + " trustedSerialNumber="
                                        + trustedSerialNumber + " signercertIssuerName.hashCode()="
                                        + signercertIssuerName.hashCode() + " signercertSerNo="
                                        + signercertSerNo);
                            }
                            if (trustedCaId == signercertIssuerName.hashCode()) {
                                if (trustedSerialNumber == null) {
                                    // We trust any certificate from this CA
                                    isTrusted = true;
                                    if (log.isTraceEnabled()) {
                                        log.trace(
                                                "Trusting request signature since ANY certificate from issuer "
                                                        + trustedCaId + " is trusted.");
                                    }
                                    break;
                                } else if (signercertSerNo.equals(trustedSerialNumber)) {
                                    // We trust this particular certificate from this CA
                                    isTrusted = true;
                                    if (log.isTraceEnabled()) {
                                        log.trace(
                                                "Trusting request signature since certificate with serialnumber "
                                                        + trustedSerialNumber + " from issuer " + trustedCaId
                                                        + " is trusted.");
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    if (!isTrusted) {
                        final String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed",
                                signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16));
                        log.info(infoMsg);
                        throw new SignRequestSignatureException(infoMsg);
                    }
                }
            }
        }
        if (enforceRequestSigning) {
            // If it verifies OK, check if it is revoked
            final CertificateStatus status = certificateStoreSession.getStatus(signercertIssuerName,
                    signercertSerNo);
            /*
             * If rci == null it means the certificate does not exist in database, we then treat it as ok, because it may be so that only revoked
             * certificates is in the (external) OCSP database.
             */
            if (status.equals(CertificateStatus.REVOKED)) {
                String serno = signercertSerNo.toString(16);
                String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.revoked", signercertSubjectName,
                        signercertIssuerName, serno);
                log.info(infoMsg);
                throw new SignRequestSignatureException(infoMsg);
            }
        }
    } else {
        if (OcspConfiguration.getEnforceRequestSigning()) {
            // Signature required
            throw new SignRequestException("Signature required");
        }
        // Next, check if there is an OcspKeyBinding where signing is required and configured for this request
        // In the case where multiple requests are bundled together they all must be trusting the signer
        for (final Req req : ocspRequest.getRequestList()) {
            OcspSigningCacheEntry ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(req.getCertID());
            if (ocspSigningCacheEntry == null) {
                ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getDefaultEntry();
            }
            if (ocspSigningCacheEntry != null
                    && ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                final OcspKeyBinding ocspKeyBinding = ocspSigningCacheEntry.getOcspKeyBinding();
                if (ocspKeyBinding.getRequireTrustedSignature()) {
                    throw new SignRequestException("Signature required");
                }
            }
        }
    }
    return ocspRequest;
}

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);//  w ww .  j  a v  a 2  s . c  o  m
    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:org.cesecore.util.CertTools.java

/**
 * Checks if a certificate is valid.// ww  w.  ja v a2  s  . c om
 * Does also print a WARN if the certificate is about to expire.
 * 
 * @param signerCert the certificate to be tested
 * @return true if the certificate is valid
 */
public static boolean isCertificateValid(final X509Certificate signerCert) {
    try {
        signerCert.checkValidity();
    } catch (CertificateExpiredException e) {
        log.error(intres.getLocalizedMessage("ocsp.errorcerthasexpired", signerCert.getSerialNumber(),
                signerCert.getIssuerDN()));
        return false;
    } catch (CertificateNotYetValidException e) {
        log.error(intres.getLocalizedMessage("ocsp.errornotyetvalid", signerCert.getSerialNumber(),
                signerCert.getIssuerDN()));
        return false;
    }
    final long warnBeforeExpirationTime = OcspConfiguration.getWarningBeforeExpirationTime();
    if (warnBeforeExpirationTime < 1) {
        return true;
    }
    final Date warnDate = new Date(new Date().getTime() + warnBeforeExpirationTime);
    try {
        signerCert.checkValidity(warnDate);
    } catch (CertificateExpiredException e) {
        log.warn(intres.getLocalizedMessage("ocsp.warncertwillexpire", signerCert.getSerialNumber(),
                signerCert.getIssuerDN(), signerCert.getNotAfter()));
    } catch (CertificateNotYetValidException e) {
        throw new Error("This should never happen.", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Time for \"certificate will soon expire\" not yet reached. You will be warned after: "
                + new Date(signerCert.getNotAfter().getTime() - warnBeforeExpirationTime));
    }
    return true;
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

private OCSPUnidResponse sendOCSPRequest(byte[] ocspPackage, X509Certificate knownTrustAnchor, boolean useGet)
        throws IOException, OCSPException, OperatorCreationException, CertificateException,
        UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final HttpURLConnection con;
    if (useGet) {
        String b64 = new String(Base64.encode(ocspPackage, false));
        URL url = new URL(httpReqPath + '/' + b64);
        con = (HttpURLConnection) url.openConnection();
    } else {/*  w w w  . ja  v  a2  s. c  o  m*/
        // POST the OCSP request
        URL url = new URL(httpReqPath);
        con = (HttpURLConnection) getUrlConnection(url);
        // we are going to do a POST
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        // POST it
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        OutputStream os = null;
        try {
            os = con.getOutputStream();
            os.write(ocspPackage);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }
    final OCSPUnidResponse ret = new OCSPUnidResponse();
    ret.setHttpReturnCode(con.getResponseCode());
    if (ret.getHttpReturnCode() != 200) {
        if (ret.getHttpReturnCode() == 401) {
            ret.setErrorCode(OCSPUnidResponse.ERROR_UNAUTHORIZED);
        } else {
            ret.setErrorCode(OCSPUnidResponse.ERROR_UNKNOWN);
        }
        return ret;
    }
    final OCSPResp response;
    {
        final InputStream in = con.getInputStream();
        if (in != null) {
            try {
                response = new OCSPResp(IOUtils.toByteArray(in));
            } finally {
                in.close();
            }
        } else {
            response = null;
        }
    }
    if (response == null) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE);
        return ret;
    }
    ret.setResp(response);
    final BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    if (brep == null) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE);
        return ret;
    }
    // Compare nonces to see if the server sent the same nonce as we sent
    final byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue()
            .getEncoded();
    if (noncerep != null) {
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        boolean eq = ArrayUtils.isEquals(this.nonce, oct.getOctets());
        if (!eq) {
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_NONCE);
            return ret;
        }
    }

    final RespID id = brep.getResponderId();
    final DERTaggedObject to = (DERTaggedObject) id.toASN1Object().toASN1Primitive();
    final RespID respId;
    final X509CertificateHolder[] chain = brep.getCerts();
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    X509Certificate signerCertificate = converter.getCertificate(chain[0]);
    final PublicKey signerPub = signerCertificate.getPublicKey();
    if (to.getTagNo() == 1) {
        // This is Name
        respId = new JcaRespID(signerCertificate.getSubjectX500Principal());
    } else {
        // This is KeyHash
        respId = new JcaRespID(signerPub, SHA1DigestCalculator.buildSha1Instance());
    }
    if (!id.equals(respId)) {
        // Response responderId does not match signer certificate responderId!
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERID);
    }
    if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(signerPub))) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNATURE);
        return ret;
    }

    /* 
     * Okay, at this point we have three different variables and six different possible valid use cases. These
     * variables are:
     *          1. If the OCSP reply is from a CA (integrated) or an OCSP responder (standalone) 
     *          2. If it was from a CA, then if that CA is self signed or a subCA
     *          3. If the server (in the integrated case) or keybinding (standalone case) was set to include the certificate chain
     */

    //If we have a chain, verify it
    if (chain.length > 1) {
        // end at one shortof chain.length, because the root certificate is (usually) not included in the OCSP response
        // TODO: improve this when we can pass in the root cert from parameter to properly validate the whole chain
        for (int i = 0; i + 1 < chain.length; i++) {
            final X509Certificate cert1 = converter.getCertificate(chain[i]);
            final X509Certificate cert2 = converter.getCertificate(chain[Math.min(i + 1, chain.length - 1)]);
            try {
                cert1.verify(cert2.getPublicKey());
            } catch (GeneralSecurityException e) {
                m_log.info("Verifying problem with", e);
                m_log.info("Certificate to be verified: " + cert1);
                m_log.info("Verifying certificate: " + cert2);
                ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
                return ret;
            }
        }
    }

    if (CertTools.isCA(signerCertificate)) {
        //Verify that the signer certificate was the same as the trust anchor
        if (!signerCertificate.getSerialNumber().equals(knownTrustAnchor.getSerialNumber())) {
            m_log.info("Signing certificate for integrated OCSP was not the provided trust anchor.");
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
            return ret;
        }
    } else if (CertTools.isOCSPCert(signerCertificate)) {
        //If an OCSP certificate was used to sign
        try {
            signerCertificate.verify(knownTrustAnchor.getPublicKey());
        } catch (GeneralSecurityException e) {
            m_log.info("Signing certificate was not signed by known trust anchor.");
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
            return ret;
        }
    } else {
        m_log.info("Signing certificate was not an OCSP certificate.");
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
        return ret;
    }

    String fnr = getFnr(brep);
    if (fnr != null) {
        ret.setFnr(fnr);
    }
    return ret;
}