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:com.turo.pushy.apns.auth.ApnsVerificationKey.java

/**
 * Loads a verification key from the given input stream.
 *
 * @param inputStream the input stream from which to load the key
 * @param teamId the ten-character, Apple-issued identifier for the team to which the key belongs
 * @param keyId the ten-character, Apple-issued identitifier for the key itself
 *
 * @return an APNs verification key with the given key ID and associated with the given team
 *
 * @throws IOException if a key could not be loaded from the given file for any reason
 * @throws NoSuchAlgorithmException if the JVM does not support elliptic curve keys
 * @throws InvalidKeyException if the loaded key is invalid for any reason
 *//*from   w ww .ja v a  2 s  . c o  m*/
public static ApnsVerificationKey loadFromInputStream(final InputStream inputStream, final String teamId,
        final String keyId) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
    final ECPublicKey verificationKey;
    {
        final String base64EncodedPublicKey;
        {
            final StringBuilder publicKeyBuilder = new StringBuilder();

            final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            boolean haveReadHeader = false;
            boolean haveReadFooter = false;

            for (String line; (line = reader.readLine()) != null;) {
                if (!haveReadHeader) {
                    if (line.contains("BEGIN PUBLIC KEY")) {
                        haveReadHeader = true;
                    }
                } else {
                    if (line.contains("END PUBLIC KEY")) {
                        haveReadFooter = true;
                        break;
                    } else {
                        publicKeyBuilder.append(line);
                    }
                }
            }

            if (!(haveReadHeader && haveReadFooter)) {
                throw new IOException("Could not find public key header/footer");
            }

            base64EncodedPublicKey = publicKeyBuilder.toString();
        }

        final byte[] keyBytes = Base64.decodeBase64(base64EncodedPublicKey);

        final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        final KeyFactory keyFactory = KeyFactory.getInstance("EC");

        try {
            verificationKey = (ECPublicKey) keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    }

    return new ApnsVerificationKey(keyId, teamId, verificationKey);
}

From source file:com.cablevision.util.sso.UtilSSO.java

/**
 * Creates a PublicKey from the specified public key file and algorithm.
 * Returns null if failure to generate PublicKey.
 * /* ww  w  .jav a2s .  co m*/
 * @param publicKeyFilepath location of public key file
 * @param algorithm algorithm of specified key file
 * @return PublicKey object representing contents of specified public key
 *         file, null if error in generating key or invalid file specified
 */
public static PublicKey getPublicKey(String publicKeyFilepath, String algorithm) throws SamlException {
    try {
        InputStream pubKey = null;

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        pubKey = cl.getResourceAsStream(publicKeyFilepath);

        byte[] bytes = IOUtils.toByteArray(pubKey);

        pubKey.close();

        System.out.println("Private bytes: " + Arrays.toString(bytes));

        pubKey.close();
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance(algorithm);
        return factory.generatePublic(pubSpec);
    } catch (FileNotFoundException e) {
        throw new SamlException("ERROR: Public key file not found - " + publicKeyFilepath);
    } catch (IOException e) {
        throw new SamlException("ERROR: Invalid public key file - " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new SamlException("ERROR: Invalid public key algorithm - " + e.getMessage());
    } catch (InvalidKeySpecException e) {
        throw new SamlException("ERROR: Invalid public key spec - " + e.getMessage());
    }
}

From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java

private void init(String args[]) {

    FileInputStream file_inputstream;
    try {/*from   w w  w  . j a v a 2 s. co m*/
        String pwd = args[ARG_KEYSTOREPASSWORD];
        String certNameInKeystore = args[ARG_CERTNAMEINKEYSTORE];
        file_inputstream = new FileInputStream(args[ARG_KEYSTOREPATH]);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, pwd.toCharArray());
        System.out.println("Keystore size " + keyStore.size());
        Enumeration aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            System.out.println(aliases.nextElement());
        }
        Key key = keyStore.getKey(certNameInKeystore, pwd.toCharArray());
        getPrintStream().println("Key information " + key.getAlgorithm() + " " + key.getFormat());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        innerSignKey = keyFactory.generatePrivate(keySpec);
        innerCertificate = keyStore.getCertificate(certNameInKeystore);
    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }

    try {
        KeyPair outerSignKeys = KeyTools.genKeys("1024", "RSA");
        outerSignKey = outerSignKeys.getPrivate();
        X509Certificate signCert = CertTools.genSelfCert("CN=cmpTest,C=SE", 5000, null,
                outerSignKeys.getPrivate(), outerSignKeys.getPublic(),
                PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), true, "BC");

        writeCertificate(signCert, "/opt/racerts", "cmpTest.pem");

        /*
        ArrayList<Certificate> certCollection = new ArrayList<Certificate>();
        certCollection.add(signCert);
        byte[] pemRaCert = CertTools.getPEMFromCerts(certCollection);
                
        FileOutputStream out = new FileOutputStream(new File("/opt/racerts/cmpStressTest.pem"));
        out.write(pemRaCert);
        out.close();
        */
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (NoSuchProviderException e1) {
        e1.printStackTrace();
    } catch (InvalidAlgorithmParameterException e1) {
        e1.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
        //} catch (FileNotFoundException e) {
        //   e.printStackTrace();
        //} catch (IOException e) {
        //   e.printStackTrace();
        //} catch (CertificateException e) {
        //   e.printStackTrace();
    }

}

From source file:eu.dety.burp.joseph.utilities.Converter.java

