Example usage for java.security.cert X509Certificate getEncoded

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

Introduction

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

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

From source file:com.adito.keystore.actions.ShowKeyStoreDispatchAction.java

/**
 * @param mapping//from  w  w w .j  av a 2s  . c o  m
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 * @throws Exception
 */
public ActionForward exportCertificate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String sel = ((ShowKeyStoreForm) form).getSelectedItem();
    KeyStore systemClientStore = ((ShowKeyStoreForm) form).getSelectedKeyStore().getKeyStore();
    FileDownloadPageInterceptListener l = (FileDownloadPageInterceptListener) CoreUtil
            .getPageInterceptListenerById(request.getSession(), "fileDownload");
    if (l == null) {
        l = new FileDownloadPageInterceptListener();
        CoreUtil.addPageInterceptListener(request.getSession(), l);
    }
    File clientCertFile = new File(CoreUtil.getTempDownloadDirectory(getSessionInfo(request)), sel + ".cer");
    FileOutputStream out = new FileOutputStream(clientCertFile);
    X509Certificate cert = (X509Certificate) systemClientStore.getCertificate(sel);
    out.write(cert.getEncoded());
    out.flush();
    out.close();
    l.addDownload(new CSRDownload(clientCertFile, clientCertFile.getName(), "application/octet-stream",
            mapping.findForward("success"), "exportCertificate.message", "keystore", sel));
    return mapping.findForward("success");
}

From source file:sernet.verinice.encryption.test.CryptoTest.java

@Test
public void certificateByteBasedCryptoTest() throws GeneralSecurityException, IOException {
    KeyPair keyPair = generateKeyPair();
    assertNotNull("Keypair is null", keyPair);
    String distinguishedName = "CN=Test, L=Berlin, C=DE";
    int days = 365;
    X509Certificate cert = generateCertificate(distinguishedName, keyPair, days);
    String certPEM = convertToPem(cert.getEncoded(), false, true);
    assertNotNull(certPEM);//from   www  .j a  va2  s. c  o m
    File certFile = File.createTempFile("veriniceCert", "PEM");
    assertNotNull(certFile);
    FileUtil.writeStringToFile(certPEM, certFile.getAbsolutePath());
    certFile.deleteOnExit();
    byte[] encryptedData = getEncryptionService().encrypt(SECRET.getBytes(), certFile);
    byte[] privateKey = keyPair.getPrivate().getEncoded();
    String privateKeyString = convertToPem(privateKey, true, false);
    File keyFile = File.createTempFile("veriniceKey", "PEM");
    assertNotNull(keyFile);
    FileUtil.writeStringToFile(privateKeyString, keyFile.getAbsolutePath());
    certFile.deleteOnExit();
    byte[] decryptedData = getEncryptionService().decrypt(encryptedData, certFile, keyFile);
    assertEquals(SECRET, new String(decryptedData));
}

From source file:org.wso2.carbon.identity.relyingparty.saml.SAMLTokenConsumer.java

/**
 * //from w  w w. jav  a 2  s. c o m
 * @param verifier
 * @return
 * @throws RelyingPartyException
 */
protected String getIssuerInfoString(SAMLTokenVerifier verifier) throws RelyingPartyException {
    String issuerInfo = null;
    OMFactory factory = null;
    OMNamespace namespace = null;
    Element keyInfo = null;
    OMElement certificates = null;
    OMElement omKeyInfo = null;
    boolean siginingSet = false;
    OMElement certElem = null;
    Iterator<X509Certificate> certIterator = null;

    try {
        factory = OMAbstractFactory.getOMFactory();
        namespace = factory.createOMNamespace(TokenVerifierConstants.NS, TokenVerifierConstants.PREFIX);
        keyInfo = verifier.getKeyInfoElement();
        certIterator = verifier.getCertificates().iterator();

        while (certIterator.hasNext()) {
            X509Certificate cert = certIterator.next();
            byte[] encodedCert = cert.getEncoded();
            String base64Encoded = Base64.encode(encodedCert);

            if (certificates == null) {
                certificates = factory.createOMElement(TokenVerifierConstants.LN_CERTIFICATES, namespace);
            }

            certElem = factory.createOMElement(TokenVerifierConstants.LN_CERTIFICATE, namespace);

            if (siginingSet == false) {
                certElem.addAttribute(TokenVerifierConstants.LN_SIGNING_CERT, "true", null);
                siginingSet = true;
            }
            certElem.setText(base64Encoded);
            certificates.addChild(certElem);
        }

        if (keyInfo != null) {
            String value = IdentityUtil.nodeToString(keyInfo);
            XMLStreamReader parser = XMLInputFactory.newInstance()
                    .createXMLStreamReader(new StringReader(value));
            StAXOMBuilder builder = new StAXOMBuilder(parser);
            omKeyInfo = builder.getDocumentElement();
        }
    } catch (Exception e) {
        log.error("Error while building issuer info", e);
        throw new RelyingPartyException("errorBuildingIssuerInfo");
    }

    if (certificates != null) {
        issuerInfo = certificates.toString();
    }

    if (omKeyInfo != null) {
        if (issuerInfo != null) {
            issuerInfo = issuerInfo + omKeyInfo.toString();
        } else {
            issuerInfo = omKeyInfo.toString();
        }
    }
    return issuerInfo;
}

