Example usage for java.security KeyFactory getInstance

List of usage examples for java.security KeyFactory getInstance

Introduction

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

Prototype

public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyFactory object that converts public/private keys of the specified algorithm.

Usage

From source file:net.jmhertlein.core.crypto.Keys.java

/**
 * Loads the Base64 encoded, PKCS8 formatted RSA private key from the file
 *
 * @param file/*from   w  w  w.  ja  v a2  s  .c o m*/
 *
 * @return
 */
public static PrivateKey loadPrivateKey(String file) {
    try {
        PKCS8EncodedKeySpec spec = getPKCS8KeySpec(file);
        if (spec == null)
            return null;
        return KeyFactory.getInstance("RSA").generatePrivate(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:com.cellngine.crypto.RSACipher.java

private KeyFactory getKeyFactory() {
    try {//from  w ww .  ja va 2s.c  o m
        return KeyFactory.getInstance(ALGORITHM);
    } catch (final NoSuchAlgorithmException e) {
        LOG.error("Unable to get key factory instance (" + ALGORITHM + ")", e);
        return null;
    }
}

From source file:com.vexsoftware.votifier.util.rsa.RSAIO.java

/**
 * Loads an RSA key pair from a directory. The directory must have the files
 * "public.key" and "private.key".//www.j  a  va 2 s  .c  o m
 * 
 * @param directory
 *            The directory to load from
 * @return The key pair
 * @throws Exception
 *             If an error occurs
 */
public static KeyPair load(File directory) throws Exception {
    // Read the public key file.
    File publicKeyFile = new File(directory + "/public.key");
    FileInputStream in = null;
    byte[] encodedPublicKey;
    try {
        in = new FileInputStream(directory + "/public.key");
        encodedPublicKey = new byte[(int) publicKeyFile.length()];
        in.read(encodedPublicKey);
        encodedPublicKey = DatatypeConverter.parseBase64Binary(new String(encodedPublicKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Read the private key file.
    File privateKeyFile = new File(directory + "/private.key");
    byte[] encodedPrivateKey;
    try {
        in = new FileInputStream(directory + "/private.key");
        encodedPrivateKey = new byte[(int) privateKeyFile.length()];
        in.read(encodedPrivateKey);
        encodedPrivateKey = DatatypeConverter.parseBase64Binary(new String(encodedPrivateKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Instantiate and return the key pair.
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return new KeyPair(publicKey, privateKey);
}

From source file:com.sammyun.util.RSAUtils.java

/**
 * RSA??/*from  w w  w. j  a  v  a2  s  .c  om*/
 * 
 * @param content ???
 * @param privateKey ?
 * @param input_charset ??
 * @return ??
 */
public static String sign(String content, String privateKey, String input_charset) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Util.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);
        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
        signature.initSign(priKey);
        signature.update(content.getBytes(input_charset));
        byte[] signed = signature.sign();
        return Base64Util.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * //from w  w w .  j a  v  a 2 s  . c  o m
 *
 * @param data
 *            ?
 * @param key
 *            
 * @return byte[] ?
 * @throws Exception
 */
private static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception {

    // ?
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}

From source file:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new DockerCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }//from  w  w w  . jav a 2  s .  c  o  m

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:com.github.aynu.yukar.framework.util.SecurityHelper.java

/**
 * RSA???//from  w w  w  .j av a 2s . c  o  m
 * <dl>
 * <dt>?
 * <dd>RSA?????????????
 * </dl>
 * @param modulus 
 * @param exponent ??
 * @return RSA?
 */
public static RSAPublicKey createPublicKey(final BigInteger modulus, final BigInteger exponent) {
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey) keyFactory.generatePublic(new RSAPublicKeySpec(modulus, exponent));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new StandardRuntimeException(e);
    }
}

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  va2s  .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:bftsmart.reconfiguration.util.RSAKeyLoader.java

private PrivateKey getPrivateKeyFromString(String key) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return privateKey;
}

From source file:com.ddubyat.develop.jhawtcode.util.PropertyUtil.java

private boolean validLicense(String email, String licenseCode) throws Exception {

    Resource res = applicationContext.getResource("classpath:jhc-public.der");
    InputStream is = res.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[4096];
    byte[] pkey;/*w  w w .ja  v a2  s  . co  m*/
    int stream;
    while ((stream = is.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, stream);
    }

    pkey = baos.toByteArray();

    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pkey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey mypk = keyFactory.generatePublic(keySpec);

    Signature instance = Signature.getInstance("SHA1withRSA");
    instance.initVerify(mypk);
    instance.update(email.getBytes());

    //BASE64Decoder decoder = new BASE64Decoder();
    //byte[] decodedBytes = decoder.decodeBuffer(licenseCode);

    return instance.verify(DatatypeConverter.parseBase64Binary(licenseCode));
}