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:org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier.java

/**
 * This method generates an OCSP Request to be sent to an OCSP endpoint.
 *
 * @param issuerCert   is the Certificate of the Issuer of the peer certificate we are interested in.
 * @param serialNumber of the peer certificate.
 * @return generated OCSP request./* w w  w  .ja  v a 2s. c  om*/
 * @throws CertificateVerificationException
 *
 */
private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws CertificateVerificationException {

    //TODO: Have to check if this is OK with synapse implementation.
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    try {

        byte[] issuerCertEnc = issuerCert.getEncoded();
        X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc);
        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();

        //  CertID structure is used to uniquely identify certificates that are the subject of
        // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560
        CertificateID id = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder,
                serialNumber);

        // basic request generation with nonce
        OCSPReqBuilder builder = new OCSPReqBuilder();
        builder.addRequest(id);

        // create details for nonce extension. The nonce extension is used to bind
        // a request to a response to prevent replay attacks. As the name implies,
        // the nonce value is something that the client should only use once within a reasonably small period.
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());

        //to create the request Extension
        builder.setRequestExtensions(new Extensions(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce,
                false, new DEROctetString(nonce.toByteArray()))));

        return builder.build();

    } catch (Exception e) {
        throw new CertificateVerificationException("Cannot generate OSCP Request with the given certificate",
                e);
    }
}

From source file:org.wso2.carbon.identity.authenticator.mutualssl.MutualSSLAuthenticator.java

/**
 * Helper method to retrieve the thumbprint of a X509 certificate
 *
 * @param cert X509 certificate//from ww w. ja  v  a2  s. c  o m
 * @return Thumbprint of the X509 certificate
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 */
private String getThumbPrint(X509Certificate cert)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] certEncoded = cert.getEncoded();
    md.update(certEncoded);
    return hexify(md.digest());
}

From source file:localca.certstore.MockCertificateStorage.java

@Override
public void setCert(String commonName, X509Certificate certificate) throws CertificateStorageException {
    if (!map.containsKey(commonName)) {
        throw new CertificateStorageException(CertificateStorageExceptionType.NOT_FOUND, commonName);
    }//w w  w  . j  a va 2s . com
    if (map.get(commonName).getEncoded() != null) {
        throw new CertificateStorageException(CertificateStorageExceptionType.ALREADY_SET, commonName);
    }
    try {
        map.put(commonName,
                new StoredCertificate(commonName, Base64.encodeBase64String(certificate.getEncoded())));
    } catch (CertificateEncodingException e) {
        throw new CertificateStorageException(e, CertificateStorageExceptionType.ENCODING_ERROR, commonName);
    }
}

From source file:org.tolven.session.OpenAMSessionWrapper.java

@Override
public String getUserX509CertificateString() {
    X509Certificate x509Certificate = getUserX509Certificate();
    if (x509Certificate == null) {
        return null;
    }//from   w w w  .jav  a 2s  .  c o  m
    try {
        StringBuffer buff = new StringBuffer();
        buff.append("-----BEGIN CERTIFICATE-----");
        buff.append("\n");
        String pemFormat = new String(Base64.encodeBase64Chunked(x509Certificate.getEncoded()));
        buff.append(pemFormat);
        buff.append("\n");
        buff.append("-----END CERTIFICATE-----");
        buff.append("\n");
        return buff.toString();
    } catch (Exception ex) {
        throw new RuntimeException("Could not convert X509Certificate into a String", ex);
    }
}

From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectParser.java

