Example usage for java.security.cert CertificateFactory getInstance

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

Introduction

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

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

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

/**
 * ./* w  w w . j  a v  a2  s.  c  o  m*/
 * 
 * @param originalText String 
 * @param signedText String 
 * @param pubKeyFile String 
 * @return boolean 
 */
public static boolean verify(String originalText, String signedText, 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);
        dsa.update(originalText.getBytes());
        return dsa.verify(HexUtils.fromHexString(signedText));
    } catch (Exception ex) {
        logger.error("errors appeared while trying to verify a signature", ex);
        return false;
    }
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Get a certificate object from given file.
 * /*from  w  ww  . j a  va2 s  .c  o  m*/
 * @param cert
 *            the file name.
 * @return a certificate object
 * @throws Exception
 */
public static X509Certificate getAbsolutePath(String cert) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(cert);
    X509Certificate c = (X509Certificate) cf.generateCertificate(in);
    return c;
}

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

/**
 * /*ww  w  . j  a  v a 2s .c  o  m*/
 * <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:com.screenslicer.common.LenientHttpsConfig.java

private LenientHttpsConfig() {
    AsyncHttpClientConfig configTmp = null;
    SSLContext sslContextTmp = null;
    try {// ww w  .  j a v a  2 s  . c  o  m
        AsyncHttpClient client = new AsyncHttpClient();
        configTmp = client.getConfig();
        IOUtils.closeQuietly(client);
        client = null;

        X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(CommonUtil.class.getResourceAsStream("screenslicer.internal.cert"));
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
        KeyManagerFactory keyManager = KeyManagerFactory.getInstance("SunX509");
        keyManager.init(keyStore, null);
        TrustManagerFactory trustManager = TrustManagerFactory.getInstance("X509");
        trustManager.init(keyStore);
        sslContextTmp = SSLContext.getInstance("TLS");
        sslContextTmp.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
    } catch (Throwable t) {
    }
    config = configTmp;
    sslContext = sslContextTmp;
}

From source file:org.apache.xml.security.keys.storage.implementations.CertsInFilesystemDirectoryResolver.java

/**
 * Method readCertsFromHarddrive//from  w w  w.  j  a va2  s  . c o  m
 *
 * @throws StorageResolverException
 */
