Convert String to PrivateKey

C

Below code works to convert string to PrivateKey


public static class DecryptionUtil {
    private static final String ASYMMETRIC_ALGO =
            "RSA/ECB/PKCS1Padding";

    public static byte[] decryptUsingPrivateKey(PrivateKey privateKey, byte[] data)
            throws IOException, GeneralSecurityException {
        Cipher pkCipher = Cipher.getInstance(ASYMMETRIC_ALGO);
        pkCipher.init(Cipher.DECRYPT_MODE, privateKey);
        return pkCipher.doFinal(data);
    }

    public static byte[] decryptUsingSymmetricKey(byte[] symmetricKey, byte[]
            data) throws InvalidCipherTextException {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new
                AESEngine(), new PKCS7Padding());
        cipher.init(false, new KeyParameter(symmetricKey));
        int outputSize = cipher.getOutputSize(data.length);
        byte[] tempOP = new byte[outputSize];
        int processLen = cipher.processBytes(data, 0, data.length, tempOP, 0);
        int outputLen = cipher.doFinal(tempOP, processLen);
        byte[] result = new byte[processLen + outputLen];
        System.arraycopy(tempOP, 0, result, 0, result.length);
        return result;
    }
}

public static PrivateKey getPrivateKey(String privateString) {

    PrivateKey privateKey = null;

    try {
       // String privateString = getString(key, context);
        if(privateString!=null){
            byte[] binCpk = Base64.decode(privateString,Base64.DEFAULT);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA","BC");
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binCpk);
            privateKey = keyFactory.generatePrivate(privateKeySpec);

        }
    }
    catch(Exception e){
        String r="";
    }
    return privateKey;
}

About the author

Ankita Deshmukh
By Ankita Deshmukh

Category