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:de.pawlidi.openaletheia.utils.CipherUtils.java

/**
 * /*from  w  ww.ja  va 2  s .c  om*/
 * @param data
 * @return
 */
public static RSAPublicKey buildPublicKey(final String key) {
    if (StringUtils.isNotEmpty(key)) {
        try {
            byte[] bytes = Converter.toBytes(key);
            KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes);
            return (RSAPublicKey) keyFactory.generatePublic(pubSpec);
        } catch (Exception e) {
            throw new RuntimeException("Cannot create " + CIPHER_ALGORITHM + " public key from " + key, e);
        }
    }
    return null;
}

From source file:com.sixsq.slipstream.cookie.CryptoUtils.java

static private String savePrivateKey(PrivateKey privateKey) throws GeneralSecurityException {
    KeyFactory fact = KeyFactory.getInstance(keyPairAlgorithm);
    PKCS8EncodedKeySpec spec = fact.getKeySpec(privateKey, PKCS8EncodedKeySpec.class);
    byte[] encoded = spec.getEncoded();
    String privateKeyStr = new Base64().encodeToString(encoded);
    return privateKeyStr;
}

From source file:com.tenduke.example.scribeoauth.JwtLoginServlet.java

/**
 * Initializes this servlet.//  w  w w .j a v  a  2 s . com
 * @param config Servlet configuration.
 * @throws ServletException For errors during init.
 */
@Override
public void init(final ServletConfig config) throws ServletException {
    //
    super.init(config);
    //
    final JSONObject jwtPublicKey = readConfiguration("idp.jwt.publickey.json", config.getServletContext());
    try {
        //
        byte[] publicKeyDecoded = Base64.decodeBase64(jwtPublicKey.getString("publicKey"));
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyDecoded);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        publicKey = keyFactory.generatePublic(keySpec);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException ex) {
        //
        throw new ServletException("No way, basic RSA based key generation failed...", ex);
    }
}

From source file:com.spotify.helios.authentication.crtauth.LdapKeyProvider.java

@Override
public RSAPublicKey getKey(final String username) throws KeyNotFoundException {
    final List<String> result = ldapTemplate.search(query().base(baseSearchPath).where("uid").is(username),
            new AttributesMapper<String>() {
                @Override/*  w ww  . j  a va 2  s.c om*/
                public String mapFromAttributes(final Attributes attributes) throws NamingException {
                    log.debug("got ldap stuff for uid {}", username);
                    return attributes.get("sshPublicKey").toString();
                }
            });

    if (result.isEmpty()) {
        throw new KeyNotFoundException();
    } else if (result.size() == 1) {
        final String r = result.get(0);
        RSAPublicKeySpec publicKeySpec;
        try {
            final String sshPublicKey = r.replace("sshPublicKey: ", "");
            publicKeySpec = TraditionalKeyParser.parsePemPublicKey(sshPublicKey);
            final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
        } catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

    throw new IllegalStateException("Found more than one LDAP user for name: " + username);
}

From source file:enc_mods.aes.java

/**
* Decrypts an AES key from a file using an RSA private key
*///from www.  j a va 2  s.  c  o  m
public void loadKey(File in, File privateKeyFile) {
    try {
        // read private key to be used to decrypt the AES key
        byte[] encodedKey = new byte[(int) privateKeyFile.length()];
        new FileInputStream(privateKeyFile).read(encodedKey);

        // create private key
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pk = kf.generatePrivate(privateKeySpec);

        // read AES key
        cipher.init(Cipher.DECRYPT_MODE, pk);
        key = new byte[AES_Key_Size / 8];
        CipherInputStream is = new CipherInputStream(new FileInputStream(in), cipher);
        is.read(key);
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.sshd.common.util.SecurityUtils.java

public static synchronized KeyFactory getKeyFactory(String algorithm)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    register();/*from  w  w w .j  av a 2s  .c  om*/
    if (getSecurityProvider() == null) {
        return KeyFactory.getInstance(algorithm);
    } else {
        return KeyFactory.getInstance(algorithm, getSecurityProvider());
    }
}

From source file:org.opentravel.schemacompiler.security.PasswordHelper.java

/**
 * Returns an encryption cipher that is based on the public encryption key file located on the
 * application's classpath./*from ww  w  .ja v a2 s .c om*/
 * 
 * @return Cipher
 * @throws GeneralSecurityException
 *             thrown if encryption key is not valid
 * @throws IOException
 *             thrown if the contents of the public key file cannot be loaded
 */
private static Cipher loadEncryptionCipher() throws GeneralSecurityException, IOException {
    BigInteger[] keyComponents = loadKeyFile(PUBLIC_KEYFILE);
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(keyComponents[0], keyComponents[1]);
    KeyFactory factory = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
    PublicKey publicKey = factory.generatePublic(keySpec);
    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);

    cipher.init(Cipher.PUBLIC_KEY, publicKey);
    return cipher;
}

From source file:jenkins.security.RSAConfidentialKey.java

/**
 * Obtains the private key (lazily.)/*from   ww w.  j ava  2 s .c o  m*/
 * <p>
 * This method is not publicly exposed as per the design principle of {@link ConfidentialKey}.
 * Instead of exposing private key, define methods that use them in specific way, such as
 * {@link RSADigitalSignatureConfidentialKey}.
 *
 * @throws Error
 *      If key cannot be loaded for some reasons, we fail.
 */
protected synchronized RSAPrivateKey getPrivateKey() {
    try {
        if (priv == null) {
            byte[] payload = load();
            if (payload == null) {
                KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
                gen.initialize(2048, new SecureRandom()); // going beyond 2048 requires crypto extension
                KeyPair keys = gen.generateKeyPair();
                priv = (RSAPrivateKey) keys.getPrivate();
                pub = (RSAPublicKey) keys.getPublic();
                store(priv.getEncoded());
            } else {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                priv = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(payload));

                RSAPrivateCrtKey pks = (RSAPrivateCrtKey) priv;
                pub = (RSAPublicKey) keyFactory
                        .generatePublic(new RSAPublicKeySpec(pks.getModulus(), pks.getPublicExponent()));
            }
        }
        return priv;
    } catch (IOException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    } catch (GeneralSecurityException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    }
}

From source file:com.shekhargulati.reactivex.rxokhttp.SslCertificates.java

private SslCertificates(final Builder builder) throws SslCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new SslCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }//from  w w w . j a va  2s.  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 (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException
            | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException
            | KeyManagementException e) {
        throw new SslCertificateException(e);
    }
}

From source file:org.javaweb.utils.RSAUtils.java

/**
 * ?/*from w  ww. j a  va2  s  .  co  m*/
 *
 * @param privateKey
 * @return
 * @throws Exception
 */
public static PrivateKey getPrivateKey(String privateKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    return keyFactory.generatePrivate(spec);
}