Example usage for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec

List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec

Introduction

In this page you can find the example usage for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec.

Prototype

public PKCS8EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new PKCS8EncodedKeySpec with the given encoded key.

Usage

From source file:com.buzzcoders.security.cryptoutils.asymmetric.AbstractAsymmetricEncryptionModule.java

public void storePrivateKey(String path, PrivateKey privateKey) {
    FileOutputStream fos = null;/*from  w  ww .j  av a 2 s . c om*/
    try {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        fos = new FileOutputStream(path);
        fos.write(pkcs8EncodedKeySpec.getEncoded());
    } catch (FileNotFoundException e) {
        LOG.error("Cannot save the private key to the specified path.", e);
    } catch (IOException e) {
        LOG.error("An I/O error occured while saving the private key", e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:org.sinekartads.utils.X509Utils.java

public static PrivateKey privateKeyFromHex(String privateKeyHex/*, EncryptionAlgorithm encryptionAlgorithm*/ ) {

    byte[] privateKeyEnc = HexUtils.decodeHex(privateKeyHex);

    PrivateKey privateKey;/*from   www  .  j  a  va  2 s .  c  om*/
    try {
        KeyFactory kf = KeyFactory.getInstance("RSA", "SunJSSE");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKeyEnc);
        privateKey = kf.generatePrivate(ks);
    } catch (NoSuchAlgorithmException e) {
        // never thrown, algorithm granted by CipherAlgorithm
        throw new RuntimeException(e);
    } catch (NoSuchProviderException e) {
        // never thrown, using a system security provider
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        // never thrown, the algorithm must be the same for the certificate's public key
        throw new RuntimeException(e);
    }

    return privateKey;
}

From source file:jenkins.security.RSAConfidentialKey.java

/**
 * Obtains the private key (lazily.)/*from   w ww . j a  va  2s  .co  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:mitm.common.security.certificate.GenerateTestCA.java

private PrivateKey decodePrivateKey(String encoded) throws Exception {
    byte[] rawKey = Hex.decodeHex(encoded.toCharArray());

    KeySpec keySpec = new PKCS8EncodedKeySpec(rawKey);

    return keyFactory.generatePrivate(keySpec);
}

From source file:com.googlecode.dex2jar.tools.ApkSign.java

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();//ww  w  . j  a v  a2  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:bftsmart.reconfiguration.util.RSAKeyLoader.java

private PrivateKey getPrivateKeyFromString(String key) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return privateKey;
}

From source file:org.soulwing.credo.service.crypto.bc.BcPKCS8PrivateKeyWrapper.java

/**
 * {@inheritDoc}/*from www.  j a v  a 2 s  .  c  o m*/
 */
@Override
public PrivateKey derive() {
    Validate.notNull(passphrase, "passphrase is required");
    InputDecryptorProvider decryptor = createPrivateKeyDecryptor();
    try {
        PrivateKeyInfo keyInfo = delegate.decryptPrivateKeyInfo(decryptor);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyInfo.getEncoded());
        return keyFactory.generatePrivate(keySpec);
    } catch (PKCSException ex) {
        throw new IncorrectPassphraseException();
    } catch (InvalidKeySpecException ex) {
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.vexsoftware.votifier.util.rsa.RSAIO.java

/**
 * Loads an RSA key pair from a directory. The directory must have the files
 * "public.key" and "private.key"./*from   www . j  ava  2 s . 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");
    FileInputStream in = null;
    byte[] encodedPublicKey;
    try {
        in = new FileInputStream(directory + "/public.key");
        encodedPublicKey = new byte[(int) publicKeyFile.length()];
        in.read(encodedPublicKey);
        encodedPublicKey = DatatypeConverter.parseBase64Binary(new String(encodedPublicKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Read the private key file.
    File privateKeyFile = new File(directory + "/private.key");
    byte[] encodedPrivateKey;
    try {
        in = new FileInputStream(directory + "/private.key");
        encodedPrivateKey = new byte[(int) privateKeyFile.length()];
        in.read(encodedPrivateKey);
        encodedPrivateKey = DatatypeConverter.parseBase64Binary(new String(encodedPrivateKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // 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: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  ww.  j a  v  a  2s .com*/
        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:nextflow.k8s.client.SSLUtils.java

public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream,
        String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase)
        throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException,
        KeyStoreException {/* w  w w.  j  a v a 2  s  .  c  o m*/
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

    byte[] keyBytes = decodePem(keyInputStream);

    PrivateKey privateKey;

    KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo);
    try {
        // First let's try PKCS8
        privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
    } catch (InvalidKeySpecException e) {
        // Otherwise try PKCS1
        RSAPrivateCrtKeySpec keySpec = decodePKCS1(keyBytes);
        privateKey = keyFactory.generatePrivate(keySpec);
    }

    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (keyStoreFile != null && keyStoreFile.length() > 0) {
        keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase);
    } else {
        loadDefaultKeyStoreFile(keyStore, keyStorePassphrase);
    }

    String alias = cert.getSubjectX500Principal().getName();
    keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[] { cert });

    return keyStore;
}