private void readCertsFromHarddrive() throws StorageResolverException {

    File certDir = new File(this.merlinsCertificatesDir);
    List<String> al = new ArrayList<String>();
    String[] names = certDir.list();

    for (int i = 0; i < names.length; i++) {
        String currentFileName = names[i];

        if (currentFileName.endsWith(".crt")) {
            al.add(names[i]);
        }
    }

    CertificateFactory cf = null;

    try {
        cf = CertificateFactory.getInstance("X.509");
    } catch (CertificateException ex) {
        throw new StorageResolverException("empty", ex);
    }

    if (cf == null) {
        throw new StorageResolverException("empty");
    }

    for (int i = 0; i < al.size(); i++) {
        String filename = certDir.getAbsolutePath() + File.separator + (String) al.get(i);
        File file = new File(filename);
        boolean added = false;
        String dn = null;

        try {
            FileInputStream fis = new FileInputStream(file);
            X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);

            fis.close();

            //add to ArrayList
            cert.checkValidity();
            this.certs.add(cert);

            dn = cert.getSubjectDN().getName();
            added = true;
        } catch (FileNotFoundException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (IOException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (CertificateNotYetValidException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (CertificateExpiredException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (CertificateException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        }

        if (added && log.isDebugEnabled()) {
            log.debug("Added certificate: " + dn);
        }
    }
}

From source file:com.googlecode.dex2jar.tools.ApkSign.java

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();//from  w w  w  .  j  a v  a2s  . c o  m
        return;
    }

    File apkIn = new File(remainingArgs[0]);
    if (!apkIn.exists()) {
        System.err.println(apkIn + " is not exists");
        usage();
        return;
    }

    if (output == null) {
        if (apkIn.isDirectory()) {
            output = new File(apkIn.getName() + "-signed.apk");
        } else {
            output = new File(FilenameUtils.getBaseName(apkIn.getName()) + "-signed.apk");
        }
    }

    if (output.exists() && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        usage();
        return;
    }
    File realJar;
    if (apkIn.isDirectory()) {
        realJar = File.createTempFile("d2j", ".jar");
        realJar.deleteOnExit();
        System.out.println("zipping " + apkIn + " -> " + realJar);
        OutHandler out = FileOut.create(realJar, true);
        try {
            new FileWalker().withStreamHandler(new OutAdapter(out)).walk(apkIn);
        } finally {
            IOUtils.closeQuietly(out);
        }
    } else {
        realJar = apkIn;
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) certificateFactory
            .generateCertificate(ApkSign.class.getResourceAsStream("ApkSign.cer"));
    KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = rSAKeyFactory.generatePrivate(
            new PKCS8EncodedKeySpec(IOUtils.toByteArray(ApkSign.class.getResourceAsStream("ApkSign.private"))));

    Class<?> clz;
    try {
        clz = Class.forName("com.android.signapk.SignApk");
    } catch (ClassNotFoundException cnfe) {
        System.err.println("please run d2j-apk-sign in a sun compatible JRE (contains sun.security.*)");
        return;
    }
    Method m = clz.getMethod("sign", X509Certificate.class, PrivateKey.class, boolean.class, File.class,
            File.class);
    m.setAccessible(true);

    System.out.println("sign " + realJar + " -> " + output);
    m.invoke(null, cert, privateKey, this.signWhole, realJar, output);
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);// Make an empty store

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
    BufferedInputStream bis = new BufferedInputStream(fis);
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        // System.out.println(cert.getPublicKey().toString());
        trustStore.setCertificateEntry("jetty" + bis.available(), cert);
    }/*from ww  w .ja v a  2 s .  c o  m*/

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                return true;
            }
            return false;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslFactory);

    return urlConnection.getInputStream();
}

From source file:mobac.mapsources.loader.MapPackManager.java

public MapPackManager(File mapPackDir) throws CertificateException, IOException {
    this.mapPackDir = mapPackDir;
    requiredMapPackVersion = Integer.parseInt(System.getProperty("mobac.mappackversion"));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certs = cf
            .generateCertificates(Utilities.loadResourceAsStream("cert/MapPack.cer"));
    mapPackCert = (X509Certificate) certs.iterator().next();
}

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

private X509Certificate loadCertificateFromPEM(String pemString) {
    CertificateFactory certFactory;
    try {/*  w  w  w .  j  av a 2 s .c o  m*/
        certFactory = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream inputStream = new ByteArrayInputStream(pemString.getBytes("US-ASCII"));

        return (X509Certificate) certFactory.generateCertificate(inputStream);
    } catch (CertificateException e) {
        e.printStackTrace();
        return null;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.candlepin.util.X509CRLEntryStreamTest.java

@Test
public void testIterateOverSerials() throws Exception {
    InputStream referenceStream = new FileInputStream(derFile);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRL referenceCrl = (X509CRL) cf.generateCRL(referenceStream);

    Set<BigInteger> referenceSerials = new HashSet<BigInteger>();

    for (X509CRLEntry entry : referenceCrl.getRevokedCertificates()) {
        referenceSerials.add(entry.getSerialNumber());
    }/*from  www  .  ja v a2s  .  com*/

    X509CRLEntryStream stream = new X509CRLEntryStream(derFile);
    try {
        Set<BigInteger> streamedSerials = new HashSet<BigInteger>();
        while (stream.hasNext()) {
            streamedSerials.add(stream.next().getSerialNumber());
        }

        assertEquals(referenceSerials, streamedSerials);
    } finally {
        referenceStream.close();
        stream.close();
    }
}