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:mitm.common.security.KeyEncoderTest.java

private static PrivateKey decodePrivateKey(String encoded) throws DecoderException, InvalidKeySpecException {
    byte[] rawKey = Hex.decodeHex(encoded.toCharArray());

    KeySpec keySpec = new PKCS8EncodedKeySpec(rawKey);

    return keyFactory.generatePrivate(keySpec);
}

From source file:de.alpharogroup.crypto.key.KeyExtensions.java

/**
 * Read private key.//w w  w.j  a v a 2  s . c om
 *
 * @param privateKeyBytes
 *            the private key bytes
 * @param provider
 *            the provider
 * @return the private key
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchProviderException
 *             is thrown if the specified provider is not registered in the security provider
 *             list.
 */
public static PrivateKey readPrivateKey(final byte[] privateKeyBytes, final String provider)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    final KeyFactory keyFactory = KeyFactory.getInstance(KeyPairGeneratorAlgorithm.RSA.getAlgorithm());
    final PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
}

From source file:org.slc.sli.bulk.extract.files.ExtractFileTest.java

private static File decrypt(File file) throws Exception {
    byte[] responseData = FileUtils.readFileToByteArray(file);

    byte[] encodediv = Arrays.copyOfRange(responseData, 0, 256);
    byte[] encodedsecret = Arrays.copyOfRange(responseData, 256, 512);
    byte[] message = Arrays.copyOfRange(responseData, 512, responseData.length);

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

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(PRIVATE_KEY.getBytes()));
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    decrypt.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] iv = decrypt.doFinal(encodediv);
    byte[] secret = decrypt.doFinal(encodedsecret);

    decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec key = new SecretKeySpec(secret, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    decrypt.init(Cipher.DECRYPT_MODE, key, ivSpec);

    byte[] unencryptedMessage = decrypt.doFinal(message);

    File decryptedTar = new File("decrypted-" + FILE_NAME + FILE_EXT);

    FileUtils.writeByteArrayToFile(decryptedTar, unencryptedMessage);

    return decryptedTar;

}

From source file:im.whistle.crypt.Crypt.java

/**
 * Decrypts a message./*from   ww w . jav  a2s  . com*/
 * @param args Arguments: enc, privateKey, sig, publicKey
 * @param callback Callback
 */
public static void decrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        // Get the arguments
        String enc = args.getString(0);
        String key = args.getString(1);
        String sig = null;
        String pub = null;
        if (args.length() == 4) {
            sig = args.getString(2);
            pub = args.getString(3);
        }
        Boolean ver = null;

        // Convert everything into byte arrays
        byte[] encRaw = Base64.decode(enc, Base64.DEFAULT);
        byte[] keyRaw = Base64.decode(stripKey(key), Base64.DEFAULT);

        // Verify signature
        if (sig != null && pub != null) {
            try {
                byte[] sigRaw = Base64.decode(sig, Base64.DEFAULT);
                byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);
                X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
                KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
                Signature s = Signature.getInstance("SHA1withRSA", "BC");
                s.initVerify(kf.generatePublic(publicKeySpec));
                s.update(encRaw);
                ver = s.verify(sigRaw);
            } catch (Exception ex) {
                Log.i("whistle", "Verification failed: " + ex.getMessage());
                ver = false;
            }
        }

        // Split enc into encrypted aes data and remaining enc
        byte[] encSplit = encRaw;
        byte[] aesRaw = new byte[RSA_BYTES];
        System.arraycopy(encSplit, 0, aesRaw, 0, aesRaw.length);
        encRaw = new byte[encSplit.length - RSA_BYTES];
        System.arraycopy(encSplit, RSA_BYTES, encRaw, 0, encRaw.length);

        // Decrypt encrypted aes data using RSAES-OAEP
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        Cipher c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding");
        c.init(Cipher.DECRYPT_MODE, kf.generatePrivate(privateKeySpec));
        aesRaw = c.doFinal(aesRaw);

        // Decrypted enc using AES-CBC
        byte[] aesKey = new byte[AES_BYTES];
        byte[] aesIv = new byte[aesRaw.length - aesKey.length];
        System.arraycopy(aesRaw, 0, aesKey, 0, aesKey.length);
        System.arraycopy(aesRaw, aesKey.length, aesIv, 0, aesIv.length);
        c = Cipher.getInstance("AES/CBC/PKCS7Padding");
        c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));
        byte[] dec = c.doFinal(encRaw);

        JSONArray res = new JSONArray();
        res.put(new String(dec, "utf-8"));
        res.put(ver);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Decrypt error:" + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

