winzipaes解密Android上的10 MB文件很慢

时间:2014-12-30 10:27:13

标签: java android encryption aes bouncycastle

我尝试在三星S5上使用AES加密的zip文件解密一个10 MB的文件,但它太慢了,这真让我感到惊讶。我熟悉AES,所以我不知道它是否会耗费大量时间。以下是我的测试结果。谁能告诉我这些结果是否合理?

无论如何都要加速AES解密?

PS。我使用SpongyCastle来避免类加载器冲突,我还修改了winzipaes以使用SpongyCastle。

测试1
装置:三星S5
Zip存档:7za a -tzip -mx = 0 -p1234 -mem = AES256 test.zip 1MB_file 10MB_file
1MB_file:1 MB
10MB_file:10 MBs test.zip:12.5 MBs
压缩率:1.00
解密和解压缩:
- > 1MB_file:3167 ms
- > 10MB_file:34137 ms

测试2
装置:三星S5
Zip存档:7za a -tzip -mx = 1 -p1234 -mem = AES256 test.zip 1MB_file 10MB_file
1MB_file:1 MB
10MB_file:10 MBs test.zip:5.4 MBs
压缩率:2.31
解密和解压缩:
- > 1MB_file:1290毫秒
- > 10MB_file:15369 ms

测试3
装置:三星S5
Zip存档:7za a -tzip -mx = 9 -p1234 -mem = AES256 test.zip 1MB_file 10MB_file
1MB_file:1 MB
10MB_file:10 MBs test.zip:5.1 MBs
压缩率:2.46
解密和解压缩:
- > 1MB_file:1202 ms
- > 10MB_file:14460 ms

winzipaes:https://code.google.com/p/winzipaes/
SpongyCastle:http://rtyley.github.io/spongycastle/

=============================================== ===================================

使用@Maarten Bodewes - owlstead解决方案

测试2
装置:三星S5
Zip存档:7za a -tzip -mx = 1 -p1234 -mem = AES256 test.zip 1MB_file 10MB_file
1MB_file:1 MB
10MB_file:10 MBs test.zip:5.4 MBs
压缩率:2.31
解密和解压缩:
- > 1MB_file:206毫秒(1290毫秒)
- > 10MB_file:1782毫秒(15369毫秒)

1 个答案:

答案 0 :(得分:4)

是的,有很多方法可以加快速度,因为winzipaes的源代码使用了一种相当低效的解密方式:它通过计算IV并初始化密码来解密每个块(用于CTR模式解密)。此可能意味着密钥经常重新初始化。此外,处理16字节块的数据也不是非常有效。这主要是因为WinZip执行的AES-CTR使用了一个小端计数器而不是大端计数器(标准化)。

解密似乎还包括在密文上计算HMAC-SHA1,这也会增加显着的开销。如果您只需要保存文本的机密性,那么您可以跳过该步骤,尽管MAC确实具有重要的安全优势,提供加密安全的完整性和真实性。

为了表明我的意思,我创建了一个小样本代码,至少在我的Java SE机器上运行得更快。根据Wayne(原始海报)的说法,Android代码的速度提高了10倍左右,在我的Java SE测试中,我“只”看到的速度是原来的3倍。

