简体   繁体   中英

Getting exception while trying to get the private key from certificate

I'm doing RSA encryption and decryption in my application.I have two files placed in assets folder, public_key.cer for encryption and private_key.cer for decryption.Getting the public key from file I'm doing like below.

CertificateFactory certFactory = CertificateFactory.getInstance(X.509, BC);
InputStream is = context.getAssets().open("public_Key.cer");
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is);
publicKey = cert.getPublicKey();

RSA encryption is working fine,while i'm facing problem while trying to get privae key from certificate.Below is the code using to get the private key

InputStream is = context.getAssets().open("private_key.cer");
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(is));
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
PrivateKey privateKey = keyFactory.generatePrivate(privSpec);

I'm getting exception.

    com.android.org.bouncycastle.jcajce.provider.asymmetric.util.ExtendedInvalidKeySpecException: unable to process key spec: java.lang.IllegalArgumentException: unknown object in getInstance: com.android.org.bouncycastle.asn1.DERApplicationSpecific
 at com.android.org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePrivate(KeyFactorySpi.java:105)
 at java.security.KeyFactory.generatePrivate(KeyFactory.java:186)
 at com.teknospire.ndasenda_agent.utils.Conversion.decryptUsingPrivateKey(Conversion.java:111)
 at com.teknospire.ndasenda_agent.utils.Conversion.getDecryptedSkey(Conversion.java:243)
 at com.teknospire.ndasenda_agent.json.JsonCreationAndExtraction.readLoginParams(JsonCreationAndExtraction.java:40)
 at com.mockUp.ndasenda.LoginActivity$LoginRequest.doInBackground(LoginActivity.java:283)
 at com.mockUp.ndasenda.LoginActivity$LoginRequest.doInBackground(LoginActivity.java:1)
 at android.os.AsyncTask$2.call(AsyncTask.java:288)
 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
 at java.lang.Thread.run(Thread.java:848)
 Caused by: java.lang.IllegalArgumentException: unknown object in getInstance: com.android.org.bouncycastle.asn1.DERApplicationSpecific
 at com.android.org.bouncycastle.asn1.ASN1Sequence.getInstance(ASN1Sequence.java:50)
 at com.android.org.bouncycastle.asn1.ASN1Sequence.getInstance(ASN1Sequence.java:33)
 at com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo.getInstance(PrivateKeyInfo.java:45)
 at com.android.org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePrivate(KeyFactorySpi.java:91)
 ... 12 more
 java.lang.NullPointerException
 at org.bouncycastle.crypto.params.KeyParameter.<init>(KeyParameter.java:13)
 at com.teknospire.ndasenda_agent.utils.Conversion.decryptUsingSessionKey(Conversion.java:145)
 at com.teknospire.ndasenda_agent.utils.Conversion.getDecryptionData(Conversion.java:185)
 at com.teknospire.ndasenda_agent.json.JsonCreationAndExtraction.readLoginParams(JsonCreationAndExtraction.java:41)
 at com.mockUp.ndasenda.LoginActivity$LoginRequest.doInBackground(LoginActivity.java:283)
 at com.mockUp.ndasenda.LoginActivity$LoginRequest.doInBackground(LoginActivity.java:1)
 at android.os.AsyncTask$2.call(AsyncTask.java:288)
 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
 at java.lang.Thread.run(Thread.java:848)

Can anyone help me, how to read private key from .cer file.

Thanks in advance.

Check this for the basic implementation

Excerpt from the site

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    byte[] input = new byte[] { (byte) 0xbe, (byte) 0xef };
    Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
        "12345678", 16), new BigInteger("11", 16));
    RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger(
        "12345678", 16), new BigInteger("12345678",
        16));

    RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
    RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec);

    cipher.init(Cipher.ENCRYPT_MODE, pubKey);

    byte[] cipherText = cipher.doFinal(input);
    System.out.println("cipher: " + new String(cipherText));

    cipher.init(Cipher.DECRYPT_MODE, privKey);
    byte[] plainText = cipher.doFinal(cipherText);
    System.out.println("plain : " + new String(plainText));

Code for getting Private key from a file:

    private KeyStore.PrivateKeyEntry getKeyFromFile(String keyStoreFile,
    String Password, Context cntx) {
    KeyStore.PrivateKeyEntry entry = null;
    try {
        AssetManager am = cntx.getAssets();
        char[] keyStorePassword = Password.toCharArray();
        // Load the KeyStore and get the signing key and certificate.
        KeyStore ks = KeyStore.getInstance("PKCS12");

        ks.load(am.open(keyStoreFile), keyStorePassword);
        String alias = ks.aliases().nextElement();

        Entry entry1 = ks.getEntry(alias, new KeyStore.PasswordProtection(
                keyStorePassword));
        entry = (KeyStore.PrivateKeyEntry) entry1;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return entry;
}

You can decrypt your data using following method:

  public byte[] decryptUsingPrivateKey(String encryptedData, Context cntx) {

    byte[] utf8 = null;
    try {
        KeyStore.PrivateKeyEntry privateKey = getKeyFromFile(
                "PrivateKeyFile.pfx", "privatekeypassword", cntx);

        Cipher rsa;
        rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsa.init(Cipher.DECRYPT_MODE, privateKey.getPrivateKey());
        utf8 = rsa.doFinal(Base64.decode(encryptedData));

    } catch (Exception e) {
        System.out.println(e);
    }

    return utf8;
}

Note:

  1. To use this you have to compile the library 'bcprov-jdk15on-152.jar' in your application
  2. Using private key file in android is not a good practice. Hope you are using it in test server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM