3

我正在为 MEGA(这个陌生人的云站点)开发一个库。如果我做对了,他们会通过以下方式从用户密码中获取 AES 主密钥:

  • 使用密码的 UTF-8 编码作为起始序列
  • 通过附加 0 扩展 s,使其长度为 16 的倍数
  • 设置 128 位主密钥 pkey 以修复初始化向量
  • 在每轮 64k 轮中:
    • 对于 s AES/ECB 的每个 128 位块 s[i],使用 s[i] 作为密钥加密 k。

总而言之,对于 28 个字符的密码,我必须对 AES 进行 128k 次调用。我的实现结果相当缓慢。如:“见鬼,那需要的时间太长了。”

DDMS 显示 GC 运行很热。我怎样才能让 AES 实现在内部或至少更有效地完成所有这些回合?每次调用都会创建一个新的字节数组,之后会被丢弃。有没有办法就地做到这一点?

public static byte[] calculatePasswordKey(String password) {
    Log.v(TAG, ">calculatePasswordKey");

    byte[] pw = password.getBytes();
    byte[] pkey = {(byte)0x93, (byte)0xC4, 0x67, (byte)0xE3, 0x7D, (byte)0xB0, (byte)0xC7, (byte)0xA4, (byte)0xD1, (byte)0xBE, 0x3F, (byte)0x81, 0x01, 0x52, (byte)0xCB, 0x56};

    //expand by appending 0s
    Log.v(TAG, Arrays.toString(pw));
    if ((pw.length & 0xf0) != 0) {
        int l = (pw.length & 0xf0) + 0x10;
        byte[] paddedpw = new byte[l];
        System.arraycopy(pw, 0, paddedpw, 0, pw.length);
        pw = paddedpw;
        Log.v(TAG, Arrays.toString(pw));
    }

    try {
        //create ciphers only once
        Cipher[] ciphers = new Cipher[pw.length / 16];
        Log.v(TAG, "Creating " + ciphers.length + " AES ciphers");
        for (int cIndex = 0; cIndex < ciphers.length; cIndex++) {
            ciphers[cIndex] = getAesEcbCipher();
            ciphers[cIndex].init(Cipher.ENCRYPT_MODE, new SecretKeySpec(pw, cIndex * 16, 16, "AES"));
        }

        Log.v(TAG, "Beginning 65536 rounds of AES encryption");
        for (int round = 0; round < 65536; round--) {
            for (Cipher c: ciphers) {
                pkey = c.update(pkey);
                if (pkey.length != 16) {
                    throw new Error("update does not work, revert to doFinal()");
                }
            }
        }
        return pkey;
    } catch (Exception e) {
        Log.e(TAG, "Cannot calculate password key: " + e.getMessage());
        e.printStackTrace();
    }
    return null;
}

非常感谢,沃尔克

4

1 回答 1

1

出于存档目的,我将我的评论作为答案,因为某些评论将来可能对某人有用。

问题出count--在第二个 for 循环中。它应该是一个count++. 实际上,代码正在执行 2^31 轮,即 2147483648 而不是所需的 65536。

于 2013-02-09T23:52:48.110 回答