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:CA.InternalCA.java

/**
 * Method to read private key from file.
 *
 * @param inputStream//from   w ww .j  a  va  2 s  .  c om
 *
 * @return
 */
private PrivateKey readPrivateKey(InputStream inputStream) {
    try {
        PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(IOUtils.toByteArray(inputStream));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(kspec);
        return privKey;
    } catch (Exception e) {
        LOG.info("Cannot load private key: " + e.getMessage());
        return null;
    }
}

From source file:hh.learnj.test.license.test.rsa.RSATest.java

/**
 * ??//from  w  w  w.j a  v a  2s  .com
 * 
 * @return
 * @throws Exception
 */
static PrivateKey getPrivateKey() throws Exception {
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decodeBase64(privateKey));
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
    return keyFactory.generatePrivate(privateKeySpec);
}

From source file:me.brjannc.plugins.sushi.AuthorizedKeysDecoder.java

public PublicKey decodePublicKey(String keyLine) throws Exception {
    bytes = null;//from   w w w .j av a2  s  .c  om
    pos = 0;

    // look for the Base64 encoded part of the line to decode
    // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
    for (String part : keyLine.split(" ")) {
        if (part.startsWith("AAAA")) {
            bytes = Base64.decodeBase64(part);
            break;
        }
    }
    if (bytes == null) {
        throw new IllegalArgumentException("no Base64 part to decode");
    }

    String type = decodeType();
    if (type.equals("ssh-rsa")) {
        BigInteger e = decodeBigInt();
        BigInteger m = decodeBigInt();
        RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
        return KeyFactory.getInstance("RSA").generatePublic(spec);
    } else if (type.equals("ssh-dss")) {
        BigInteger p = decodeBigInt();
        BigInteger q = decodeBigInt();
        BigInteger g = decodeBigInt();
        BigInteger y = decodeBigInt();
        DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
        return KeyFactory.getInstance("DSA").generatePublic(spec);
    } else {
        throw new IllegalArgumentException("unknown type " + type);
    }
}

From source file:com.dev.cty.utils.googleplay.Security.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key.//www.ja v  a  2  s. co  m
 *
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey) {
    try {
        byte[] decodedKey = Base64.decode(encodedPublicKey);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
        return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        logger.info("Invalid key specification.");
        throw new IllegalArgumentException(e);
    } catch (Base64DecoderException e) {
        logger.info("Base64 decoding failed.");
        throw new IllegalArgumentException(e);
    }
}

From source file:org.echocat.marquardt.example.keyprovisioning.KeyFileReadingKeyPairProvider.java

private PublicKey loadPublicKey(final String publicKeyFileName) {
    LOGGER.debug("Reading public key file {}.", publicKeyFileName);
    final byte[] keyFilePayload = readKeyFile(publicKeyFileName);
    final X509EncodedKeySpec spec = new X509EncodedKeySpec(keyFilePayload);
    try {//from  w w  w.java 2  s. c o  m
        final KeyFactory keyFactory = KeyFactory.getInstance(rsa.getJavaInternalName());
        return keyFactory.generatePublic(spec);
    } catch (final GeneralSecurityException e) {
        throw new IllegalArgumentException(
                "Failed to create public key from keyfile " + publicKeyFileName + ".", e);
    }
}

From source file:my.adam.smo.common.AsymmetricEncryptionBox.java

@PostConstruct
public void init() throws NoSuchAlgorithmException {
    keyGen = KeyPairGenerator.getInstance("RSA");

    try {/*from w ww. jav a  2 s . co  m*/
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decode(this.privKeyS));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        prvKey = keyFactory.generatePrivate(privKeySpec);
    } catch (InvalidKeySpecException e) {
        logger.error("invalid private key", e);
    }

    try {
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decode(this.pubKeyS));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException e) {
        logger.error("invalid public key", e);
    }
}

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

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

    // ?
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // ?
    PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

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

    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}

From source file:com.vexsoftware.votifier.crypto.RSAIO.java

/**
 * Loads an RSA key pair from a directory. The directory must have the files
 * "public.key" and "private.key"./*from   w  ww .  ja v a 2s . c o  m*/
 * 
 * @param directory
 *            The directory to load from
 * @return The key pair
 * @throws Exception
 *             If an error occurs
 */
public static KeyPair load(File directory) throws Exception {
    // Read the public key file.
    File publicKeyFile = new File(directory + "/public.key");
    byte[] encodedPublicKey = FileUtils.readFileToByteArray(publicKeyFile);
    encodedPublicKey = DatatypeConverter.parseBase64Binary(new String(encodedPublicKey));

    // Read the private key file.
    File privateKeyFile = new File(directory + "/private.key");
    byte[] encodedPrivateKey = FileUtils.readFileToByteArray(privateKeyFile);
    encodedPrivateKey = DatatypeConverter.parseBase64Binary(new String(encodedPrivateKey));

    // Instantiate and return the key pair.
    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:hh.learnj.test.license.test.rsacoder.RSACoder.java

/**
 * // w  w w.  j av  a  2s  . co  m
 * 
 * @param data?
 * @param key
 *            
 * @return byte[] ?
 */
public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception {

    // 
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // ?
    // ???
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
    // 
    PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    return cipher.doFinal(data);
}

From source file:org.haox.pki.Pkix.java

public static PrivateKey getPrivateKey(InputStream inputStream, String password)
        throws GeneralSecurityException, IOException {
    if (password == null)
        password = "";
    // If the provided InputStream is encrypted, we need a password to decrypt
    // it. If the InputStream is not encrypted, then the password is ignored
    // (can be null).  The InputStream can be DER (raw ASN.1) or PEM (base64).
    PKCS8Key pkcs8 = new PKCS8Key(inputStream, password.toCharArray());

    // If an unencrypted PKCS8 key was provided, then this actually returns
    // exactly what was originally passed inputStream (with no changes).  If an OpenSSL
    // key was provided, it gets reformatted as PKCS #8 first, and so these
    // bytes will still be PKCS #8, not OpenSSL.
    byte[] decrypted = pkcs8.getDecryptedBytes();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted);

    // A Java PrivateKey object is born.
    PrivateKey pk = null;//from   w w  w  .  ja v a  2s.  com
    if (pkcs8.isDSA()) {
        pk = KeyFactory.getInstance("DSA").generatePrivate(spec);
    } else if (pkcs8.isRSA()) {
        pk = KeyFactory.getInstance("RSA").generatePrivate(spec);
    }

    // For lazier types:
    pk = pkcs8.getPrivateKey();

    return pk;
}