/**
 * Build RSA {@link PublicKey} from RSA JWK JSON object
 * /*from   w ww.j  a v  a2 s. co m*/
 * @param input
 *            RSA JSON Web Key {@link JSONObject}
 * @return {@link PublicKey} or null
 */
private static PublicKey buildRsaPublicKeyByJwk(JSONObject input) {
    try {
        BigInteger modulus = new BigInteger(Base64.decodeBase64(input.get("n").toString()));
        BigInteger publicExponent = new BigInteger(Base64.decodeBase64(input.get("e").toString()));

        loggerInstance.log(Converter.class, "RSA PublicKey values: N: " + modulus + " E: " + publicExponent,
                Logger.LogLevel.DEBUG);
        return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    } catch (Exception e) {
        return null;
    }
}

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * Reads a private key form a url// w  w  w.  j a  v a2s. c  o  m
 *
 * @param privateKeyUrl the url containing the private key
 * @return the read private key
 *
 * @throws IOException if any.
 * @throws GeneralSecurityException
 *                             if any.
 */
@Nullable
public static RSAPrivateKey readPrivateKey(@Nullable URL privateKeyUrl)
        throws IOException, GeneralSecurityException {
    //If a null url is given - just return null
    if (privateKeyUrl == null) {
        return null;
    }

    //We have an url --> return it
    DataInputStream in = new DataInputStream(privateKeyUrl.openStream());
    try {
        byte[] keyBytes = IOUtils.toByteArray(in);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);

        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(keyBytes);
        return (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
    } finally {
        in.close();
    }
}

From source file:com.znsx.util.licence.LicenceUtil.java

/**
 * ???//  ww w  .j  av a 2  s . com
 * 
 * @param data
 *            ??
 * @param publicKey
 *            2
 * @param signature
 *            base64????
 * @return
 * @throws Exception
 * @author huangbuji
 *         <p />
 *         Create at 2014-2-12 ?5:37:18
 */
public static boolean verifyBinKey(String data, byte[] publicKey, String signature) throws Exception {
    Base64 base64 = new Base64();
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    PublicKey pub = KeyFactory.getInstance("DSA").generatePublic(keySpec);
    // ?
    Signature sign = Signature.getInstance("DSA");
    sign.initVerify(pub);
    sign.update(data.getBytes("utf8"));
    // return sign.verify(decoder.decodeBuffer(signature));
    return sign.verify(base64.decode(signature.getBytes("utf8")));
}

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Main method to initialise the private key from the database
 * @throws Exception//w w w .  j a  va 2s .co m
 */
private void initialisePrivateKey() throws Exception {

    if (encodedPrivateKey == null)
        throw new Exception("An encoded Base64 private key has not been specified.");

    try {
        //Read key files back and decode them from BASE64
        byte[] privateKeyBytes = Base64.decodeBase64(encodedPrivateKey);

        // Convert back to public and private key objects
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        privateKey = keyFactory.generatePrivate(privateKeySpec);

    } catch (InvalidKeySpecException e) {
        throw new Exception("Invalid key specifications. Not a valid key entry." + e.getCause());
    } catch (NoSuchAlgorithmException e) {
        throw new Exception("There is no such algorithm. Please check the JDK ver." + e.getCause());
    }
}

From source file:SecureConnection.java

public byte[] getPublicKey(byte[] otherPubKeyBytes) throws Exception {
    KeyFactory keyFac = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(otherPubKeyBytes);
    PublicKey otherPubKey = keyFac.generatePublic(x509KeySpec);
    DHParameterSpec dhParamSpec = ((DHPublicKey) otherPubKey).getParams();
    return this.getPublicKeyStep2(dhParamSpec);
}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Retrieves a public key stored in a local file
 * <p>/* w  w  w  .  ja  v a 2  s  . c  o  m*/
 * 
 * @param pubPath path to the public key on the local filesystem
 * @return the key encapsulated in a regular JCE container
 * @throws KeyException the key could not be retrieved or is malformed
 */
public static PublicKey getPublicKey(String pubPath) throws KeyException {
    byte[] bytes;
    File f = new File(pubPath);
    FileInputStream fin;

    String algo = "", tmp = "";

    // recover public key bytes
    try {
        fin = new FileInputStream(f);
        DataInputStream in = new DataInputStream(fin);
        int read, tot = 0;
        while ((read = in.read()) != '\n') {
            algo += (char) read;
            tot++;
        }
        tot++;
        while ((read = in.read()) != '\n') {
            tmp += (char) read;
            tot++;
        }
        tot++;

        bytes = new byte[(int) f.length() - tot];
        in.readFully(bytes);
        in.close();
    } catch (Exception e) {
        throw new KeyException("Could not retrieve public key from " + pubPath, e);
    }

    // reconstruct public key
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(bytes);
    PublicKey pubKey;
    KeyFactory keyFactory;

    try {
        keyFactory = KeyFactory.getInstance(algo);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyException("Cannot initialize key factory", e);
    }

    try {
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new KeyException("Cannot re-generate public key", e);
    }

    return pubKey;
}

From source file:org.aon.esolutions.appconfig.client.util.RSAEncryptUtil.java

/**
 * Generates Public Key from BASE64 encoded string
 * @param key BASE64 encoded string which represents the key
 * @return The PublicKey/*www.  ja  v  a2  s  .  c  o m*/
 * @throws java.lang.Exception
 */
public static PublicKey getPublicKeyFromString(String key) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decodeBASE64(key));
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    return publicKey;
}