Example usage for java.security.cert Certificate toString

List of usage examples for java.security.cert Certificate toString

Introduction

In this page you can find the example usage for java.security.cert Certificate toString.

Prototype

public abstract String toString();

Source Link

Document

Returns a string representation of this certificate.

Usage

From source file:com.google.appengine.tck.appidentity.AppIdentityServiceTest.java

private Exception createExceptionForLog(Exception e, int certNum, Certificate cert) {
    return new Exception(e + ": certNum:" + certNum + " : " + cert.toString());
}

From source file:org.jasig.portal.security.provider.saml.SSLSecurityImpl.java

private void setSSLClientCredentials(PrivateKey pk, Certificate cert) throws KeyStoreException,
        NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException {
    this.logger.info("Private key: [{}].", pk.toString());
    this.logger.info("Certificate: [{}].", cert.toString());
    KeyStore ks = KeyStore.getInstance("JKS", "SUN");
    ks.load(null, null);//from   ww  w .  j a v  a  2s  .com
    Certificate[] certificates = new Certificate[1];
    certificates[0] = cert;
    String keystorePass = UUID.randomUUID().toString();
    ks.setKeyEntry("sp", pk, keystorePass.toCharArray(), certificates);
    this.keyStore = ks;
    this.keyStorePass = keystorePass;
}

From source file:com.netflix.ice.login.saml.Saml.java

public LoginResponse processLogin(HttpServletRequest request) throws LoginMethodException {
    IceSession iceSession = new IceSession(request.getSession());
    iceSession.voidSession(); //a second login request voids anything previous
    logger.info("Saml::processLogin");
    LoginResponse lr = new LoginResponse();
    String assertion = (String) request.getParameter("SAMLResponse");
    if (assertion == null) {
        lr.redirectTo = config.singleSignOnUrl;
        return lr;
    }//w  ww . j  av a 2s.  c o m
    logger.trace("Received SAML Assertion: " + assertion);
    try {
        // 1.1 2.0 schemas
        Schema schema = SAMLSchemaBuilder.getSAML11Schema();

        //get parser pool manager
        BasicParserPool parserPoolManager = new BasicParserPool();
        parserPoolManager.setNamespaceAware(true);
        parserPoolManager.setIgnoreElementContentWhitespace(true);
        parserPoolManager.setSchema(schema);

        String data = new String(Base64.decode(assertion));
        logger.info("Decoded SAML Assertion: " + data);

        StringReader reader = new StringReader(data);
        Document document = parserPoolManager.parse(reader);
        Element documentRoot = document.getDocumentElement();

        QName qName = new QName(documentRoot.getNamespaceURI(), documentRoot.getLocalName(),
                documentRoot.getPrefix());

        //get an unmarshaller
        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(documentRoot);

        //unmarshall using the document root element
        XMLObject xmlObj = unmarshaller.unmarshall(documentRoot);
        Response response = (Response) xmlObj;
        for (Assertion myAssertion : response.getAssertions()) {
            if (!myAssertion.isSigned()) {
                logger.error("SAML Assertion not signed");
                throw new LoginMethodException("SAML Assertions must be signed by a trusted provider");
            }

            Signature assertionSignature = myAssertion.getSignature();
            SAMLSignatureProfileValidator profVal = new SAMLSignatureProfileValidator();

            logger.info("Validating SAML Assertion");
            // will throw a ValidationException 
            profVal.validate(assertionSignature);

            //Credential signCred = assertionSignature.getSigningCredential();
            boolean goodSignature = false;
            for (Certificate trustedCert : trustedSigningCerts) {
                BasicCredential cred = new BasicCredential();
                cred.setPublicKey(trustedCert.getPublicKey());
                SignatureValidator validator = new SignatureValidator(cred);
                try {
                    validator.validate(assertionSignature);
                } catch (ValidationException ve) {
                    /* Not a good key! */
                    logger.debug("Not signed by " + trustedCert.toString());
                    continue;
                }
                logger.info("Assertion trusted from " + trustedCert.toString());
                processAssertion(iceSession, myAssertion, lr);
                goodSignature = true;
                break;
            }

            if (goodSignature) {
                lr.loginSuccess = true;
            }

        }
    } catch (org.xml.sax.SAXException saxe) {
        logger.error(saxe.toString());
    } catch (org.opensaml.xml.parse.XMLParserException xmlpe) {
        logger.error(xmlpe.toString());
    } catch (org.opensaml.xml.io.UnmarshallingException uee) {
        logger.error(uee.toString());
    } catch (org.opensaml.xml.validation.ValidationException ve) {
        throw new LoginMethodException("SAML Assertion Signature was not usable: " + ve.toString());
    }
    return lr;
}

