Search code examples
androidbouncycastle

Bouncy Castle key generation extremely slow on Android


I have an Android crypto app that's built with Bouncy Castle (actually using Spongy Castle but essentially the same thing). For some reason key generation is EXTREMELY slow (on the order of several minutes).

Here is a test method I'm using:

@Test
public void testHMAC()
{
    System.out.println(getTestAnnouncement("testHMAC"));

    long start = System.currentTimeMillis();

    final PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToBytes(("mypassword").toCharArray()), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 8192);
    byte[] key = ((KeyParameter)generator.generateDerivedParameters(256)).getKey();

    long time = System.currentTimeMillis() - start;
    Assert.assertTrue("Generated " + key.length + "-byte key, took " + time + "ms", true);
}

When I run this on my 2.4 GHz Intel Core 2 Duo machine, it takes around 0.05 seconds (50 ms). When I run that same method on Android, it takes several hundred thousand milliseconds (i.e. ~3-5 minutes).

I'm running it on an HTC Thunderbolt running Android 2.2.1. The application targets 2.1, if that makes any difference (I remember reading something about < 2.2 not having JIT but I assume the app target would make no difference, as long as the actual OS on the phone is >= 2.2). This is a pretty powerful phone which has a 1 GHz Snapdragon processor, and it seems strange that generating a key would take that many orders of magnitude longer than on a PC. What are possible causes of this issue?


Solution

  • Jake, although the tracing JIT should work well with Crypto library, can you try doing this with the NDK? From what I've heard, even after the JIT, the performance improvement on the NDK is significant. (Of the order of 10-50x)