Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:io.fabric8.utils.cxf.WebClients.java

public static KeyStore createKeyStore(String clientCertData, File clientCertFile, String clientKeyData,
        File clientKeyFile, String clientKeyAlgo, char[] clientKeyPassword) throws Exception {
    try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

        InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
        PEMReader reader = new PEMReader(keyInputStream);
        RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec();
        KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);//from  ww w . j  ava2  s .c om

        String alias = cert.getSubjectX500Principal().getName();
        keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert });

        return keyStore;
    }
}

From source file:com.icanft.common.startup.ValidateLicense.java

/**
 * License/*from w  w  w  . j ava2s . com*/
 * 
 * @param licenseColl LicenseColl
 * @param path String
 * @return boolean
 */
public static boolean validateLicense(LicenseColl licenseColl, String path) {
    // ??
    boolean payedUser = true;
    List<String> macAddressList = CollectMacAddress.getMacAddress();
    for (LicenseInfo licenseInfo : licenseColl.getLicenseInfoList()) {
        String productName = licenseInfo.getProductName();
        String expirationDate = licenseInfo.getExpiration();
        String signature = licenseInfo.getSignature();
        boolean flag = false;
        String data = new StringBuffer().append(productName).append(expirationDate).toString();
        java.security.cert.CertificateFactory cf;
        try {
            cf = java.security.cert.CertificateFactory.getInstance("X.509");

            java.security.cert.Certificate cert = cf
                    .generateCertificate(new FileInputStream(path + "/WEB-INF/fbrp.cer"));

            // 
            PublicKey pubKey = cert.getPublicKey();
            // ??Signature
            Signature sig = Signature.getInstance("SHA1withDSA");
            sig.initVerify(pubKey);
            sig.update(InternationalizationUtil.getBytes(data));
            // ?License
            boolean verifies = true;
            //                  sig.verify(Base64.decodeBase64(InternationalizationUtil
            //                  .getBytes(signature)));
            if (verifies) {
                Date evalDate = DateTimeUtil.parseDate(expirationDate);
                if (evalDate.before(new Date())) {
                    // ?
                    payedUser = false;
                } else {
                    flag = true;
                    payedUser = true;
                    System.out.println(
                            "" + productName + " License" + expirationDate + "?");
                }
            }
        } catch (Exception e) {
            log.error("", e);
        }

        if (!flag) {
            payedUser = false;
            System.out.println(
                    "" + productName + " License??License?");
        }
    }
    return payedUser;
}

From source file:com.mqm.frame.infrastructure.util.ValidateLicense.java

/**
 * License//  w w w .jav  a  2  s .c  om
 * 
 * @param licenseColl LicenseColl
 * @param path String
 * @return boolean
 */
public static boolean validateLicense(LicenseColl licenseColl, String path) {
    // ??
    boolean payedUser = true;
    List<String> macAddressList = CollectMacAddress.getMacAddress();
    for (LicenseInfo licenseInfo : licenseColl.getLicenseInfoList()) {
        String productName = licenseInfo.getProductName();
        String expirationDate = licenseInfo.getExpiration();
        String signature = licenseInfo.getSignature();
        boolean flag = false;
        String data = new StringBuffer().append(productName).append(expirationDate).toString();
        java.security.cert.CertificateFactory cf;
        try {
            cf = java.security.cert.CertificateFactory.getInstance("X.509");

            java.security.cert.Certificate cert = cf
                    .generateCertificate(new FileInputStream(path + "/WEB-INF/fbrp.cer"));

            // 
            PublicKey pubKey = cert.getPublicKey();
            // ??Signature
            Signature sig = Signature.getInstance("SHA1withDSA");
            sig.initVerify(pubKey);
            sig.update(InternationalizationUtil.getBytes(data));
            // ?License
            boolean verifies = sig.verify(Base64.decode((InternationalizationUtil.getBytes(signature))));
            if (verifies) {
                Date evalDate = DateTimeUtil.parseDate(expirationDate);
                if (evalDate.before(new Date())) {
                    // ?
                    payedUser = false;
                } else {
                    flag = true;
                    payedUser = true;
                    System.out.println(
                            "" + productName + " License" + expirationDate + "?");
                }
            }
        } catch (Exception e) {
            log.error("", e);
        }

        if (!flag) {
            payedUser = false;
            System.out.println(
                    "" + productName + " License??License?");
        }
    }
    return payedUser;
}

From source file:com.qm.frame.infrastructure.util.ValidateLicense.java

/**
 * License//from   www .ja v  a  2  s.  c o m
 * 
 * @param licenseColl LicenseColl
 * @param path String
 * @return boolean
 */
public static boolean validateLicense(LicenseColl licenseColl, String path) {
    // ??
    boolean payedUser = true;
    List<String> macAddressList = CollectMacAddress.getMacAddress();
    for (LicenseInfo licenseInfo : licenseColl.getLicenseInfoList()) {
        String productName = licenseInfo.getProductName();
        String expirationDate = licenseInfo.getExpiration();
        String signature = licenseInfo.getSignature();
        boolean flag = false;
        String data = new StringBuffer().append(productName).append(expirationDate).toString();
        java.security.cert.CertificateFactory cf;
        try {
            cf = java.security.cert.CertificateFactory.getInstance("X.509");

            java.security.cert.Certificate cert = cf
                    .generateCertificate(new FileInputStream(path + "/WEB-INF/qm.cer"));

            // 
            PublicKey pubKey = cert.getPublicKey();
            // ??Signature
            Signature sig = Signature.getInstance("SHA1withDSA");
            sig.initVerify(pubKey);
            sig.update(InternationalizationUtil.getBytes(data));
            // ?License
            boolean verifies = sig.verify(Base64.decode((InternationalizationUtil.getBytes(signature))));
            if (verifies) {
                Date evalDate = DateTimeUtil.parseDate(expirationDate);
                if (evalDate.before(new Date())) {
                    // ?
                    payedUser = false;
                } else {
                    flag = true;
                    payedUser = true;
                    System.out.println(
                            "" + productName + " License" + expirationDate + "?");
                }
            }
        } catch (Exception e) {
            log.error("", e);
        }

        if (!flag) {
            payedUser = false;
            System.out.println(
                    "" + productName + " License??License?");
        }
    }
    return payedUser;
}

