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:io.fabric8.utils.cxf.WebClients.java

public static KeyStore createKeyStore(String clientCertData, File clientCertFile, String clientKeyData,
        File clientKeyFile, String clientKeyAlgo, char[] clientKeyPassword) throws Exception {
    try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

        InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
        PEMReader reader = new PEMReader(keyInputStream);
        RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec();
        KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);/*  w w  w.j a  v a2s.c  om*/

        String alias = cert.getSubjectX500Principal().getName();
        keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert });

        return keyStore;
    }
}

From source file:com.turo.pushy.apns.auth.ApnsSigningKey.java

/**
 * Loads a signing 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 signing 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  w w  .  j av  a2 s. c  om
public static ApnsSigningKey loadFromInputStream(final InputStream inputStream, final String teamId,
        final String keyId) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
    final ECPrivateKey signingKey;
    {
        final String base64EncodedPrivateKey;
        {
            final StringBuilder privateKeyBuilder = 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 PRIVATE KEY")) {
                        haveReadHeader = true;
                    }
                } else {
                    if (line.contains("END PRIVATE KEY")) {
                        haveReadFooter = true;
                        break;
                    } else {
                        privateKeyBuilder.append(line);
                    }
                }
            }

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

            base64EncodedPrivateKey = privateKeyBuilder.toString();
        }

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

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

        try {
            signingKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    }

    return new ApnsSigningKey(keyId, teamId, signingKey);
}

From source file:com.adobe.acs.commons.adobeio.service.impl.IntegrationServiceImpl.java

private PrivateKey getPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buildPkcs8Key(jwtServiceConfig.privateKey()));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(keySpec);
}

From source file:net.oauth.jsontoken.JsonTokenTestBase.java

@Override
protected void setUp() throws Exception {
    final Verifier hmacVerifier = new HmacSHA256Verifier(SYMMETRIC_KEY);

    VerifierProvider hmacLocator = new VerifierProvider() {
        @Override/*from w  w  w  .  j av a2 s.c om*/
        public List<Verifier> findVerifier(String signerId, String keyId) {
            return Lists.newArrayList(hmacVerifier);
        }
    };

    VerifierProvider rsaLocator = new DefaultPublicKeyLocator(new IdentityServerDescriptorProvider(),
            new ServerInfoResolver() {
                @Override
                public ServerInfo resolve(URI uri) {
                    return JsonServerInfo.getDocument(SERVER_INFO_DOCUMENT);
                }
            });

    locators = new VerifierProviders();
    locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator);
    locators.setVerifierProvider(SignatureAlgorithm.RS256, rsaLocator);

    EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decodeBase64(PRIVATE_KEY));
    KeyFactory fac = KeyFactory.getInstance("RSA");
    privateKey = (RSAPrivateKey) fac.generatePrivate(spec);

    //final Verifier hmacVerifierFromRuby = new HmacSHA256Verifier("R9bPJ_QRlcgK_hDLgu1Klg".getBytes());
    final Verifier hmacVerifierFromRuby = new HmacSHA256Verifier("secret".getBytes());
    VerifierProvider hmacLocatorFromRuby = new VerifierProvider() {
        @Override
        public List<Verifier> findVerifier(String signerId, String keyId) {
            return Lists.newArrayList(hmacVerifierFromRuby);
        }
    };
    locatorsFromRuby = new VerifierProviders();
    locatorsFromRuby.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocatorFromRuby);
}

From source file:de.alpharogroup.crypto.key.reader.PrivateKeyReader.java

/**
 * Read private key.//from   w w  w.  j a v a2 s . co m
 *
 * @param privateKeyBytes
 *            the private key bytes
 * @param provider
 *            the provider
 * @param algorithm
 *            the algorithm for the {@link KeyFactory}
 * @return the private key
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchProviderException
 *             is thrown if the specified provider is not registered in the security provider
 *             list.
 */
public static PrivateKey readPrivateKey(final byte[] privateKeyBytes, final String provider,
        final String algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    final KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    final PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
}

From source file:com.vmware.o11n.plugin.crypto.model.CryptoUtil.java