的变化:

  • 创建了用于ZIP
  • 的特殊小端计数器模式
  • 由于上述
  • 而简化/优化的解密器代码
  • 删除每个文件的双键派生(D'oh!)
  • 选项不验证MAC(回报相对较小,SHA1非常快)
  • 使用AESFastEngine,没关系,但是嘿......

很可能可以为加密器创建相同类型的优化。

注意:

  • .zip加密是每个存储文件,因此每个存储文件也需要进行一次密钥派生,效率相当低。加密.zip文件本身会更有效率。
  • 使用解密器的JCA版本可以提供加速,并且Android可以在更高版本中使用OpenSSL代码(尽管它必须执行逐块加密)。

-

/**
 * Adapter for bouncy castle crypto implementation (decryption).
 *
 * @author olaf@merkert.de
 * @author owlstead
 */
public class AESDecrypterOwlstead extends AESCryptoBase implements AESDecrypter {


    private final boolean verify;

    public AESDecrypterOwlstead(boolean verify) {
        this.verify = verify;
    }

    // TODO consider keySize (but: we probably need to adapt the key size for the zip file as well)
    public void init( String pwStr, int keySize, byte[] salt, byte[] pwVerification ) throws ZipException {
        byte[] pwBytes = pwStr.getBytes();

        super.saltBytes = salt;

        PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
        generator.init( pwBytes, salt, ITERATION_COUNT );

        cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT*2 + 16);
        byte[] keyBytes = ((KeyParameter)cipherParameters).getKey();

        this.cryptoKeyBytes = new byte[ KEY_SIZE_BYTE ];
        System.arraycopy( keyBytes, 0, cryptoKeyBytes, 0, KEY_SIZE_BYTE );

        this.authenticationCodeBytes = new byte[ KEY_SIZE_BYTE ];
        System.arraycopy( keyBytes, KEY_SIZE_BYTE, authenticationCodeBytes, 0, KEY_SIZE_BYTE );

        // based on SALT + PASSWORD (password is probably correct)
        this.pwVerificationBytes = new byte[ 2 ];
        System.arraycopy( keyBytes, KEY_SIZE_BYTE*2, this.pwVerificationBytes, 0, 2 );

        if( !ByteArrayHelper.isEqual( this.pwVerificationBytes, pwVerification ) ) {
            throw new ZipException("wrong password - " + ByteArrayHelper.toString(this.pwVerificationBytes) + "/ " + ByteArrayHelper.toString(pwVerification));
        }

        cipherParameters = new KeyParameter(cryptoKeyBytes);

        // checksum added to the end of the encrypted data, update on each encryption call

        if (this.verify) {
            this.mac = new HMac( new SHA1Digest() );
            this.mac.init( new KeyParameter(authenticationCodeBytes) );
        }

        this.aesCipher = new SICZIPBlockCipher(new AESFastEngine());
        this.blockSize = aesCipher.getBlockSize();

        // incremented on each 16 byte block and used as encryption NONCE (ivBytes)

        // warning: non-CTR; little endian IV and starting with 1 instead of 0

        nonce = 1;

        byte[] ivBytes = ByteArrayHelper.toByteArray( nonce, 16 );

        ParametersWithIV ivParams = new ParametersWithIV(cipherParameters, ivBytes);
        aesCipher.init( false, ivParams );
    }

    // --------------------------------------------------------------------------

    protected CipherParameters cipherParameters;

    protected SICZIPBlockCipher aesCipher;

    protected HMac mac;


    @Override
    public void decrypt(byte[] in, int length) {
        if (verify) {
            mac.update(in, 0, length);
        }
        aesCipher.processBytes(in, 0, length, in, 0);
    }

    public byte[] getFinalAuthentication() {
        if (!verify) {
            return null;
        }
        byte[] macBytes = new byte[ mac.getMacSize() ];
        mac.doFinal( macBytes, 0 );
        byte[] macBytes10 = new byte[10];
        System.arraycopy( macBytes, 0, macBytes10, 0, 10 );
        return macBytes10;
    }
}

当然,您还需要引用的SICZIPCipher

/**
 * Implements the Segmented Integer Counter (SIC) mode on top of a simple
 * block cipher. This mode is also known as CTR mode. This CTR mode
 * was altered to comply with the ZIP little endian counter and
 * different starting point.
 */
