Search code examples
androidencryptionencryption-asymmetric

Trying to get asymmetric RSA encryption to work


The following method does not work. decodedMessage ends up with garbage in it instead of the expected results.

I'm following an example here that supposedly works.

public static void POCSimple()
{
    String secretMessage = "short message";
    PublicKey publicKey = null;
    PrivateKey privateKey = null;
    String encodedMessage = "";
    byte[] encodedBytes = null;
    String decodedMessage ="";
    byte[] decodedBytes = null;


    try
    {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        KeyPair kp = kpg.genKeyPair();
        publicKey = kp.getPublic();
        privateKey = kp.getPrivate();

        Cipher c1 = Cipher.getInstance("RSA");
        c1.init(Cipher.ENCRYPT_MODE, publicKey);
        encodedBytes = c1.doFinal(secretMessage.getBytes());
        encodedMessage = Base64.encodeToString(encodedBytes, Base64.DEFAULT);

        Cipher c2 = Cipher.getInstance("RSA");
        c2.init(Cipher.DECRYPT_MODE, privateKey);
        decodedBytes = c2.doFinal(encodedBytes);
        decodedMessage = Base64.encodeToString(decodedBytes, Base64.DEFAULT);

        String mystring = "look at results";

    }
    catch (Exception e)
    {
        String status = e.toString();
    }


}

Any help would be most appreciated. Thanks, Dean


Solution

  • It turns out that in my original code, decodedBytes contained the properly decrypted bytes. The following command was turning decodedBytes into junk characters ...

    decodedMessage = Base64.encodeToString(decodedBytes, Base64.DEFAULT);
    

    I replaced that code with ...

    String str = new String(decodedBytes, "UTF-8");
    

    And this solved the problem probably because decodedBytes had never been Base64 encoded in the first place.

    I also found that using straight RSA I can only encrypt a maximum of 245 bytes if I use a 2048 bit key. less if I use a 1024 bit key.

    If larger strings need to be encrypted using asymmetric Public/Private keys then I need to first encrypt a string using symmetric AES and then encrypt the AES key with the public RSA key and send both the encrypted AES key and the encrypted message over the wire where the receiver can decrypt the AES key using their private RSA key. The AES key can be randomly generated in the sending code.