/**
 * Read public key from file.// ww  w  .java2s  .  c  o m
 * @param filePath
 * @return
 * @throws IOException
 */
public PrivateKey readPrivateKeyFromFile(String filePath) throws Exception {
    // Read file to a byte array.
    String privateKeyFileName = filePath;
    Path path = Paths.get(privateKeyFileName);
    byte[] privKeyByteArray = Files.readAllBytes(path);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyByteArray);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey myPrivKey = keyFactory.generatePrivate(keySpec);
    return myPrivKey;
}

From source file:com.ibm.dbwkl.helper.CryptionModule.java

/**
 * @return PrivateKey Instance/*from w  w  w  .j a va2  s  .co  m*/
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
private RSAPrivateKey getPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] privateKeyBytes = null;
    RSAPrivateKey privateKey = null;

    privateKeyBytes = getPrivateKeyBytes();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);

    return privateKey;
}

From source file:com.cablevision.util.sso.UtilSSO.java

/**
 * Creates a PrivateKey from the specified public key file and algorithm.
 * Returns null if failure to generate PrivateKey.
 * //ww  w.ja v a 2  s . c o m
 * @param PrivateKeyFilepath location of public key file
 * @param algorithm algorithm of specified key file
 * @return PrivateKey object representing contents of specified private key
 *         file, null if error in generating key or invalid file specified
 */
public static PrivateKey getPrivateKey(String privateKeyFilepath, String algorithm) throws SamlException {
    try {
        InputStream privKey = null;

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        privKey = cl.getResourceAsStream(privateKeyFilepath);

        byte[] bytes = IOUtils.toByteArray(privKey);

        privKey.close();

        System.out.println("Private bytes: " + Arrays.toString(bytes));

        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance(algorithm);
        return factory.generatePrivate(privSpec);
    } catch (FileNotFoundException e) {
        throw new SamlException("ERROR: Private key file not found - " + privateKeyFilepath);
    } catch (IOException e) {
        throw new SamlException("ERROR: Invalid private key file - " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new SamlException("ERROR: Invalid private key algorithm - " + e.getMessage());
    } catch (InvalidKeySpecException e) {
        throw new SamlException("ERROR: Invalid private key spec - " + e.getMessage());
    }
}

From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java

private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);

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

    return (RSAPrivateKey) factory.generatePrivate(spec);
}

From source file:com.clustercontrol.util.KeyCheck.java

/**
 * ?// ww  w  .j  ava2s . c om
 * com.clustercontrol.key.KeyGenerator????????public??
 * @param str
 * @return
 * @throws HinemosUnknown
 */
public static PrivateKey getPrivateKey(String str) throws HinemosUnknown {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(string2Byte(str));
        return keyFactory.generatePrivate(privateKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new HinemosUnknown("getPrivateKey fail " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new HinemosUnknown("getPrivateKey fail " + e.getMessage(), e);
    }
}

From source file:de.tum.in.tumcampus.services.GcmIntentService.java

/**
 * Loads the private key from preferences
 *
 * @return The private key object/*from w  w w  .  j  a  v a2 s.  c o  m*/
 */
private PrivateKey getPrivateKeyFromSharedPrefs() {
    String privateKeyString = Utils.getInternalSettingString(this, Const.PRIVATE_KEY, "");
    byte[] privateKeyBytes = Base64.decode(privateKeyString, Base64.DEFAULT);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        return keyFactory.generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        Utils.log(e);
    }
    return null;
}