From source file:eu.europa.ec.markt.dss.signature.pades.PAdESProfileEPES.java

CMSSignedDataGenerator createCMSSignedDataGenerator(ContentSigner contentSigner,
        DigestCalculatorProvider digestCalculatorProvider, final SignatureParameters parameters,
        final byte[] messageDigest) throws IOException {
    try {/* ww  w .ja  va  2 s  .c  om*/

        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        X509Certificate signerCertificate = parameters.getSigningCertificate();

        X509CertificateHolder certHolder = new X509CertificateHolder(signerCertificate.getEncoded());

        SignerInfoGeneratorBuilder sigenb = new SignerInfoGeneratorBuilder(digestCalculatorProvider);

        final CAdESProfileEPES profile = new CAdESProfileEPES(true);

        sigenb = sigenb.setSignedAttributeGenerator(new CMSAttributeTableGenerator() {
            @Override
            public AttributeTable getAttributes(Map params) throws CMSAttributeTableGenerationException {
                Hashtable clone = (Hashtable) profile.getSignedAttributes(parameters).clone();

                if (!clone.containsKey(CMSAttributes.contentType)) {
                    DERObjectIdentifier contentType = (DERObjectIdentifier) params
                            .get(CMSAttributeTableGenerator.CONTENT_TYPE);

                    // contentType will be null if we're trying to generate a counter signature.
                    if (contentType != null) {
                        Attribute attr = new Attribute(CMSAttributes.contentType, new DERSet(contentType));
                        clone.put(attr.getAttrType(), attr);
                    }
                }

                if (!clone.containsKey(CMSAttributes.messageDigest)) {
                    System.out.println("Digest propos : "
                            + org.apache.commons.codec.binary.Hex.encodeHexString(messageDigest));
                    // byte[] messageDigest = (byte[]) params.get(CMSAttributeTableGenerator.DIGEST);
                    Attribute attr = new Attribute(CMSAttributes.messageDigest,
                            new DERSet(new DEROctetString(messageDigest)));
                    clone.put(attr.getAttrType(), attr);
                }

                if (parameters.getCommitmentTypeIndication() != null
                        && !parameters.getCommitmentTypeIndication().isEmpty()) {
                    ASN1EncodableVector vector = new ASN1EncodableVector();
                    for (String id : parameters.getCommitmentTypeIndication()) {
                        vector.add(new DERObjectIdentifier(id));
                    }
                    DERSet set = new DERSet(new DERSequence(vector));
                    Attribute attr = new Attribute(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.16"), set);
                    clone.put(attr.getAttrType(), attr);
                }

                return new AttributeTable(clone);
            }
        });

        // sigenb.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(new AttributeTable(
        // new Hashtable<ASN1ObjectIdentifier, ASN1Encodable>())));

        /*
         * We don't include a unsigned attribute table if not needed : a unsignedAttrs of signerInfo includes no
         * Attribute, UnsignedAttributes ::= SET SIZE (1..MAX) OF Attribute(defined in RFC3852).
         */
        SignerInfoGenerator sigen = sigenb.build(contentSigner, certHolder);

        generator.addSignerInfoGenerator(sigen);

        Collection<X509Certificate> certs = new ArrayList<X509Certificate>();
        if (parameters.getCertificateChain() == null
                || !parameters.getCertificateChain().contains(parameters.getSigningCertificate())) {
            certs.add(parameters.getSigningCertificate());
        }
        certs.addAll(parameters.getCertificateChain());
        JcaCertStore certStore = new JcaCertStore(certs);
        generator.addCertificates(certStore);

        System.out.println("Gnrator cr");
        return generator;

    } catch (CertificateException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    } catch (CMSException e) {
        throw new IOException(e);
    }

}

From source file:net.firejack.platform.model.config.GatewayLoader.java

/**
 * @param lookup/*from www .  j a  va  2  s.c om*/
 * @param port
 * @return
 */
public Environments getConfig(String lookup, Integer port) {
    processSiteMinderConfigs();
    try {
        File keystore = InstallUtils.getKeyStore();

        String url = Env.FIREJACK_URL.getValue();

        logger.info("Load config from: " + url);

        KeyPair keyPair = KeyUtils.generate(keystore);

        if (keyPair == null) {
            throw new IllegalStateException("Key not found");
        }

        String name = InetAddress.getLocalHost().getHostName();
        X509Certificate certificate = KeyUtils.generateCertificate(url, 1, keyPair);

        String cert = new String(Base64.encode(certificate.getEncoded()));
        OPFEngine.init(url, lookup, name, cert);

        ServerNodeConfig config = new ServerNodeConfig();
        config.setServerName(name);
        config.setHost(InetAddress.getLocalHost().getHostAddress());
        config.setPort(port);
        config.setNodeType(ServerNodeType.GATEWAY);
        config.setLookup(lookup);
        config.setCert(certificate.getEncoded());

        InputStream stream = OPFEngine.RegistryService.registerSlaveNode(config);

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(stream, output);
        byte[] decrypted = KeyUtils.decrypt(keyPair.getPrivate(), output.toByteArray());

        return InstallUtils.deserialize(new ByteArrayInputStream(decrypted));
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

public byte[] getEncodedCertificate() {
    X509Certificate certificate = getCertificate();
    try {// w ww.  j av  a2  s .co m
        return certificate.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
}

From source file:com.yubico.u2f.data.DeviceRegistration.java

public DeviceRegistration(String keyHandle, String publicKey, X509Certificate attestationCert, long counter)
        throws U2fBadInputException {
    this.keyHandle = keyHandle;
    this.publicKey = publicKey;
    try {//from www  . j  a  v a2 s .  c  o  m
        this.attestationCert = U2fB64Encoding.encode(attestationCert.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new U2fBadInputException("Malformed attestation certificate", e);
    }
    this.counter = counter;
}

From source file:be.fedict.eid.dss.model.bean.IdentityServiceBean.java

/**
 * {@inheritDoc}//  w  ww .j a  v  a  2s .  co  m
 */
public String getIdentityFingerprint() {

    PrivateKeyEntry identity = findIdentity();
    if (null == identity) {
        return null;
    }
    X509Certificate certificate = (X509Certificate) identity.getCertificate();
    if (null == certificate) {
        return null;
    }
    String fingerprint;
    try {
        fingerprint = DigestUtils.shaHex(certificate.getEncoded());
    } catch (CertificateEncodingException e) {
        LOG.error("cert encoding error: " + e.getMessage(), e);
        return null;
    }
    return fingerprint;
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

public String getCertificate(final String keyStoreName, final String keyStorePwd, final String certAlias,
        final boolean withTag) {
    try {/* w ww. ja v  a  2s .co m*/
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
        ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray());
        if (ctlKeyStore.containsAlias(certAlias)) {
            final X509Certificate odlCert = (X509Certificate) ctlKeyStore.getCertificate(certAlias);
            final String cert = DatatypeConverter.printBase64Binary(odlCert.getEncoded());
            if (withTag) {
                final StringBuilder sb = new StringBuilder();
                sb.append(KeyStoreConstant.BEGIN_CERTIFICATE);
                sb.append("\n");
                sb.append(cert);
                sb.append("\n");
                sb.append(KeyStoreConstant.END_CERTIFICATE);
                return sb.toString();
            }
            return cert;
        }
        LOG.info("{} KeyStore does not contain alias {}", keyStoreName, certAlias);
        return null;
    } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException e) {
        LOG.error("Failed to get Certificate {}", e.getMessage());
        return null;
    }
}

From source file:edu.vt.middleware.crypt.KeyStoreCli.java

/**
 * Prints a string representation of the given certificate to STDOUT. For an
 * X.509 certificate, prints important fields.
 *
 * @param  cert  Certificate to print.//from w w w.jav a 2  s.  com
 *
 * @throws  Exception  On print errors.
 */
protected void printCertificate(final Certificate cert) throws Exception {
    if (cert instanceof X509Certificate) {
        final X509Certificate xCert = (X509Certificate) cert;
        final byte[] encodedCert = xCert.getEncoded();
        System.out.println("Subject: " + xCert.getSubjectDN());
        System.out.println("Issuer: " + xCert.getIssuerDN());
        System.out.println("Serial: " + hexConv.fromBytes(xCert.getSerialNumber().toByteArray()));
        System.out.println("Valid not before: " + xCert.getNotBefore());
        System.out.println("Valid not after: " + xCert.getNotAfter());
        System.out.println("MD5 fingerprint: " + md5.digest(encodedCert, hexConv));
        System.out.println("SHA1 fingerprint: " + sha1.digest(encodedCert, hexConv));
    } else {
        System.out.println(cert);
    }
}