saleks28

Untitled

Sep 14th, 2020
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 28.31 KB | None | 0 0
  1. #include <jni.h>            // For JNI types and JNI functions
  2. #include <stdio.h>          // For FILE
  3. #include <string.h>         // For strlen(), strcat(), strncpy(), strdup()
  4. #include <stdlib.h>         // For calloc(), free()
  5. #include <libgen.h>         // For basename() - only for Linux
  6. #include <android/log.h>    // For __android_log_print()
  7. #include <stdint.h>
  8.  
  9. // for logging from NDK
  10. //#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,"NDK_TAG",__VA_ARGS__)
  11. #define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,"NDK_TAG",__VA_ARGS__)
  12.  
  13. /*------------------------------------------------------------------------------------------------*/
  14.  
  15. // The #ifndef-guard allows it to be configured before #include'ing or at compile time.
  16.  
  17. #ifndef ECB
  18. #define ECB 1
  19. #endif
  20.  
  21. #define AES128 1
  22. //#define AES192 1
  23. //#define AES256 1
  24.  
  25. #define AES_BLOCKLEN 16 // Block length in bytes - AES is 128b block only
  26.  
  27. #if defined(AES256) && (AES256 == 1)
  28. #define AES_KEYLEN 32
  29.     #define AES_keyExpSize 240
  30. #elif defined(AES192) && (AES192 == 1)
  31. #define AES_KEYLEN 24
  32.     #define AES_keyExpSize 208
  33. #else
  34. #define AES_KEYLEN 16   // Key length in bytes
  35. #define AES_keyExpSize 176
  36. #endif
  37.  
  38. struct AES_ctx
  39. {
  40.     uint8_t RoundKey[AES_keyExpSize];
  41. #if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
  42.     uint8_t Iv[AES_BLOCKLEN];
  43. #endif
  44. };
  45.  
  46. void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key);
  47. #if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
  48. void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv);
  49. void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv);
  50. #endif
  51.  
  52. #if defined(ECB) && (ECB == 1)
  53. // buffer size is exactly AES_BLOCKLEN bytes;
  54. // you need only AES_init_ctx as IV is not used in ECB
  55. // NB: ECB is considered insecure for most uses
  56. void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf);
  57. void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf);
  58.  
  59. #endif // #if defined(ECB) && (ECB == !)
  60.  
  61.  
  62. #if defined(CBC) && (CBC == 1)
  63. // buffer size MUST be mutile of AES_BLOCKLEN;
  64. // Suggest https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
  65. // NOTES: you need to set IV in ctx via AES_init_ctx_iv() or AES_ctx_set_iv()
  66. //        no IV should ever be reused with the same key
  67. void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length);
  68. void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length);
  69.  
  70. #endif // #if defined(CBC) && (CBC == 1)
  71.  
  72.  
  73. #if defined(CTR) && (CTR == 1)
  74.  
  75. // Same function for encrypting as for decrypting.
  76. // IV is incremented for every block, and used after encryption as XOR-compliment for output
  77. // Suggesting https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
  78. // NOTES: you need to set IV in ctx with AES_init_ctx_iv() or AES_ctx_set_iv()
  79. //        no IV should ever be reused with the same key
  80. void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length);
  81.  
  82. #endif // #if defined(CTR) && (CTR == 1)
  83.  
  84. /*
  85.  
  86. This is an implementation of the AES algorithm, specifically ECB, CTR and CBC mode.
  87. Block size can be chosen in aes.h - available choices are AES128, AES192, AES256.
  88.  
  89. The implementation is verified against the test vectors in:
  90.   National Institute of Standards and Technology Special Publication 800-38A 2001 ED
  91.  
  92. ECB-AES128
  93. ----------
  94.  
  95.   plain-text:
  96.     6bc1bee22e409f96e93d7e117393172a
  97.     ae2d8a571e03ac9c9eb76fac45af8e51
  98.     30c81c46a35ce411e5fbc1191a0a52ef
  99.     f69f2445df4f9b17ad2b417be66c3710
  100.  
  101.   key:
  102.     2b7e151628aed2a6abf7158809cf4f3c
  103.  
  104.   resulting cipher
  105.     3ad77bb40d7a3660a89ecaf32466ef97
  106.     f5d3d58503b9699de785895a96fdbaaf
  107.     43b1cd7f598ece23881b00e3ed030688
  108.     7b0c785e27e8ad3f8223207104725dd4
  109.  
  110.  
  111. NOTE:   String length must be evenly divisible by 16byte (str_len % 16 == 0)
  112.         You should pad the end of the string with zeros if this is not the case.
  113.         For AES192/256 the key size is proportionally larger.
  114.  
  115. */
  116.  
  117.  
  118. /*****************************************************************************/
  119. /* Includes:                                                                 */
  120. /*****************************************************************************/
  121. #include <string.h> // CBC mode, for memset
  122.  
  123. /*****************************************************************************/
  124. /* Defines:                                                                  */
  125. /*****************************************************************************/
  126. // The number of columns comprising a state in AES. This is a constant in AES. Value=4
  127. #define Nb 4
  128.  
  129. #if defined(AES256) && (AES256 == 1)
  130. #define Nk 8
  131.     #define Nr 14
  132. #elif defined(AES192) && (AES192 == 1)
  133. #define Nk 6
  134.     #define Nr 12
  135. #else
  136. #define Nk 4        // The number of 32 bit words in a key.
  137. #define Nr 10       // The number of rounds in AES Cipher.
  138. #endif
  139.  
  140. // jcallan@github points out that declaring Multiply as a function
  141. // reduces code size considerably with the Keil ARM compiler.
  142. // See this link for more information: https://github.com/kokke/tiny-AES-C/pull/3
  143. #ifndef MULTIPLY_AS_A_FUNCTION
  144. #define MULTIPLY_AS_A_FUNCTION 0
  145. #endif
  146.  
  147.  
  148.  
  149.  
  150. /*****************************************************************************/
  151. /* Private variables:                                                        */
  152. /*****************************************************************************/
  153. // state - array holding the intermediate results during decryption.
  154. typedef uint8_t state_t[4][4];
  155.  
  156.  
  157.  
  158. // The lookup-tables are marked const so they can be placed in read-only storage instead of RAM
  159. // The numbers below can be computed dynamically trading ROM for RAM -
  160. // This can be useful in (embedded) bootloader applications, where ROM is often limited.
  161. static const uint8_t sbox[256] = {
  162.         //0     1    2      3     4    5     6     7      8    9     A      B    C     D     E     F
  163.         0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
  164.         0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
  165.         0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  166.         0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
  167.         0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
  168.         0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  169.         0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
  170.         0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
  171.         0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  172.         0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
  173.         0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
  174.         0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  175.         0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
  176.         0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
  177.         0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  178.         0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };
  179.  
  180. static const uint8_t rsbox[256] = {
  181.         0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
  182.         0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
  183.         0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  184.         0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
  185.         0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
  186.         0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  187.         0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
  188.         0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
  189.         0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  190.         0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
  191.         0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
  192.         0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  193.         0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
  194.         0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
  195.         0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  196.         0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };
  197.  
  198. // The round constant word array, Rcon[i], contains the values given by
  199. // x to the power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)
  200. static const uint8_t Rcon[11] = {
  201.         0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 };
  202.  
  203. /*
  204.  * Jordan Goulder points out in PR #12 (https://github.com/kokke/tiny-AES-C/pull/12),
  205.  * that you can remove most of the elements in the Rcon array, because they are unused.
  206.  *
  207.  * From Wikipedia's article on the Rijndael key schedule @ https://en.wikipedia.org/wiki/Rijndael_key_schedule#Rcon
  208.  *
  209.  * "Only the first some of these constants are actually used – up to rcon[10] for AES-128 (as 11 round keys are needed),
  210.  *  up to rcon[8] for AES-192, up to rcon[7] for AES-256. rcon[0] is not used in AES algorithm."
  211.  */
  212.  
  213.  
  214. /*****************************************************************************/
  215. /* Private functions:                                                        */
  216. /*****************************************************************************/
  217. /*
  218. static uint8_t getSBoxValue(uint8_t num)
  219. {
  220.   return sbox[num];
  221. }
  222. */
  223. #define getSBoxValue(num) (sbox[(num)])
  224. /*
  225. static uint8_t getSBoxInvert(uint8_t num)
  226. {
  227.   return rsbox[num];
  228. }
  229. */
  230. #define getSBoxInvert(num) (rsbox[(num)])
  231.  
  232. // This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states.
  233. static void KeyExpansion(uint8_t* RoundKey, const uint8_t* Key)
  234. {
  235.     unsigned i, j, k;
  236.     uint8_t tempa[4]; // Used for the column/row operations
  237.  
  238.     // The first round key is the key itself.
  239.     for (i = 0; i < Nk; ++i)
  240.     {
  241.         RoundKey[(i * 4) + 0] = Key[(i * 4) + 0];
  242.         RoundKey[(i * 4) + 1] = Key[(i * 4) + 1];
  243.         RoundKey[(i * 4) + 2] = Key[(i * 4) + 2];
  244.         RoundKey[(i * 4) + 3] = Key[(i * 4) + 3];
  245.     }
  246.  
  247.     // All other round keys are found from the previous round keys.
  248.     for (i = Nk; i < Nb * (Nr + 1); ++i)
  249.     {
  250.         {
  251.             k = (i - 1) * 4;
  252.             tempa[0]=RoundKey[k + 0];
  253.             tempa[1]=RoundKey[k + 1];
  254.             tempa[2]=RoundKey[k + 2];
  255.             tempa[3]=RoundKey[k + 3];
  256.  
  257.         }
  258.  
  259.         if (i % Nk == 0)
  260.         {
  261.             // This function shifts the 4 bytes in a word to the left once.
  262.             // [a0,a1,a2,a3] becomes [a1,a2,a3,a0]
  263.  
  264.             // Function RotWord()
  265.             {
  266.                 const uint8_t u8tmp = tempa[0];
  267.                 tempa[0] = tempa[1];
  268.                 tempa[1] = tempa[2];
  269.                 tempa[2] = tempa[3];
  270.                 tempa[3] = u8tmp;
  271.             }
  272.  
  273.             // SubWord() is a function that takes a four-byte input word and
  274.             // applies the S-box to each of the four bytes to produce an output word.
  275.  
  276.             // Function Subword()
  277.             {
  278.                 tempa[0] = getSBoxValue(tempa[0]);
  279.                 tempa[1] = getSBoxValue(tempa[1]);
  280.                 tempa[2] = getSBoxValue(tempa[2]);
  281.                 tempa[3] = getSBoxValue(tempa[3]);
  282.             }
  283.  
  284.             tempa[0] = tempa[0] ^ Rcon[i/Nk];
  285.         }
  286. #if defined(AES256) && (AES256 == 1)
  287.         if (i % Nk == 4)
  288.     {
  289.       // Function Subword()
  290.       {
  291.         tempa[0] = getSBoxValue(tempa[0]);
  292.         tempa[1] = getSBoxValue(tempa[1]);
  293.         tempa[2] = getSBoxValue(tempa[2]);
  294.         tempa[3] = getSBoxValue(tempa[3]);
  295.       }
  296.     }
  297. #endif
  298.         j = i * 4; k=(i - Nk) * 4;
  299.         RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0];
  300.         RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1];
  301.         RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2];
  302.         RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3];
  303.     }
  304. }
  305.  
  306. void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key)
  307. {
  308.     KeyExpansion(ctx->RoundKey, key);
  309. }
  310. #if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
  311. void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv)
  312. {
  313.     KeyExpansion(ctx->RoundKey, key);
  314.     memcpy (ctx->Iv, iv, AES_BLOCKLEN);
  315. }
  316. void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv)
  317. {
  318.     memcpy (ctx->Iv, iv, AES_BLOCKLEN);
  319. }
  320. #endif
  321.  
  322. // This function adds the round key to state.
  323. // The round key is added to the state by an XOR function.
  324. static void AddRoundKey(uint8_t round, state_t* state, const uint8_t* RoundKey)
  325. {
  326.     uint8_t i,j;
  327.     for (i = 0; i < 4; ++i)
  328.     {
  329.         for (j = 0; j < 4; ++j)
  330.         {
  331.             (*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j];
  332.         }
  333.     }
  334. }
  335.  
  336. // The SubBytes Function Substitutes the values in the
  337. // state matrix with values in an S-box.
  338. static void SubBytes(state_t* state)
  339. {
  340.     uint8_t i, j;
  341.     for (i = 0; i < 4; ++i)
  342.     {
  343.         for (j = 0; j < 4; ++j)
  344.         {
  345.             (*state)[j][i] = getSBoxValue((*state)[j][i]);
  346.         }
  347.     }
  348. }
  349.  
  350. // The ShiftRows() function shifts the rows in the state to the left.
  351. // Each row is shifted with different offset.
  352. // Offset = Row number. So the first row is not shifted.
  353. static void ShiftRows(state_t* state)
  354. {
  355.     uint8_t temp;
  356.  
  357.     // Rotate first row 1 columns to left
  358.     temp           = (*state)[0][1];
  359.     (*state)[0][1] = (*state)[1][1];
  360.     (*state)[1][1] = (*state)[2][1];
  361.     (*state)[2][1] = (*state)[3][1];
  362.     (*state)[3][1] = temp;
  363.  
  364.     // Rotate second row 2 columns to left
  365.     temp           = (*state)[0][2];
  366.     (*state)[0][2] = (*state)[2][2];
  367.     (*state)[2][2] = temp;
  368.  
  369.     temp           = (*state)[1][2];
  370.     (*state)[1][2] = (*state)[3][2];
  371.     (*state)[3][2] = temp;
  372.  
  373.     // Rotate third row 3 columns to left
  374.     temp           = (*state)[0][3];
  375.     (*state)[0][3] = (*state)[3][3];
  376.     (*state)[3][3] = (*state)[2][3];
  377.     (*state)[2][3] = (*state)[1][3];
  378.     (*state)[1][3] = temp;
  379. }
  380.  
  381. static uint8_t xtime(uint8_t x)
  382. {
  383.     return ((x<<1) ^ (((x>>7) & 1) * 0x1b));
  384. }
  385.  
  386. // MixColumns function mixes the columns of the state matrix
  387. static void MixColumns(state_t* state)
  388. {
  389.     uint8_t i;
  390.     uint8_t Tmp, Tm, t;
  391.     for (i = 0; i < 4; ++i)
  392.     {
  393.         t   = (*state)[i][0];
  394.         Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ;
  395.         Tm  = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm);  (*state)[i][0] ^= Tm ^ Tmp ;
  396.         Tm  = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm);  (*state)[i][1] ^= Tm ^ Tmp ;
  397.         Tm  = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm);  (*state)[i][2] ^= Tm ^ Tmp ;
  398.         Tm  = (*state)[i][3] ^ t ;              Tm = xtime(Tm);  (*state)[i][3] ^= Tm ^ Tmp ;
  399.     }
  400. }
  401.  
  402. // Multiply is used to multiply numbers in the field GF(2^8)
  403. // Note: The last call to xtime() is unneeded, but often ends up generating a smaller binary
  404. //       The compiler seems to be able to vectorize the operation better this way.
  405. //       See https://github.com/kokke/tiny-AES-c/pull/34
  406. #if MULTIPLY_AS_A_FUNCTION
  407. static uint8_t Multiply(uint8_t x, uint8_t y)
  408. {
  409.   return (((y & 1) * x) ^
  410.        ((y>>1 & 1) * xtime(x)) ^
  411.        ((y>>2 & 1) * xtime(xtime(x))) ^
  412.        ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^
  413.        ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))); /* this last call to xtime() can be omitted */
  414.   }
  415. #else
  416. #define Multiply(x, y)                                \
  417.       (  ((y & 1) * x) ^                              \
  418.       ((y>>1 & 1) * xtime(x)) ^                       \
  419.       ((y>>2 & 1) * xtime(xtime(x))) ^                \
  420.       ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^         \
  421.       ((y>>4 & 1) * xtime(xtime(xtime(xtime(x))))))   \
  422.  
  423. #endif
  424.  
  425. #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
  426. // MixColumns function mixes the columns of the state matrix.
  427. // The method used to multiply may be difficult to understand for the inexperienced.
  428. // Please use the references to gain more information.
  429. static void InvMixColumns(state_t* state)
  430. {
  431.     int i;
  432.     uint8_t a, b, c, d;
  433.     for (i = 0; i < 4; ++i)
  434.     {
  435.         a = (*state)[i][0];
  436.         b = (*state)[i][1];
  437.         c = (*state)[i][2];
  438.         d = (*state)[i][3];
  439.  
  440.         (*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);
  441.         (*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);
  442.         (*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);
  443.         (*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);
  444.     }
  445. }
  446.  
  447.  
  448. // The SubBytes Function Substitutes the values in the
  449. // state matrix with values in an S-box.
  450. static void InvSubBytes(state_t* state)
  451. {
  452.     uint8_t i, j;
  453.     for (i = 0; i < 4; ++i)
  454.     {
  455.         for (j = 0; j < 4; ++j)
  456.         {
  457.             (*state)[j][i] = getSBoxInvert((*state)[j][i]);
  458.         }
  459.     }
  460. }
  461.  
  462. static void InvShiftRows(state_t* state)
  463. {
  464.     uint8_t temp;
  465.  
  466.     // Rotate first row 1 columns to right
  467.     temp = (*state)[3][1];
  468.     (*state)[3][1] = (*state)[2][1];
  469.     (*state)[2][1] = (*state)[1][1];
  470.     (*state)[1][1] = (*state)[0][1];
  471.     (*state)[0][1] = temp;
  472.  
  473.     // Rotate second row 2 columns to right
  474.     temp = (*state)[0][2];
  475.     (*state)[0][2] = (*state)[2][2];
  476.     (*state)[2][2] = temp;
  477.  
  478.     temp = (*state)[1][2];
  479.     (*state)[1][2] = (*state)[3][2];
  480.     (*state)[3][2] = temp;
  481.  
  482.     // Rotate third row 3 columns to right
  483.     temp = (*state)[0][3];
  484.     (*state)[0][3] = (*state)[1][3];
  485.     (*state)[1][3] = (*state)[2][3];
  486.     (*state)[2][3] = (*state)[3][3];
  487.     (*state)[3][3] = temp;
  488. }
  489. #endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
  490.  
  491. // Cipher is the main function that encrypts the PlainText.
  492. static void Cipher(state_t* state, const uint8_t* RoundKey)
  493. {
  494.     uint8_t round = 0;
  495.  
  496.     // Add the First round key to the state before starting the rounds.
  497.     AddRoundKey(0, state, RoundKey);
  498.  
  499.     // There will be Nr rounds.
  500.     // The first Nr-1 rounds are identical.
  501.     // These Nr rounds are executed in the loop below.
  502.     // Last one without MixColumns()
  503.     for (round = 1; ; ++round)
  504.     {
  505.         SubBytes(state);
  506.         ShiftRows(state);
  507.         if (round == Nr) {
  508.             break;
  509.         }
  510.         MixColumns(state);
  511.         AddRoundKey(round, state, RoundKey);
  512.     }
  513.     // Add round key to last round
  514.     AddRoundKey(Nr, state, RoundKey);
  515. }
  516.  
  517. #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
  518. static void InvCipher(state_t* state, const uint8_t* RoundKey)
  519. {
  520.     uint8_t round = 0;
  521.  
  522.     // Add the First round key to the state before starting the rounds.
  523.     AddRoundKey(Nr, state, RoundKey);
  524.  
  525.     // There will be Nr rounds.
  526.     // The first Nr-1 rounds are identical.
  527.     // These Nr rounds are executed in the loop below.
  528.     // Last one without InvMixColumn()
  529.     for (round = (Nr - 1); ; --round)
  530.     {
  531.         InvShiftRows(state);
  532.         InvSubBytes(state);
  533.         AddRoundKey(round, state, RoundKey);
  534.         if (round == 0) {
  535.             break;
  536.         }
  537.         InvMixColumns(state);
  538.     }
  539.  
  540. }
  541. #endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
  542.  
  543. /*****************************************************************************/
  544. /* Public functions:                                                         */
  545. /*****************************************************************************/
  546. #if defined(ECB) && (ECB == 1)
  547.  
  548.  
  549. void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf)
  550. {
  551.     // The next function call encrypts the PlainText with the Key using AES algorithm.
  552.     Cipher((state_t*)buf, ctx->RoundKey);
  553. }
  554.  
  555. void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf)
  556. {
  557.     // The next function call decrypts the PlainText with the Key using AES algorithm.
  558.     InvCipher((state_t*)buf, ctx->RoundKey);
  559. }
  560.  
  561.  
  562. #endif // #if defined(ECB) && (ECB == 1)
  563.  
  564.  
  565. #if defined(CBC) && (CBC == 1)
  566.  
  567.  
  568. static void XorWithIv(uint8_t* buf, const uint8_t* Iv)
  569. {
  570.     uint8_t i;
  571.     for (i = 0; i < AES_BLOCKLEN; ++i) // The block in AES is always 128bit no matter the key size
  572.     {
  573.         buf[i] ^= Iv[i];
  574.     }
  575. }
  576.  
  577. void AES_CBC_encrypt_buffer(struct AES_ctx *ctx, uint8_t* buf, uint32_t length)
  578. {
  579.     uintptr_t i;
  580.     uint8_t *Iv = ctx->Iv;
  581.     for (i = 0; i < length; i += AES_BLOCKLEN)
  582.     {
  583.         XorWithIv(buf, Iv);
  584.         Cipher((state_t*)buf, ctx->RoundKey);
  585.         Iv = buf;
  586.         buf += AES_BLOCKLEN;
  587.     }
  588.     /* store Iv in ctx for next call */
  589.     memcpy(ctx->Iv, Iv, AES_BLOCKLEN);
  590. }
  591.  
  592. void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf,  uint32_t length)
  593. {
  594.     uintptr_t i;
  595.     uint8_t storeNextIv[AES_BLOCKLEN];
  596.     for (i = 0; i < length; i += AES_BLOCKLEN)
  597.     {
  598.         memcpy(storeNextIv, buf, AES_BLOCKLEN);
  599.         InvCipher((state_t*)buf, ctx->RoundKey);
  600.         XorWithIv(buf, ctx->Iv);
  601.         memcpy(ctx->Iv, storeNextIv, AES_BLOCKLEN);
  602.         buf += AES_BLOCKLEN;
  603.     }
  604.  
  605. }
  606.  
  607. #endif // #if defined(CBC) && (CBC == 1)
  608.  
  609.  
  610.  
  611. #if defined(CTR) && (CTR == 1)
  612.  
  613. /* Symmetrical operation: same function for encrypting as for decrypting. Note any IV/nonce should never be reused with the same key */
  614. void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length)
  615. {
  616.     uint8_t buffer[AES_BLOCKLEN];
  617.  
  618.     unsigned i;
  619.     int bi;
  620.     for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi)
  621.     {
  622.         if (bi == AES_BLOCKLEN) /* we need to regen xor compliment in buffer */
  623.         {
  624.  
  625.             memcpy(buffer, ctx->Iv, AES_BLOCKLEN);
  626.             Cipher((state_t*)buffer,ctx->RoundKey);
  627.  
  628.             /* Increment Iv and handle overflow */
  629.             for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi)
  630.             {
  631.                 /* inc will overflow */
  632.                 if (ctx->Iv[bi] == 255)
  633.                 {
  634.                     ctx->Iv[bi] = 0;
  635.                     continue;
  636.                 }
  637.                 ctx->Iv[bi] += 1;
  638.                 break;
  639.             }
  640.             bi = 0;
  641.         }
  642.  
  643.         buf[i] = (buf[i] ^ buffer[bi]);
  644.     }
  645. }
  646.  
  647. #endif // #if defined(CTR) && (CTR == 1)
  648.  
  649. /*------------------------------------------------------------------------------------------------*/
  650.  
  651. // шифрует строку XOR-шифрованием с ключом 0xff
  652. bool encryptFile(const char *filePath, const char *dirPath, uint8_t *key, bool isRemove)
  653. {
  654.     FILE *inFile = NULL;
  655.     FILE *outFile = NULL;
  656.     inFile = fopen(filePath, "rb");
  657.  
  658.     if (inFile == NULL) {
  659.         LOGE("Error: cannot open file %s", filePath);
  660.         return false;
  661.     }
  662.  
  663.     char *newFile = NULL;
  664.     // выделяем имя файла из абсолютного пути
  665.     char *pathBuf = strdup(filePath);
  666.     char *fileName = basename(pathBuf);
  667.  
  668.     newFile = (char *)calloc(strlen(dirPath) + strlen(fileName) + strlen("_encrypted") + 1, sizeof(char));
  669.     strcat(strcat(strcat(newFile, dirPath), fileName), "_encrypted");
  670.  
  671.     outFile = fopen(newFile, "wb");
  672.     if (outFile == NULL) {
  673.         LOGE("Error: cannot open file %s", newFile);
  674.         return false;
  675.     }
  676.  
  677.     //temp
  678.  
  679.     //uint8_t key[16] = { (uint8_t) 0x2b, (uint8_t) 0x7e, (uint8_t) 0x15, (uint8_t) 0x16, (uint8_t) 0x28, (uint8_t) 0xae, (uint8_t) 0xd2, (uint8_t) 0xa6, (uint8_t) 0xab, (uint8_t) 0xf7, (uint8_t) 0x15, (uint8_t) 0x88, (uint8_t) 0x09, (uint8_t) 0xcf, (uint8_t) 0x4f, (uint8_t) 0x3c };
  680.  
  681.     struct AES_ctx ctx;
  682.     AES_init_ctx(&ctx, key);
  683.  
  684.     // считывание данных блоками, AES-шифрование, запись шифротекста в новый файл
  685.     size_t readCtr = 0;
  686.     uint8_t buf[AES_BLOCKLEN] = {0};
  687.     while (readCtr = fread(buf, sizeof(char), AES_BLOCKLEN, inFile)) {
  688.         for (size_t i = 0; i < readCtr; i++) {
  689.             AES_ECB_encrypt(&ctx, buf);
  690.         }
  691.         fwrite(buf, sizeof(char), readCtr, outFile);
  692.     }
  693.  
  694.     fclose(inFile);
  695.     fclose(outFile);
  696.     free(newFile);
  697.     free(pathBuf);
  698.  
  699.     if (isRemove)
  700.         remove(filePath);
  701.  
  702.     return true;
  703. }
  704.  
  705. bool decryptFile(const char *filePath, const char *dirPath, uint8_t * key, bool isRemove) {
  706.     FILE *inFile = NULL;
  707.     FILE *outFile = NULL;
  708.     inFile = fopen(filePath, "rb");
  709.  
  710.     if (inFile == NULL) {
  711.         LOGE("Error: cannot open file %s", filePath);
  712.         return false;
  713.     }
  714.  
  715.     char *newFile = NULL;
  716.     // выделяем имя файла из абсолютного пути
  717.     char *pathBuf = strdup(filePath);
  718.     char *fileName = basename(pathBuf);
  719.  
  720.     // память под имя файла без _encrypted
  721.     char *cutFileName = (char *)calloc(strlen(fileName) - strlen("_encrypted"), sizeof(char));
  722.     strncpy(cutFileName, fileName, strlen(fileName) - strlen("_encrypted"));
  723.     // новая память под путь: папка decrypt + имя файла
  724.     newFile = (char *)calloc(strlen(dirPath) + strlen(cutFileName), sizeof(char));
  725.     strcat(strcat(newFile, dirPath), cutFileName);
  726.     free(cutFileName);
  727.  
  728.     outFile = fopen(newFile, "wb");
  729.     if (outFile == NULL) {
  730.         LOGE("Error: cannot open file %s", newFile);
  731.         return false;
  732.     }
  733.  
  734.     //temp
  735.  
  736.     //uint8_t key[16] = { (uint8_t) 0x2b, (uint8_t) 0x7e, (uint8_t) 0x15, (uint8_t) 0x16, (uint8_t) 0x28, (uint8_t) 0xae, (uint8_t) 0xd2, (uint8_t) 0xa6, (uint8_t) 0xab, (uint8_t) 0xf7, (uint8_t) 0x15, (uint8_t) 0x88, (uint8_t) 0x09, (uint8_t) 0xcf, (uint8_t) 0x4f, (uint8_t) 0x3c };
  737.  
  738.     struct AES_ctx ctx;
  739.     AES_init_ctx(&ctx, key);
  740.  
  741.     // считывание данных блоками, AES-шифрование, запись шифротекста в новый файл
  742.     size_t readCtr = 0;
  743.     uint8_t buf[AES_BLOCKLEN] = {0};
  744.     while (readCtr = fread(buf, sizeof(char), AES_BLOCKLEN, inFile)) {
  745.         for (size_t i = 0; i < readCtr; i++) {
  746.             AES_ECB_decrypt(&ctx, buf);
  747.         }
  748.         fwrite(buf, sizeof(char), readCtr, outFile);
  749.     }
  750.  
  751.     fclose(inFile);
  752.     fclose(outFile);
  753.     free(newFile);
  754.     free(pathBuf);
  755.  
  756.     if (isRemove)
  757.         remove(filePath);
  758.  
  759.     return true;
  760.  
  761. }
  762.  
  763. extern "C" JNIEXPORT jboolean JNICALL
  764. Java_io_nemiron_fileencryptor_utils_CipherData_decryptFile(JNIEnv *env, jobject, jstring key, jstring filePath, jstring dirPath) {
  765.     const char *nativeFilePath = env->GetStringUTFChars(filePath, JNI_FALSE);
  766.     const char *nativeDirPath = env->GetStringUTFChars(dirPath, JNI_FALSE);
  767.     uint8_t * nativeKey = (uint8_t*)env->GetStringUTFChars(key, JNI_FALSE);
  768.  
  769.     bool check = decryptFile(nativeFilePath, nativeDirPath, nativeKey, false);
  770.     env->ReleaseStringUTFChars(filePath, nativeFilePath);
  771.     env->ReleaseStringUTFChars(dirPath, nativeDirPath);
  772.  
  773.     if (!check)
  774.         return  JNI_FALSE;
  775.     return JNI_TRUE;
  776. }
  777.  
  778. extern "C" JNIEXPORT jboolean JNICALL
  779. Java_io_nemiron_fileencryptor_utils_CipherData_encryptFile(JNIEnv *env, jobject, jstring key, jstring filePath, jstring dirPath, jboolean isRemove) {
  780.  
  781.     const char *nativeFilePath = env->GetStringUTFChars(filePath, JNI_FALSE);
  782.     const char *nativeDirPath = env->GetStringUTFChars(dirPath, JNI_FALSE);
  783.     uint8_t * nativeKey = (uint8_t*)env->GetStringUTFChars(key, JNI_FALSE);
  784.  
  785.     bool check = encryptFile(nativeFilePath, nativeDirPath, nativeKey, isRemove);
  786.  
  787.     env->ReleaseStringUTFChars(filePath, nativeFilePath);
  788.     env->ReleaseStringUTFChars(dirPath, nativeDirPath);
  789.  
  790.     if (!check)
  791.         return JNI_FALSE;
  792.     return JNI_TRUE;
  793. }
Add Comment
Please, Sign In to add comment