Example usage for java.security.cert Certificate getEncoded

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

Introduction

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

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

From source file:be.fedict.hsm.ws.impl.DigitalSignatureServicePortImpl.java

@Override
@WebMethod(operationName = "get-certificate-chain")
@WebResult(name = "Response", targetNamespace = "urn:oasis:names:tc:dss:1.0:core:schema", partName = "GetCertificateChainResponse")
public ResponseBaseType getCertificateChain(
        @WebParam(name = "GetCertificateChainRequest", targetNamespace = "urn:be:fedict:hsm-proxy:ws:dss:profiles:hsm-proxy:1.0", partName = "GetCertificateChainRequest") GetCertificateChainRequest getCertificateChainRequest) {
    String requestId = getCertificateChainRequest.getRequestID();
    AnyType optionalInputs = getCertificateChainRequest.getOptionalInputs();
    if (null == optionalInputs) {
        LOG.error("missing dss:OptionalInputs");
        return errorResponse(ResultMajor.REQUESTER_ERROR);
    }//from ww w  . j  a v  a  2  s. c o  m
    List<Object> optionalInputsContent = optionalInputs.getAny();
    String alias = null;
    for (Object object : optionalInputsContent) {
        if (object instanceof KeySelector) {
            KeySelector keySelector = (KeySelector) object;
            KeyInfoType keyInfo = keySelector.getKeyInfo();
            if (null == keyInfo) {
                LOG.error("missing ds:KeyInfo");
                return errorResponse(ResultMajor.REQUESTER_ERROR);
            }
            List<Object> keyInfoContent = keyInfo.getContent();
            for (Object keyInfoObject : keyInfoContent) {
                if (keyInfoObject instanceof JAXBElement) {
                    JAXBElement jaxbElement = (JAXBElement) keyInfoObject;
                    alias = (String) jaxbElement.getValue();
                }
            }
        }
    }
    if (null == alias) {
        LOG.error("missing dss:KeySelector/ds:KeyInfo/ds:KeyName");
        return errorResponse(ResultMajor.REQUESTER_ERROR);
    }
    LOG.debug("get certificate chain for alias: " + alias);
    Certificate[] certificateChain;
    try {
        certificateChain = this.signatureService.getCertificateChain(alias);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("no such algo: " + e.getMessage());
        return errorResponse(ResultMajor.REQUESTER_ERROR);
    }
    if (null == certificateChain) {
        LOG.error("no cert chain found");
        return errorResponse(ResultMajor.REQUESTER_ERROR);
    }
    ResponseBaseType response = this.objectFactory.createResponseBaseType();
    response.setRequestID(requestId);
    response.setProfile(DSSConstants.HSM_PROXY_DSS_PROFILE_URI);

    Result result = this.objectFactory.createResult();
    response.setResult(result);
    result.setResultMajor(ResultMajor.SUCCESS.getUri());

    KeyInfoType keyInfo = this.xmldsigObjectFactory.createKeyInfoType();
    AnyType optionalOutputs = this.objectFactory.createAnyType();
    optionalOutputs.getAny().add(this.xmldsigObjectFactory.createKeyInfo(keyInfo));
    response.setOptionalOutputs(optionalOutputs);

    List<Object> keyInfoContent = keyInfo.getContent();
    X509DataType x509Data = this.xmldsigObjectFactory.createX509DataType();
    keyInfoContent.add(this.xmldsigObjectFactory.createX509Data(x509Data));

    List<Object> x509DataContent = x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName();
    for (Certificate certificate : certificateChain) {
        try {
            x509DataContent
                    .add(this.xmldsigObjectFactory.createX509DataTypeX509Certificate(certificate.getEncoded()));
        } catch (CertificateEncodingException e) {
            LOG.error("certificate encoding error: " + e.getMessage());
            return errorResponse(ResultMajor.RESPONDER_ERROR);
        }
    }

    return response;
}

From source file:org.kuali.kfs.sys.service.DataObjectRestServiceTest.java

