简体   繁体   中英

How to do decryption of a file in Java/Android which is encrypted using RSACertificate.der and RSAPrivatekey.p12

I am working on Android application for Encryption and decryption using RSA algorithm. My intention is to decry-pt a file which is encrypted by server using RSACertificate.der and RSAPrivatekey.p12 files.

Now I have a Example.encriptedfile, RSACertificat.der and RSAPrivatekey.p12 files I would like to decrypt the above example.encrypted file using above keys in JAVA

The implementation for getting Privatekey And Decryption code using Cipher is

The file is example.encrypted file.

    byte[] descryptedData = null;
    try {
        byte[] data = new byte[(int) file.length()];
        new FileInputStream(file).read(data)

        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(con.getAssets().open("rsaPrivate.p12"), "password".toCharArray());
        pk = (PrivateKey)keystore.getKey("1", "password".toCharArray());

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, pk );
        descryptedData = cipher.doFinal(data);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return new String(descryptedData);

The exception getting for the fallowing code is

java.security.InvalidKeyException: unknown key type passed to RSA
at com.android.org.bouncycastle.jcajce.provider.asymmetric.rsa.CipherSpi.engineInit(CipherSpi.java:277)
at com.android.org.bouncycastle.jcajce.provider.asymmetric.rsa.CipherSpi.engineInit(CipherSpi.java:381)
at javax.crypto.Cipher.init(Cipher.java:519)
at javax.crypto.Cipher.init(Cipher.java:479)

So can any one provide the suggestions and solutions to implement this

Thanks in advance.

But same

If it's encrypted with the private key it isn't encrypted at all, as anyone who can get the public key can decrypt it, which could be anybody.

If the intention was really to encrypt it, it should have been encrypted with the public key.

Possibly however the intention was to sign it, in which case what you have to do is verify it against the public key. For which you need the public key, which is in the certificate. So you load the certificate into a Certificate, using the java.security.cert API and then use a java.security.Signature object to verify the signature with, using the public key obtained from the Certificate.

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