Example usage for java.security.cert Certificate getEncoded

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

Introduction

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

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

From source file:org.wso2.carbon.dataservices.core.auth.JWTAuthorizationProvider.java

/**
 * Get the alias for the X509 certificate thumb
 * @param thumb//from ww w  . j a  v a2 s  . c o  m
 * @param keyStore
 * @return
 * @throws org.apache.axis2.AxisFault
 */
private String getAliasForX509CertThumb(byte[] thumb, KeyStore keyStore) throws AxisFault {
    Certificate cert = null;
    MessageDigest sha = null;

    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e1) {
        log.error("noSHA1availabe");
        throw new AxisFault("noSHA1availabe");
    }
    try {
        for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            Certificate[] certs = keyStore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = keyStore.getCertificate(alias);
                if (cert == null) {
                    return null;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            sha.reset();
            try {
                sha.update(cert.getEncoded());
            } catch (CertificateEncodingException e1) {
                log.error("Error encoding certificate");
                throw new AxisFault("Error encoding certificate");
            }
            byte[] data = sha.digest();
            if (new String(thumb).equals(hexify(data))) {
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        log.error("KeyStore exception while getting alias for X509CertThumb");
        throw new AxisFault("KeyStore exception while getting alias for X509CertThumb");
    }
    return null;
}

From source file:edu.byu.wso2.apim.extensions.JWTDecoder.java

private String getAliasForX509CertThumb(KeyStore keyStore, byte[] thumb, MessageContext synapseContext) {
    SynapseLog synLog = getLog(synapseContext);
    Certificate cert = null;
    MessageDigest sha = null;// w  w w  .  ja  v  a 2  s .co  m

    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        handleSigVerificationException(e, synapseContext);
    }
    try {
        for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate[] certs = keyStore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = keyStore.getCertificate(alias);
                if (cert == null) {
                    return null;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            sha.reset();
            try {
                sha.update(cert.getEncoded());
            } catch (CertificateEncodingException e1) {
                //throw new Exception("Error encoding certificate");
            }
            byte[] data = sha.digest();
            if (new String(thumb).equals(hexify(data))) {
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("Found matching alias: " + alias);
                }
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        if (log.isErrorEnabled()) {
            log.error("Error getting alias from keystore", e);
        }
    }
    return null;
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

@Override
/**/*from  w  w w.  j a va 2 s.  co  m*/
 * @see org.apache.ws.security.components.crypto.Crypto#getAliasForX509CertThumb(byte[])
 */
public String getAliasForX509CertThumb(byte[] thumb) throws WSSecurityException {
    Certificate cert;
    MessageDigest sha;
    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e1) {
        throw new WSSecurityException(0, "noSHA1availabe");
    }
    try {
        for (Enumeration e = keystore.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            Certificate[] certs = this.getCertificates(alias);
            if (certs == null || certs.length == 0) {
                return null;
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            sha.reset();
            try {
                sha.update(cert.getEncoded());
            } catch (CertificateEncodingException e1) {
                throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError");
            }
            byte[] data = sha.digest();

            if (Arrays.equals(data, thumb)) {
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore");
    }
    return null;
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java

@Override
public byte[] sign(final InputStream content) throws IOException {

    try {/*from   ww w  . j a v  a2s  .c  o  m*/

        KeyPair key = this.propertyStore.getKeyPair();

        PrivateKey privKey = key.getPrivate();

        Certificate certificate = this.propertyStore.getCertificate(key);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate
                .getInstance(certificate.getEncoded());
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privKey);
        gen.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                        .build(sha1Signer, new X509CertificateHolder(cert)));

        CMSProcessableByteArray msg = new CMSProcessableByteArray(IOUtils.toByteArray(content));

        CMSSignedData signedData = gen.generate(msg, false);

        return signedData.getEncoded();

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

From source file:org.gluu.oxeleven.rest.GenerateKeyRestServiceImpl.java

public Response generateKey(String sigAlg, Long expirationTime) {
    Response.ResponseBuilder builder = Response.ok();

    try {/*from   w  w w  .ja va 2s. c o  m*/
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromName(sigAlg);

        if (signatureAlgorithm == null) {
            builder = Response.status(Response.Status.BAD_REQUEST);
            builder.entity(StringUtils.getErrorResponse("invalid_request",
                    "The request asked for an operation that cannot be supported because the server does not support the provided signatureAlgorithm parameter."));
        } else if (expirationTime == null) {
            builder = Response.status(Response.Status.BAD_REQUEST);
            builder.entity(StringUtils.getErrorResponse("invalid_request",
                    "The request asked for an operation that cannot be supported because the expiration time parameter is mandatory."));
        } else if (signatureAlgorithm == SignatureAlgorithm.NONE
                || signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.HMAC)) {
            builder = Response.status(Response.Status.BAD_REQUEST);
            builder.entity(StringUtils.getErrorResponse("invalid_request",
                    "The provided signature algorithm parameter is not supported."));
        } else {
            String dnName = configuration.getDnName();
            String alias = pkcs11Service.generateKey(dnName, signatureAlgorithm, expirationTime);
            PublicKey publicKey = pkcs11Service.getPublicKey(alias);
            Certificate certificate = pkcs11Service.getCertificate(alias);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put(KEY_ID, alias);
            jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily());
            jsonObject.put(KEY_USE, "sig");
            jsonObject.put(ALGORITHM, signatureAlgorithm.getName());
            jsonObject.put(EXPIRATION_TIME, expirationTime);
            if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
                RSAPublicKeyImpl rsaPublicKey = (RSAPublicKeyImpl) publicKey;
                jsonObject.put(MODULUS, Base64Util.base64UrlEncode(rsaPublicKey.getModulus().toByteArray()));
                jsonObject.put(EXPONENT,
                        Base64Util.base64UrlEncode(rsaPublicKey.getPublicExponent().toByteArray()));
            } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
                ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
                jsonObject.put(CURVE, signatureAlgorithm.getCurve());
                jsonObject.put(X, Base64Util.base64UrlEncode(ecPublicKey.getW().getAffineX().toByteArray()));
                jsonObject.put(Y, Base64Util.base64UrlEncode(ecPublicKey.getW().getAffineY().toByteArray()));
            }
            JSONArray x5c = new JSONArray();
            x5c.put(Base64.encodeBase64String(certificate.getEncoded()));
            jsonObject.put(CERTIFICATE_CHAIN, x5c);

            builder.entity(jsonObject.toString());
        }
    } catch (CertificateException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (KeyStoreException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (NoSuchProviderException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (SignatureException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (JSONException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    }

    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoTransform(false);
    cacheControl.setNoStore(true);
    builder.cacheControl(cacheControl);
    builder.header("Pragma", "no-cache");
    return builder.build();
}

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

/**
 * @see org.apache.ws.security.components.crypto.Crypto#getAliasForX509CertThumb(byte[])
 *///from   w  ww  . ja  v a2 s  .c o m
public String getAliasForX509CertThumb(byte[] thumb) throws WSSecurityException {
    Certificate cert;
    MessageDigest sha;
    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e1) {
        throw new WSSecurityException(0, "noSHA1availabe");
    }
    try {
        for (Enumeration e = keystore.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            Certificate[] certs = this.getCertificates(alias);
            if (certs == null || certs.length == 0) {
                return null;
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            sha.reset();
            try {
                sha.update(cert.getEncoded());
            } catch (CertificateEncodingException e1) {
                throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError");
            }
            byte[] data = sha.digest();

            if (Arrays.equals(data, thumb)) {
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore");
    }
    return null;
}

From source file:org.wso2.carbon.apimgt.impl.token.AbstractJWTGenerator.java

/**
 * Helper method to add public certificate to JWT_HEADER to signature verification.
 *
 * @param endUserName//from www . j  a v a2 s .  c om
 * @throws APIManagementException
 */
private String addCertToHeader(String endUserName) throws APIManagementException {

    try {
        //get tenant domain
        String tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
        //get tenantId
        int tenantId = APIUtil.getTenantId(endUserName);
        Certificate publicCert = null;

        if (!(publicCerts.containsKey(tenantId))) {
            //get tenant's key store manager
            APIUtil.loadTenantRegistry(tenantId);
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            KeyStore keyStore = null;
            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                //derive key store name
                String ksName = tenantDomain.trim().replace(".", "-");
                String jksName = ksName + ".jks";
                keyStore = tenantKSM.getKeyStore(jksName);
                publicCert = keyStore.getCertificate(tenantDomain);
            } else {
                keyStore = tenantKSM.getPrimaryKeyStore();
                publicCert = tenantKSM.getDefaultPrimaryCertificate();
            }
            if (publicCert != null) {
                publicCerts.put(tenantId, publicCert);
            }
        } else {
            publicCert = publicCerts.get(tenantId);
        }

        //generate the SHA-1 thumbprint of the certificate
        //TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization
        MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
        byte[] der = publicCert.getEncoded();
        digestValue.update(der);
        byte[] digestInBytes = digestValue.digest();

        String publicCertThumbprint = hexify(digestInBytes);
        String base64EncodedThumbPrint = Base64Utils.encode(publicCertThumbprint.getBytes());
        //String headerWithCertThumb = JWT_HEADER.replaceAll("\\[1\\]", base64EncodedThumbPrint);
        //headerWithCertThumb = headerWithCertThumb.replaceAll("\\[2\\]", signatureAlgorithm);
        //return headerWithCertThumb;

        StringBuilder jwtHeader = new StringBuilder();
        //Sample header
        //{"typ":"JWT", "alg":"SHA256withRSA", "x5t":"NmJmOGUxMzZlYjM2ZDRhNTZlYTA1YzdhZTRiOWE0NWI2M2JmOTc1ZA=="}
        //{"typ":"JWT", "alg":"[2]", "x5t":"[1]"}
        jwtHeader.append("{\"typ\":\"JWT\",");
        jwtHeader.append("\"alg\":\"");
        jwtHeader.append(SHA256_WITH_RSA.equals(signatureAlgorithm)
                ? JWTSignatureAlg.SHA256_WITH_RSA.getJwsCompliantCode()
                : signatureAlgorithm);
        jwtHeader.append("\",");

        jwtHeader.append("\"x5t\":\"");
        jwtHeader.append(base64EncodedThumbPrint);
        jwtHeader.append("\"");

        jwtHeader.append("}");
        return jwtHeader.toString();

    } catch (KeyStoreException e) {
        String error = "Error in obtaining tenant's keystore";
        throw new APIManagementException(error);
    } catch (CertificateEncodingException e) {
        String error = "Error in generating public cert thumbprint";
        throw new APIManagementException(error);
    } catch (NoSuchAlgorithmException e) {
        String error = "Error in generating public cert thumbprint";
        throw new APIManagementException(error);
    } catch (Exception e) {
        String error = "Error in obtaining tenant's keystore";
        throw new APIManagementException(error);
    }
}

From source file:org.wso2.carbon.apimgt.keymgt.token.AbstractJWTGenerator.java

/**
 * Helper method to add public certificate to JWT_HEADER to signature verification.
 *
 * @param endUserName - The end user name
 * @throws APIManagementException//from w  w w .  j a  va2  s. c  o m
 */
private String addCertToHeader(String endUserName) throws APIManagementException {

    try {
        //get tenant domain
        String tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
        //get tenantId
        int tenantId = APIUtil.getTenantId(endUserName);
        Certificate publicCert;

        if (!(publicCerts.containsKey(tenantId))) {
            //get tenant's key store manager
            APIUtil.loadTenantRegistry(tenantId);
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            KeyStore keyStore;
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                //derive key store name
                String ksName = tenantDomain.trim().replace('.', '-');
                String jksName = ksName + ".jks";
                keyStore = tenantKSM.getKeyStore(jksName);
                publicCert = keyStore.getCertificate(tenantDomain);
            } else {
                //keyStore = tenantKSM.getPrimaryKeyStore();
                publicCert = tenantKSM.getDefaultPrimaryCertificate();
            }
            if (publicCert != null) {
                publicCerts.put(tenantId, publicCert);
            }
        } else {
            publicCert = publicCerts.get(tenantId);
        }

        //generate the SHA-1 thumbprint of the certificate
        //TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization
        MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
        if (publicCert != null) {
            byte[] der = publicCert.getEncoded();
            digestValue.update(der);
            byte[] digestInBytes = digestValue.digest();
            Base64 base64 = new Base64(true);
            String base64UrlEncodedThumbPrint = base64.encodeToString(digestInBytes).trim();
            StringBuilder jwtHeader = new StringBuilder();
            //Sample header
            //{"typ":"JWT", "alg":"SHA256withRSA", "x5t":"a_jhNus21KVuoFx65LmkW2O_l10"}
            //{"typ":"JWT", "alg":"[2]", "x5t":"[1]"}
            jwtHeader.append("{\"typ\":\"JWT\",");
            jwtHeader.append("\"alg\":\"");
            jwtHeader.append(getJWSCompliantAlgorithmCode(signatureAlgorithm));
            jwtHeader.append("\",");

            jwtHeader.append("\"x5t\":\"");
            jwtHeader.append(base64UrlEncodedThumbPrint);
            jwtHeader.append('\"');

            jwtHeader.append('}');
            return jwtHeader.toString();
        } else {
            String error = "Error in obtaining tenant's keystore";
            throw new APIManagementException(error);
        }

    } catch (KeyStoreException e) {
        String error = "Error in obtaining tenant's keystore";
        throw new APIManagementException(error, e);
    } catch (CertificateEncodingException e) {
        String error = "Error in generating public cert thumbprint";
        throw new APIManagementException(error, e);
    } catch (NoSuchAlgorithmException e) {
        String error = "Error in generating public cert thumbprint";
        throw new APIManagementException(error, e);
    } catch (Exception e) {
        String error = "Error in obtaining tenant's keystore";
        throw new APIManagementException(error, e);
    }
}

From source file:org.apache.ws.security.components.crypto.CryptoBase.java

/**
 * Lookup a X509 Certificate in the keystore according to a given
 * Thumbprint.//www.java  2  s  .  c  om
 * <p/>
 * The search gets all alias names of the keystore, then reads the certificate chain
 * or certificate for each alias. Then the thumbprint for each user certificate
 * is compared with the thumbprint parameter.
 *
 * @param thumb The SHA1 thumbprint info bytes
 * @return alias name of the certificate that matches the thumbprint
 *         or null if no such certificate was found.
 * @throws org.apache.ws.security.WSSecurityException
 *          if problems during keystore handling or wrong certificate
 */
public String getAliasForX509CertThumb(byte[] thumb) throws WSSecurityException {
    Certificate cert = null;
    MessageDigest sha = null;

    if (keystore == null) {
        return null;
    }

    try {
        sha = MessageDigest.getInstance("SHA-1");
        sha.reset();
    } catch (NoSuchAlgorithmException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noSHA1availabe", null, e);
    }
    try {
        for (Enumeration e = keystore.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            Certificate[] certs = keystore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a  result.
                cert = keystore.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            try {
                sha.update(cert.getEncoded());
            } catch (CertificateEncodingException ex) {
                throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError",
                        null, ex);
            }
            byte[] data = sha.digest();

            if (Arrays.equals(data, thumb)) {
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return null;
}

From source file:org.ejbca.core.model.ca.publisher.GeneralPurposeCustomPublisher.java

/**
 * Writes certificate to temporary file and executes an external command with
 * the full pathname of the temporary file as argument. The temporary file
 * is the encoded form of the certificate e.g. X.509 certificates would be
 * encoded as ASN.1 DER. All parameters but incert are ignored.
 * //  w ww . java2 s . c o m
 * @param incert
 *            The certificate
 * @param username
 *            The username
 * @param type
 *            The certificate type
 * 
 * @see org.ejbca.core.model.ca.publisher.ICustomPublisher#storeCertificate(org.ejbca.core.model.log.Admin,
 *      java.security.cert.Certificate, java.lang.String, java.lang.String,
 *      int, int)
 */
@Override
public boolean storeCertificate(AuthenticationToken admin, Certificate incert, String username, String password,
        String userDN, String cafp, int status, int type, long revocationDate, int revocationReason, String tag,
        int certificateProfileId, long lastUpdate, ExtendedInformation extendedinformation)
        throws PublisherException {
    if (log.isTraceEnabled()) {
        log.trace(">storeCertificate, Storing Certificate for user: " + username);
    }

    if (status == CertificateConstants.CERT_REVOKED) {
        // Call separate script for revocation
        revokeCertificate(admin, incert, revocationReason);
    } else if (status == CertificateConstants.CERT_ACTIVE) {
        // Don't publish non-active certificates
        // Make sure that an external command was specified
        if (certExternalCommandFileName == null) {
            String msg = intres.getLocalizedMessage("publisher.errormissingproperty",
                    certExternalCommandPropertyName);
            log.error(msg);
            throw new PublisherException(msg);
        }
        // Run internal method to create tempfile and run the command
        List<String> arguments = new ArrayList<>();
        arguments.add(String.valueOf(type));
        try {
            arguments.add(CertTools.getSubjectDN(incert));
            arguments.add(CertTools.getIssuerDN(incert));
            arguments.add(CertTools.getSerialNumberAsString(incert));
            runWithTempFile(certExternalCommandFileName, incert.getEncoded(), certFailOnErrorCode,
                    certFailOnStandardError, arguments);
        } catch (CertificateEncodingException e) {
            String msg = intres.getLocalizedMessage("publisher.errorcertconversion");
            log.error(msg);
            throw new PublisherException(msg);
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<storeCertificate");
    }
    return true;
}