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.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>/*from w w w  .  j  a va2  s . c o m*/
 * ?????
 * </p>
 * 
 * @param data ?
 * @param privateKey ?(BASE64?)
 * 
 * @return String
 * @throws Exception Exception
 */
public static String sign(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateK);
    signature.update(data);
    return new String(Base64.encodeBase64(signature.sign()));
}

From source file:org.casbah.provider.SSLeayEncoder.java

public static RSAPrivateCrtKey decodeKey(String pemData, String keypass) throws CAProviderException {

    BufferedReader reader = null;
    try {/*from w w w.j  a  v a  2 s .  c  o  m*/
        String strippedData = PemEncoder.stripArmor(pemData);

        String[] portions = strippedData.split("(?m)^\\n");
        if ((portions == null) || (portions.length != 3)) {
            throw new CAProviderException("Could not extract metainfo from file", null);
        }
        Properties props = new Properties();
        props.load(new StringReader(portions[1]));
        String procType = props.getProperty(PROC_TYPE);
        if ((procType == null) || (!procType.equals(SUPPORTED_PROC_TYPE))) {
            throw new CAProviderException("Missing or invalid Proc-Type declaration", null);
        }
        String dekInfo = props.getProperty(DEK_INFO);
        if (dekInfo == null) {
            throw new CAProviderException("Missing DEK-Info declaration", null);
        }
        String[] infoPortions = dekInfo.split(",");
        if ((infoPortions == null) || (infoPortions.length != 2)
                || (!SSLEAY_ENC_ALGORITHM.equals(infoPortions[0]))) {
            throw new CAProviderException("Invalid DEK-Info declaration", null);
        }

        byte[] decData = decryptKey(portions[2], Hex.decodeHex(infoPortions[1].toCharArray()), keypass);

        PKCS1EncodedKeySpec encodedKeySpec = new PKCS1EncodedKeySpec(decData);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        return (RSAPrivateCrtKey) keyFactory.generatePrivate(encodedKeySpec.toRsaKeySpec());

    } catch (CAProviderException cpe) {
        throw cpe;
    } catch (Exception e) {
        throw new CAProviderException("Could not decode SSLeay key", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.nexmo.client.auth.JWTAuthMethod.java

public JWTAuthMethod(final String applicationId, final byte[] privateKey)
        throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    this.applicationId = applicationId;

    byte[] decodedPrivateKey = privateKey;
    if (privateKey[0] == '-') {
        decodedPrivateKey = decodePrivateKey(privateKey);
    }//from www  .  j a  v  a2s  . co  m
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decodedPrivateKey);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey key = kf.generatePrivate(spec);
    this.signer = new JWTSigner(key);
}

From source file:com.adito.security.pki.dsa.SshDssPublicKey.java

/**
 * Creates a new SshDssPublicKey object.
 *
 * @param key/*w w  w . j  a  v a2 s .c  o  m*/
 *
 * @throws InvalidKeyException
 */
public SshDssPublicKey(byte[] key) throws InvalidKeyException {
    try {
        DSAPublicKeySpec dsaKey;

        // Extract the key information
        ByteArrayReader bar = new ByteArrayReader(key);
        String header = bar.readString();

        if (!header.equals(getAlgorithmName())) {
            throw new InvalidKeyException();
        }

        BigInteger p = bar.readBigInteger();
        BigInteger q = bar.readBigInteger();
        BigInteger g = bar.readBigInteger();
        BigInteger y = bar.readBigInteger();
        dsaKey = new DSAPublicKeySpec(y, p, q, g);

        KeyFactory kf = KeyFactory.getInstance("DSA");

        pubkey = (DSAPublicKey) kf.generatePublic(dsaKey);
    } catch (Exception e) {
        throw new InvalidKeyException();
    }
}

From source file:com.adito.security.pki.dsa.SshDssPrivateKey.java

/**
 * Creates a new SshDssPrivateKey object.
 *
 * @param key//from w  w w  .j  a  v  a2s .  c o m
 *
 * @throws InvalidKeyException
 */
public SshDssPrivateKey(byte[] key) throws InvalidKeyException {
    try {
        DSAPrivateKeySpec dsaKey;

        // Extract the key information
        ByteArrayReader bar = new ByteArrayReader(key);
        String header = bar.readString();

        if (!header.equals(getAlgorithmName())) {
            throw new InvalidKeyException();
        }

        BigInteger p = bar.readBigInteger();
        BigInteger q = bar.readBigInteger();
        BigInteger g = bar.readBigInteger();
        BigInteger x = bar.readBigInteger();
        dsaKey = new DSAPrivateKeySpec(x, p, q, g);

        KeyFactory kf = KeyFactory.getInstance("DSA");
        prvkey = (DSAPrivateKey) kf.generatePrivate(dsaKey);
    } catch (Exception e) {
        throw new InvalidKeyException();
    }
}

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

private PrivateKey loadPrivateKey(final String privateKeyFile) {
    LOGGER.debug("Reading private key file {}.", privateKeyFile);
    final byte[] keyFilePayload = readKeyFile(privateKeyFile);
    final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyFilePayload);
    try {// w  w  w. j av a  2 s.com
        final KeyFactory keyFactory = KeyFactory.getInstance(rsa.getJavaInternalName());
        return keyFactory.generatePrivate(spec);
    } catch (final GeneralSecurityException e) {
        throw new IllegalArgumentException("Failed to create private key from keyfile " + privateKeyFile + ".",
                e);
    }
}

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

/**
 * //www  . ja  v a2s. co  m
 *
 * @param publicKey
 * @return
 * @throws Exception
 */
public static PublicKey getPublicKey(String publicKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(publicKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    return keyFactory.generatePublic(spec);
}

From source file:net.nicholaswilliams.java.licensing.encryption.KeyFileUtilities.java

public static PublicKey readEncryptedPublicKey(byte[] fileContents, char[] passphrase) {
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Encryptor.decryptRaw(fileContents, passphrase));

    try {//from  w  ww  .  ja  v a 2s  .co m
        return KeyFactory.getInstance(KeyFileUtilities.keyAlgorithm).generatePublic(publicKeySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new AlgorithmNotSupportedException(KeyFileUtilities.keyAlgorithm, e);
    } catch (InvalidKeySpecException e) {
        throw new InappropriateKeySpecificationException(e);
    }
}

From source file:com.kuya.cordova.plugin.util.Security.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key.//from   w w w. ja  v a  2  s .c om
 *
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey) {
    Log.d(TAG, "generatePublicKey " + 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) {
        Log.e(TAG, "Invalid key specification.");
        throw new IllegalArgumentException(e);
    } catch (Base64DecoderException e) {
        Log.e(TAG, "Base64 decoding failed.");
        throw new IllegalArgumentException(e);
    }
}

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

public static KeyPair loadRSAKeys() {
    try {//from ww w  .j  ava 2s. com
        km_log.i("Loading RSA key pair from disk.");
        byte[] privEncoded = Files.readAllBytes(privkeyFile.toPath());
        byte[] pubEncoded = Files.readAllBytes(pubkeyFile.toPath());

        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.decodeBase64(pubEncoded));
        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privEncoded));

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PublicKey pubkey = keyFactory.generatePublic(pubSpec);
        PrivateKey privkey = keyFactory.generatePrivate(privSpec);

        return new KeyPair(pubkey, privkey);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        km_log.e("Error while loading keypair!");
        e.printStackTrace();
    }
    return null;
}