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:be.fedict.trust.repository.MemoryCertificateRepository.java

@Override
public boolean isTrustPoint(X509Certificate certificate) {
    String fingerprint = getFingerprint(certificate);
    X509Certificate trustPoint = this.trustPoints.get(fingerprint);
    if (null == trustPoint) {
        return false;
    }//from   ww  w .j  a v a 2  s. com
    try {
        /*
         * We cannot used certificate.equals(trustPoint) here as the
         * certificates might be loaded by different security providers.
         */
        return Arrays.equals(certificate.getEncoded(), trustPoint.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new IllegalArgumentException("certificate encoding error: " + e.getMessage(), e);
    }
}

From source file:mx.bigdata.sat.cfdi.CFDv33.java

@Override
public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
    String nc = new String(cert.getSerialNumber().toByteArray());
    cert.checkValidity();//w w  w  . j  av  a  2  s .c  o  m
    byte[] bytes = cert.getEncoded();
    Base64 b64 = new Base64(-1);
    String certStr = b64.encodeToString(bytes);
    document.setCertificado(certStr);
    document.setNoCertificado(nc);
    String signature = getSignature(key);
    document.setSello(signature);
}

From source file:com.otterca.persistence.entity.X509CertificateEntity.java

/**
 * Cache values within certificate. They should never be set directly and
 * the actual values in the database should be created via triggers.
 * //  w  w w .j  av a 2 s. c om
 * @param cert
 */
protected final void cacheAttributes(X509Certificate cert) throws CertificateEncodingException, IOException {
    serialNumber = cert.getSerialNumber();
    certificate = cert.getEncoded();
    subject = cert.getSubjectDN().getName();
    issuer = cert.getIssuerDN().getName();
    notBefore = cert.getNotBefore();
    notAfter = cert.getNotAfter();

    //name = x509CertUtil.getName(cert);
    //fingerprint = x509CertUtil.getFingerprint(cert);
    //certHash = x509CertUtil.getCertificateHash(cert);
    //iHash = x509CertUtil.getIHash(cert);
    //sHash = x509CertUtil.getSHash(cert);
    //akidHash = x509CertUtil.getAkidHash(cert);
    //skidHash = x509CertUtil.getSkidHash(cert);
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileC.java

/**
 * Create a reference to a X509Certificate
 * //  w  w w .j a v  a 2 s .c o m
 * @param cert
 * @return
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 */
private OtherCertID makeOtherCertID(X509Certificate cert)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    MessageDigest sha1digest = MessageDigest.getInstance(X509ObjectIdentifiers.id_SHA1.getId(),
            new BouncyCastleProvider());
    byte[] d = sha1digest.digest(cert.getEncoded());
    LOG.info(new DEROctetString(d).getDERObject().toString());
    OtherHash hash = new OtherHash(sha1digest.digest(cert.getEncoded()));
    OtherCertID othercertid = new OtherCertID(new DERSequence(hash.getDERObject()));
    return othercertid;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESService.java

private CMSSignedDataGenerator createCMSSignedDataGenerator(ContentSigner contentSigner,
        DigestCalculatorProvider digestCalculatorProvider, SignatureParameters parameters,
        CAdESProfileBES cadesProfile, boolean includeUnsignedAttributes, CMSSignedData originalSignedData)
        throws IOException {

    try {/*from  w  ww .  j av  a  2  s. c  om*/

        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        X509Certificate signerCertificate = parameters.getSigningCertificate();

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

        SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(
                digestCalculatorProvider);

        sigInfoGeneratorBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(
                new AttributeTable(cadesProfile.getSignedAttributes(parameters))));

        sigInfoGeneratorBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(
                (includeUnsignedAttributes) ? new AttributeTable(cadesProfile.getUnsignedAttributes(parameters))
                        : null));

        SignerInfoGenerator sigInfoGen = sigInfoGeneratorBuilder.build(contentSigner, certHolder);

        generator.addSignerInfoGenerator(sigInfoGen);
        if (originalSignedData != null) {
            generator.addSigners(originalSignedData.getSignerInfos());
        }

        Collection<X509Certificate> certs = new ArrayList<X509Certificate>();
        certs.add(parameters.getSigningCertificate());

        if (parameters.getCertificateChain() != null) {
            for (X509Certificate c : parameters.getCertificateChain()) {
                if (!c.getSubjectX500Principal()
                        .equals(parameters.getSigningCertificate().getSubjectX500Principal())) {
                    certs.add(c);
                }
            }
        }

        JcaCertStore certStore = new JcaCertStore(certs);
        generator.addCertificates(certStore);
        if (originalSignedData != null) {
            generator.addCertificates(originalSignedData.getCertificates());
        }

        return generator;

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

}

From source file:org.wso2.carbon.identity.saml.application.listener.listeners.SAMLMetadataListener.java