protected String sendQuery(String urlToRead, String requestMethod) {
    URL url;//from   w  w  w  . j av a2  s .c om
    HttpURLConnection conn;
    BufferedReader rd;
    String line;
    String result = "";

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(requestMethod);

        Signature rsa = getDigitalSignatureService().getSignatureForSigning();
        String moduleKeyStoreAlias = getJavaSecurityManagementService().getModuleKeyStoreAlias();
        conn.addRequestProperty(KSBConstants.DIGITAL_SIGNATURE_HEADER,
                new String(Base64.encodeBase64(rsa.sign()), "UTF-8"));
        //conn.addRequestProperty(KSBConstants.KEYSTORE_ALIAS_HEADER, moduleKeyStoreAlias);
        Certificate cert = getJavaSecurityManagementService().getCertificate(moduleKeyStoreAlias);
        conn.addRequestProperty(KSBConstants.KEYSTORE_CERTIFICATE_HEADER,
                new String(Base64.encodeBase64(cert.getEncoded()), "UTF-8"));

        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        rd.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

From source file:org.cesecore.certificates.util.Base64Test.java

@Test
public void testBase64Small() throws Exception {
    // Testcert is on long line of base 64 encoded stuff
    byte[] certBytes = Base64.decode(testcert_oneline.getBytes());
    assertNotNull(certBytes);/*from  w  w w .  j  a  va  2  s .  co m*/
    // This should be a cert
    Certificate cert = CertTools.getCertfromByteArray(certBytes);
    assertNotNull(cert);
    // Base64 encode it again
    byte[] encBytes = Base64.encode(cert.getEncoded(), false);
    assertEquals(new String(encBytes), testcert_oneline);
    // Testcert_crlf has \n after each line
    certBytes = Base64.decode(testcert_crlf.getBytes());
    assertNotNull(certBytes);
    // This should be a cert
    cert = CertTools.getCertfromByteArray(certBytes);
    assertNotNull(cert);
    // Base64 encode it again
    encBytes = Base64.encode(cert.getEncoded(), true);
    assertEquals(new String(encBytes), testcert_crlf);
    // This is the same method as above
    encBytes = Base64.encode(cert.getEncoded());
    assertEquals(new String(encBytes), testcert_crlf);
}

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

/** This is the same constructor as in CrmtRAPbeRequestTest, but it's hard to refactor not to duplicate this code.
 */// w  w w  .j  a  va2  s .c om
public CrmfRAPbeTcpRequestTest(String arg0) throws CertificateException {
    super(arg0);
    CryptoProviderTools.installBCProvider();
    // Try to use AdminCA1 if it exists
    CAInfo adminca1 = caAdminSessionRemote.getCAInfo(admin, "AdminCA1");
    if (adminca1 == null) {
        Collection<Integer> caids = caSession.getAvailableCAs(admin);
        Iterator<Integer> iter = caids.iterator();
        while (iter.hasNext()) {
            caid = iter.next().intValue();
        }
    } else {
        caid = adminca1.getCAId();
    }
    if (caid == 0) {
        assertTrue("No active CA! Must have at least one active CA to run tests!", false);
    }
    CAInfo cainfo = caAdminSessionRemote.getCAInfo(admin, caid);
    Collection<Certificate> certs = cainfo.getCertificateChain();
    if (certs.size() > 0) {
        Iterator<Certificate> certiter = certs.iterator();
        Certificate cert = certiter.next();
        String subject = CertTools.getSubjectDN(cert);
        if (StringUtils.equals(subject, cainfo.getSubjectDN())) {
            // Make sure we have a BC certificate
            cacert = (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded());
        }
    } else {
        log.error("NO CACERT for caid " + caid);
    }
    issuerDN = cacert.getIssuerDN().getName();
    // Configure CMP for this test
    updatePropertyOnServer(CmpConfiguration.CONFIG_OPERATIONMODE, "ra");
    updatePropertyOnServer(CmpConfiguration.CONFIG_ALLOWRAVERIFYPOPO, "true");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RESPONSEPROTECTION, "pbe");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_AUTHENTICATIONSECRET, "password");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_CERTIFICATEPROFILE, CPNAME);
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_ENDENTITYPROFILE, EEPNAME);
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONMODULE, CmpConfiguration.AUTHMODULE_HMAC);
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONPARAMETERS, "-");
    // Configure a Certificate profile (CmpRA) using ENDUSER as template and check "Allow validity override".
    if (certificateProfileSession.getCertificateProfile(admin, CPNAME) == null) {
        CertificateProfile cp = new EndUserCertificateProfile();
        cp.setAllowValidityOverride(true);
        try { // TODO: Fix this better
            certificateProfileSession.addCertificateProfile(admin, CPNAME, cp);
        } catch (CertificateProfileExistsException e) {
            e.printStackTrace();
        }
    }
    int cpId = certificateProfileSession.getCertificateProfileId(admin, CPNAME);
    if (endEntityProfileSession.getEndEntityProfile(admin, EEPNAME) == null) {
        // Configure an EndEntity profile (CmpRA) with allow CN, O, C in DN and rfc822Name (uncheck 'Use entity e-mail field' and check 'Modifyable'), MS UPN in altNames in the end entity profile.
        EndEntityProfile eep = new EndEntityProfile(true);
        eep.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, "" + cpId);
        eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId);
        eep.setModifyable(DnComponents.RFC822NAME, 0, true);
        eep.setUse(DnComponents.RFC822NAME, 0, false); // Don't use field from "email" data
        try {
            endEntityProfileSession.addEndEntityProfile(admin, EEPNAME, eep);
        } catch (EndEntityProfileExistsException e) {
            log.error("Could not create end entity profile.", e);
        }
    }
}

