Skip to content Skip to sidebar Skip to footer

Cannot Generate Rsa Private Key On Android

I have a PEM RSA private key and read it from the hard-cord string. It works on Android below 4.3 but does not work on Android 4.4 and 5. In Android 4.4 above, I get the error. 0

Solution 1:

use this code. now i test it and work well.I use it in Android studio

public static PrivateKey stringtoprivatekey(String privateKeyString)
    {

        try {
            if (privateKeyString.contains("-----BEGIN PRIVATE KEY-----") || privateKeyString.contains("-----END PRIVATE KEY-----"))
                privateKeyString = privateKeyString.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "");
            if (privateKeyString.contains("-----BEGIN RSA PRIVATE KEY-----") || privateKeyString.contains("-----END RSA PRIVATE KEY-----"))
                privateKeyString = privateKeyString.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", "");

            privateKeyString = privateKeyString.replaceAll("\\r|\\n", "");
            byte[] privateKeyDER = Base64.decode(privateKeyString, Base64.DEFAULT);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyDER));
            return privateKey;

        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
            return null;
        }
    }

Post a Comment for "Cannot Generate Rsa Private Key On Android"