1 #include "CryptoHelper.h"
2
3 #include <cstring>
4 #include <limits.h>
5
6 namespace tgcalls {
7
PrepareAesKeyIv(const uint8_t * key,const uint8_t * msgKey,int x)8 AesKeyIv PrepareAesKeyIv(const uint8_t *key, const uint8_t *msgKey, int x) {
9 auto result = AesKeyIv();
10
11 const auto sha256a = ConcatSHA256(
12 MemorySpan{ msgKey, 16 },
13 MemorySpan{ key + x, 36 });
14 const auto sha256b = ConcatSHA256(
15 MemorySpan{ key + 40 + x, 36 },
16 MemorySpan{ msgKey, 16 });
17 const auto aesKey = result.key.data();
18 const auto aesIv = result.iv.data();
19 memcpy(aesKey, sha256a.data(), 8);
20 memcpy(aesKey + 8, sha256b.data() + 8, 16);
21 memcpy(aesKey + 8 + 16, sha256a.data() + 24, 8);
22 memcpy(aesIv, sha256b.data(), 4);
23 memcpy(aesIv + 4, sha256a.data() + 8, 8);
24 memcpy(aesIv + 4 + 8, sha256b.data() + 24, 4);
25
26 return result;
27 }
28
AesProcessCtr(MemorySpan from,void * to,AesKeyIv && aesKeyIv)29 void AesProcessCtr(MemorySpan from, void *to, AesKeyIv &&aesKeyIv) {
30 auto aes = AES_KEY();
31 AES_set_encrypt_key(
32 reinterpret_cast<const unsigned char*>(aesKeyIv.key.data()),
33 aesKeyIv.key.size() * CHAR_BIT,
34 &aes);
35
36 unsigned char ecountBuf[16] = { 0 };
37 unsigned int offsetInBlock = 0;
38
39 #ifdef OPENSSL_IS_BORINGSSL
40 AES_ctr128_encrypt(
41 reinterpret_cast<const unsigned char*>(from.data),
42 reinterpret_cast<unsigned char*>(to),
43 from.size,
44 &aes,
45 reinterpret_cast<unsigned char*>(aesKeyIv.iv.data()),
46 ecountBuf,
47 &offsetInBlock);
48 #else
49 CRYPTO_ctr128_encrypt(
50 reinterpret_cast<const unsigned char*>(from.data),
51 reinterpret_cast<unsigned char*>(to),
52 from.size,
53 &aes,
54 reinterpret_cast<unsigned char*>(aesKeyIv.iv.data()),
55 ecountBuf,
56 &offsetInBlock,
57 block128_f(AES_encrypt));
58 #endif
59 }
60
61 } // namespace tgcalls
62