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:Main.java

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

    try {/* w ww  . ja  va  2  s. com*/
        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")));

        RSAPrivateKeySpec privRsaSpec = new RSAPrivateKeySpec(n, d);
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "SC");
        privKey = (RSAPrivateKey) keyfact.generatePrivate(privRsaSpec);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return privKey;
}

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

public static PrivateKey readKey(String keypass, byte[] keyData) throws CAProviderException {
    try {/* w w w  . j  a v a2  s  .  c om*/
        EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(keyData);
        PBEKeySpec keySpec = new PBEKeySpec(keypass.toCharArray());
        SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pkInfo.getAlgName());
        PKCS8EncodedKeySpec encodedKeySpec = pkInfo.getKeySpec(pbeKeyFactory.generateSecret(keySpec));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateCrtKey) keyFactory.generatePrivate(encodedKeySpec);
    } catch (Exception e) {
        throw new CAProviderException("Could not decode private key", e);
    }

}

From source file:net.sf.zekr.common.util.CryptoUtils.java

public static byte[] sign(byte[] text, byte[] prvKeyBytes) throws GeneralSecurityException {
    PKCS8EncodedKeySpec prvSpec = new PKCS8EncodedKeySpec(prvKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PrivateKey prvKey = keyFactory.generatePrivate(prvSpec);
    Signature sig = Signature.getInstance("SHA1withDSA");
    sig.initSign(prvKey);//w ww .java2 s  .c o  m
    sig.update(text);
    return sig.sign();
}

From source file:org.waveprotocol.wave.crypto.CertUtil.java

public static PrivateKey getPrivateKeyFromBytes(byte[] derKey) throws GeneralSecurityException {
    KeyFactory fac = KeyFactory.getInstance("RSA");
    EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(derKey);
    return fac.generatePrivate(privKeySpec);
}

From source file:org.wso2.carbon.identity.test.common.testng.utils.ReadCertStoreSampleUtil.java

public static PrivateKey getSamplePrivateKey() throws Exception {
    // Read in the key into a String
    StringBuilder pkcs8Lines = new StringBuilder();
    BufferedReader rdr = new BufferedReader(new StringReader(PRIVATE_KEY));
    String line;/*from   ww w.  j a v  a2s  .c  om*/
    while ((line = rdr.readLine()) != null) {
        pkcs8Lines.append(line);
    }

    // Remove the "BEGIN" and "END" lines, as well as any whitespace

    String pkcs8Pem = pkcs8Lines.toString();
    pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replaceAll("\\s+", "");

    // Base64 decode the result

    byte[] pkcs8EncodedBytes = Base64.decodeBase64(pkcs8Pem);

    // extract the private key

    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(keySpec);
}

From source file:facturatron.facturacion.PAC.finkok.ClassicKeyLoader.java

/**
 * @param crtInputStream    Flujo de entrada del certificado del cual se obtiene la llave privada
 * @param passwd            Contrasea con la cual se puede obtener la informacin de la llave
 *                          privada/*  w w  w  . ja v a2  s . co m*/
 *
 * @return  Llave privada encapsulada en el objeto {@link PrivateKey}
 *
 * @throws KeyException Lanzada si existe un problema con la lectura de la llave privada. La
 *                      excepcin es lanzada si alguno de estos casos se presenta:
 *                      <ul>
 *                          <li>
 *                              Error de lectura del flujo de entrada del documento.
 *                          </li>
 *                          <li>
 *                              Error en la obtencn de la informacin de la llave privada debido
 *                              a que la contrasea no es correcta.
 *                          </li>
 *                          <li>
 *                              Error en la obtencin de la llave privada debido a que el algoritmo
 *                              de cifrado no es el adecuado para el certificado.
 *                          </li>
 *                      </ul>
 */
public static PrivateKey loadPKCS8PrivateKey(InputStream crtInputStream, String passwd) throws KeyException {
    byte[] decrypted = null;
    PrivateKey privateKey = null;

    try {
        decrypted = (passwd != null) ? getCertBytes(crtInputStream, passwd.toCharArray())
                : getBytes(crtInputStream);
    } catch (IOException ioe) {
        throw new KeyException("Error de E/S al leer la informacin del certificado", ioe.getCause());
    }

    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(decrypted);

    try {
        KeyFactory kf = KeyFactory.getInstance("RSA");
        privateKey = kf.generatePrivate(keysp);
    } catch (GeneralSecurityException gse) {
        throw new KeyException("Error al obtener la informacin del certificado debido a su codificacin",
                gse.getCause());
    }

    return privateKey;
}

From source file:fr.mby.saml2.sp.impl.helper.SecurityHelper.java

/**
 * Build a private Key from DER resource.
 * /* w  w  w .  ja  v  a 2  s  .  c o  m*/
 * @param certificate
 *            the DER resource
 * @param pkSpecClass
 *            the java key specification class
 * @param type
 *            the certificate type
 * @return the java.security.cert.Certificate
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws IllegalArgumentException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws IOException
 */
public static PrivateKey buildPrivateKey(final Resource privateKey, final Class<EncodedKeySpec> pkSpecClass,
        final String type) throws SecurityException, NoSuchMethodException, IllegalArgumentException,
        InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchAlgorithmException,
        InvalidKeySpecException, IOException {
    PrivateKey result = null;

    final Constructor<EncodedKeySpec> keySpecConstructor = pkSpecClass.getConstructor(byte[].class);
    final byte[] keyBytes = SecurityHelper.readBytesFromFilePath(privateKey);
    if (keyBytes != null) {
        final EncodedKeySpec keySpec = keySpecConstructor.newInstance(keyBytes);
        final KeyFactory pkFactory = KeyFactory.getInstance(type);
        result = pkFactory.generatePrivate(keySpec);
    }

    return result;
}

From source file:dk.nversion.jwt.CryptoUtils.java

public static PrivateKey loadPrivateKey(String filename)
        throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
    PrivateKey key = null;/*from w w  w .  j  a  va 2 s  . c  o  m*/
    InputStream is = null;
    try {
        is = new FileInputStream(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        boolean inKey = false;

        String line;
        while ((line = br.readLine()) != null) {
            if (!inKey) {
                if (line.startsWith("-----BEGIN PRIVATE KEY-----")) {
                    inKey = true;
                }
            } else {
                if (line.startsWith("-----END PRIVATE KEY-----")) {
                    break;
                }
                builder.append(line);
            }
        }

        byte[] encoded = Base64.decodeBase64(builder.toString());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        key = kf.generatePrivate(keySpec);

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                // Ignore
            }
        }
    }
    return key;
}

From source file:com.searchbox.utils.DecryptLicense.java

public static byte[] decrypt(byte[] inpBytes) throws Exception {

    byte[] pkbytes = Base64.decodeBase64(privkey);
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkbytes);
    PrivateKey pk = keyFactory.generatePrivate(privateKeySpec);

    Cipher cipher = Cipher.getInstance(xform);
    cipher.init(Cipher.DECRYPT_MODE, pk);
    return cipher.doFinal(inpBytes);
}

From source file:Main.java

static Key base64ToRsaPrivateKey(String b64) {
    if (b64 != null) {
        try {//from  w  w  w  . j  a  v  a2 s.  c  om
            byte[] keyBytes = decodeB64(b64);
            if (keyBytes != null) {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes);
                return keyFactory.generatePrivate(privateKeySpec);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}