/**
 * Generate a RSA Private Key from a KeySpec
 *
 * @param keySpec//from  w w  w. ja va2 s.  com
 * @return RSA Private Key
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
private static PrivateKey getPrivateKey(KeySpec keySpec)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory fac = KeyFactory.getInstance(KEYFACTORY_ALGORITHM);
    return fac.generatePrivate(keySpec);
}

From source file:com.forsrc.utils.MyRsa2Utils.java

/**
 * Gets private key.//from w w  w .j  av a 2 s . c  o m
 *
 * @param key the key
 * @return the private key
 * @throws RsaException the rsa exception
 */
public static PrivateKey getPrivateKey(String key) throws RsaException {
    byte[] keyBytes;
    try {
        keyBytes = (new Base64()).decode(key);
    } catch (Exception e) {
        throw new RsaException(e);
    }
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance(RsaKey.ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new RsaException(e);
    }
    PrivateKey privateKey = null;
    try {
        privateKey = keyFactory.generatePrivate(keySpec);
    } catch (InvalidKeySpecException e) {
        throw new RsaException(e);
    }
    return privateKey;
}

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

/**
 * Generates Private Key from BASE64 encoded string
 * @param key BASE64 encoded string which represents the key
 * @return The PrivateKey//  www.j a v  a2 s . c o  m
 * @throws java.lang.Exception
 */
public static PrivateKey getPrivateKeyFromString(String key) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decodeBASE64(key));
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return privateKey;
}

From source file:com.oneis.common.utils.SSLCertificates.java

private static PrivateKey readPEMPrivateKey(String filename)
        throws java.io.IOException, java.security.GeneralSecurityException {
    ByteArrayInputStream bIn = readPEM(filename);
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    if (!(seq.getObjectAt(1) instanceof DERInteger)) {
        throw new RuntimeException("Can't read RSA private key from " + filename
                + " - if file starts '-----BEGIN PRIVATE KEY-----' then it needs converting to RSA format with 'openssl rsa -in server-in.key -out server.key'.");
    }/*from  www . jav a  2  s .c  om*/
    DERInteger mod = (DERInteger) seq.getObjectAt(1);
    DERInteger pubExp = (DERInteger) seq.getObjectAt(2);
    DERInteger privExp = (DERInteger) seq.getObjectAt(3);
    DERInteger p1 = (DERInteger) seq.getObjectAt(4);
    DERInteger p2 = (DERInteger) seq.getObjectAt(5);
    DERInteger exp1 = (DERInteger) seq.getObjectAt(6);
    DERInteger exp2 = (DERInteger) seq.getObjectAt(7);
    DERInteger crtCoef = (DERInteger) seq.getObjectAt(8);

    RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(mod.getValue(), pubExp.getValue(),
            privExp.getValue(), p1.getValue(), p2.getValue(), exp1.getValue(), exp2.getValue(),
            crtCoef.getValue());

    KeyFactory factory = KeyFactory.getInstance("RSA");
    return factory.generatePrivate(privSpec);
}

From source file:org.iavante.sling.commons.services.impl.EncryptionServiceImpl.java

public String encryptMessage(String message, String key, String encoding) throws Exception {
    String urlDecodedKey;/*from w  w  w.j a va2  s.c  o  m*/
    byte[] encryptedMessage;
    urlDecodedKey = java.net.URLDecoder.decode(key, encoding);
    // Generate the public key from a String
    PublicKey pk = (PublicKey) KeyFactory.getInstance("RSA").generatePublic(
            new X509EncodedKeySpec(Base64.decodeBase64(urlDecodedKey.getBytes(defaultEncoding))));
    // Get an instance of the Cipher for RSA encryption/decryption
    Cipher c = Cipher.getInstance("RSA");
    // Initiate the Cipher, telling it that it is going to Encrypt, giving
    // it the public key
    c.init(Cipher.ENCRYPT_MODE, pk);
    // c.init(Cipher.ENCRYPT_MODE, extractInfo(key));
    encryptedMessage = c.doFinal(message.getBytes(defaultEncoding));
    return java.net.URLEncoder.encode(new String(Base64.encodeBase64(encryptedMessage)), encoding);
}