From source file:at.gv.egiz.pdfas.moa.MOAConnector.java

public MOAConnector(Configuration config, java.security.cert.Certificate certificate)
        throws CertificateException, FileNotFoundException, IOException {
    if (certificate != null) {
        if (certificate instanceof X509Certificate) {
            this.certificate = (X509Certificate) certificate;
        } else {/*  w  ww  .  j  av  a  2 s. c  o  m*/
            this.certificate = new X509Certificate(certificate.getEncoded());
        }
    }
    init(config);
}

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

public CrmfRARequestCustomSerialNoTest() throws Exception {
    this.cmpConfiguration = (CmpConfiguration) this.globalConfigurationSession
            .getCachedConfiguration(CmpConfiguration.CMP_CONFIGURATION_ID);

    // Try to use ManagementCA if it exists
    final CAInfo managementca;

    managementca = this.caSession.getCAInfo(ADMIN, "ManagementCA");

    if (managementca == null) {
        final Collection<Integer> caids;

        caids = this.caSession.getAuthorizedCaIds(ADMIN);

        final Iterator<Integer> iter = caids.iterator();
        int tmp = 0;
        while (iter.hasNext()) {
            tmp = iter.next().intValue();
        }//from ww w . ja v a2  s.  co m
        this.caid = tmp;
    } else {
        this.caid = managementca.getCAId();
    }
    if (this.caid == 0) {
        assertTrue("No active CA! Must have at least one active CA to run tests!", false);
    }
    final CAInfo cainfo;

    cainfo = this.caSession.getCAInfo(ADMIN, this.caid);

    Collection<Certificate> certs = cainfo.getCertificateChain();
    if (certs.size() > 0) {
        Iterator<Certificate> certiter = certs.iterator();
        Certificate cert = certiter.next();
        String subject = CertTools.getSubjectDN(cert);
        if (StringUtils.equals(subject, cainfo.getSubjectDN())) {
            // Make sure we have a BC certificate
            try {
                this.cacert = (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded());
            } catch (Exception e) {
                throw new Error(e);
            }
        } else {
            this.cacert = null;
        }
    } else {
        log.error("NO CACERT for caid " + this.caid);
        this.cacert = null;
    }
    this.issuerDN = this.cacert != null ? this.cacert.getIssuerDN().getName()
            : "CN=ManagementCA,O=EJBCA Sample,C=SE";
}

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

