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:io.vertx.config.vault.utils.Certificates.java

/**
 * See https://stackoverflow.com/questions/3313020/write-x509-certificate-into-pem-formatted-string-in-java
 *
 * @param certificate An X509 certificate
 * @param file        the file/*w w  w  . j  a v a  2  s. com*/
 * @throws CertificateEncodingException
 * @throws FileNotFoundException
 */
private static void writeCertToPem(final X509Certificate certificate, final File file)
        throws CertificateEncodingException, IOException {
    final Base64.Encoder encoder = Base64.getEncoder();

    final String certHeader = "-----BEGIN CERTIFICATE-----\n";
    final String certFooter = "\n-----END CERTIFICATE-----";
    final byte[] certBytes = certificate.getEncoded();
    final String certContents = new String(encoder.encode(certBytes));
    final String certPem = certHeader + certContents + certFooter;
    FileUtils.write(file, certPem);
}

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

static 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.apache.rahas.impl.util.CommonUtil.java

/**
 * Creates the X509 data element in a SAML issuer token. Should create an element similar to following,
 * <X509Data xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
 *                         xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
 *   <X509Certificate>//from   www.  ja  va  2 s. c  o m
 *       MIICNTCCAZ6gAwIB...
 *   </X509Certificate>
 * </X509Data>
 * @param clientCert Client certificate to be used when generating X509 data
 * @return  SAML X509Data representation.
 * @throws TrustException If an error occurred while creating X509Data and X509Certificate.
 */
static X509Data createX509Data(X509Certificate clientCert) throws TrustException {

    byte[] clientCertBytes;
    try {
        clientCertBytes = clientCert.getEncoded();
    } catch (CertificateEncodingException e) {
        log.error("An error occurred while encoding certificate.", e);
        throw new TrustException("An error occurred while encoding certificate.", e);
    }
    String base64Cert = Base64.encode(clientCertBytes);

    org.opensaml.xml.signature.X509Certificate x509Certificate = (org.opensaml.xml.signature.X509Certificate) CommonUtil
            .buildXMLObject(org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);

    x509Certificate.setValue(base64Cert);

    X509Data x509Data = (X509Data) CommonUtil.buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
    x509Data.getX509Certificates().add(x509Certificate);

    return x509Data;
}

From source file:ee.ria.xroad.signer.certmanager.OcspClient.java

private static OCSPReq createRequest(X509Certificate subjectCert, X509Certificate issuerCert,
        PrivateKey signerKey, X509Certificate signerCert, String signAlgoId) throws Exception {
    OCSPReqBuilder requestBuilder = new OCSPReqBuilder();

    CertificateID id = CryptoUtils.createCertId(subjectCert, issuerCert);
    requestBuilder.addRequest(id);//from ww w  .j  a  v a 2 s .c  o  m

    if (signerKey != null && signerCert != null) {
        X509CertificateHolder signerCertHolder = new X509CertificateHolder(signerCert.getEncoded());
        ContentSigner contentSigner = CryptoUtils.createContentSigner(signAlgoId, signerKey);

        log.trace("Creating signed OCSP request for certificate '{}' (signed by {})",
                subjectCert.getSubjectX500Principal(), signerCertHolder.getSubject());

        // needs to be set when generating signed requests
        requestBuilder.setRequestorName(signerCertHolder.getSubject());

        return requestBuilder.build(contentSigner, new X509CertificateHolder[] { signerCertHolder });
    }

    log.trace("Creating unsigned OCSP request for certificate '{}'", subjectCert.getSubjectX500Principal());

    return requestBuilder.build();
}

From source file:be.fedict.eidviewer.lib.file.imports.Version35CSVFile.java

public static void X509CertToCSV(X509Certificate certificate, String label, OutputStreamWriter writer)
        throws Exception {
    writer.write(String.format("%s;1;%s;;", label, X509Utilities.eidBase64Encode(certificate.getEncoded())));
}

From source file:eu.europa.ejusticeportal.dss.applet.model.token.CertificateDisplayUtils.java

/**
 * Calculate a digest of the signing certificate. This is used to get a unique id for it.
 * /*from  w  w  w .  j av a  2s .c o  m*/
 * @param cert the certificate to digest
 * @return the digest (SHA1, encoded as hex)
 */
