| 5 |
| #include <inttypes.h> |
| 6 | #include <android/log.h> |
| 7 | #include "aes.h" |
| 8 | #include "log.h" |
| 9 |
| 10 | JNIEXPORT jbyteArray Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *env, jclass class, jbyteArray _what, jbyteArray _key, jbyteArray _iv, jboolean encrypt, jboolean changeIv) { |
| 11 | unsigned char *what = (unsigned char *)(*env)->GetByteArrayElements(env, _what, NULL); |
| 12 | unsigned char *key = (unsigned char *)(*env)->GetByteArrayElements(env, _key, NULL); |
| 13 | unsigned char *__iv = (unsigned char *)(*env)->GetByteArrayElements(env, _iv, NULL); |
| 14 | unsigned char *iv = 0; |
| 15 |
| 16 | if (!changeIv) { |
| 17 | iv = (unsigned char *)malloc((*env)->GetArrayLength(env, _iv)); |
| 18 | memcpy(iv, __iv, (*env)->GetArrayLength(env, _iv)); |
| 19 | } else { |
| 20 | iv = __iv; |
| 21 | } |
| 22 |
| 23 | int len = (*env)->GetArrayLength(env, _what); |
| 24 | AES_KEY akey; |
| 25 | if (!encrypt) { |
| 26 | AES_set_decrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey); |
| 27 | AES_ige_encrypt(what, what, len, &akey, iv, AES_DECRYPT); |
| 28 | } else { |
| 29 | AES_set_encrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey); |
| 30 | AES_ige_encrypt(what, what, len, &akey, iv, AES_ENCRYPT); |
| 31 | } |
| 32 | (*env)->ReleaseByteArrayElements(env, _what, what, 0); |
| 33 | (*env)->ReleaseByteArrayElements(env, _key, key, JNI_ABORT); |
| 34 | if (!changeIv) { |
| 35 | (*env)->ReleaseByteArrayElements(env, _iv, __iv, JNI_ABORT); |
| 36 | free(iv); |
| 37 | } else { |
| 38 | (*env)->ReleaseByteArrayElements(env, _iv, __iv, 0); |
| 39 | } |
| 40 | return _what; |
| 41 | } |
| 42 |
| 43 | uint64_t gcd(uint64_t a, uint64_t b){ |
| 44 | while(a != 0 && b != 0) { |
| 45 | while((b & 1) == 0) b >>= 1; |
| 46 | while((a & 1) == 0) a >>= 1; |
| 47 | if(a > b) a -= b; else b -= a; |
| 48 | } |
| 49 | return b == 0 ? a : b; |
| 50 | } |
| 51 |
| 52 | JNIEXPORT jlong Java_org_telegram_messenger_Utilities_doPQNative(JNIEnv* env, jclass class, jlong _what) { |
| 53 | uint64_t what = _what; |
| 54 | int it = 0, i, j; |
| 55 | uint64_t g = 0; |
| 56 | for (i = 0; i < 3 || it < 1000; i++){ |
| 57 | int q = ((lrand48() & 15) + 17) % what; |
| 58 | uint64_t x = (long long)lrand48() % (what - 1) + 1, y = x; |
| 59 | int lim = 1 << (i + 18), j; |
| 60 | for(j = 1; j < lim; j++){ |
| 61 | ++it; |
| 62 | uint64_t a = x, b = x, c = q; |
| 63 | while(b){ |
| 64 | if(b & 1){ |
| 65 | c += a; |
| 66 | if(c >= what) c -= what; |
| 67 | } |
| 68 | a += a; |
| 69 | if(a >= what) a -= what; |
| 70 | b >>= 1; |
| 71 | } |
| 72 | x = c; |
| 73 | uint64_t z = x < y ? what + x - y : x - y; |
| 74 | g = gcd(z, what); |
| 75 | if(g != 1) break; |
| 76 | if(!(j & (j - 1))) y = x; |
| 77 | } |
| 78 | if(g > 1 && g < what) break; |
| 79 | } |
| 80 | return g; |
| 81 | } |
| 82 |