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.ws.EjbcaWSTest.java

@Test
public void test19RevocationApprovals() throws Exception {
    log.trace(">test19RevocationApprovals");
    final String APPROVINGADMINNAME = "superadmin";
    final String TOKENSERIALNUMBER = "42424242";
    final String TOKENUSERNAME = "WSTESTTOKENUSER3";
    final String ERRORNOTSENTFORAPPROVAL = "The request was never sent for approval.";
    final String ERRORNOTSUPPORTEDSUCCEEDED = "Reactivation of users is not supported, but succeeded anyway.";

    // Generate random username and CA name
    String randomPostfix = Integer.toString(secureRandom.nextInt(999999));
    String caname = "wsRevocationCA" + randomPostfix;
    String username = "wsRevocationUser" + randomPostfix;
    int cryptoTokenId = 0;
    int caID = -1;
    try {//from ww  w . j  a  v a2 s. c  om
        cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(intAdmin, caname, "1024");
        final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId,
                AlgorithmConstants.SIGALG_SHA1_WITH_RSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
        caID = RevocationApprovalTest.createApprovalCA(intAdmin, caname, CAInfo.REQ_APPROVAL_REVOCATION,
                caAdminSessionRemote, caSession, catoken);
        X509Certificate adminCert = (X509Certificate) certificateStoreSession
                .findCertificatesByUsername(APPROVINGADMINNAME).iterator().next();
        Set<X509Certificate> credentials = new HashSet<X509Certificate>();
        credentials.add(adminCert);
        Set<Principal> principals = new HashSet<Principal>();
        principals.add(adminCert.getSubjectX500Principal());
        AuthenticationToken approvingAdmin = simpleAuthenticationProvider
                .authenticate(new AuthenticationSubject(principals, credentials));
        //AuthenticationToken approvingAdmin = new X509CertificateAuthenticationToken(principals, credentials);
        //Admin approvingAdmin = new Admin(adminCert, APPROVINGADMINNAME, null);
        try {
            X509Certificate cert = createUserAndCert(username, caID);
            String issuerdn = cert.getIssuerDN().toString();
            String serno = cert.getSerialNumber().toString(16);
            // revoke via WS and verify response
            try {
                ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (WaitingForApprovalException_Exception e1) {
            }
            try {
                ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (ApprovalException_Exception e1) {
            }
            RevokeStatus revokestatus = ejbcaraws.checkRevokationStatus(issuerdn, serno);
            assertNotNull(revokestatus);
            assertTrue(revokestatus.getReason() == RevokedCertInfo.NOT_REVOKED);
            // Approve revocation and verify success
            approveRevocation(intAdmin, approvingAdmin, username,
                    RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD,
                    ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession,
                    approvalExecutionSession, caID);
            // Try to unrevoke certificate
            try {
                ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.NOT_REVOKED);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (WaitingForApprovalException_Exception e) {
            }
            try {
                ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.NOT_REVOKED);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (ApprovalException_Exception e) {
            }
            // Approve revocation and verify success
            approveRevocation(intAdmin, approvingAdmin, username, RevokedCertInfo.NOT_REVOKED,
                    ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession,
                    approvalExecutionSession, caID);
            // Revoke user
            try {
                ejbcaraws.revokeUser(username, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, false);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (WaitingForApprovalException_Exception e) {
            }
            try {
                ejbcaraws.revokeUser(username, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, false);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (ApprovalException_Exception e) {
            }
            // Approve revocation and verify success
            approveRevocation(intAdmin, approvingAdmin, username,
                    RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD,
                    ApprovalDataVO.APPROVALTYPE_REVOKEENDENTITY, certificateStoreSession, approvalSession,
                    approvalExecutionSession, caID);
            // Try to reactivate user
            try {
                ejbcaraws.revokeUser(username, RevokedCertInfo.NOT_REVOKED, false);
                assertTrue(ERRORNOTSUPPORTEDSUCCEEDED, false);
            } catch (AlreadyRevokedException_Exception e) {
            }
        } finally {
            endEntityManagementSession.deleteUser(intAdmin, username);
        }
        try {
            // Create a hard token issued by this CA
            createHardToken(TOKENUSERNAME, caname, TOKENSERIALNUMBER);
            assertTrue(ejbcaraws.existsHardToken(TOKENSERIALNUMBER));
            // Revoke token
            try {
                ejbcaraws.revokeToken(TOKENSERIALNUMBER, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (WaitingForApprovalException_Exception e) {
            }
            try {
                ejbcaraws.revokeToken(TOKENSERIALNUMBER, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                assertTrue(ERRORNOTSENTFORAPPROVAL, false);
            } catch (ApprovalException_Exception e) {
            }
            // Approve actions and verify success
            approveRevocation(intAdmin, approvingAdmin, TOKENUSERNAME,
                    RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD,
                    ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession,
                    approvalExecutionSession, caID);
        } finally {
            hardTokenSessionRemote.removeHardToken(intAdmin, TOKENSERIALNUMBER);
        }
    } finally {
        // Nuke CA
        try {
            caAdminSessionRemote.revokeCA(intAdmin, caID, RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED);
        } finally {
            caSession.removeCA(intAdmin, caID);
            CryptoTokenTestUtils.removeCryptoToken(intAdmin, cryptoTokenId);
        }
    }
    log.trace("<test19RevocationApprovals");
}

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

public void test03CrmfHttpOkUser() throws Exception {
    log.trace(">test02CrmfHttpOkUser");
    // Create a new good user
    createCmpUser();/*from   w  w  w  .  jav a  2 s. c om*/

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

    PKIMessage req = genCertReq(issuerDN, userDN, keys, cacert, nonce, transid, false, null, null, null, null);
    assertNotNull(req);
    int reqId = req.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();
    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);
    checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, true, null);
    X509Certificate cert = checkCmpCertRepMessage(userDN, cacert, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertNull("AltNames was not null (" + altNames + ").", altNames);

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN, cacert, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(confirm);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200);
    checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, null);
    checkCmpPKIConfirmMessage(userDN, cacert, resp);

    // Now revoke the bastard!
    PKIMessage rev = genRevReq(issuerDN, userDN, cert.getSerialNumber(), cacert, nonce, transid, true);
    assertNotNull(rev);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(rev);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200);
    checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, null);
    checkCmpFailMessage(resp, "PKI Message is not athenticated properly. No HMAC protection was found.", 23,
            reqId, 1);
    log.trace("<test02CrmfHttpOkUser");
}

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

/**
 * Valida mediante ocsp RFC 2560, el certificado indicado.
 * /*from w ww .ja va  2s  .  c o m*/
 * @param certificadoX509
 *            Certificado que deseamos validar.
 * @param certificadoX509Emisor
 *            Certificado emisor del certificado a validar.
 * @return
 * @throws CertPathValidatorException
 */
private CodigoError validarOCSP(X509Certificate certificadoX509, X509Certificate certificadoX509Emisor)
        throws CertPathValidatorException {
    // Si la validacin esta desactivada consideramos el certificado
    // validado.
    if (validacionOnline) {
        try {
            // Generamos la peticin OCSP para el certificado.
            OCSPReq request = generateRequest(certificadoX509, certificadoX509Emisor);

            // Recuperamos la url desde la que realizar la validacin OCSP
            String url = getUrlOCSP(certificadoX509);

            // Bytes del request
            byte[] byteRequest = request.getEncoded();

            // Enviamos la peticin y recuperamos la respuesta
            InputStream inResponse = sendRequest(url, byteRequest);
            OCSPResp ocspResponse = new OCSPResp(inResponse);

            // but why Response Status is 6(No Valid)..?
            if (OCSPResponseStatus.SUCCESSFUL == ocspResponse.getStatus()) {
                log.info("Obtenida respuesta correcta OCSP.  Estado:" + ocspResponse.getStatus());
                CertificateID certID = new CertificateID(CertificateID.HASH_SHA1, certificadoX509Emisor,
                        certificadoX509.getSerialNumber());
                BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject();

                // Comprobamos que la respuesta OCSP no ha sido manipulada y
                // ha sido firmada por un certificado de confianza.
                // Recupero el certificado con el que debe haber sido
                // firmado el ocsp
                checkOCSP(brep);
                SingleResp[] singleResp = brep.getResponses();

                for (SingleResp resp : singleResp) {
                    CertificateID respCertID = resp.getCertID();
                    if (respCertID.equals(certID)) {
                        Object status = resp.getCertStatus();
                        if (status == CertificateStatus.GOOD) {
                            log.debug("OCSPChecker: Status of certificate is: good");
                            break;
                        } else if (status instanceof org.bouncycastle.ocsp.RevokedStatus) {
                            log.debug("OCSPChecker: Status of certificate is: revoked");
                            throw new CertPathValidatorException("Certificate has been revoked");
                        } else if (status instanceof org.bouncycastle.ocsp.UnknownStatus) {
                            log.debug("OCSPChecker: Status of certificate is: unknown");
                            throw new CertPathValidatorException("Certificate's revocation status is unknown");
                        } else {
                            log.debug("Status of certificate is: not recognized");
                            throw new CertPathValidatorException("Unknown OCSP response for certificate");
                        }
                    }

                }

                return CodigoError.OK_CERTIFICADO_VALIDADO;
            } else {
                /**
                 * successful (0), --Response has valid confirmations
                 * malformedRequest (1), --Illegal confirmation request
                 * internalError (2), --Internal error in issuer tryLater
                 * (3), --Try again later --(4) is not used sigRequired (5),
                 * --Must sign the request unauthorized (6) --Request
                 * unauthorized
                 */
                if (OCSPResponseStatus.MALFORMED_REQUEST == ocspResponse.getStatus()) {
                    log.warn(
                            "Obtenida respuesta Incorrecta OCSP: malformedRequest (1), --Illegal confirmation request. estatus: "
                                    + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_URL;
                } else if (OCSPResponseStatus.INTERNAL_ERROR == ocspResponse.getStatus()) {
                    log.warn(
                            "Obtenida respuesta Incorrecta OCSP: internalError (2),--Internal error in issuer. estatus: "
                                    + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_INTERNAL_ERROR;
                } else if (OCSPResponseStatus.TRY_LATER == ocspResponse.getStatus()) {
                    log.warn("Obtenida respuesta Incorrecta OCSP: tryLater (3), --Try again later. estatus: "
                            + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_TRY_LATER;
                } else if (OCSPResponseStatus.SIG_REQUIRED == ocspResponse.getStatus()) {
                    log.warn(
                            "Obtenida respuesta Incorrecta OCSP: sigRequired(5),--Must sign the request. estatus: "
                                    + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_INTERNAL_ERROR;
                } else if (OCSPResponseStatus.SIG_REQUIRED == ocspResponse.getStatus()) {
                    log.warn(
                            "Obtenida respuesta Incorrecta OCSP: unauthorized (6)--Request unauthorized. estatus: "
                                    + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_INTERNAL_ERROR;
                } else {
                    log.warn(
                            "Obtenida una respuesta incorrecta OCSP, probablemente el certificado este caducado.");
                    return CodigoError.ERROR_VALIDACION_CERTIFICADO_CADUCADO;
                }

            }

        } catch (OCSPException e) {
            log.fatal(CodigoError.ERROR_OCSP_INTERNAL_ERROR, e);
            return CodigoError.ERROR_OCSP_INTERNAL_ERROR;
        } catch (ExcepcionErrorInterno e) {
            log.error("No se puede validar el certificado. ", e);
            return e.getCodError();
        } catch (IOException e) {
            log.fatal(CodigoError.ERROR_INTERNO, e);
            return CodigoError.ERROR_INTERNO;
        }
    } else {
        log.info("La validacin online OCSP esta desactivada. Consideramos el certificado Vlido.");
        return CodigoError.OK_CERTIFICADO_VALIDADO;
    }
}

From source file:com.netscape.cms.servlet.cert.RenewalProcessor.java

private BigInteger getSerialNumberFromCert(HttpServletRequest request) throws EBaseException {

    SSLClientCertProvider sslCCP = new SSLClientCertProvider(request);
    X509Certificate[] certs = sslCCP.getClientCertificateChain();

    if (certs == null || certs.length == 0) {
        CMS.debug("RenewalProcessor: missing SSL client certificate chain");
        throw new BadRequestException("Missing SSL client certificate chain");
    }//from  w w w  .  j a  v  a 2  s .c o  m

    CMS.debug("RenewalProcessor: has SSL client cert chain");
    // shouldn't expect leaf cert to be always at the
    // same location

    X509Certificate clientCert = null;
    for (X509Certificate cert : certs) {

        CMS.debug("RenewalProcessor: cert " + cert.getSubjectDN());
        clientCert = cert;

        byte[] extBytes = clientCert.getExtensionValue("2.5.29.19");

        // try to see if this is a leaf cert
        // look for BasicConstraint extension
        if (extBytes == null) {
            // found leaf cert
            CMS.debug("RenewalProcessor: found leaf cert");
            break;
        }

        CMS.debug("RenewalProcessor: found cert having BasicConstraints ext");
        // it's got BasicConstraints extension
        // so it's not likely to be a leaf cert,
        // however, check the isCA field regardless

        try {
            BasicConstraintsExtension bce = new BasicConstraintsExtension(true, extBytes);
            if (!(Boolean) bce.get("is_ca")) {
                CMS.debug("RenewalProcessor: found CA cert in chain");
                break;
            } // else found a ca cert, continue

        } catch (Exception e) {
            CMS.debug("RenewalProcessor: Invalid certificate extension:" + e);
            throw new BadRequestException("Invalid certificate extension: " + e.getMessage(), e);
        }
    }

    // clientCert cannot be null here

    return clientCert.getSerialNumber();
}

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

/**
 * @param userDN/*from   w w  w .ja va2s.  c  o m*/
 *            for new certificate.
 * @param keys
 *            key of the new certificate.
 * @param sFailMessage
 *            if !=null then EJBCA is expected to fail. The failure response
 *            message string is checked against this parameter.
 * @return If it is a certificate request that results in a successful certificate issuance, this certificate is returned
 * @throws Exception
 */
private X509Certificate crmfHttpUserTest(X500Name userDN, KeyPair keys, String sFailMessage,
        BigInteger customCertSerno) throws Exception {

    X509Certificate ret = null;
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;
    {
        final PKIMessage one = genCertReq(this.issuerDN, userDN, keys, this.cacert, nonce, transid, true, null,
                null, null, customCertSerno, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        assertNotNull(req);
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        // do not check signing if we expect a failure (sFailMessage==null)
        checkCmpResponseGeneral(resp, this.issuerDN, userDN, this.cacert, nonce, transid, sFailMessage == null,
                null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        if (sFailMessage == null) {
            ret = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
            // verify if custom cert serial number was used
            if (customCertSerno != null) {
                assertTrue(ret.getSerialNumber().toString(16) + " is not same as expected "
                        + customCertSerno.toString(16), ret.getSerialNumber().equals(customCertSerno));
            }
        } else {
            checkCmpFailMessage(resp, sFailMessage, CmpPKIBodyConstants.ERRORMESSAGE, reqId,
                    PKIFailureInfo.badRequest, PKIFailureInfo.incorrectData);
        }
    }
    {
        // Send a confirm message to the CA
        final String hash = "foo123";
        final PKIMessage con = genCertConfirm(userDN, this.cacert, nonce, transid, hash, reqId);
        assertNotNull(con);
        PKIMessage confirm = protectPKIMessage(con, false, PBEPASSWORD, 567);
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(confirm);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, this.issuerDN, userDN, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(userDN, this.cacert, resp);
    }
    return ret;
}

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

@Test
public void testKeyRenewal() throws Exception {
    //Add localhost to list of rekeying triggering hosts.
    Set<String> originalHosts = OcspConfiguration.getRekeyingTriggingHosts();
    String originalRekeyingPassword = OcspConfiguration.getRekeyingTriggingPassword();
    configurationSession.setConfigurationValue(OcspConfiguration.REKEYING_TRIGGERING_HOSTS, "127.0.0.1");
    configurationSession.setConfigurationValue(OcspConfiguration.REKEYING_TRIGGERING_PASSWORD, "foo123");
    ocspResponseGeneratorTestSession.reloadOcspSigningCache();
    List<X509Certificate> oldValues = ocspResponseGeneratorTestSession.getCacheOcspCertificates();
    try {/*from  w ww . ja va  2  s  .com*/
        X509Certificate cert = getActiveTestCert();
        X509Certificate caCertificate = getCaCert(cert);
        helper.renewAllKeys();
        ocspResponseGeneratorTestSession.reloadOcspSigningCache();
        List<X509Certificate> newValues = ocspResponseGeneratorTestSession.getCacheOcspCertificates();
        //Make sure that cache contains one and only one value
        assertEquals(
                "Cache contains a different amount of values after rekeying than before. This indicates a test failure",
                oldValues.size(), newValues.size());
        //Make check that the certificate has changed (sanity check)
        X509Certificate newSigningCertificate = null;
        for (X509Certificate signingCertificate : newValues) {
            if (CertTools.getIssuerDN(signingCertificate).equals(CertTools.getSubjectDN(caCertificate))) {
                newSigningCertificate = signingCertificate;
                break;
            }
        }
        assertNotEquals("The same certificate was returned after the renewal process. Key renewal failed",
                cert.getSerialNumber(), newSigningCertificate.getSerialNumber());
        //Make sure that the new certificate is signed by the CA certificate
        try {
            newSigningCertificate.verify(caCertificate.getPublicKey());
        } catch (SignatureException e) {
            log.error("Exception caught", e);
            fail("The new signing certificate was not signed correctly.");
        }

    } finally {
        StringBuilder originalHostsString = new StringBuilder();
        for (String host : originalHosts.toArray(new String[originalHosts.size()])) {
            originalHostsString.append(host + ";");
        }
        configurationSession.setConfigurationValue(OcspConfiguration.REKEYING_TRIGGERING_HOSTS,
                originalHostsString.toString());
        configurationSession.setConfigurationValue(OcspConfiguration.REKEYING_TRIGGERING_PASSWORD,
                originalRekeyingPassword);
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

private String revokeInternal(User revoker, Enrollment enrollment, String reason, boolean genCRL)
        throws RevocationException, InvalidArgumentException {

    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }//  w w w. ja v a 2 s . co  m

    if (enrollment == null) {
        throw new InvalidArgumentException("revokee enrollment is not set");
    }
    if (revoker == null) {
        throw new InvalidArgumentException("revoker is not set");
    }

    logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url));

    try {
        setUpSSL();

        // get cert from to-be-revoked enrollment
        BufferedInputStream pem = new BufferedInputStream(
                new ByteArrayInputStream(enrollment.getCert().getBytes()));
        CertificateFactory certFactory = CertificateFactory
                .getInstance(Config.getConfig().getCertificateFormat());
        X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem);

        // get its serial number
        String serial = DatatypeConverter.printHexBinary(certificate.getSerialNumber().toByteArray());

        // get its aki
        // 2.5.29.35 : AuthorityKeyIdentifier
        byte[] extensionValue = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId());
        ASN1OctetString akiOc = ASN1OctetString.getInstance(extensionValue);
        String aki = DatatypeConverter
                .printHexBinary(AuthorityKeyIdentifier.getInstance(akiOc.getOctets()).getKeyIdentifier());

        // build request body
        RevocationRequest req = new RevocationRequest(caName, null, serial, aki, reason, genCRL);
        String body = req.toJson();

        // send revoke request
        JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker);
        logger.debug("revoke done");

        if (genCRL) {
            if (resp.isEmpty()) {
                throw new RevocationException("Failed to return CRL, revoke response is empty");
            }
            if (resp.isNull("CRL")) {
                throw new RevocationException("Failed to return CRL");
            }
            return resp.getString("CRL");
        }
        return null;
    } catch (CertificateException e) {
        logger.error("Cannot validate certificate. Error is: " + e.getMessage());
        throw new RevocationException("Error while revoking cert. " + e.getMessage(), e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RevocationException("Error while revoking the user. " + e.getMessage(), e);

    }
}

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

/**
 * Gets Serial number of the certificate.
 *
 * @param cert Certificate//from   w  w w  .  j  a  v  a2  s  . c om
 *
 * @return BigInteger containing the certificate serialNumber. Can be 0 for CVC certificates with alphanumering serialnumbers if the sequence does not contain any number characters at all.
 */
public static BigInteger getSerialNumber(Certificate cert) {
    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:com.viettel.hqmc.DAO.FilesExpandDAO.java

public String actionSignCA() throws IOException {
    boolean result = true;
    String base64Hash = "";
    String base64Hash0 = "";
    String certSerial = "";
    String fileId = "";
    String outPutFileFinal = "";
    String outPutFileFinal2 = "";
    String fileName = "";
    String fileToSign = "";
    String errorCode = "";
    SignPdfFile pdfSig = new SignPdfFile();
    try {//from   w  w w.  j av a  2 s.  co  m
        fileId = getRequest().getParameter("fileId");
        String rootCert = null, base64Certificate = null, certChain;
        Base64 decoder = new Base64();
        certChain = new String(decoder.decode(getRequest().getParameter("cert").replace("_", "+").getBytes()),
                "UTF-8");
        String sToFind = getRequest().getParameter("signType");
        String path = getRequest().getParameter("path");
        String[] pathArr = path.split(";");
        fileToSign = pathArr[0];
        fileName = pathArr[1];
        String[] chain;
        try {
            chain = certChain.split(",");
            rootCert = chain[1];
            base64Certificate = chain[0];
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            errorCode = "SI_001";
            result = false;
        }
        // hieptq update 150615
        if (base64Certificate == null) {
            errorCode = "SI_002";
            result = false;
        }
        X509Certificate x509Cert = null;
        X509Certificate x509CertChain = null;
        try {
            x509Cert = CertUtils.getX509Cert(base64Certificate);
            x509CertChain = CertUtils.getX509Cert(rootCert);
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            errorCode = "SI_003";
            result = false;
        }

        PDFServerClientSignature pdfSCS = new PDFServerClientSignature();
        ResourceBundle rb = ResourceBundle.getBundle("config");
        String TSA_LINK = rb.getString("tsaUrl");
        pdfSCS.setTSA_LINK(TSA_LINK);
        String checkOcspStr = rb.getString("checkOCSP");
        Long checkOCSP = Long.parseLong(checkOcspStr);
        try {
            certSerial = x509Cert.getSerialNumber().toString(16);
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            errorCode = "SI_004";
            result = false;
        }
        // hieptq update 160615 - check serial        
        String filePath = rb.getString("sign_temp_plugin");
        File f = new File(filePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        outPutFileFinal = filePath + fileName;
        CaUserDAOHE ca = new CaUserDAOHE();
        boolean checkCaUser = true;
        if (!ca.checkCaSerial("SerialNumber:[" + certSerial + "]")) {
            errorCode = "SI_005";
            result = false;
        }
        try {
            if (checkOCSP == 1l) {
                OCSP.RevocationStatus.CertStatus status = checkRevocationStatus((X509Certificate) x509Cert,
                        (X509Certificate) x509CertChain);
                if (status != OCSP.RevocationStatus.CertStatus.GOOD) {
                    errorCode = "SI_006";
                    result = false;
                }
            }
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            errorCode = "SI_007";
            result = false;
        }
        if (checkCaUser) {
            String folderPath = ResourceBundleUtil.getString("sign_image");
            String linkImageSign = folderPath + getUserId() + ".png";
            String linkImageStamp = folderPath + "attpStamp.png";
            if ((linkImageSign == null && "".equals(linkImageSign))
                    || (linkImageStamp == null && "".equals(linkImageStamp))) {
                errorCode = "SI_008";
                result = false;
            }
            try {
                if ("PDHS".equals(sToFind)) {
                    // ky lanh dao
                    if (fileToSign == null && "".equals(fileToSign)) {
                        errorCode = "SI_009";
                        result = false;
                    }
                    sToFind = "<SI>";
                    SearchTextLocations ptl = new SearchTextLocations();
                    List local = ptl.searchLocation(sToFind, fileToSign, SearchTextLocations.SEARCH_TOPDOWN,
                            SearchTextLocations.FIND_ONE);
                    String location = "0;0;0";
                    int pageNumber, lx, ly;
                    if (local != null && local.size() > 0) {
                        location = local.get(0).toString();
                    }
                    String[] parts = location.split(";");
                    pageNumber = Integer.parseInt(parts[0]);
                    lx = (int) Float.parseFloat(parts[1]);
                    ly = (int) Float.parseFloat(parts[2]);
                    ly = convertLocation(ly);
                    base64Hash = pdfSig.createHash(fileToSign, outPutFileFinal, new Certificate[] { x509Cert },
                            pageNumber, linkImageSign, lx + 70, ly + 130, 120, 70, "LD");
                }
                if ("PDHS_VT".equals(sToFind)) {
                    // ky van thu
                    if (fileToSign == null && "".equals(fileToSign)) {
                        errorCode = "SI_010";
                        result = false;
                    }
                    String sToFindtemp = "<SI>";
                    SearchTextLocations ptl = new SearchTextLocations();
                    List local = ptl.searchLocation(sToFindtemp, fileToSign, SearchTextLocations.SEARCH_TOPDOWN,
                            SearchTextLocations.FIND_ONE);
                    String location = "0;0;0";
                    int pageNumber, lx, ly;
                    if (local != null && local.size() > 0) {
                        location = local.get(0).toString();
                    }
                    String[] parts = location.split(";");
                    pageNumber = Integer.parseInt(parts[0]);
                    lx = (int) Float.parseFloat(parts[1]);
                    ly = (int) Float.parseFloat(parts[2]);
                    ly = convertLocation(ly);
                    base64Hash = pdfSig.createHash(fileToSign, outPutFileFinal, new Certificate[] { x509Cert },
                            pageNumber, linkImageStamp, lx + 23, ly + 115, 90, 90, "VT");
                }
            } catch (Exception ex) {
                LogUtil.addLog(ex);//binhnt sonar a160901
                System.out.println("ERROR SI_012|" + ex.getMessage());
                errorCode = "SI_012";
                result = false;
            }

        } else {
            errorCode = "SI_013";
            result = false;
        }
    } catch (JsonSyntaxException ex) {
        LogUtil.addLog(ex);//binhnt sonar a160901
        errorCode = "SI_014";
        result = false;
    } catch (Exception ex) {
        LogUtil.addLog(ex);//binhnt sonar a160901
        errorCode = "SI_015";
        result = false;
    } finally {

    }
    List resultMessage = new ArrayList();
    if (result) {
        HttpServletRequest req = getRequest();
        HttpSession session = req.getSession();
        session.setAttribute("PDFSignature", pdfSig);
        resultMessage.add("1");
        resultMessage.add("Lu d liu thnh cng");
        resultMessage.add(base64Hash);
        resultMessage.add(certSerial);
        resultMessage.add(fileId);
        resultMessage.add(outPutFileFinal);
        resultMessage.add(fileName);
        resultMessage.add(base64Hash0);
        resultMessage.add(outPutFileFinal2);
    } else {
        resultMessage.add("0");
        resultMessage.add("Lu d liu khng thnh cng " + errorCode);
    }
    jsonDataGrid.setItems(resultMessage);
    return GRID_DATA;
}