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:Main.java

public static KeyPair loadKeyPair(Context context, String name)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(context.getFilesDir(), name + "_public.key");
    FileInputStream fis = new FileInputStream(filePublicKey);
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);/*from   w  w w. ja va 2 s. c o m*/
    fis.close();

    // Read Private Key.
    File filePrivateKey = new File(context.getFilesDir(), name + "_private.key");
    fis = new FileInputStream(filePrivateKey);
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);
    fis.close();

    // Generate KeyPair.
    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:dk.nversion.jwt.CryptoUtils.java

public static PrivateKey loadPrivateKey(String filename)
        throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
    PrivateKey key = null;/*from w w  w.  jav a 2 s  . c  o  m*/
    InputStream is = null;
    try {
        is = new FileInputStream(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        boolean inKey = false;

        String line;
        while ((line = br.readLine()) != null) {
            if (!inKey) {
                if (line.startsWith("-----BEGIN PRIVATE KEY-----")) {
                    inKey = true;
                }
            } else {
                if (line.startsWith("-----END PRIVATE KEY-----")) {
                    break;
                }
                builder.append(line);
            }
        }

        byte[] encoded = Base64.decodeBase64(builder.toString());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        key = kf.generatePrivate(keySpec);

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                // Ignore
            }
        }
    }
    return key;
}

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

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

    // ??
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);

    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // ??
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

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

    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}

From source file:com.searchbox.utils.DecryptLicense.java

public static byte[] decrypt(byte[] inpBytes) throws Exception {

    byte[] pkbytes = Base64.decodeBase64(privkey);
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkbytes);
    PrivateKey pk = keyFactory.generatePrivate(privateKeySpec);

    Cipher cipher = Cipher.getInstance(xform);
    cipher.init(Cipher.DECRYPT_MODE, pk);
    return cipher.doFinal(inpBytes);
}

From source file:br.edu.ufcg.lsd.commune.network.signature.Util.java

public static PublicKey decodePublicKey(String pubKeyStr) throws InvalidKeySpecException {
    byte[] binaryArray = decodeStringOnBase64(pubKeyStr);
    KeyFactory keyFactory;//w  ww  .j  a va 2s.  co  m
    try {
        keyFactory = KeyFactory.getInstance(SignatureConstants.KEY_GEN_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        //We're assuming that we are always instantiating a valid algorithm
        throw new CommuneRuntimeException(e);
    }
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryArray);
    return keyFactory.generatePublic(publicKeySpec);
}

From source file:org.hypoport.jwt.common.Toolbox.java

public static RSAPublicKey readRSAPublicKey(FileReader keyReader) throws Exception {
    return (RSAPublicKey) KeyFactory.getInstance("RSA")
            .generatePublic(new X509EncodedKeySpec(readPemFile(keyReader)));
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.SSLUtils.java

public static KeyStore readKeyAndCert(final String pemContent, final String keyPass)
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
        InvalidKeySpecException {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/*w  w w  .j  a  va2  s.  c o m*/

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    final KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    final List<String> lines = readLines(pemContent);

    String currentHeader = null;
    final StringBuilder current = new StringBuilder();
    final Map<String, String> entries = new LinkedHashMap<String, String>();
    for (final String line : lines) {
        if (line == null) {
            continue;
        }

        if (line.startsWith("-----BEGIN")) {
            currentHeader = line.trim();
            current.setLength(0);
        } else if (line.startsWith("-----END")) {
            entries.put(currentHeader, current.toString());
        } else {
            current.append(line.trim());
        }
    }

    final List<Certificate> certs = new ArrayList<Certificate>();
    for (int pass = 0; pass < 2; pass++) {
        for (final Map.Entry<String, String> entry : entries.entrySet()) {
            final String header = entry.getKey();
            final byte[] data = decodeBase64(entry.getValue());

            if (pass > 0 && header.contains("BEGIN PRIVATE KEY")) {
                final KeySpec spec = new PKCS8EncodedKeySpec(data);
                final PrivateKey key = keyFactory.generatePrivate(spec);
                ks.setKeyEntry("key", key, keyPass.toCharArray(), certs.toArray(new Certificate[] {}));
            } else if (pass < 1 && header.contains("BEGIN CERTIFICATE")) {
                final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data));

                ks.setCertificateEntry("certificate", c);
                certs.add(c);
            }
        }
    }

    return ks;
}

From source file:com.github.ibole.infrastructure.security.ECDSA.java

public static void jdkECDSA() {
    try {//  w w  w  .j  a  v  a 2 s  .  c o  m
        // 1.?
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
        keyPairGenerator.initialize(256);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
        ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();

        // 2.??
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());

        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Signature signature = Signature.getInstance("SHA256withECDSA");
        signature.initSign(privateKey);
        signature.update(src.getBytes());
        byte[] res = signature.sign();
        System.out.println("??" + Base64.encodeBase64String(res));

        // 3.???
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
        keyFactory = KeyFactory.getInstance("EC");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        signature = Signature.getInstance("SHA256withECDSA");
        signature.initVerify(publicKey);
        signature.update(src.getBytes());
        boolean bool = signature.verify(res);
        System.out.println("?" + bool);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.jasig.cas.util.PrivateKeyFactoryBean.java

protected Object createInstance() throws Exception {
    final InputStream privKey = this.location.getInputStream();
    try {//from www.java  2s  .  c o m
        final byte[] bytes = new byte[privKey.available()];
        privKey.read(bytes);
        privKey.close();
        final PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance(this.algorithm);
        return factory.generatePrivate(privSpec);
    } finally {
        privKey.close();
    }
}