Example usage for java.security KeyFactory generatePrivate

List of usage examples for java.security KeyFactory generatePrivate

Introduction

In this page you can find the example usage for java.security KeyFactory generatePrivate.

Prototype

public final PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a private key object from the provided key specification (key material).

Usage

From source file:com.gamesalutes.utils.EncryptUtils.java

/**
 * Reads a PKCS8 formatted private key from file.
 * //from   w  ww. j  av  a2  s  .c o  m
 * @param in the <code>InputStream</code> containing the key
 * @param alg the key algorithm
 * @return the read key
 * @throws Exception if error occurs reading the key
 */
public static PrivateKey readPKCS8(InputStream in, String alg) throws Exception {
    try {
        if (alg == null)
            throw new NullPointerException("alg");
        //alg = alg.toUpperCase();
        //if(!alg.equals("DSA") || !alg.equals("RSA"))
        //   throw new IllegalArgumentException("Illegal key alg=" + alg);
        byte[] encodedKey = ByteUtils.readBytes(in);
        KeyFactory kf = KeyFactory.getInstance(alg);
        try {
            return kf.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
        } catch (Exception e) {
            // maybe key was in PEM so convert to binary
            encodedKey = EncryptUtils.fromPemtoBinary(encodedKey);
            return kf.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
        }
    } finally {
        MiscUtils.closeStream(in);
    }
}

From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java

/**
 * Load an encrypted PKCS #8 private key from the specified stream. The
 * encoding of the private key may be PEM or DER.
 *
 * @param is//from  www .  j a va  2 s. com
 *            Stream load the encrypted private key from
 * @param password
 *            Password to decrypt
 * @return The private key
 * @throws PrivateKeyUnencryptedException
 *             If private key is unencrypted
 * @throws PrivateKeyPbeNotSupportedException
 *             If private key PBE algorithm is not supported
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static PrivateKey loadEncrypted(InputStream is, Password password) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);

    // Check pkcs #8 is not unencrypted
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));

    if (encType == null) {
        // Not a valid PKCS #8 private key
        throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
    }

    if (encType == UNENCRYPTED) {
        throw new PrivateKeyUnencryptedException(res.getString("Pkcs8IsUnencrypted.exception.message"));
    }

    byte[] encPvk = null;
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));

    if (pemInfo != null) {
        // It is - get DER from PEM
        encPvk = pemInfo.getContent();
    }

    /*
     * If we haven't got the encrypted bytes via PEM then just use
     * stream contents directly (assume it is DER encoded)
     */
    if (encPvk == null) {
        // Read in encrypted private key bytes
        encPvk = streamContents;
    }

    try {
        // Create encrypted private key information from bytes
        EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(encPvk);

        // Get wrapping algorithm
        String encAlg = epki.getAlgName();

        // Check algorithm is supported
        if (!checkSupportedForDecrypt(encAlg)) {
            throw new PrivateKeyPbeNotSupportedException(encAlg, MessageFormat
                    .format(res.getString("PrivateKeyWrappingAlgUnsupported.exception.message"), encAlg));
        }

        // Create algorithm parameters and decryption key
        AlgorithmParameters encAlgParams = epki.getAlgParameters();
        PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(encAlg);
        SecretKey pbeKey = keyFact.generateSecret(pbeKeySpec);

        // Create cipher to create
        Cipher cipher = Cipher.getInstance(encAlg);

        // Do decryption
        cipher.init(Cipher.DECRYPT_MODE, pbeKey, encAlgParams);
        PKCS8EncodedKeySpec privateKeySpec = epki.getKeySpec(cipher);

        // Get encoding of private key
        byte[] pvkBytes = privateKeySpec.getEncoded();

        // Determine private key algorithm from key bytes
        String privateKeyAlgorithm = getPrivateKeyAlgorithm(pvkBytes);

        // Use Key Factory to create private key from encoding
        KeyFactory keyFactory = KeyFactory.getInstance(privateKeyAlgorithm);
        PrivateKey pvk = keyFactory.generatePrivate(privateKeySpec);

        return pvk;
    } catch (GeneralSecurityException ex) {
        throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
    }
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Decrypt string with RSA algorithm, ECB mode, OAEPWithSHA-256AndMGF1 padding
 * Asymmetric encryption, with private and public key
 *
 * @param string           string to decrypt
 * @param privateKeyString private key// w  ww .j  a va2 s .  c om
 * @return decrypted string
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String decryptStringAsymmetric(String string, String privateKeyString)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, InvalidKeySpecException {

    Cipher cipher = Cipher.getInstance(RSA_CIPHER);

    byte[] privateKeyBytes = decodeStringToBase64Bytes(privateKeyString);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PrivateKey privateKey = kf.generatePrivate(keySpec);

    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] bytes = decodeStringToBase64Bytes(string);
    byte[] encodedBytes = cipher.doFinal(bytes);

    return decodeBase64BytesToString(encodedBytes);
}

