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.hsm.model.security.SecurityAuditGeneratorBean.java

private String getSubjectIdentifier(X509Certificate subjectCertificate) {
    try {/*from   w ww. ja  v a 2s .  c  o  m*/
        String subjectIdentifier = getSubjectIdentifier(subjectCertificate.getEncoded());
        return subjectIdentifier;
    } catch (CertificateEncodingException e) {
        LOG.debug("X509 encoding error: " + e.getMessage());
        return null;
    }
}

From source file:org.wso2.carbon.identity.saml.application.listener.util.SAMLMetadataParser.java

private String convertToPem(X509Certificate cert) throws CertificateEncodingException {
    StringBuilder pemBuilder = new StringBuilder();
    pemBuilder.append(new String(Base64.encodeBase64(cert.getEncoded())));
    return pemBuilder.toString();
}

From source file:com.vmware.admiral.auth.lightwave.pc.X509CertificateHelper.java

public String x509CertificateToBase64(X509Certificate x509Certificate) throws CertificateEncodingException {
    Base64 base64 = new Base64();

    return new String(base64.encode(x509Certificate.getEncoded()));
}

From source file:org.midonet.api.auth.vsphere.FingerprintTrustManager.java

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    Preconditions.checkArgument(chain != null && chain.length > 0);
    Preconditions.checkArgument(!StringUtils.isEmpty(authType));

    MessageDigest messageDigest;//  ww  w . ja  va 2  s. c  om
    try {
        messageDigest = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException(e);
    }

    for (X509Certificate certificate : chain) {
        final byte[] rawCertificateFingerprint = messageDigest.digest(certificate.getEncoded());

        final List<String> hexCertificateFingerprint = new ArrayList<>();

        for (byte aByte : rawCertificateFingerprint) {
            hexCertificateFingerprint.add(String.format("%02X", aByte));
        }

        final String fullCertificateFingerprint = Joiner.on(":").join(hexCertificateFingerprint);

        log.debug(String.format("Checking fingerprint %s for certificate %s", fullCertificateFingerprint,
                certificate.getSubjectDN()));

        if (trustedFingerprint.equalsIgnoreCase(fullCertificateFingerprint)) {
            log.debug(String.format("Found a the trusted fingerprint %s " + "for certificate %s",
                    fullCertificateFingerprint, certificate.getSubjectDN()));
            return;
        }
    }

    throw new CertificateException("No trusted certificate found");
}

From source file:mitm.application.djigzo.james.Certificates.java

private void writeObject(ObjectOutputStream out) throws IOException {
    try {/*from  w w  w.j ava2s  .co  m*/
        out.writeLong(serialVersionUID);

        /*
         * Write the number of certificates so we know how many we have to read when deserializing.
         */
        out.writeInt(certificates.size());

        for (X509Certificate certificate : certificates) {
            byte[] encoded = certificate.getEncoded();
            /* 
             * write the size of the encoded certificate so we can restore it 
             */
            out.writeInt(encoded.length);
            out.write(certificate.getEncoded());
        }
    } catch (CertificateEncodingException e) {
        throw new IOException(e);
    }
}

From source file:org.jvnet.hudson.update_center.Signing.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  ww.ja  v a2  s.  c  o  m
public 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.

    // this is for computing a digest
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

    // this is for computing a signature
    PrivateKey key = ((KeyPair) new PEMReader(new FileReader(privateKey)).readObject()).getPrivate();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);
    SignatureOutputStream sos = new SignatureOutputStream(sig);

    // this is for verifying that signature validates
    Signature verifier = Signature.getInstance("SHA1withRSA");
    verifier.initVerify(signer.getPublicKey());
    SignatureOutputStream vos = new SignatureOutputStream(verifier);

    o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(new TeeOutputStream(dos, sos), vos), "UTF-8"));

    // digest
    byte[] digest = sha1.digest();
    sign.put("digest", new String(Base64.encodeBase64(digest)));

    // signature
    byte[] s = sig.sign();
    sign.put("signature", new String(Base64.encodeBase64(s)));

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

    // did the signature validate?
    if (!verifier.verify(s))
        throw new GeneralSecurityException(
                "Signature failed to validate. Either the certificate and the private key weren't matching, or a bug in the program.");

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

