I wanna encrypt my files on PC(Windows 7, 64bit) and decrypt 'em on Android.
I use this algo to encrypt files.
http://gladman.plushost.co.uk/oldsite/AES/aes-byte-29-08-08.zip
I encrypt my files on PC, push them to SDcard.
Unfortunately when I try to decrypt them on Android,
the result is different,
files are completely unreadable...!
What's wrong with my code?
jbyteArray Java_com_example_hellojni_HelloJni_decrypt(JNIEnv* env, jobject thiz, jstring fileName) {
......
/* read the file into the buffer */
size_t result = fread (buffer_in, 1, file_size, fin);
if (result!=file_size) { fputs("Reading error", stderr); exit(3); } /* end if */
fclose(fin);
/* decrypt file */
aes_context ctx[1];
aes_set_key(key, 16, ctx);
long i;
for (i=0; i<num_block; i++) {
long begin = i*16;
char *block = copyBlock(buffer_in, file_size, begin, 16), /* copy buffer_in[begin] ~ buffer_in[begin+16-1] to block[] */
*tmp = (char*)malloc(sizeof(char)*16);
aes_decrypt(block, tmp, ctx);
fillBuffer(buffer_out, out_size, tmp, begin, 16); /* copy tmp[] to buffer_out[begin] ~ buffer_out[begin+16-1] */
free(tmp);
free(block);
} /* end for */
......
} /* end Java_com_example_hellojni_HelloJni_decrypt() */
I know the discrepancy happens in aes.c:
return_type aes_set_key( const unsigned char key[], length_type keylen, aes_context ctx[1] ) {
......
for( cc = keylen, rc = 1; cc < hi; cc += 4 ) {
uint_8t tt, t0, t1, t2, t3;
/* difference begins here */
t0 = ctx->ksch[cc - 4];
t1 = ctx->ksch[cc - 3];
t2 = ctx->ksch[cc - 2];
t3 = ctx->ksch[cc - 1];
.......
} /* end for */
return 0;
} /* end aes_set_key() */
but why?!
Help needed badly!
In general, you should not try to implement AES (or any other cryptographic algorithm) yourself (other to learn how it works) - use known libraries for production purposes.
For Java (you are using JNI here, aren't you?), use the Cryptography API (javax.crypto) which comes with the JRE. The same API is also available for Android (either the one which comes with the engine, or the BouncyCastle variant).
Then, make sure you are using
the same mode of operation (e.g. ECB (not recommended), CBC, CTR, CFB, OFB) for the block cipher. I have no idea which mode is done by your C implementation, maybe ECB. I suppose the default for Android is CBC.
the same key for encrypting and decryption.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With