private X509Certificate parseCmsCertificate(X509Certificate certificate) {
    ProvisioningCmsCertificateParser parser = new ProvisioningCmsCertificateParser();
    try {/*from  w w w.  ja va 2s.c o  m*/
        parser.parse(ValidationResult.withLocation(location), certificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new AbstractX509CertificateWrapperException(e);
    }
    return parser.getCertificate().getCertificate();
}

From source file:org.votingsystem.web.ejb.SignatureBean.java

public boolean isSignerCertificate(Set<UserVS> signers, X509Certificate cert)
        throws CertificateEncodingException {
    for (UserVS userVS : signers) {
        if (Arrays.equals(userVS.getCertificate().getEncoded(), cert.getEncoded()))
            return true;
    }//from   w ww.j av  a2 s. c o m
    return false;
}

From source file:com.vmware.certificate.Client.java

/**
 * returns a PEM Encoded String from a X509Certificate
 *
 * @param certificate//from ww  w .j a v  a 2  s  .c o m
 * @return
 * @throws Exception
 */
private String getEncodedStringFromCertificate(X509Certificate certificate) throws Exception {
    if (certificate == null) {
        throw new IllegalStateException("Invalid Certificate, certificate cannot be null");
    }

    String encoded = new String(Base64.encodeBase64(certificate.getEncoded()));
    StringBuffer pemencode = new StringBuffer();
    for (int x = 0; x < encoded.length(); x++) {

        if ((x > 0) && (x % 64 == 0)) {
            pemencode.append("\n");
            pemencode.append(encoded.charAt(x));
        } else {
            pemencode.append(encoded.charAt(x));

        }
    }
    return BEGIN_CERT + pemencode.toString() + END_CERT;

}

From source file:be.fedict.eid.tsl.tool.TslInternalFrame.java

@Override
public void valueChanged(TreeSelectionEvent event) {
    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    if (treeNode.isLeaf()) {
        TrustService trustService = (TrustService) treeNode.getUserObject();
        this.serviceName.setText(trustService.getName());
        this.serviceType.setText(trustService.getType()
                .substring(trustService.getType().indexOf("Svctype/") + "Svctype/".length()));
        this.serviceStatus.setText(trustService.getStatus()
                .substring(trustService.getStatus().indexOf("Svcstatus/") + "Svcstatus/".length()));
        X509Certificate certificate = trustService.getServiceDigitalIdentity();
        byte[] encodedCertificate;
        try {/*from   w ww  . j  a v  a2 s . co  m*/
            encodedCertificate = certificate.getEncoded();
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("cert: " + e.getMessage(), e);
        }
        String sha1Thumbprint = DigestUtils.shaHex(encodedCertificate);
        this.serviceSha1Thumbprint.setText(sha1Thumbprint);

        String sha256Thumbprint = DigestUtils.sha256Hex(encodedCertificate);
        this.serviceSha256Thumbprint.setText(sha256Thumbprint);

        this.validityBegin.setText(certificate.getNotBefore().toString());
        this.validityEnd.setText(certificate.getNotAfter().toString());
    } else {
        this.serviceName.setText("");
        this.serviceType.setText("");
        this.serviceStatus.setText("");
        this.serviceSha1Thumbprint.setText("");
        this.serviceSha256Thumbprint.setText("");
        this.validityBegin.setText("");
        this.validityEnd.setText("");
    }
}

From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateAuthenticator.java

/**
 * validate the certificate using the selected subject.
 *
 * @param subject               matched string or the username that uses to authenticate.
 * @param authenticationContext authenticationContext.
 * @param cert                  x509 certificate.
 * @param claims                user claims.
 *//*from  ww w . ja  v  a 2 s. co  m*/
private void validateUsingSubject(String subject, AuthenticationContext authenticationContext,
        X509Certificate cert, Map<ClaimMapping, String> claims) throws AuthenticationFailedException {

    byte[] data;
    try {
        data = cert.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new AuthenticationFailedException(
                "Encoded certificate is not found in the certificate with subjectDN: " + cert.getSubjectDN(),
                e);
    }
    AuthenticatedUser authenticatedUser = getUsername(authenticationContext);

    if (log.isDebugEnabled()) {
        log.debug("Getting X509Certificate username");
    }

    if (authenticatedUser != null) {
        if (log.isDebugEnabled()) {
            log.debug("Authenticated username is: " + authenticatedUser);
        }
        String authenticatedUserName = authenticatedUser.getAuthenticatedSubjectIdentifier();
        if (authenticatedUserName.equals(subject)) {
            addOrValidateCertificate(subject, authenticationContext, data, claims, cert);
        } else {
            authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_ERROR_CODE,
                    X509CertificateConstants.USERNAME_CONFLICT);
            throw new AuthenticationFailedException(
                    "Couldn't find X509 certificate to this authenticated user: " + authenticatedUserName);
        }
    } else {
        addOrValidateCertificate(subject, authenticationContext, data, claims, cert);
    }
}

From source file:com.foundstone.certinstaller.CertInstallerActivity.java

/**
 * Install the X509Certificate using the KeyChain intent and specifying a
 * certificate. The return code is used here to know when type of cert was
 * installed.// w w  w.  j  a v a 2s  . c o m
 * 
 * @param cert
 * @param code
 * @throws Exception
 */
private void installCert(X509Certificate cert, Integer code) throws Exception {

    byte[] keystore = cert.getEncoded();
    Intent installIntent = KeyChain.createInstallIntent();
    installIntent.putExtra(KeyChain.EXTRA_CERTIFICATE, keystore);
    startActivityForResult(installIntent, code);
}