Reputation: 151
I am working on a library for MEGA (the cloud site of this strange person). If I got it right, they derive a AES masterkey from the users password by:
All in all, for a 28 character password, I have to make 128k calls to AES. My implementation turns out to be rather slow. As in: "Hell, that takes way too long."
DDMS shows me that the GC is running hot. How can I get the AES implementation to do all those rounds internally or at least more efficiently? Each call creates a new byte array that is thrown away afterwards. Is there a way to do this inplace?
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;
}
Thanks a lot, Volker
Upvotes: 3
Views: 211
Reputation: 1101
For archiving purpose I'm writing my comment as an answer, as some of the comments may be useful to someone in the future.
The problem is the count--
in the second for loop. It should be a count++
. As it is, the code is performing 2^31 rounds, i.e., 2147483648 instead of the desired 65536.
Upvotes: 1