I need to encrypt some String
using XTEA algorithm, and found this code but I'm not sure how to use it and I get a java.lang.ArrayIndexOutOfBoundsException
.
Here's how I'm using it:
XTEA mXTEA = new XTEA();
mXTEA.setKey(XTEA_KEY.getBytes());
byte[] b = someString.getBytes();
mXTEA.encrypt(b, 0, b.length);
More specifically, I'm not sure what are the last two parameters of encrypt
. I assumed that off
is some offset and len
is the length of the input stream.
Edit
Her's the full stack trace:
08-12 16:42:03.475: E/AndroidRuntime(23894): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=14; index=14
08-12 16:42:03.475: E/AndroidRuntime(23894): at xxx.XTEA.encryptBlock(XTEA.java:56)
08-12 16:42:03.475: E/AndroidRuntime(23894): at xxx.XTEA.encrypt(XTEA.java:43)
Anybody can help?
Answer
As suggested by John Skeet, I the string must be padded to get to a multiple of 8:
int len = myString.length();
int newLen = len + (8- len % 8);
while(myString.length()<newSize){
myString += "\0";
}
Looking at the code and the Wikipedia entry on XTEA it looks like the problem is that it only works on blocks of 8 bytes, and you're providing 14 bytes (which isn't a multiple of 8).
You'll probably need to add some padding, and either just chop off trailing 0s from the plaintext, or if you need to be able to represent U+0000 in the actual text, you could add a bit of data to say how much real data there is.