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, Provider provider) throws NoSuchAlgorithmException 

Source Link

Document

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

Usage

From source file:com.launchkey.sdk.crypto.JCECrypto.java

/**
 * Get an RSA private key utilizing the provided provider and PEM formatted string
 * @param provider Provider to generate the key
 * @param pem PEM formatted key string/*from   w  ww .j ava  2  s  .  c o  m*/
 * @return
 */
public static RSAPrivateKey getRSAPrivateKeyFromPEM(Provider provider, String pem) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", provider);
        return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(getKeyBytesFromPEM(pem)));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Algorithm SHA256withRSA is not available", e);
    } catch (InvalidKeySpecException e) {
        throw new IllegalArgumentException("Invalid PEM provided", e);
    }
}

From source file:com.cloudbees.tftwoway.Client.java

private static PrivateKey loadRSAKey(String path) throws Exception {
    try (InputStream fis = new FileInputStream(path)) {
        try (PemReader pemReader = new PemReader(new InputStreamReader(fis))) {
            byte[] pemBytes = pemReader.readPemObject().getContent();

            KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
            KeySpec spec = new PKCS8EncodedKeySpec(pemBytes);

            return keyFactory.generatePrivate(spec);
        }//from w  w  w .ja v  a2s  .c om
    }
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static String decrypt(String message, String encodedKey) throws SecurityException {
    try {// w  w w. j  a v a  2  s .com
        if (StringUtils.isBlank(encodedKey)) {
            throw new SecurityException(
                    "Activation key was not found. Please make sure your instance is correctly configured.");
        }

        // decode key
        byte[] binaryKey = hexToByteArray(encodedKey);

        // create RSA public key cipher
        Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
        try {
            // create private key
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PublicKey pk = kf.generatePublic(publicKeySpec);
            pkCipher.init(Cipher.DECRYPT_MODE, pk);

        } catch (InvalidKeySpecException e) {
            // decrypting with private key?
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PrivateKey pk = kf.generatePrivate(privateKeySpec);
            pkCipher.init(Cipher.DECRYPT_MODE, pk);
        }

        // decrypt
        String[] chunks = StringUtils.split(message, ";");
        if (chunks == null) {
            throw new SecurityException(
                    "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.");
        }
        StringBuilder clearText = new StringBuilder();
        for (String chunk : chunks) {
            byte[] byteChunk = hexToByteArray(chunk);
            clearText.append(new String(pkCipher.doFinal(byteChunk), "UTF-8"));
        }
        return clearText.toString();
    } catch (NumberFormatException e) {
        throw new SecurityException(
                "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.",
                e);
    } catch (IOException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchPaddingException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (InvalidKeySpecException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (InvalidKeyException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchProviderException e) {
        throw new SecurityException(
                "Failed to find encryption provider. Please use Java version with cryptography support.", e);
    } catch (IllegalBlockSizeException e) {
        throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.",
                e);
    } catch (BadPaddingException e) {
        throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.",
                e);
    }

}

From source file:com.mycompany.bankinterface.crypto.Signer.java

public boolean isVerified(String clearText, String signature, String signerPublicKey) throws SignerException {

    boolean isVerified = false;

    byte[] signerPublicKeyBytes = Base64.decodeBase64(signerPublicKey);
    byte[] signatureAsBytes = Base64.decodeBase64(signature);

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(signerPublicKeyBytes);
    KeyFactory keyFactory;/*from   ww  w  . ja  v a  2s .  com*/

    try {
        keyFactory = KeyFactory.getInstance(PUBLIC_KEY_ALGORITHM, PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SignerException("Failed to create key factory", ex);
    }

    PublicKey pubKey;

    try {
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException ex) {
        throw new SignerException("Failed to create public key", ex);
    }

    Signature dsa;

    try {
        dsa = Signature.getInstance(SIGNER_ALGORITHM, PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SignerException("Could not get signing instance", ex);
    }

    try {
        dsa.initVerify(pubKey);
        dsa.update(clearText.getBytes());
        isVerified = dsa.verify(signatureAsBytes);

    } catch (InvalidKeyException | SignatureException ex) {
        throw new SignerException("Could not verify data", ex);
    }

    return isVerified;
}

From source file:com.launchkey.sdk.crypto.JCECrypto.java

/**
 * Get an RSA public key utilizing the provided provider and PEM formatted string
 * @param provider Provider to generate the key
 * @param pem PEM formatted key string// w ww.j  a v a2 s.  c  o m
 * @return
 */
public static RSAPublicKey getRSAPublicKeyFromPEM(Provider provider, String pem) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", provider);
        return (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(getKeyBytesFromPEM(pem)));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Algorithm SHA256withRSA is not available", e);
    } catch (InvalidKeySpecException e) {
        throw new IllegalArgumentException("Invalid PEM provided", e);
    }
}

From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java

public static PublicKey getPubKey(byte[] bytes)
        throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
    KeyFactory kf = KeyFactory.getInstance("ECDSA", "SC");
    return kf.generatePublic(new X509EncodedKeySpec(bytes));
}

