RSA decryption with a public key

25,402

Java has got the Java Cryptography Extension Framework, which is just designed for these things.

BouncyCastle is a Cryptography Provider for this framework. This means, it provides your Java Cryptography Extension with implementations of cryptography algorithms.

You'll find the basic classes for this in the packages java.security and javax.crypto

To decrypt your message with a public key you could try the following:

// Use RSA/NONE/NoPadding as algorithm and BouncyCastle as crypto provider
Cipher asymmetricCipher = Cipher.getInstance("RSA/NONE/NoPadding", "BC");

// asume, that publicKeyBytes contains a byte array representing
// your public key
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);

KeyFactory keyFactory;
keyFactory = KeyFactory.getInstance(publicKeySpec.getFormat());
Key key = keyFactory.generatePublic(publicKeySpec);

// initialize your cipher
asymmetricCipher.init(Cipher.DECRYPT_MODE, key);
// asuming, cipherText is a byte array containing your encrypted message
byte[] plainText = asymmetricCipher.doFinal(cipherText);

Please note, that this example is very basic and lacks several try catch blocks. Also, you should not use an asymmetric cipher without padding as this makes you vulnerable to replay attacks. You may also encounter issues with the key length. In some Java packages, the maximum allowed key length is restricted. This may be solved by using the unlimited strength policy files.

I hope, this helps you in getting started with the Java cryptography.

Share:
25,402
Mike
Author by

Mike

Android Dev

Updated on July 16, 2022

Comments

  • Mike
    Mike almost 2 years

    I've got some decryption problems in my Android project.

    I'm getting a string signed with a private key and I have to verify(decrypt) it with a public key. I'd like to get exactly the same result as if I were using a PHP function - openssl_public_decrypt ( http://php.net/manual/pl/function.openssl-public-decrypt.php )

    I have to do this in my Java project, so I can use Java libs (e.g BouncyCastle, or something else, any recommendations? )

    Any ideas how to solve this?

    Ok, here's my code. I'm getting the public key like this

    PEMReader reader = new PEMReader(new InputStreamReader(ctx
                    .getAssets().open("pubkey.pem")));
            Object obj;
            while ((obj = reader.readObject()) != null) {
                 if (obj instanceof RSAPublicKey) {
                    pubKey = (RSAPublicKey) obj;
                    return pubKey;
                }
            }
    

    And I always get the public key without any problems.

    Cipher c = Cipher.getInstance("RSA/NONE/NoPadding", "SC");
    c.init(Cipher.DECRYPT_MODE, pubKey);
    byte[] result = c.doFinal(data_to_decrypt.getBytes());
    

    And as a result(after converting bytes to string) I get 022c06571c6a263b389fcd93159cb311abb880bddf51b7c916dd1ae...

    where php functions returns sd8dsa348acvcx87|00454|OK|15000|CDE and this is a correct output.

  • Mike
    Mike about 12 years
    Thanks for your answer. I had a similiar solution before, it works but I get as a result sth like this: 022c06571c6a263b389fcd93159cb311abb880bddf51b7c916dd1ae... where php function returns decrypted string, where is a problem with that ?
  • Francis
    Francis about 12 years
    The method returns a byte array. Did you convert the result to a String? Also I just recognize, that i did not assign the result of the doFinal method to a variable... going to edit the answer...
  • Mike
    Mike about 12 years
    I convert the result to String, and the output from my previous comment is a String converted from array of bytes
  • Mike
    Mike about 12 years
    I edit my first post, and add some code, maybe it will be helpful in finding the solution.
  • Jono
    Jono about 11 years
    Hi. what gets translated in byte array for the public key? is it the following example below: ---- BEGIN SSH2 PUBLIC KEY ---- Comment: "rsa-key-20130520" AAAAB3NzaC1yc2EAAAABJQAAAIEAsE8aR2CIWuQgkeOsPhHDuGo+Rokr2cT+‌​KS5L sJFbEkB0R3XYXnOT3DU0CFrmHUX1PpcfTOSdxCIfeSXFHCGGWEXm4qx7ptNp‌​m4vP Scuzmlr/fjuQdb7lBQ0+OEP2LKuRHxt5oEVZvq/EvwENS5T2BiVUSvTwXUS6‌​SKCh ERydjXE= ---- END SSH2 PUBLIC KEY ----
  • arvind.mohan
    arvind.mohan almost 8 years
    @Francis I have a similar use case, where I would decrypt using a public key on an android device. Can you please help me out, how should I proceed? I do not have any prior experience in cryptography.
  • Ege Kuzubasioglu
    Ege Kuzubasioglu over 6 years
    KeyFactory X.509 implemention not found