From source file:com.google.appengine.tck.appidentity.AppIdentityServiceTest.java

private boolean verifySignatureWithAllCertsForApp(byte[] blob, byte[] signedBlob,
        Collection<PublicCertificate> certsForApp) {

    if (certsForApp.isEmpty()) {
        throw new IllegalStateException("No certificates to validate.  Must have at least 1.");
    }//  w  w w .ja v  a 2 s .  c  o m
    int currentCertNum = 0;
    int totalValid = 0;
    int totalInvalid = 0;
    List<Exception> allExceptions = new ArrayList<>();

    for (PublicCertificate publicCert : certsForApp) {
        Signature signature;
        Certificate cert = null;
        currentCertNum++;

        log.info("Processing certNum:" + currentCertNum);
        try {
            byte[] certBytes = publicCert.getX509CertificateInPemFormat().getBytes("UTF-8");
            InputStream stream = new ByteArrayInputStream(certBytes);
            signature = Signature.getInstance("SHA256withRSA"); // Make this configurable?
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            cert = cf.generateCertificate(stream);
            log.info(cert.toString());

            PublicKey pk = cert.getPublicKey();
            signature.initVerify(pk);
            signature.update(blob);
            boolean isValidSignature = signature.verify(signedBlob);

            if (isValidSignature) {
                totalValid++;
            } else {
                totalInvalid++;
            }
            log.info("certNum:" + currentCertNum + ": is valid:" + isValidSignature);

            // These can be thrown:
            // UnsupportedEncodingException, NoSuchAlgorithmException, CertificateException,
            // SignatureException, InvalidKeyException
        } catch (Exception e) {
            Exception logException = createExceptionForLog(e, currentCertNum, cert);
            allExceptions.add(logException);
            log.info(e.toString());
        }
    }
    String summary = "totalCerts:" + certsForApp.size() + ": totalValid:" + totalValid + " totalInvalid:"
            + totalInvalid + " totalExceptions:" + allExceptions.size();
    log.info(summary);

    // At least one certificate caused an exception so make test Error.
    if (allExceptions.size() > 0) {
        throw new IllegalStateException(summary + "\n\n" + exceptionListToString(allExceptions));
    }

    // At least one signature was valid and no exceptions thrown.
    return (totalValid > 0);
}

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