From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java

public static PrivateKey getPrivKey(byte[] bytes)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    KeyFactory kf = KeyFactory.getInstance("ECDSA", "SC");
    return kf.generatePrivate(new PKCS8EncodedKeySpec(bytes));
}

From source file:org.jboss.aerogear.cordova.crypto.CryptoPlugin.java

private java.security.KeyPair parseKeyPairFromJson(byte[] encodedPublicKey, byte[] encodedPrivateKey) {
    try {//from   ww  w. j  a v a2 s  .  c  o m
        KeyFactory fact = KeyFactory.getInstance("ECDH", AeroGearCrypto.PROVIDER);
        PublicKey publicKey2 = fact.generatePublic(new X509EncodedKeySpec(encodedPublicKey));
        java.security.PrivateKey privateKey2 = fact.generatePrivate(new PKCS8EncodedKeySpec(encodedPrivateKey));
        return new java.security.KeyPair(publicKey2, privateKey2);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("could not reconstruct key pair from json!", e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("could not reconstruct key pair from json!", e);
    } catch (NoSuchProviderException e) {
        throw new RuntimeException("could not reconstruct key pair from json!", e);
    }
}

From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java

/**
 * Decode based on X, Y 32 byte integers
 * @param pubKey//from   w  ww . j  a v a  2 s  . c o m
 * @param curveName - Example secp256r1
 * @return
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public static PublicKey getPubKeyFromCurve(byte[] pubKey, String curveName)
        throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {

    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName);
    KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
    ECNamedCurveSpec params = new ECNamedCurveSpec(curveName, spec.getCurve(), spec.getG(), spec.getN());
    ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey);
    ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);
    ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec);
    return pk;
}

From source file:edu.vt.middleware.crypt.CryptProvider.java

/**
 * <p>This finds a <code>KeyFactory</code> using the known providers and the
 * supplied algorithm parameter.</p>
 *
 * @param  algorithm  <code>String</code> name
 *
 * @return  <code>KeyFactory</code>
 *
 * @throws  CryptException  if the algorithm is not available from any
 * provider or if the provider is not available in the environment
 *///from  www. ja va  2s  .  c  om
public static KeyFactory getKeyFactory(final String algorithm) throws CryptException {
    final Log logger = LogFactory.getLog(CryptProvider.class);
    KeyFactory kf = null;
    for (int i = 0; i < providers.length; i++) {
        try {
            kf = KeyFactory.getInstance(algorithm, providers[i]);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm + " in " + providers[i]);
            }
        } catch (NoSuchProviderException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find provider " + providers[i]);
            }
        } finally {
            if (kf != null) {
                break;
            }
        }
    }
    if (kf == null) {
        try {
            kf = KeyFactory.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm);
            }
            throw new CryptException(e.getMessage());
        }
    }
    return kf;
}