public CmpRAUnidTest(String arg0) throws Exception {
    super(arg0);/*from  w  w  w. j  a v  a  2 s .  com*/
    CryptoProviderTools.installBCProvider();
    // Try to use AdminCA1 if it exists
    final CAInfo adminca1 = this.caAdminSession.getCAInfo(this.admin, "AdminCA1");
    if (adminca1 == null) {
        final Collection<Integer> caids = this.caSession.getAvailableCAs(this.admin);
        final Iterator<Integer> iter = caids.iterator();
        int tmp = 0;
        while (iter.hasNext()) {
            tmp = iter.next().intValue();
            if (tmp != 0) {
                break;
            }
        }
        this.caid = tmp;
    } else {
        this.caid = adminca1.getCAId();
    }
    if (this.caid == 0) {
        assertTrue("No active CA! Must have at least one active CA to run tests!", false);
    }
    final CAInfo cainfo = this.caAdminSession.getCAInfo(this.admin, this.caid);
    final Collection<Certificate> certs = cainfo.getCertificateChain();
    if (certs.size() > 0) {
        final Iterator<Certificate> certiter = certs.iterator();
        final Certificate cert = certiter.next();
        final String subject = CertTools.getSubjectDN(cert);
        if (StringUtils.equals(subject, cainfo.getSubjectDN())) {
            // Make sure we have a BC certificate
            this.cacert = (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded());
        } else {
            this.cacert = null;
        }
    } else {
        this.cacert = null;
        log.error("NO CACERT for caid " + this.caid);
    }
    this.issuerDN = this.cacert.getIssuerDN().getName();
    // Configure CMP for this test
    updatePropertyOnServer(CmpConfiguration.CONFIG_OPERATIONMODE, "ra");
    updatePropertyOnServer(CmpConfiguration.CONFIG_ALLOWRAVERIFYPOPO, "true");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RESPONSEPROTECTION, "pbe");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_AUTHENTICATIONSECRET, PBEPASSWORD);
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_CERTIFICATEPROFILE, "KeyId");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_ENDENTITYPROFILE, "KeyId");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RACANAME, cainfo.getName());
    updatePropertyOnServer(CmpConfiguration.CONFIG_CERTREQHANDLER_CLASS, UnidFnrHandler.class.getName());
    // Configure a Certificate profile (CmpRA) using ENDUSER as template
    if (this.certificateProfileSession.getCertificateProfile(this.admin, CPNAME) == null) {
        final CertificateProfile cp = new EndUserCertificateProfile();
        try { // TODO: Fix this better
            this.certificateProfileSession.addCertificateProfile(this.admin, CPNAME, cp);
        } catch (CertificateProfileExistsException e) {
            log.error("Certificate profile exists: ", e);
        }
    }
    final int cpId = this.certificateProfileSession.getCertificateProfileId(this.admin, CPNAME);
    if (this.endEntityProfileSession.getEndEntityProfile(this.admin, EEPNAME) == null) {
        final EndEntityProfile eep = new EndEntityProfile(true);
        eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId);
        try {
            this.endEntityProfileSession.addEndEntityProfile(this.admin, EEPNAME, eep);
        } catch (EndEntityProfileExistsException e) {
            log.error("Could not create end entity profile.", e);
        }
    }
    this.keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
}

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

public CrmfRATcpRequestTest(String arg0) throws CertificateEncodingException, CertificateException {
    super(arg0);/*from  w w w . j av a  2  s  .c  om*/
    CryptoProviderTools.installBCProvider();
    // Try to use AdminCA1 if it exists
    CAInfo adminca1 = caAdminSession.getCAInfo(admin, "AdminCA1");
    if (adminca1 == null) {
        Collection<Integer> caids = caSession.getAvailableCAs(admin);
        Iterator<Integer> iter = caids.iterator();
        while (iter.hasNext()) {
            caid = iter.next().intValue();
        }
    } else {
        caid = adminca1.getCAId();
    }
    if (caid == 0) {
        assertTrue("No active CA! Must have at least one active CA to run tests!", false);
    }
    CAInfo cainfo = caAdminSession.getCAInfo(admin, caid);
    Collection<Certificate> certs = cainfo.getCertificateChain();
    if (certs.size() > 0) {
        Iterator<Certificate> certiter = certs.iterator();
        Certificate cert = certiter.next();
        String subject = CertTools.getSubjectDN(cert);
        if (StringUtils.equals(subject, cainfo.getSubjectDN())) {
            // Make sure we have a BC certificate
            cacert = (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded());
        }
    } else {
        log.error("NO CACERT for caid " + caid);
    }
    issuerDN = cacert.getIssuerDN().getName();
    // Configure CMP for this test
    updatePropertyOnServer(CmpConfiguration.CONFIG_OPERATIONMODE, "ra");
    updatePropertyOnServer(CmpConfiguration.CONFIG_ALLOWRAVERIFYPOPO, "true");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RESPONSEPROTECTION, "signature");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_AUTHENTICATIONSECRET, PBEPASSWORD);
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_ENDENTITYPROFILE, "EMPTY");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RA_CERTIFICATEPROFILE, "ENDUSER");
    updatePropertyOnServer(CmpConfiguration.CONFIG_RACANAME, "AdminCA1");
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONMODULE, CmpConfiguration.AUTHMODULE_HMAC);
    updatePropertyOnServer(CmpConfiguration.CONFIG_AUTHENTICATIONPARAMETERS, "-");
}

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

/** Handles CVC certificate requests. These are the special certificates for EAC ePassport PKI.
 * //from  w ww . ja v  a2 s  .  com
 * @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);
}