From source file:org.globus.pkcs11.PKCS11Util.java

/**
 * Loads a certificate onto the PKCS11 device and labels it with the specified
 * label/*from  www . j a  va 2s .  c om*/
 */
public static PKCS11Object instantiateUserCert(X509Certificate userCert, String label, byte[] id)
        throws CertificateEncodingException {

    Name issuer = (Name) userCert.getIssuerDN();
    Name subject = (Name) userCert.getSubjectDN();

    byte[] issuerBytes = issuer.getEncoded();
    byte[] subjectBytes = subject.getEncoded();

    if (label == null) {
        label = subject.toString();
    }

    logger.debug("Instantiating user cert with label " + label + " on device");
    //X_509 CERTIFICATE
    int[] certAttributes = { PKCS11Object.CLASS, PKCS11Object.TOKEN, PKCS11Object.LABEL,
            PKCS11Object.CERTIFICATE_TYPE, PKCS11Object.ID, PKCS11Object.SUBJECT, PKCS11Object.ISSUER,
            PKCS11Object.SERIAL_NUMBER, PKCS11Object.VALUE };

    Object[] certAttrValues = { PKCS11Object.CERTIFICATE, PKCS11Object.TRUE, label, PKCS11Object.X_509, id,
            subjectBytes, issuerBytes, userCert.getSerialNumber().toByteArray(), userCert.getEncoded() };

    return session.createObject(certAttributes, certAttrValues);
}

From source file:no.digipost.signature.client.asice.signature.CreateXAdESProperties.java

public Document createPropertiesToSign(final List<ASiCEAttachable> files, final X509Certificate certificate) {
    byte[] certificateDigestValue;
    try {/*  w w  w. ja v  a  2s.co m*/
        certificateDigestValue = sha1(certificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new CertificateException("Unable to get encoded from of certificate", e);
    }

    DigestAlgAndValueType certificateDigest = new DigestAlgAndValueType(sha1DigestMethod,
            certificateDigestValue);
    X509IssuerSerialType certificateIssuer = new X509IssuerSerialType(certificate.getIssuerDN().getName(),
            certificate.getSerialNumber());
    SigningCertificate signingCertificate = new SigningCertificate(
            singletonList(new CertIDType(certificateDigest, certificateIssuer, null)));

    Date now = new Date();
    SignedSignatureProperties signedSignatureProperties = new SignedSignatureProperties(now, signingCertificate,
            null, null, null, null);
    SignedDataObjectProperties signedDataObjectProperties = new SignedDataObjectProperties(
            dataObjectFormats(files), null, null, null, null);
    SignedProperties signedProperties = new SignedProperties(signedSignatureProperties,
            signedDataObjectProperties, "SignedProperties");
    QualifyingProperties qualifyingProperties = new QualifyingProperties(signedProperties, null, "#Signature",
            null);

    DOMResult domResult = new DOMResult();
    marshaller.marshal(qualifyingProperties, domResult);
    Document document = (Document) domResult.getNode();

    // Explicitly mark the SignedProperties Id as an Document ID attribute, so that it will be eligble as a reference for signature.
    // If not, it will not be treated as something to sign.
    markAsIdProperty(document, "SignedProperties", "Id");

    return document;
}

From source file:test.unit.be.fedict.eid.tsl.FingerprintTest.java

@Test
public void testECSSLFingerprint() throws Exception {
    // setup//from  w  ww.ja  v  a 2 s  . com
    X509Certificate sslCert = TrustTestUtils.loadCertificateFromResource("eu/ec.europa.eu.der");

    // operate
    LOG.debug("EC SSL SHA-1 fingerprint: " + DigestUtils.shaHex(sslCert.getEncoded()));
    LOG.debug("EC SSL SHA-256 fingerprint: " + DigestUtils.sha256Hex(sslCert.getEncoded()));
}

From source file:com.connectsdk.service.config.WebOSTVServiceConfig.java

private String exportCertificateToPEM(X509Certificate cert) {
    try {/*from w  ww  .  ja va  2 s  . com*/
        if (cert == null)
            return null;
        return Base64.encodeToString(cert.getEncoded(), Base64.DEFAULT);
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        return null;
    }
}