From source file:io.hops.hopsworks.util.CertificateHelper.java

private static X509Certificate getX509Cert(File cert) throws IllegalStateException {
    try (InputStream inStream = new FileInputStream(cert)) {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Cert = (X509Certificate) factory.generateCertificate(inStream);
        return x509Cert;
    } catch (CertificateException | IOException ex) {
        LOG.log(Level.SEVERE, "cert ex {0}", ex);
        throw new IllegalStateException("cert ex", ex);
    }//  ww  w  . j  a v  a2  s  . c om
}

From source file:se.leap.bitmaskclient.ConfigHelper.java

/**
 * Adds a new X509 certificate given its input stream and its provider name
 *
 * @param provider    used to store the certificate in the keystore
 * @param inputStream from which X509 certificate must be generated.
 *///from   ww w. ja  v a 2s  .  c  o  m
public static void addTrustedCertificate(String provider, InputStream inputStream) {
    CertificateFactory cf;
    try {
        cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
        keystore_trusted.setCertificateEntry(provider, cert);
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:io.vertx.config.vault.utils.Certificates.java

/**
 * Called by the constructor method prior to configuring and launching the Vault instance.  Uses Bouncy Castle
 * (https://www.bouncycastle.org) to programmatically generate a private key and X509 certificate for use by
 * the Vault server instance in accepting SSL connections.
 *//*w  ww  . j  ava2  s. c om*/
public static void createVaultCertAndKey() throws Exception {
    if (SSL_DIRECTORY.isDirectory() && CERT_PEMFILE.isFile()) {
        try (FileInputStream fis = new FileInputStream(CERT_PEMFILE)) {
            CertificateFactory fact = CertificateFactory.getInstance("X.509");
            vaultCertificate = (X509Certificate) fact.generateCertificate(fis);
        }
        return;
    }

    SSL_DIRECTORY.mkdirs();

    // Generate a certificate and private key for Vault, and write them to disk in PEM format.  Also store the
    // original X509Certificate object in a member variable, so it can later be used by "createClientCertAndKey()".
    final KeyPair keyPair = generateKeyPair();
    vaultCertificate = generateCert(keyPair,
            "C=AU, O=The Legion of the Bouncy Castle, OU=Vault Server Certificate, CN=localhost");
    writeCertToPem(vaultCertificate, CERT_PEMFILE);
    writePrivateKeyToPem(keyPair.getPrivate(), PRIVATE_KEY_PEMFILE);
}

From source file:kr.co.exsoft.eframework.util.LicenseUtil.java

/**
 * //from  ww  w. j  ava 2  s .com
 * <pre>
 * 1.  : ??   APPLICATION
 * 2.  :
 * </pre>
 * @Method Name : decipherLicenseKey
 * @param licenseKey
 * @return String
 * @throws Exception
 */
public static String decipherLicenseKey(String licenseKey) throws Exception {

    String ret = null;

    if (StringUtils.isNotBlank(licenseKey)) {

        // ??   ? public key ?
        URL url = ClassLoader.getSystemResource("kr/co/exsoft/eframework/cert/exsoft.cer");
        FileInputStream certfis = new FileInputStream(new File(url.getFile()));

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate cert = cf.generateCertificate(certfis);

        PublicKey key = cert.getPublicKey();

        // ??  .
        ret = unspell(licenseKey, key);
    }

    return ret;
}

From source file:oracle.custom.ui.utils.ServerUtils.java

public static PublicKey getServerPublicKey(String domainName) throws Exception {
    HttpClient client = getClient(domainName);
    PublicKey key = null;/*www  . j a  v a  2 s . c  o m*/
    String url = getIDCSBaseURL(domainName) + "/admin/v1/SigningCert/jwk";
    URI uri = new URI(url);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Authorization", "Bearer " + AccessTokenUtils.getAccessToken(domainName));
    HttpResponse response = client.execute(host, httpGet);
    try {
        HttpEntity entity2 = response.getEntity();
        String res = EntityUtils.toString(entity2);
        EntityUtils.consume(entity2);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("result is " + res);
        SigningKeys signingKey = mapper.readValue(res, SigningKeys.class);

        String base64Cert = signingKey.getKeys().get(0).getX5c().get(0);
        byte encodedCert[] = Base64.getDecoder().decode(base64Cert);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(encodedCert);

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);
        key = cert.getPublicKey();
    } finally {
        if (response instanceof CloseableHttpResponse) {
            ((CloseableHttpResponse) response).close();
        }
    }
    return key;
}

From source file:com.linkage.crm.csb.sign.CtSignature.java

/**
 * .//from  w  w w . ja  va 2 s . co  m
 * 
 * @param pubKeyFile String 
 * @return Signature 
 */
public static Signature createSignatureForVerify(String pubKeyFile) {
    try {
        CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
        FileInputStream fin = new FileInputStream(pubKeyFile);
        X509Certificate certificate = (X509Certificate) certificatefactory.generateCertificate(fin);
        PublicKey pub = certificate.getPublicKey();
        Signature dsa = Signature.getInstance("SHA1withDSA");
        dsa.initVerify(pub);
        return dsa;
    } catch (Exception ex) {
        logger.error("errors appeared while trying to verify a signature", ex);
        return null;
    }
}