public class SICZIPBlockCipher
    extends StreamBlockCipher
    implements SkippingStreamCipher
{
    private final BlockCipher     cipher;
    private final int             blockSize;

    private byte[]          IV;
    private byte[]          counter;
    private byte[]          counterOut;
    private int             byteCount;

    /**
     * Basic constructor.
     *
     * @param c the block cipher to be used.
     */
    public SICZIPBlockCipher(BlockCipher c)
    {
        super(c);

        this.cipher = c;
        this.blockSize = cipher.getBlockSize();
        this.IV = new byte[blockSize];
        this.counter = new byte[blockSize];
        this.counterOut = new byte[blockSize];
        this.byteCount = 0;
    }

    public void init(
        boolean             forEncryption, //ignored by this CTR mode
        CipherParameters    params)
        throws IllegalArgumentException
    {
        if (params instanceof ParametersWithIV)
        {
            ParametersWithIV ivParam = (ParametersWithIV)params;
            byte[] iv = ivParam.getIV();
            System.arraycopy(iv, 0, IV, 0, IV.length);

            // if null it's an IV changed only.
            if (ivParam.getParameters() != null)
            {
                cipher.init(true, ivParam.getParameters());
            }

            reset();
        }
        else
        {
            throw new IllegalArgumentException("SICZIP mode requires ParametersWithIV");
        }
    }

    public String getAlgorithmName()
    {
        return cipher.getAlgorithmName() + "/SICZIP";
    }

    public int getBlockSize()
    {
        return cipher.getBlockSize();
    }

    public int processBlock(byte[] in, int inOff, byte[] out, int outOff)
          throws DataLengthException, IllegalStateException
    {
        processBytes(in, inOff, blockSize, out, outOff);

        return blockSize;
    }

    protected byte calculateByte(byte in)
          throws DataLengthException, IllegalStateException
    {
        if (byteCount == 0)
        {
            cipher.processBlock(counter, 0, counterOut, 0);

            return (byte)(counterOut[byteCount++] ^ in);
        }

        byte rv = (byte)(counterOut[byteCount++] ^ in);

        if (byteCount == counter.length)
        {
            byteCount = 0;

            incrementCounter();
        }

        return rv;
    }

    private void incrementCounter()
    {
        // increment counter by 1.
        for (int i = 0; i < counter.length && ++counter[i] == 0; i++)
        {
            ; // do nothing - pre-increment and test for 0 in counter does the job.
        }
    }

    private void decrementCounter()
    {
        // TODO test - owlstead too lazy to test

        if (counter[counter.length - 1] == 0)
        {
            boolean nonZero = false;

            for (int i = 0; i < counter.length; i++)
            {
                if (counter[i] != 0)
                {
                    nonZero = true;
                }
            }

            if (!nonZero)
            {
                throw new IllegalStateException("attempt to reduce counter past zero.");
            }
        }

        // decrement counter by 1.
        for (int i = 0; i < counter.length && --counter[i] == -1; i++)
        {
            ;
        }
    }

    private void adjustCounter(long n)
    {
        if (n >= 0)
        {
            long numBlocks = (n + byteCount) / blockSize;

            for (long i = 0; i != numBlocks; i++)
            {
                incrementCounter();
            }

            byteCount = (int)((n + byteCount) - (blockSize * numBlocks));
        }
        else
        {
            long numBlocks = (-n - byteCount) / blockSize;

            for (long i = 0; i != numBlocks; i++)
            {
                decrementCounter();
            }

            int gap = (int)(byteCount + n + (blockSize * numBlocks));

            if (gap >= 0)
            {
                byteCount = 0;
            }
            else
            {
                decrementCounter();
                byteCount =  blockSize + gap;
            }
        }
    }

    public void reset()
    {
        System.arraycopy(IV, 0, counter, 0, counter.length);
        cipher.reset();
        this.byteCount = 0;
    }

    public long skip(long numberOfBytes)
    {
        adjustCounter(numberOfBytes);

        cipher.processBlock(counter, 0, counterOut, 0);

        return numberOfBytes;
    }

    public long seekTo(long position)
    {
        reset();

        return skip(position);
    }

    public long getPosition()
    {
        byte[] res = new byte[IV.length];

        System.arraycopy(counter, 0, res, 0, res.length);

        for (int i = 0; i < res.length; i++)
        {
            int v = (res[i] - IV[i]);

            if (v < 0)
            {
               res[i + 1]--;
               v += 256;
            }

            res[i] = (byte)v;
        }

        // TODO still broken - owlstead too lazy to fix for zip
        return Pack.bigEndianToLong(res, res.length - 8) * blockSize + byteCount;
    }
}