private String getCertFromKeyStore(String alias, String tenantDomain) {

    int tenantId = 0;
    try {//from w ww . j  ava 2  s  .c  om
        tenantId = IdentitySAMLListenerComponent.getRealmService().getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error getting the tenant ID for the tenant domain " + tenantDomain, e);
        }

        return null;
    }
    // get an instance of the corresponding Key Store Manager instance
    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);

    KeyStore keyStore;

    try {
        if (MultitenantConstants.SUPER_TENANT_ID != tenantId) {// for tenants, load public key from their
            // generated key store
            keyStore = keyStoreManager.getKeyStore(SAMLSSOUtil.generateKSNameFromDomainName(tenantDomain));
        } else { // for super tenant, load the default pub. cert using the config. in carbon.xml
            keyStore = keyStoreManager.getPrimaryKeyStore();
        }
        X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
        return new String(Base64.encodeBase64(cert.getEncoded()));
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error retrieving the public certificate for alias " + alias, e);
        }
    }

    return null;
}

From source file:org.wso2.carbon.core.bootup.validator.SystemValidator.java

/**
 * Generate the MD5 thumbprint of the certificate
 *
 * @param certificate that we need the thumbprint
 * @return MD5 thumbprint value/*from w  w  w.  ja v  a  2  s . c  o  m*/
 * @throws CertificateEncodingException
 * @throws NoSuchAlgorithmException
 */
private String getCertFingerprint(X509Certificate certificate)
        throws CertificateEncodingException, NoSuchAlgorithmException {
    MessageDigest digestValue = MessageDigest.getInstance("MD5");
    byte[] der = certificate.getEncoded();
    digestValue.update(der);
    byte[] digestInBytes = digestValue.digest();
    return hexify(digestInBytes);
}

From source file:com.vmware.identity.openidconnect.client.AdminServerHelper.java

private String convertToBase64PEMString(X509Certificate x509Certificate) throws OIDCClientException {

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    BASE64Encoder encoder = new BASE64Encoder();
    try {//from   w  w  w.j  a v  a 2s.com
        byteArrayOutputStream.write(X509Factory.BEGIN_CERT.getBytes());
        byteArrayOutputStream.write("\n".getBytes());
        encoder.encodeBuffer(x509Certificate.getEncoded(), byteArrayOutputStream);
        byteArrayOutputStream.write(X509Factory.END_CERT.getBytes());
        byteArrayOutputStream.write("\n".getBytes());
    } catch (IOException | CertificateEncodingException e) {
        throw new OIDCClientException("Failed to convert certificate: " + e.getMessage(), e);
    }
    return byteArrayOutputStream.toString();
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

private String convertToBase64PEMString(X509Certificate x509Certificate) throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byteArrayOutputStream.write("-----BEGIN CERTIFICATE-----".getBytes());
    byteArrayOutputStream.write("\n".getBytes());
    byteArrayOutputStream.write(Base64Utils.encodeToBytes(x509Certificate.getEncoded()));
    byteArrayOutputStream.write("-----END CERTIFICATE-----".getBytes());
    byteArrayOutputStream.write("\n".getBytes());
    return byteArrayOutputStream.toString();
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Generates a canonicalized JSON format of the given object, and put the signature in it.
 * Because it mutates the signed object itself, validating the signature needs a bit of work,
 * but this enables a signature to be added transparently.
 *//*from   w  w  w.j  a va  2s .c o  m*/
protected void sign(JSONObject o) throws GeneralSecurityException, IOException {
    JSONObject sign = new JSONObject();

    List<X509Certificate> certs = getCertificateChain();
    X509Certificate signer = certs.get(0); // the first one is the signer, and the rest is the chain to a root CA.

    PrivateKey key = ((KeyPair) new PEMReader(new FileReader(privateKey)).readObject()).getPrivate();

    // first, backward compatible signature for <1.433 Jenkins that forgets to flush the stream.
    // we generate this in the original names that those Jenkins understands.
    SignatureGenerator sg = new SignatureGenerator(signer, key);
    o.writeCanonical(new OutputStreamWriter(sg.getOut(), "UTF-8"));
    sg.addRecord(sign, "");

    // then the correct signature, into names that don't collide.
    OutputStream raw = new NullOutputStream();
    if (canonical != null) {
        raw = new FileOutputStream(canonical);
    }
    sg = new SignatureGenerator(signer, key);
    o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(sg.getOut(), raw), "UTF-8")).close();
    sg.addRecord(sign, "correct_");

    // and certificate chain
    JSONArray a = new JSONArray();
    for (X509Certificate cert : certs)
        a.add(new String(Base64.encodeBase64(cert.getEncoded())));
    sign.put("certificates", a);

    o.put("signature", sign);
}