简体   繁体   中英

Using Cipher.doFinal(byte[] b) decrypts faster after first decryption?

I have the following code:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey mSecretKey = keyGen.generateKey();

public byte[] encrypt(byte[] data) {
    try {
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        SecretKeySpec k = new SecretKeySpec(mSecretKey.getEncoded(), "AES");
        c.init(Cipher.ENCRYPT_MODE, k);
        byte[] encryptedData = c.doFinal(data);
        return Bytes.concat(c.getIV(), encryptedData);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public byte[] decrypt(byte[] encryptedData) {
    try {
        byte[] iv = Arrays.copyOfRange(encryptedData, 0, 16);
        SecretKeySpec k = new SecretKeySpec(mSecretKey.getEncoded(), "AES");
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        c.init(Cipher.DECRYPT_MODE, k, new IvParameterSpec(iv));
        byte[] decrypted = c.doFinal(Arrays.copyOfRange(encryptedData, 16, encryptedData.length));
        return decrypted;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

For some reason, I find that if I execute something like the following:

byte[] encrypted = encrypt(some_byte_array);

byte[] decrypt1 = decrypt(encrypted);
byte[] decrypt2 = decrypt(encrypted);
...
byte[] decryptN = decrypt(encrypted);

That the first ever decryption (and on occasion the first couple) will always take longer than the following decryption. This is not limited to decrypting the same encryption, however. For example, if I encrypt two byte arrays, a and b , if I decrypt the encryption of a first, then the decryption of b will execute much faster.

So basically, the first (sometimes couple of) call(s) to decrypt is always slower than all subsequent calls. I did some of my own benchmarking and found that the difference seems to be in my call to c.doFinal(Arrays.copyOfRange(encryptedData, 16, encryptedData.length) , which takes longer the first (sometimes couple of) times around than it does after.

I apologize in advance if this is a dumb question, and thanks for any help.

The first time byte-code is run in Java it is typically compiled (by the JVM) to native code through the JIT compiler. After that, it saves the native code and uses it again. Therefore, I would expect subsequent invocations to be faster than the first. See also, startup delay and optimizations .

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