@Override
public CertificateDataWrapper createCertificate(final AuthenticationToken admin,
        final EndEntityInformation endEntityInformation, final CA ca, final RequestMessage request,
        final PublicKey pk, final int keyusage, final Date notBefore, final Date notAfter,
        final Extensions extensions, final String sequence, CertificateGenerationParams certGenParams,
        final long updateTime) throws AuthorizationDeniedException, IllegalNameException,
        CustomCertificateSerialNumberException, CertificateCreateException, CertificateRevokeException,
        CertificateSerialNumberException, CryptoTokenOfflineException, IllegalKeyException,
        CertificateExtensionException, IllegalValidityException, CAOfflineException, InvalidAlgorithmException {
    if (log.isTraceEnabled()) {
        log.trace(/*from www  .j  a  va2  s . co m*/
                ">createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)");
    }

    // Even though CA is passed as an argument to this method, we do check authorization on that.
    // To make sure we properly log authorization checks needed to issue a cert.
    // We need to check that admin have rights to create certificates, and have access to the CA
    if (!accessSession.isAuthorized(admin, StandardRules.CREATECERT.resource(),
            StandardRules.CAACCESS.resource() + ca.getCAId())) {
        final String msg = intres.getLocalizedMessage("createcert.notauthorized", admin.toString(),
                ca.getCAId());
        throw new AuthorizationDeniedException(msg);
    }

    // Audit log that we received the request
    final Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("subjectdn", endEntityInformation.getDN());
    details.put("requestX500name", (request == null || request.getRequestX500Name() == null) ? "null"
            : request.getRequestX500Name().toString());
    details.put("certprofile", endEntityInformation.getCertificateProfileId());
    details.put("keyusage", keyusage);
    details.put("notbefore", notBefore);
    details.put("notafter", notAfter);
    details.put("sequence", sequence);
    details.put("publickey", new String(Base64.encode(pk.getEncoded(), false)));
    logSession.log(EventTypes.CERT_REQUEST, EventStatus.SUCCESS, ModuleTypes.CERTIFICATE, ServiceTypes.CORE,
            admin.toString(), String.valueOf(ca.getCAId()), null, endEntityInformation.getUsername(), details);

    // Set up audit logging of CT pre-certificate
    addCTLoggingCallback(certGenParams, admin.toString());

    try {
        CertificateDataWrapper result = null;
        // If the user is of type USER_INVALID, it cannot have any other type (in the mask)
        if (endEntityInformation.getType().isType(EndEntityTypes.INVALID)) {
            final String msg = intres.getLocalizedMessage("createcert.usertypeinvalid",
                    endEntityInformation.getUsername());
            throw new CertificateCreateException(msg);
        }
        final Certificate cacert = ca.getCACertificate();
        final String caSubjectDN = CertTools.getSubjectDN(cacert);
        assertSubjectEnforcements(ca, caSubjectDN, endEntityInformation, pk);
        // Retrieve the certificate profile this user should have, checking for authorization to the profile
        final int certProfileId = endEntityInformation.getCertificateProfileId();
        final CertificateProfile certProfile = getCertificateProfile(certProfileId, ca.getCAId());

        // Check that the request public key fulfills policy
        verifyKey(pk, certProfile);

        // Below we have a small loop if it would happen that we generate the same serial number twice
        // If using only 4 byte serial numbers this do happen once in a while
        Certificate cert = null;
        String cafingerprint = null;
        String serialNo = "unknown";
        final boolean useCustomSN;
        {
            final ExtendedInformation ei = endEntityInformation.getExtendedinformation();
            useCustomSN = ei != null && ei.certificateSerialNumber() != null;
        }
        final int maxRetrys;
        if (useCustomSN) {
            if (ca.isUseCertificateStorage() && !isUniqueCertificateSerialNumberIndex()) {
                final String msg = intres.getLocalizedMessage("createcert.not_unique_certserialnumberindex");
                log.error(msg);
                throw new CustomCertificateSerialNumberException(msg);
            }
            if (!certProfile.getAllowCertSerialNumberOverride()) {
                final String msg = intres.getLocalizedMessage(
                        "createcert.certprof_not_allowing_cert_sn_override", Integer.valueOf(certProfileId));
                log.info(msg);
                throw new CustomCertificateSerialNumberException(msg);
            }
            maxRetrys = 1;
        } else {
            maxRetrys = 5;
        }

        // Before storing the new certificate, check if single active certificate constraint is active, and if so let's revoke all active and unexpired certificates
        if (certProfile.isSingleActiveCertificateConstraint()) {
            for (Certificate certificate : certificateStoreSession.findCertificatesBySubjectAndIssuer(
                    endEntityInformation.getCertificateDN(), caSubjectDN, true)) {
                //Authorization to the CA was already checked at the head of this method, so no need to do so now
                certificateStoreSession.setRevokeStatusNoAuth(admin, certificate, new Date(),
                        RevokedCertInfo.REVOCATION_REASON_SUPERSEDED, endEntityInformation.getDN());
            }
        }

        CertificateSerialNumberException storeEx = null; // this will not be null if stored == false after the below passage
        for (int retrycounter = 0; retrycounter < maxRetrys; retrycounter++) {
            final CryptoToken cryptoToken = cryptoTokenManagementSession
                    .getCryptoToken(ca.getCAToken().getCryptoTokenId());
            if (cryptoToken == null) {
                final String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getCAId());
                log.info(msg);
                CryptoTokenOfflineException exception = new CryptoTokenOfflineException(
                        "CA's CryptoToken not found.");
                auditFailure(admin, exception, exception.getMessage(),
                        "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                        ca.getCAId(), endEntityInformation.getUsername());
                throw exception;
            }
            cert = ca.generateCertificate(cryptoToken, endEntityInformation, request, pk, keyusage, notBefore,
                    notAfter, certProfile, extensions, sequence, certGenParams);
            serialNo = CertTools.getSerialNumberAsString(cert);
            cafingerprint = CertTools.getFingerprintAsString(cacert);
            // Store certificate in the database, if this CA is configured to do so.
            if (!ca.isUseCertificateStorage()) {
                result = new CertificateDataWrapper(cert, null, null);
                break; // We have our cert and we don't need to store it.. Move on..
            }
            try {
                // Remember for CVC serialNo can be alphanumeric, so we can't just try to decode that using normal Java means (BigInteger.valueOf)...
                assertSerialNumberForIssuerOk(ca, caSubjectDN, CertTools.getSerialNumber(cert));
                // Tag is reserved for future use, currently only null
                final String tag = null;
                // Authorization was already checked by since this is a private method, the CA parameter should
                // not be possible to get without authorization
                result = certificateStoreSession.storeCertificateNoAuth(admin, cert,
                        endEntityInformation.getUsername(), cafingerprint, CertificateConstants.CERT_ACTIVE,
                        certProfile.getType(), certProfileId, tag, updateTime);
                storeEx = null;
                break;
            } catch (CertificateSerialNumberException e) {
                // If we have created a unique index on (issuerDN,serialNumber) on table CertificateData we can
                // get a CreateException here if we would happen to generate a certificate with the same serialNumber
                // as one already existing certificate.
                if (retrycounter + 1 < maxRetrys) {
                    log.info("Can not store certificate with serNo (" + serialNo
                            + "), will retry (retrycounter=" + retrycounter
                            + ") with a new certificate with new serialNo: " + e.getMessage());
                }
                storeEx = e;
            }
        }
        if (storeEx != null) {
            if (useCustomSN) {
                final String msg = intres
                        .getLocalizedMessage("createcert.cert_serial_number_already_in_database", serialNo);
                log.info(msg);
                throw new CustomCertificateSerialNumberException(msg);
            }
            log.error("Can not store certificate in database in 5 tries, aborting: ", storeEx);
            throw storeEx;
        }

        // Finally we check if this certificate should not be issued as active, but revoked directly upon issuance
        int revreason = RevokedCertInfo.NOT_REVOKED;
        ExtendedInformation ei = endEntityInformation.getExtendedinformation();
        if (ei != null) {
            revreason = ei.getIssuanceRevocationReason();
            if (revreason != RevokedCertInfo.NOT_REVOKED) {
                // If we don't store the certificate in the database, we wont support revocation/reactivation so issuing revoked certificates would be
                // really strange.
                if (ca.isUseCertificateStorage()) {
                    certificateStoreSession.setRevokeStatusNoAuth(admin, cert, new Date(), revreason,
                            endEntityInformation.getDN());
                } else {
                    log.warn(
                            "CA configured to revoke issued certificates directly, but not to store issued the certificates. Revocation will be ignored. Please verify your configuration.");
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Generated certificate with SerialNumber '" + serialNo + "' for user '"
                    + endEntityInformation.getUsername() + "', with revocation reason=" + revreason);
            log.debug(cert.toString());
        }

        // Audit log that we issued the certificate
        final Map<String, Object> issuedetails = new LinkedHashMap<String, Object>();
        issuedetails.put("subjectdn", endEntityInformation.getDN());
        issuedetails.put("certprofile", endEntityInformation.getCertificateProfileId());
        issuedetails.put("issuancerevocationreason", revreason);
        try {
            issuedetails.put("cert", new String(Base64.encode(cert.getEncoded(), false)));
        } catch (CertificateEncodingException e) {
            //Should not be able to happen at this point
            throw new IllegalStateException();
        }
        logSession.log(EventTypes.CERT_CREATION, EventStatus.SUCCESS, ModuleTypes.CERTIFICATE,
                ServiceTypes.CORE, admin.toString(), String.valueOf(ca.getCAId()), serialNo,
                endEntityInformation.getUsername(), issuedetails);

        if (log.isTraceEnabled()) {
            log.trace(
                    "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)");
        }
        return result;
        // We need to catch and re-throw all of these exception just because we need to audit log all failures
    } catch (CustomCertificateSerialNumberException e) {
        log.info(e.getMessage());
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (AuthorizationDeniedException e) {
        log.info(e.getMessage());
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (CertificateCreateException e) {
        log.info(e.getMessage());
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        // Rollback
        throw e;
    } catch (CryptoTokenOfflineException e) {
        final String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getCAId());
        log.info(msg);
        auditFailure(admin, e, e.getMessage(),
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (CAOfflineException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (InvalidAlgorithmException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (IllegalValidityException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (OperatorCreationException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        // Rollback
        throw new CertificateCreateException(e);
    } catch (SignatureException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        // Rollback
        throw new CertificateCreateException(e);
    } catch (CertificateExtensionException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    }

}

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

/**
 * Dumps a certificate (cvc or x.509) to string format, suitable for manual inspection/debugging.
 * //  w  w w.ja  v a2s  .c o m
 * @param cert Certificate
 * 
 * @return String with cvc or asn.1 dump.
 */
public static String dumpCertificateAsString(final Certificate cert) {
    String ret = null;
    if (cert instanceof X509Certificate) {
        try {
            final Certificate c = getCertfromByteArray(cert.getEncoded());
            ret = c.toString();
            // ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(cert.getEncoded()));
            // ASN1Primitive obj = ais.readObject();
            // ret = ASN1Dump.dumpAsString(obj);
        } catch (CertificateException e) {
            ret = e.getMessage();
        }
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        final CVCObject obj = cvccert.getCVCertificate();
        ret = obj.getAsText("");
    } else {
        throw new IllegalArgumentException(
                "dumpCertificateAsString: Certificate of type " + cert.getType() + " is not implemented");
    }
    return ret;
}

From source file:org.ejbca.ui.web.RequestHelper.java

/**
 * Handles PKCS10 certificate request, these are constructed as: <code> CertificationRequest
 * ::= SEQUENCE { certificationRequestInfo  CertificationRequestInfo, signatureAlgorithm
 * AlgorithmIdentifier{{ SignatureAlgorithms }}, signature                       BIT STRING }
 * CertificationRequestInfo ::= SEQUENCE { version             INTEGER { v1(0) } (v1,...),
 * subject             Name, subjectPKInfo   SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
 * attributes          [0] Attributes{{ CRIAttributes }}} SubjectPublicKeyInfo { ALGORITHM :
 * IOSet} ::= SEQUENCE { algorithm           AlgorithmIdentifier {{IOSet}}, subjectPublicKey
 * BIT STRING }</code> PublicKey's encoded-format has to be RSA X.509.
 *
 * @param signsession signsession to get certificate from
 * @param caSession a reference to CaSessionBean
 * @param b64Encoded base64 encoded pkcs10 request message
 * @param username username of requesting user
 * @param password password of requesting user
 * @param resulttype should indicate if a PKCS7 or just the certificate is wanted.
 * @param doSplitLines/*from  www. j a  va  2 s  .c  o  m*/
 * @return Base64 encoded byte[] 
 * @throws AuthorizationDeniedException 
 * @throws CesecoreException 
 * @throws EjbcaException 
 * @throws CertificateException 
 * @throws CertificateEncodingException 
 * @throws CertificateExtensionException if b64Encoded specified invalid extensions
 */
public CertificateRequestResponse pkcs10CertRequest(SignSessionLocal signsession, CaSessionLocal caSession,
        byte[] b64Encoded, String username, String password, CertificateResponseType resulttype,
        boolean doSplitLines) throws EjbcaException, CesecoreException, AuthorizationDeniedException,
        CertificateEncodingException, CertificateException, CertificateExtensionException {
    byte[] encoded = null;
    Certificate cert = null;
    PKCS10RequestMessage req = RequestMessageUtils.genPKCS10RequestMessage(b64Encoded);
    req.setUsername(username);
    req.setPassword(password);
    ResponseMessage resp = signsession.createCertificate(administrator, req, X509ResponseMessage.class, null);
    cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    switch (resulttype) {
    case ENCODED_CERTIFICATE:
        encoded = Base64.encode(cert.getEncoded(), doSplitLines);
        break;
    case ENCODED_CERTIFICATE_CHAIN:
        CAInfo caInfo = signsession.getCAFromRequest(administrator, req, false).getCAInfo();
        LinkedList<Certificate> chain = new LinkedList<Certificate>(caInfo.getCertificateChain());
        chain.addFirst(cert);
        encoded = CertTools.getPemFromCertificateChain(chain);
        break;
    case ENCODED_PKCS7:
        encoded = Base64.encode(signsession.createPKCS7(administrator, cert, true), doSplitLines);
        break;
    default:
        break;
    }
    log.debug("Created certificate (PKCS7) for " + username);
    if (debug != null) {
        debug.print("<h4>Generated certificate:</h4>");
        debug.printInsertLineBreaks(cert.toString().getBytes());
    }
    return new CertificateRequestResponse(cert, encoded);
}

From source file:org.ejbca.ui.web.RequestHelper.java

/** Handles CVC certificate requests. These are the special certificates for EAC ePassport PKI.
 * //ww  w  .  ja v  a  2  s .c o m
 * @param signsession signsession to get certificate from
 * @param b64Encoded base64 encoded cvc request message
 * @param username username of requesting user
 * @param password password of requesting user
 * @return Base64 encoded byte[] 
 * @throws Exception
 */
public byte[] cvcCertRequest(SignSessionLocal signsession, byte[] b64Encoded, String username, String password)
        throws Exception {
    CVCRequestMessage req = RequestMessageUtils.genCVCRequestMessage(b64Encoded);
    req.setUsername(username);
    req.setPassword(password);
    // Yes it says X509ResponseMessage, but for CVC it means it just contains the binary certificate blob
    ResponseMessage resp = signsession.createCertificate(administrator, req, X509ResponseMessage.class, null);
    Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    byte[] result = cert.getEncoded();
    log.debug("Created CV certificate for " + username);
    if (debug != null) {
        debug.print("<h4>Generated certificate:</h4>");
        debug.printInsertLineBreaks(cert.toString().getBytes());
    }
    return Base64.encode(result);
}

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

/**
 * Dumps a certificate (cvc or x.509) to string format, suitable for manual inspection/debugging.
 *
 * @param cert Certificate/*from w  ww .  j a v a 2s .c o  m*/
 *
 * @return String with cvc or asn.1 dump.
 */
public static String dumpCertificateAsString(final Certificate cert) {
    String ret = null;
    if (cert instanceof X509Certificate) {
        try {
            final Certificate c = getCertfromByteArray(cert.getEncoded());
            ret = c.toString();
            //             ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(cert.getEncoded()));
            //             DERObject obj = ais.readObject();
            //             ret = ASN1Dump.dumpAsString(obj);
        } catch (CertificateException e) {
            ret = e.getMessage();
        }
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        final CVCObject obj = cvccert.getCVCertificate();
        ret = obj.getAsText("");
    } else {
        throw new IllegalArgumentException(
                "dumpCertificateAsString: Certificate of type " + cert.getType() + " is not implemented");
    }
    return ret;
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

/**
 * addCACertificateToTrustStore adds a CA cert to the set of certificates used for signature validation
 *
 * @param caCert an X.509 certificate// w ww .j  a v a2 s .com
 * @param alias  an alias associated with the certificate. Used as shorthand for the certificate during crypto operations
 * @throws CryptoException
 * @throws InvalidArgumentException
 */
void addCACertificateToTrustStore(Certificate caCert, String alias)
        throws InvalidArgumentException, CryptoException {

    if (alias == null || alias.isEmpty()) {
        throw new InvalidArgumentException(
                "You must assign an alias to a certificate when adding to the trust store.");
    }

    if (caCert == null) {
        throw new InvalidArgumentException("Certificate cannot be null.");
    }

    try {
        if (config.extraLogLevel(10)) {
            if (null != diagnosticFileDumper) {
                logger.trace(format("Adding cert to trust store. alias: %s. certificate:", alias)
                        + diagnosticFileDumper.createDiagnosticFile(alias + "cert: " + caCert.toString()));
            }
        }
        synchronized (certificateSet) {
            if (certificateSet.contains(alias)) {
                return;
            }

            getTrustStore().setCertificateEntry(alias, caCert);
            certificateSet.add(alias);

        }
    } catch (KeyStoreException e) {
        String emsg = "Unable to add CA certificate to trust store. Error: " + e.getMessage();
        logger.error(emsg, e);
        throw new CryptoException(emsg, e);
    }
}