首页 > 解决方案 > 循环中的加密和解密在 Java 中的第一次迭代后给出更快的结果

问题描述

我正在测试一个使用 RSA 使用不同公钥多次加密 32 字节数据的情况。这是我的代码:

    List<Long> colDurSetup = new ArrayList();
    List<Long> colDurEnc = new ArrayList();
    List<Long> colDurDec = new ArrayList();
    List<PublicKey> pubKeys = new ArrayList();
    List<PrivateKey> privKeys = new ArrayList();

    for(int i=0; i<10;i++) {
        long timeStart = System.currentTimeMillis();
        KeyPair kp = buildKeyPair();
        long timeEnd = System.currentTimeMillis();
        long dur = timeEnd-timeStart;
        colDurSetup.add(dur);
        pubKeys.add(kp.getPublic());
        System.out.println(kp.getPublic().getEncoded().length);
        privKeys.add(kp.getPrivate());
        System.out.println(kp.getPrivate().getEncoded().length);
    }

    SecureRandom r = new SecureRandom();
    byte[] data = new byte[32];
    r.nextBytes(data);
    System.err.println(Arrays.toString(data));

    System.out.println("data length "+data.length);

    for(int i=0;i<10;i++) {
        long timeStart = System.nanoTime();
        byte[] ciphertext = encrypt(pubKeys.get(i), data);
        long timeEnd = System.nanoTime();
        long dur = timeEnd-timeStart;
        System.out.println("enc duration "+dur);
        colDurEnc.add(dur);
        System.out.println(timeStart);
        System.out.println(timeEnd);

        System.out.println("ciphertext length "+ciphertext.length);
        System.err.println("cip "+Arrays.toString(ciphertext));

        long timeStart2 = System.nanoTime();
        byte[] decrypted = decrypt(privKeys.get(i), ciphertext);
        long timeEnd2 = System.nanoTime();

        long dur2 = timeEnd2-timeStart2;
        colDurDec.add(dur2);
        System.err.println("dec "+Arrays.toString(decrypted));
        System.out.println("dec duration "+dur2);
    }

public static KeyPair buildKeyPair() throws NoSuchAlgorithmException {
    final int keySize = 2048;
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(keySize, random);      
    return keyPairGenerator.genKeyPair();
}

public static byte[] encrypt(PublicKey publicKey, byte[] message) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");  
    cipher.init(Cipher.ENCRYPT_MODE, publicKey, random);  
    return cipher.doFinal(message);  
}

public static byte[] decrypt(PrivateKey privateKey, byte [] encrypted) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");  
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return cipher.doFinal(encrypted);
}

当我运行它时,我注意到第一次迭代比其他迭代需要更多的时间来加密和解密,我不知道为什么。结果如下:

enc duration 231
dec duration 4
enc duration 0
dec duration 4
enc duration 0
dec duration 4
enc duration 0
dec duration 4
enc duration 0
dec duration 4
enc duration 1
dec duration 3
enc duration 0
dec duration 4
enc duration 0
dec duration 4
enc duration 0
dec duration 4
enc duration 0
dec duration 4

我假设因为它运行相同,那么所有迭代都应该给出相同的持续时间,但结果证明我错了。代码有什么问题吗?

标签: javaencryptionrsa

解决方案


推荐阅读