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

/**
 * Method to read private key from file.
 *
 * @param inputStream/*from w w  w. ja  va2  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: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);
    }//w  w  w .java 2 s .  c o  m
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decodedPrivateKey);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey key = kf.generatePrivate(spec);
    this.signer = new JWTSigner(key);
}

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

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

    try {/*from w  w  w .j  a  v  a2 s .com*/
        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:org.waveprotocol.wave.crypto.WaveSignerFactory.java

private PrivateKey getPrivateKey(InputStream privateKeyStream) throws SignatureException {
    try {/*  w w w  .  j a  v  a  2  s  . com*/
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(readBase64Bytes(privateKeyStream));
        KeyFactory keyFac = KeyFactory.getInstance("RSA");
        return keyFac.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (InvalidKeySpecException e) {
        throw new SignatureException(e);
    } catch (IOException e) {
        throw new SignatureException(e);
    }
}

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 {//from w  ww.  j av a2s .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:com.googlecode.dex2jar.tools.ApkSign.java

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();/*from   ww  w.j  a  va2 s  . co  m*/
        return;
    }

    File apkIn = new File(remainingArgs[0]);
    if (!apkIn.exists()) {
        System.err.println(apkIn + " is not exists");
        usage();
        return;
    }

    if (output == null) {
        if (apkIn.isDirectory()) {
            output = new File(apkIn.getName() + "-signed.apk");
        } else {
            output = new File(FilenameUtils.getBaseName(apkIn.getName()) + "-signed.apk");
        }
    }

    if (output.exists() && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        usage();
        return;
    }
    File realJar;
    if (apkIn.isDirectory()) {
        realJar = File.createTempFile("d2j", ".jar");
        realJar.deleteOnExit();
        System.out.println("zipping " + apkIn + " -> " + realJar);
        OutHandler out = FileOut.create(realJar, true);
        try {
            new FileWalker().withStreamHandler(new OutAdapter(out)).walk(apkIn);
        } finally {
            IOUtils.closeQuietly(out);
        }
    } else {
        realJar = apkIn;
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) certificateFactory
            .generateCertificate(ApkSign.class.getResourceAsStream("ApkSign.cer"));
    KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = rSAKeyFactory.generatePrivate(
            new PKCS8EncodedKeySpec(IOUtils.toByteArray(ApkSign.class.getResourceAsStream("ApkSign.private"))));

    Class<?> clz;
    try {
        clz = Class.forName("com.android.signapk.SignApk");
    } catch (ClassNotFoundException cnfe) {
        System.err.println("please run d2j-apk-sign in a sun compatible JRE (contains sun.security.*)");
        return;
    }
    Method m = clz.getMethod("sign", X509Certificate.class, PrivateKey.class, boolean.class, File.class,
            File.class);
    m.setAccessible(true);

    System.out.println("sign " + realJar + " -> " + output);
    m.invoke(null, cert, privateKey, this.signWhole, realJar, output);
}

From source file:org.apache.cordova.crypt.Crypt.java

public String decrypt(String data, String privatekey) throws IllegalBlockSizeException, BadPaddingException,
        InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
    privatekey = privatekey.replaceAll("(-+BEGIN PRIVATE KEY-+\\r?\\n|-+END PRIVATE KEY-+\\r?\\n?)", "");
    byte[] dataCipher = Base64.decode(data, Base64.DEFAULT);

    try {//from  w  w  w.j a va 2 s  . c  om
        byte[] privatekeyRaw = Base64.decode(privatekey, Base64.DEFAULT);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privatekeyRaw);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PrivateKey priv = fact.generatePrivate(keySpec);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, priv);
        byte[] decrypted = cipher.doFinal(dataCipher);
        Log.w("CRYPT", new String(decrypted, "UTF-8"));

        return new String(decrypted, "UTF-8");

    } catch (Exception e) {
        Log.w("CRYPT", e);
        return null;
    }

}

From source file:jenkins.security.RSAConfidentialKey.java

/**
 * Obtains the private key (lazily.)//  w ww.ja v a2  s  .  c  o  m
 * <p>
 * This method is not publicly exposed as per the design principle of {@link ConfidentialKey}.
 * Instead of exposing private key, define methods that use them in specific way, such as
 * {@link RSADigitalSignatureConfidentialKey}.
 *
 * @throws Error
 *      If key cannot be loaded for some reasons, we fail.
 */
protected synchronized RSAPrivateKey getPrivateKey() {
    try {
        if (priv == null) {
            byte[] payload = load();
            if (payload == null) {
                KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
                gen.initialize(2048, new SecureRandom()); // going beyond 2048 requires crypto extension
                KeyPair keys = gen.generateKeyPair();
                priv = (RSAPrivateKey) keys.getPrivate();
                pub = (RSAPublicKey) keys.getPublic();
                store(priv.getEncoded());
            } else {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                priv = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(payload));

                RSAPrivateCrtKey pks = (RSAPrivateCrtKey) priv;
                pub = (RSAPublicKey) keyFactory
                        .generatePublic(new RSAPublicKeySpec(pks.getModulus(), pks.getPublicExponent()));
            }
        }
        return priv;
    } catch (IOException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    } catch (GeneralSecurityException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    }
}

From source file:net.networksaremadeofstring.cyllell.Authentication.java

private String SignHeaders(String dataToSign)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchProviderException {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decode(this.PrivateKey.getBytes(), 0));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, pk);

    byte[] EncryptedStream = new byte[cipher.getOutputSize(dataToSign.length())];
    try {/*from  w w w  .  j a  v a  2s  .com*/
        cipher.doFinal(dataToSign.getBytes(), 0, dataToSign.length(), EncryptedStream, 0);
    } catch (ShortBufferException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Base64.encodeToString(EncryptedStream, Base64.NO_WRAP);
}

From source file:enc_mods.aes.java

/**
* Decrypts an AES key from a file using an RSA private key
*///from   w w  w.  j  ava  2  s  .co m
public void loadKey(File in, File privateKeyFile) {
    try {
        // read private key to be used to decrypt the AES key
        byte[] encodedKey = new byte[(int) privateKeyFile.length()];
        new FileInputStream(privateKeyFile).read(encodedKey);

        // create private key
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pk = kf.generatePrivate(privateKeySpec);

        // read AES key
        cipher.init(Cipher.DECRYPT_MODE, pk);
        key = new byte[AES_Key_Size / 8];
        CipherInputStream is = new CipherInputStream(new FileInputStream(in), cipher);
        is.read(key);
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}