From source file:com.netscape.cms.servlet.test.DRMTest.java

/**
 * Verify the generated asymmetric key pair.
 *
 * @param keyAlgorithm - Algorithm used to generate keys.
 * @param privateKey - binary data of the private key.
 * @param publicKey - binary data of he public key.
 * @return//from  w ww . ja  v a 2s .  c o m
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IOException
 */
public static boolean isKeyPairValid(String keyAlgorithm, byte[] privateKey, byte[] publicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException,
        IOException {
    String algorithm = keyAlgorithm.toUpperCase();
    String signingAlgorithm = "SHA1with" + algorithm;
    KeyFactory factory = KeyFactory.getInstance(algorithm);
    PrivateKey priKey = factory.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
    PublicKey pubKey = factory.generatePublic(new X509EncodedKeySpec(publicKey));
    Signature sig = Signature.getInstance(signingAlgorithm);
    sig.initSign(priKey);
    String s = "Data to test asymmetric keys.";
    sig.update(s.getBytes());

    // Sign the data with the private key.
    byte[] realSig = sig.sign();

    Signature sig2 = Signature.getInstance(signingAlgorithm);
    sig2.initVerify(pubKey);

    sig2.update(s.getBytes());
    // Verify the signature with the public key.
    return sig2.verify(realSig);
}

From source file:com.orange.oidc.secproxy_service.KryptoUtils.java

public static RSAPrivateKey privKeyFromJwk(String jwkp) {
    RSAPrivateKey privKey = null;

    try {/* w  w w  .j  a  v a2s .c  o m*/
        JSONObject jk = new JSONObject(jwkp).getJSONArray("keys").getJSONObject(0);

        BigInteger n = new BigInteger(1, decodeB64(jk.getString("n")));
        BigInteger d = new BigInteger(1, decodeB64(jk.getString("d")));
        // BigInteger e = new BigInteger(1, decodeB64(jk.getString("e")));

        // Log.d("privKeyFromJwk","n "+n);
        // Log.d("privKeyFromJwk","d "+d);
        // Log.d("privKeyFromJwk","e "+e);

        RSAPrivateKeySpec privRsaSpec = new RSAPrivateKeySpec(n, d);
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "SC");
        privKey = (RSAPrivateKey) keyfact.generatePrivate(privRsaSpec);
        // Log.d("privKeyFromJwk","priv key length "+privRsaSpec.getModulus().toByteArray().length);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return privKey;
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * x509/*from   w ww  . ja v  a 2  s.c  om*/
 * 
 * @param f
 * @param algom
 *            ? getSupportedAlgorithmName (AlgorithmType.KeyFactory)
 * @param isPublic
 *            true?false??
 * @return
 */
public static Key loadX509Key(File f, String algom, boolean isPublic) {
    try {
        byte[] keyData = IOUtils.toByteArray(f);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyData);
        KeyFactory keyFactory = KeyFactory.getInstance(algom);
        Key result = (isPublic) ? keyFactory.generatePublic(keySpec) : keyFactory.generatePrivate(keySpec);
        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * PKCS8/*from  w  w  w. j  a v a2 s  .c om*/
 * 
 * @param f
 * @param algom
 *            
 * @param isPublic
 *            true?false??
 * @return
 */
public static Key loadPKCS8Key(File f, String algom, boolean isPublic) {
    try {
        byte[] keyData = IOUtils.toByteArray(f);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyData);
        KeyFactory keyFactory = KeyFactory.getInstance(algom);
        Key result = (isPublic) ? keyFactory.generatePublic(keySpec) : keyFactory.generatePrivate(keySpec);
        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

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

public static String decrypt(String message, String encodedKey) throws SecurityException {
    try {//from   w w  w. j av  a2  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:org.xdi.oxauth.model.util.JwtUtil.java

public static byte[] getSignatureRS256(byte[] signingInput, RSAPrivateKey rsaPrivateKey)
        throws SignatureException, InvalidKeyException, NoSuchProviderException, InvalidKeySpecException,
        NoSuchAlgorithmException {
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
            rsaPrivateKey.getPrivateExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec);

    Signature signature = Signature.getInstance("SHA256withRSA", "BC");
    signature.initSign(privateKey);/*from ww  w . ja va 2 s .c om*/
    signature.update(signingInput);

    return signature.sign();
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static byte[] getSignatureRS384(byte[] signingInput, RSAPrivateKey rsaPrivateKey)
        throws SignatureException, InvalidKeyException, NoSuchProviderException, InvalidKeySpecException,
        NoSuchAlgorithmException {
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
            rsaPrivateKey.getPrivateExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec);

    Signature signature = Signature.getInstance("SHA384withRSA", "BC");
    signature.initSign(privateKey);/*from  www .j  a  v a  2s .co  m*/
    signature.update(signingInput);

    return signature.sign();
}