public static String digest(X509Certificate cert) {
    String digest = null;
    try {
        MessageDigest sha1digest = MessageDigest.getInstance(X509ObjectIdentifiers.id_SHA1.getId(),
                new BouncyCastleProvider());
        digest = Hex.encodeHexString(sha1digest.digest(cert.getEncoded()));
    } catch (Exception e) {
        ExceptionUtils.throwException(new UnexpectedException(e), LOG);
    }
    return digest;
}

From source file:com.vmware.demo.SamlUtils.java

public static String convertToPemFormat(X509Certificate cert) throws SamlException {
    try {//from  w  w w.j av  a2  s .co  m
        byte[] cert64 = Base64.encodeBase64(cert.getEncoded());
        String strCert = new String(cert64, SamlGenerator.ENC_UTF8);
        return convertCertToPemFormat(strCert);
    } catch (Exception e) {
        throw new SamlException("Failed to create PEM certificate from cert.", e);
    }
}

From source file:com.vmware.demo.SamlUtils.java

/**
 * Generate a new self-signed certificate for a given keypair.
 *
 * @param pubKey - organization's public key
 * @param privKey - organization's private key
 * @param orgName - organization's name// w  w  w .  ja  v  a2s .  c o  m
 * @return the new certicate in base64 format (NO PEM wrapping)
 * @throws SamlException
 */
public static String generateCertPEM(KeyPair key, String issuer) throws SamlException {
    String pemCert = null;

    try {
        X509Certificate binCert = generateCert(key, issuer);
        byte[] cert64 = Base64.encodeBase64(binCert.getEncoded());
        pemCert = new String(cert64, SamlGenerator.ENC_UTF8);
    } catch (Exception e) {
        throw new SamlException("Unable to generate PEM certificate from key, issuer = " + issuer, e);
    }

    return pemCert;

}

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

/**
 * Add certificate into claims.// w ww.ja  va2  s  .  c  o m
 *
 * @param username        name of the user
 * @param x509Certificate x509 certificate
 * @return boolean status of the action
 * @throws AuthenticationFailedException authentication failed exception
 */
public static boolean addCertificate(String username, X509Certificate x509Certificate)
        throws AuthenticationFailedException {
    Map<String, String> claims = new HashMap<>();
    UserRealm userRealm = getUserRealm(username);
    try {
        if (userRealm != null) {
            claims.put(getClaimUri(), Base64.encode(x509Certificate.getEncoded()));
            String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
            userRealm.getUserStoreManager().setUserClaimValues(tenantAwareUsername, claims,
                    X509CertificateConstants.DEFAULT);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("UserRealm is null for username: " + username);
            }
            throw new AuthenticationFailedException("Cannot find the user realm for the given tenant domain : "
                    + CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
        }
    } catch (CertificateException e) {
        throw new AuthenticationFailedException("Error while retrieving certificate of user: " + username, e);
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Error while retrieving the user store manager ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("X509 certificate is added for user: " + username);
    }
    return true;
}

From source file:org.gvnix.service.roo.addon.addon.security.GvNix509TrustManager.java

/**
 * Export the given certificate to a file in SRC_MAIN_RESOURCES. The cert
 * file will have given <code>{alias}.cer</code> as file name.
 * <p>/*w  ww .  j  a va 2s  .  c om*/
 * <b>We don't use Roo FileManager API</b> here in order to create cert
 * files because in this way if we have any problem importing them to the
 * JVM <code>cacerts</cacerts> Roo won't undo the cert files creation.
 * </p>
 * 
 * @param alias
 * @param cert
 * @param fileManager
 * @param pathResolver
 * @throws Exception
 */
public static void saveCertFile(String alias, X509Certificate cert, FileManager fileManager,
        PathResolver pathResolver) throws Exception {

    String aliasCerFileName = alias.concat(".cer");
    String cerFilePath = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_RESOURCES, ""),
            aliasCerFileName);

    if (!fileManager.exists(cerFilePath)) {

        File cerFile = new File(cerFilePath);
        OutputStream os = null;
        try {
            os = new FileOutputStream(cerFile);
            os.write(cert.getEncoded());
        } finally {
            IOUtils.closeQuietly(os);
        }
        logger.info("Created ".concat(Path.SRC_MAIN_RESOURCES.name()).concat("/").concat(aliasCerFileName));
    }
}