wm_crypto_hard.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "core_804.h"
  5. #include "wm_irq.h"
  6. #include "wm_regs.h"
  7. #include "wm_debug.h"
  8. #include "wm_crypto_hard.h"
  9. #include "wm_internal_flash.h"
  10. #include "wm_pmu.h"
  11. //#define TEST_ALL_CRYPTO
  12. #undef DIGIT_BIT
  13. #define DIGIT_BIT 28//32
  14. #define SOFT_RESET_RC4 25
  15. #define SOFT_RESET_AES 26
  16. #define SOFT_RESET_DES 27
  17. #define RNG_SWITCH 28
  18. #define RNG_LOAD_SEED 29
  19. #define RNG_START 30
  20. #define TRNG_EN 0
  21. #define TRNG_SEL 1
  22. #define TRNG_DIG_BYPASS 2
  23. #define TRNG_CP 3
  24. #define TRNG_INT_MASK 6
  25. #define USE_TRNG 1
  26. #define DES_KEY_LEN 8
  27. #define DES3_KEY_LEN 24
  28. #define DES3_IV_LEN 8
  29. #define SHA1_HASH_SIZE 20
  30. #define MD5_HASH_SIZE 16
  31. #define STORE32H(x, y) { \
  32. (y)[0] = (unsigned char)(((x)>>24)&255); \
  33. (y)[1] = (unsigned char)(((x)>>16)&255); \
  34. (y)[2] = (unsigned char)(((x)>>8)&255); \
  35. (y)[3] = (unsigned char)((x)&255); \
  36. }
  37. #define STORE32L(x, y) { \
  38. unsigned long __t = (x); memcpy(y, &__t, 4); \
  39. }
  40. //#define CRYPTO_LOG printf
  41. #define CRYPTO_LOG(...)
  42. //extern volatile uint32_t sys_count;
  43. #define sys_count tls_os_get_time()
  44. extern void delay_cnt(int count);
  45. struct wm_crypto_ctx g_crypto_ctx = {0,0
  46. #ifndef CONFIG_KERNEL_NONE
  47. ,NULL
  48. #endif
  49. };
  50. #if 1
  51. typedef s32 psPool_t;
  52. #include "libtommath.h"
  53. extern int wpa_mp_init (mp_int * a);
  54. #define pstm_set(a, b) mp_set((mp_int *)a, b)
  55. #define pstm_init(pool, a) wpa_mp_init((mp_int *)a)
  56. #define pstm_count_bits(a) mp_count_bits((mp_int *)a)
  57. #define pstm_init_for_read_unsigned_bin(pool, a, len) mp_init_for_read_unsigned_bin((mp_int *)a, len)
  58. #define pstm_read_unsigned_bin(a, b, c) mp_read_unsigned_bin((mp_int *)a, b, c)
  59. #define pstm_copy(a, b) mp_copy((mp_int *)a, (mp_int *)b)
  60. #define pstm_clear(a) mp_clear((mp_int *)a)
  61. #define pstm_clamp(a) mp_clamp((mp_int *)a)
  62. #define pstm_mulmod(pool, a, b, c, d) mp_mulmod((mp_int *)a, (mp_int *)b, (mp_int *)c, (mp_int *)d)
  63. #define pstm_exptmod(pool, G, X, P, Y) mp_exptmod((mp_int *)G, (mp_int *)X, (mp_int *)P, (mp_int *)Y)
  64. #define pstm_reverse mp_reverse
  65. #define pstm_cmp mp_cmp
  66. #define pstm_to_unsigned_bin_nr(pool, a, b) mp_to_unsigned_bin_nr((mp_int *)a, (unsigned char *)b)
  67. #define pstm_2expt(a, b) mp_2expt((mp_int *)a, b)
  68. #define pstm_mod(pool, a, b, c) mp_mod((mp_int *)a, (mp_int *)b, (mp_int *)c)
  69. #endif
  70. void RSA_F_IRQHandler(void)
  71. {
  72. RSACON = 0x00;
  73. g_crypto_ctx.rsa_complete = 1;
  74. }
  75. void CRYPTION_IRQHandler(void)
  76. {
  77. tls_reg_write32(HR_CRYPTO_SEC_STS, 0x10000);
  78. g_crypto_ctx.gpsec_complete = 1;
  79. }
  80. #if 1
  81. static int16 pstm_get_bit (hstm_int *a, int16 idx)
  82. {
  83. int16 r;
  84. int16 n = idx / DIGIT_BIT;
  85. int16 m = idx % DIGIT_BIT;
  86. if (a->used <= 0)
  87. {
  88. return 0;
  89. }
  90. r = (a->dp[n] >> m) & 0x01;
  91. return r;
  92. }
  93. #endif
  94. u32 Reflect(u32 ref, u8 ch)
  95. {
  96. int i;
  97. u32 value = 0;
  98. for( i = 1; i < ( ch + 1 ); i++ )
  99. {
  100. if( ref & 1 )
  101. value |= 1 << ( ch - i );
  102. ref >>= 1;
  103. }
  104. return value;
  105. }
  106. #ifndef CONFIG_KERNEL_NONE
  107. void tls_crypto_sem_lock(void)
  108. {
  109. if (g_crypto_ctx.gpsec_lock == NULL)
  110. {
  111. return;
  112. }
  113. tls_os_sem_acquire(g_crypto_ctx.gpsec_lock, 0);
  114. }
  115. void tls_crypto_sem_unlock(void)
  116. {
  117. if (g_crypto_ctx.gpsec_lock == NULL)
  118. {
  119. return;
  120. }
  121. tls_os_sem_release(g_crypto_ctx.gpsec_lock);
  122. }
  123. #else
  124. #define tls_crypto_sem_lock
  125. #define tls_crypto_sem_unlock
  126. #endif
  127. void tls_crypto_set_key(void *key, int keylen)
  128. {
  129. uint32_t *key32 = (uint32_t *)key;
  130. int i = 0;
  131. for(i = 0; i < keylen / 4 && i < 6; i++)
  132. {
  133. M32(HR_CRYPTO_KEY0 + (4 * i)) = key32[i];
  134. }
  135. if(keylen == 32)
  136. {
  137. M32(HR_CRYPTO_KEY6) = key32[6];
  138. M32(HR_CRYPTO_KEY7) = key32[7];
  139. }
  140. }
  141. void tls_crypto_set_iv(void *iv, int ivlen)
  142. {
  143. uint32_t *IV32 = (uint32_t *)iv;
  144. if(ivlen >= 8)
  145. {
  146. M32(HR_CRYPTO_IV0) = IV32[0];
  147. M32(HR_CRYPTO_IV0 + 4) = IV32[1];
  148. }
  149. if(ivlen == 16)
  150. {
  151. M32(HR_CRYPTO_IV1) = IV32[2];
  152. M32(HR_CRYPTO_IV1 + 4) = IV32[3];
  153. }
  154. }
  155. /**
  156. * @brief This function is used to stop random produce.
  157. *
  158. * @param[in] None
  159. *
  160. * @retval 0 success
  161. * @retval other failed
  162. *
  163. * @note None
  164. */
  165. int tls_crypto_random_stop(void)
  166. {
  167. unsigned int sec_cfg;
  168. #if USE_TRNG
  169. #else
  170. unsigned int val;
  171. #endif
  172. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  173. #if USE_TRNG
  174. sec_cfg = 0x40;
  175. tls_reg_write32(HR_CRYPTO_TRNG_CR, sec_cfg);
  176. g_crypto_ctx.gpsec_complete = 0;
  177. #else
  178. val = tls_reg_read32(HR_CRYPTO_SEC_CFG);
  179. sec_cfg = val & ~(1 << RNG_START);
  180. tls_reg_write32(HR_CRYPTO_SEC_CFG, sec_cfg);
  181. #endif
  182. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  183. tls_crypto_sem_unlock();
  184. return ERR_CRY_OK;
  185. }
  186. /**
  187. * @brief This function initializes random digit seed and BIT number.
  188. *
  189. * @param[in] seed The random digit seed.
  190. * @param[in] rng_switch The random digit bit number. (0: 16bit 1:32bit)
  191. *
  192. * @retval 0 success
  193. * @retval other failed
  194. *
  195. * @note None
  196. */
  197. int tls_crypto_random_init(u32 seed, CRYPTO_RNG_SWITCH rng_switch)
  198. {
  199. unsigned int sec_cfg;
  200. tls_crypto_sem_lock();
  201. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  202. #if USE_TRNG
  203. sec_cfg = (1 << TRNG_INT_MASK) | (4 << TRNG_CP) | (1 << TRNG_SEL) | (1 << TRNG_EN);
  204. sec_cfg &= ~(1 << TRNG_INT_MASK);
  205. g_crypto_ctx.gpsec_complete = 0;
  206. tls_reg_write32(HR_CRYPTO_TRNG_CR, sec_cfg);
  207. #else
  208. tls_reg_write32(HR_CRYPTO_KEY0, seed);
  209. sec_cfg = (rng_switch << RNG_SWITCH) | (1 << RNG_LOAD_SEED) | (1 << RNG_START);
  210. tls_reg_write32(HR_CRYPTO_SEC_CFG, sec_cfg);
  211. #endif
  212. return ERR_CRY_OK;
  213. }
  214. /**
  215. * @brief This function is used to get random digit content.
  216. *
  217. * @param[in] out Pointer to the output of random digit.
  218. * @param[in] len The random digit bit number will output.
  219. *
  220. * @retval 0 success
  221. * @retval other failed
  222. *
  223. * @note None
  224. */
  225. int tls_crypto_random_bytes(unsigned char *out, u32 len)
  226. {
  227. unsigned int val;
  228. uint32 inLen = len;
  229. int randomBytes = 2;
  230. #if USE_TRNG
  231. delay_cnt(1000);
  232. randomBytes = 4;
  233. #else
  234. val = tls_reg_read32(HR_CRYPTO_SEC_CFG);
  235. randomBytes = val & (1 << RNG_SWITCH) ? 4 : 2;
  236. #endif
  237. while(inLen > 0)
  238. {
  239. #if USE_TRNG
  240. while (!g_crypto_ctx.gpsec_complete)
  241. {
  242. }
  243. g_crypto_ctx.gpsec_complete = 0;
  244. #endif
  245. val = tls_reg_read32(HR_CRYPTO_RNG_RESULT);
  246. if(inLen >= randomBytes)
  247. {
  248. memcpy(out, (char *)&val, randomBytes);
  249. out += randomBytes;
  250. inLen -= randomBytes;
  251. }
  252. else
  253. {
  254. memcpy(out, (char *)&val, inLen);
  255. inLen = 0;
  256. }
  257. }
  258. //tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  259. return ERR_CRY_OK;
  260. }
  261. /**
  262. * @brief This function is used to generate true random number.
  263. *
  264. * @param[in] out Pointer to the output of random number.
  265. * @param[in] len The random number length.
  266. *
  267. * @retval 0 success
  268. * @retval other failed
  269. *
  270. * @note None
  271. */
  272. int tls_crypto_trng(unsigned char *out, u32 len)
  273. {
  274. unsigned int sec_cfg, val;
  275. uint32 inLen = len;
  276. int randomBytes = 4;
  277. tls_crypto_sem_lock();
  278. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  279. sec_cfg = (1 << TRNG_INT_MASK) | (4 << TRNG_CP) | (1 << TRNG_SEL) | (1 << TRNG_EN);
  280. tls_reg_write32(HR_CRYPTO_TRNG_CR, sec_cfg);
  281. sec_cfg &= ~(1 << TRNG_INT_MASK);
  282. tls_reg_write32(HR_CRYPTO_TRNG_CR, sec_cfg);
  283. delay_cnt(1000);
  284. while(inLen > 0)
  285. {
  286. g_crypto_ctx.gpsec_complete = 0;
  287. while (!g_crypto_ctx.gpsec_complete)
  288. {
  289. }
  290. g_crypto_ctx.gpsec_complete = 0;
  291. val = tls_reg_read32(HR_CRYPTO_RNG_RESULT);
  292. if(inLen >= randomBytes)
  293. {
  294. memcpy(out, (char *)&val, randomBytes);
  295. out += randomBytes;
  296. inLen -= randomBytes;
  297. }
  298. else
  299. {
  300. memcpy(out, (char *)&val, inLen);
  301. inLen = 0;
  302. }
  303. }
  304. tls_reg_write32(HR_CRYPTO_TRNG_CR, 0x40);
  305. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  306. tls_crypto_sem_unlock();
  307. return ERR_CRY_OK;
  308. }
  309. int tls_crypto_random_bytes_range(unsigned char *out, u32 len, u32 range)
  310. {
  311. unsigned int val, i;
  312. val = tls_reg_read32(HR_CRYPTO_SEC_CFG);
  313. for(i = 0; i< len; i++) {
  314. val = tls_reg_read32(HR_CRYPTO_RNG_RESULT);
  315. out[i] = val % range;
  316. // printf("rand val:%d, val:%d\r\n", val, out[i]);
  317. }
  318. return ERR_CRY_OK;
  319. }
  320. /**
  321. * @brief This function initializes a RC4 encryption algorithm,
  322. * i.e. fills the psCipherContext_t structure pointed to by ctx with necessary data.
  323. *
  324. * @param[in] ctx Pointer to the Cipher Context.
  325. * @param[in] key Pointer to the key.
  326. * @param[in] keylen the length of key.
  327. *
  328. * @retval 0 success
  329. * @retval other failed
  330. *
  331. * @note The first parameter ctx must be a structure which is allocated externally.
  332. * And all of Context parameters in the initializing methods should be allocated externally too.
  333. */
  334. int tls_crypto_rc4_init(psCipherContext_t *ctx, const unsigned char *key, u32 keylen)
  335. {
  336. if(keylen != 16 && keylen != 32)
  337. {
  338. return ERR_FAILURE;
  339. }
  340. memcpy(ctx->arc4.state, key, keylen);
  341. ctx->arc4.byteCount = keylen;
  342. return ERR_CRY_OK;
  343. }
  344. /**
  345. * @brief This function encrypts a variable length data stream according to RC4.
  346. * The RC4 algorithm it generates a "keystream" which is simply XORed with the plaintext to produce the ciphertext stream.
  347. * Decryption is exactly the same as encryption. This function also decrypts a variable length data stream according to RC4.
  348. *
  349. * @param[in] ctx Pointer to the Cipher Context.
  350. * @param[in] in Pointer to the input plaintext data stream(or the encrypted text data stream) of variable length.
  351. * @param[in] out Pointer to the resulting ciphertext data stream.
  352. * @param[in] len Length of the plaintext data stream in octets.
  353. *
  354. * @retval 0 success
  355. * @retval other failed
  356. *
  357. * @note None
  358. */
  359. int tls_crypto_rc4(psCipherContext_t *ctx, unsigned char *in, unsigned char *out, u32 len)
  360. {
  361. unsigned int sec_cfg;
  362. unsigned char *key = ctx->arc4.state;
  363. u32 keylen = ctx->arc4.byteCount;
  364. tls_crypto_sem_lock();
  365. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  366. tls_crypto_set_key(key, keylen);
  367. tls_reg_write32(HR_CRYPTO_SRC_ADDR, (unsigned int)in);
  368. tls_reg_write32(HR_CRYPTO_DEST_ADDR, (unsigned int)out);
  369. sec_cfg = (CRYPTO_METHOD_RC4 << 16) | (1 << SOFT_RESET_RC4) | (len & 0xFFFF);
  370. if(keylen == 32)
  371. {
  372. sec_cfg |= (1 << 31);
  373. }
  374. tls_reg_write32(HR_CRYPTO_SEC_CFG, sec_cfg);
  375. CRYPTO_LOG("[%d]:rc4[%d] start\n", sys_count, len);
  376. g_crypto_ctx.gpsec_complete = 0;
  377. tls_reg_write32(HR_CRYPTO_SEC_CTRL, 0x1);//start crypto
  378. while (!g_crypto_ctx.gpsec_complete)
  379. {
  380. }
  381. g_crypto_ctx.gpsec_complete = 0;
  382. CRYPTO_LOG("[%d]:rc4 end status: %x\n", sys_count, tls_reg_read32(HR_CRYPTO_SEC_STS));
  383. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  384. tls_crypto_sem_unlock();
  385. return ERR_CRY_OK;
  386. }
  387. /**
  388. * @brief This function initializes a AES encryption algorithm, i.e. fills the psCipherContext_t structure pointed to by ctx with necessary data.
  389. *
  390. * @param[in] ctx Pointer to the Cipher Context.
  391. * @param[in] IV Pointer to the Initialization Vector
  392. * @param[in] key Pointer to the key.
  393. * @param[in] keylen the length of key.
  394. * @param[in] cbc the encryption mode, AES supports ECB/CBC/CTR modes.
  395. *
  396. * @retval 0 success
  397. * @retval other failed
  398. *
  399. * @note None
  400. */
  401. int tls_crypto_aes_init(psCipherContext_t *ctx, const unsigned char *IV, const unsigned char *key, u32 keylen, CRYPTO_MODE cbc)
  402. {
  403. int x = 0;
  404. if (keylen != 16)
  405. return ERR_FAILURE;
  406. memcpy(ctx->aes.key.skey, key, keylen);
  407. ctx->aes.key.type = cbc;
  408. ctx->aes.key.rounds = 16;
  409. if(IV)
  410. {
  411. for (x = 0; x < ctx->aes.key.rounds; x++)
  412. {
  413. ctx->aes.IV[x] = IV[x];
  414. }
  415. }
  416. return ERR_CRY_OK;
  417. }
  418. /**
  419. * @brief This function encrypts or decrypts a variable length data stream according to AES.
  420. *
  421. * @param[in] ctx Pointer to the Cipher Context.
  422. * @param[in] in Pointer to the input plaintext data stream(or the encrypted text data stream) of variable length.
  423. * @param[in] out Pointer to the resulting ciphertext data stream.
  424. * @param[in] len Length of the plaintext data stream in octets.
  425. * @param[in] dec The cryption way which indicates encryption or decryption.
  426. *
  427. * @retval 0 success
  428. * @retval other failed
  429. *
  430. * @note None
  431. */
  432. int tls_crypto_aes_encrypt_decrypt(psCipherContext_t *ctx, unsigned char *in, unsigned char *out, u32 len, CRYPTO_WAY dec)
  433. {
  434. unsigned int sec_cfg;
  435. u32 keylen = 16;
  436. unsigned char *key = (unsigned char *)ctx->aes.key.skey;
  437. unsigned char *IV = ctx->aes.IV;
  438. CRYPTO_MODE cbc = (CRYPTO_MODE)(ctx->aes.key.type & 0xFF);
  439. tls_crypto_sem_lock();
  440. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  441. tls_crypto_set_key(key, keylen);
  442. tls_crypto_set_iv(IV, 16);
  443. tls_reg_write32(HR_CRYPTO_SRC_ADDR, (unsigned int)in);
  444. tls_reg_write32(HR_CRYPTO_DEST_ADDR, (unsigned int)out);
  445. sec_cfg = (CRYPTO_METHOD_AES << 16) | (1 << SOFT_RESET_AES) | (dec << 20) | (cbc << 21) | (len & 0xFFFF);
  446. tls_reg_write32(HR_CRYPTO_SEC_CFG, sec_cfg);
  447. CRYPTO_LOG("[%d]:aes[%d] %s %s start\n", sys_count, len, dec == CRYPTO_WAY_ENCRYPT ? "ENCRYPT" : "DECRYPT",
  448. cbc == CRYPTO_MODE_ECB ? "ECB" : (cbc == CRYPTO_MODE_CBC ? "CBC" : (cbc == CRYPTO_MODE_CTR ? "CTR" : "MAC")));
  449. g_crypto_ctx.gpsec_complete = 0;
  450. tls_reg_write32(HR_CRYPTO_SEC_CTRL, 0x1);//start crypto
  451. while (!g_crypto_ctx.gpsec_complete)
  452. {
  453. }
  454. g_crypto_ctx.gpsec_complete = 0;
  455. CRYPTO_LOG("[%d]:aes end %d\n", sys_count, tls_reg_read32(HR_CRYPTO_SEC_STS) & 0xFFFF);
  456. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  457. tls_crypto_sem_unlock();
  458. return ERR_CRY_OK;
  459. }
  460. /**
  461. * @brief This function initializes a 3DES encryption algorithm, i.e. fills the psCipherContext_t structure pointed to by ctx with necessary data.
  462. *
  463. * @param[in] ctx Pointer to the Cipher Context.
  464. * @param[in] IV Pointer to the Initialization Vector
  465. * @param[in] key Pointer to the key.
  466. * @param[in] keylen the length of key.
  467. * @param[in] cbc the encryption mode, 3DES supports ECB/CBC modes.
  468. *
  469. * @retval 0 success
  470. * @retval other failed
  471. *
  472. * @note None
  473. */
  474. int tls_crypto_3des_init(psCipherContext_t *ctx, const unsigned char *IV, const unsigned char *key, u32 keylen, CRYPTO_MODE cbc)
  475. {
  476. unsigned int x;
  477. if (keylen != DES3_KEY_LEN)
  478. return ERR_FAILURE;
  479. memcpy(ctx->des3.key.ek[0], key, keylen);
  480. ctx->des3.key.ek[1][0] = cbc;
  481. ctx->des3.blocklen = DES3_IV_LEN;
  482. if(IV)
  483. {
  484. for (x = 0; x < ctx->des3.blocklen; x++)
  485. {
  486. ctx->des3.IV[x] = IV[x];
  487. }
  488. }
  489. return ERR_CRY_OK;
  490. }
  491. /**
  492. * @brief This function encrypts or decrypts a variable length data stream according to 3DES.
  493. *
  494. * @param[in] ctx Pointer to the Cipher Context.
  495. * @param[in] in Pointer to the input plaintext data stream(or the encrypted text data stream) of variable length.
  496. * @param[in] out Pointer to the resulting ciphertext data stream.
  497. * @param[in] len Length of the plaintext data stream in octets.
  498. * @param[in] dec The cryption way which indicates encryption or decryption.
  499. *
  500. * @retval 0 success
  501. * @retval other failed
  502. *
  503. * @note None
  504. */
  505. int tls_crypto_3des_encrypt_decrypt(psCipherContext_t *ctx, unsigned char *in, unsigned char *out, u32 len, CRYPTO_WAY dec)
  506. {
  507. unsigned int sec_cfg;
  508. u32 keylen = DES3_KEY_LEN;
  509. unsigned char *key = (unsigned char *)(unsigned char *)ctx->des3.key.ek[0];
  510. unsigned char *IV = ctx->des3.IV;
  511. CRYPTO_MODE cbc = (CRYPTO_MODE)(ctx->des3.key.ek[1][0] & 0xFF);
  512. tls_crypto_sem_lock();
  513. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  514. tls_crypto_set_key(key, keylen);
  515. tls_crypto_set_iv(IV, DES3_IV_LEN);
  516. tls_reg_write32(HR_CRYPTO_SRC_ADDR, (unsigned int)in);
  517. tls_reg_write32(HR_CRYPTO_DEST_ADDR, (unsigned int)out);
  518. sec_cfg = (CRYPTO_METHOD_3DES << 16) | (1 << SOFT_RESET_DES) | (dec << 20) | (cbc << 21) | (len & 0xFFFF);
  519. tls_reg_write32(HR_CRYPTO_SEC_CFG, sec_cfg);
  520. CRYPTO_LOG("[%d]:3des[%d] %s %s start\n", sys_count, len, dec == CRYPTO_WAY_ENCRYPT ? "ENCRYPT" : "DECRYPT",
  521. cbc == CRYPTO_MODE_ECB ? "ECB" : "CBC");
  522. g_crypto_ctx.gpsec_complete = 0;
  523. tls_reg_write32(HR_CRYPTO_SEC_CTRL, 0x1);//start crypto
  524. while (!g_crypto_ctx.gpsec_complete)
  525. {
  526. }
  527. g_crypto_ctx.gpsec_complete = 0;
  528. CRYPTO_LOG("[%d]:3des end %d\n", sys_count, tls_reg_read32(HR_CRYPTO_SEC_STS) & 0xFFFF);
  529. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  530. tls_crypto_sem_unlock();
  531. return ERR_CRY_OK;
  532. }
  533. /**
  534. * @brief This function initializes a DES encryption algorithm, i.e. fills the psCipherContext_t structure pointed to by ctx with necessary data.
  535. *
  536. * @param[in] ctx Pointer to the Cipher Context.
  537. * @param[in] IV Pointer to the Initialization Vector
  538. * @param[in] key Pointer to the key.
  539. * @param[in] keylen the length of key.
  540. * @param[in] cbc the encryption mode, DES supports ECB/CBC modes.
  541. *
  542. * @retval 0 success
  543. * @retval other failed
  544. *
  545. * @note None
  546. */
  547. int tls_crypto_des_init(psCipherContext_t *ctx, const unsigned char *IV, const unsigned char *key, u32 keylen, CRYPTO_MODE cbc)
  548. {
  549. unsigned int x;
  550. if (keylen != DES_KEY_LEN)
  551. return ERR_FAILURE;
  552. memcpy(ctx->des3.key.ek[0], key, keylen);
  553. ctx->des3.key.ek[1][0] = cbc;
  554. ctx->des3.blocklen = DES3_IV_LEN;
  555. if(IV)
  556. {
  557. for (x = 0; x < ctx->des3.blocklen; x++)
  558. {
  559. ctx->des3.IV[x] = IV[x];
  560. }
  561. }
  562. return ERR_CRY_OK;
  563. }
  564. /**
  565. * @brief This function encrypts or decrypts a variable length data stream according to DES.
  566. *
  567. * @param[in] ctx Pointer to the Cipher Context.
  568. * @param[in] in Pointer to the input plaintext data stream(or the encrypted text data stream) of variable length.
  569. * @param[in] out Pointer to the resulting ciphertext data stream.
  570. * @param[in] len Length of the plaintext data stream in octets.
  571. * @param[in] dec The cryption way which indicates encryption or decryption.
  572. *
  573. * @retval 0 success
  574. * @retval other failed
  575. *
  576. * @note None
  577. */
  578. int tls_crypto_des_encrypt_decrypt(psCipherContext_t *ctx, unsigned char *in, unsigned char *out, u32 len, CRYPTO_WAY dec)
  579. {
  580. unsigned int sec_cfg;
  581. u32 keylen = DES_KEY_LEN;
  582. unsigned char *key = (unsigned char *)ctx->des3.key.ek[0];
  583. unsigned char *IV = ctx->des3.IV;
  584. CRYPTO_MODE cbc = (CRYPTO_MODE)(ctx->des3.key.ek[1][0] & 0xFF);
  585. //uint32_t *IV32 = (uint32_t *)IV;
  586. tls_crypto_sem_lock();
  587. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  588. tls_crypto_set_key(key, keylen);
  589. tls_crypto_set_iv(IV, DES3_IV_LEN);
  590. tls_reg_write32(HR_CRYPTO_SRC_ADDR, (unsigned int)in);
  591. tls_reg_write32(HR_CRYPTO_DEST_ADDR, (unsigned int)out);
  592. sec_cfg = (CRYPTO_METHOD_DES << 16) | (1 << SOFT_RESET_DES) | (dec << 20) | (cbc << 21) | (len & 0xFFFF);
  593. tls_reg_write32(HR_CRYPTO_SEC_CFG, sec_cfg);
  594. CRYPTO_LOG("[%d]:des[%d] %s %s start\n", sys_count, len, dec == CRYPTO_WAY_ENCRYPT ? "ENCRYPT" : "DECRYPT",
  595. cbc == CRYPTO_MODE_ECB ? "ECB" : "CBC");
  596. g_crypto_ctx.gpsec_complete = 0;
  597. tls_reg_write32(HR_CRYPTO_SEC_CTRL, 0x1);//start crypto
  598. while (!g_crypto_ctx.gpsec_complete)
  599. {
  600. }
  601. g_crypto_ctx.gpsec_complete = 0;
  602. CRYPTO_LOG("[%d]:des end %d\n", sys_count, tls_reg_read32(HR_CRYPTO_SEC_STS) & 0xFFFF);
  603. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  604. tls_crypto_sem_unlock();
  605. return ERR_CRY_OK;
  606. }
  607. /**
  608. * @brief This function initializes a CRC algorithm, i.e. fills the psCrcContext_t structure pointed to by ctx with necessary data.
  609. *
  610. * @param[in] ctx Pointer to the CRC Context.
  611. * @param[in] key The initialization key.
  612. * @param[in] crc_type The CRC type, supports CRC8/CRC16 MODBUS/CRC16 CCITT/CRC32
  613. * @param[in] mode Set input or outpu reflect.
  614. * @param[in] dec The cryption way which indicates encryption or decryption.
  615. * see OUTPUT_REFLECT
  616. * see INPUT_REFLECT
  617. *
  618. * @retval 0 success
  619. * @retval other failed
  620. *
  621. * @note None
  622. */
  623. int tls_crypto_crc_init(psCrcContext_t *ctx, u32 key, CRYPTO_CRC_TYPE crc_type, u8 mode)
  624. {
  625. ctx->state = key;
  626. ctx->type = crc_type;
  627. ctx->mode = mode;
  628. return ERR_CRY_OK;
  629. }
  630. /**
  631. * @brief This function updates the CRC value with a variable length bytes.
  632. * This function may be called as many times as necessary, so the message may be processed in blocks.
  633. *
  634. * @param[in] ctx Pointer to the CRC Context.
  635. * @param[in] in Pointer to a variable length bytes
  636. * @param[in] len The bytes 's length
  637. *
  638. * @retval 0 success
  639. * @retval other failed
  640. *
  641. * @note None
  642. */
  643. int tls_crypto_crc_update(psCrcContext_t *ctx, unsigned char *in, u32 len)
  644. {
  645. unsigned int sec_cfg;
  646. tls_crypto_sem_lock();
  647. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  648. sec_cfg = (CRYPTO_METHOD_CRC << 16) | (ctx->type << 21) | (ctx->mode << 23) | (len & 0xFFFF);
  649. tls_reg_write32(HR_CRYPTO_SEC_CFG, sec_cfg);
  650. if(ctx->mode & OUTPUT_REFLECT)
  651. {
  652. u8 ch_crc = 16;
  653. u32 state = 0;
  654. switch(ctx->type)
  655. {
  656. case CRYPTO_CRC_TYPE_8:
  657. ch_crc = 8;
  658. break;
  659. case CRYPTO_CRC_TYPE_16_MODBUS:
  660. ch_crc = 16;
  661. break;
  662. case CRYPTO_CRC_TYPE_16_CCITT:
  663. ch_crc = 16;
  664. break;
  665. case CRYPTO_CRC_TYPE_32:
  666. ch_crc = 32;
  667. break;
  668. default:
  669. break;
  670. }
  671. state = Reflect(ctx->state, ch_crc);
  672. tls_reg_write32(HR_CRYPTO_CRC_KEY, state);
  673. }
  674. else
  675. tls_reg_write32(HR_CRYPTO_CRC_KEY, ctx->state);
  676. tls_reg_write32(HR_CRYPTO_SRC_ADDR, (unsigned int)in);
  677. g_crypto_ctx.gpsec_complete = 0;
  678. tls_reg_write32(HR_CRYPTO_SEC_CTRL, 0x1);//start crypto
  679. while (!g_crypto_ctx.gpsec_complete)
  680. {
  681. }
  682. g_crypto_ctx.gpsec_complete = 0;
  683. ctx->state = tls_reg_read32(HR_CRYPTO_CRC_RESULT);
  684. tls_reg_write32(HR_CRYPTO_SEC_CTRL, 0x4);//clear crc fifo
  685. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  686. tls_crypto_sem_unlock();
  687. return ERR_CRY_OK;
  688. }
  689. /**
  690. * @brief This function ends a CRC operation and produces a CRC value.
  691. *
  692. * @param[in] ctx Pointer to the CRC Context.
  693. * @param[in] crc_val Pointer to the CRC value.
  694. *
  695. * @retval 0 success
  696. * @retval other failed
  697. *
  698. * @note None
  699. */
  700. int tls_crypto_crc_final(psCrcContext_t *ctx, u32 *crc_val)
  701. {
  702. *crc_val = ctx->state;
  703. return ERR_CRY_OK;
  704. }
  705. static void hd_sha1_compress(psDigestContext_t *md)
  706. {
  707. unsigned int sec_cfg, val;
  708. int i = 0;
  709. tls_crypto_sem_lock();
  710. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  711. tls_reg_write32(HR_CRYPTO_SRC_ADDR, (unsigned int)md->u.sha1.buf);
  712. sec_cfg = (CRYPTO_METHOD_SHA1 << 16) | (64 & 0xFFFF); // TODO
  713. tls_reg_write32(HR_CRYPTO_SEC_CFG, sec_cfg);
  714. tls_reg_write32(HR_CRYPTO_SHA1_DIGEST0, md->u.sha1.state[0]);
  715. tls_reg_write32(HR_CRYPTO_SHA1_DIGEST1, md->u.sha1.state[1]);
  716. tls_reg_write32(HR_CRYPTO_SHA1_DIGEST2, md->u.sha1.state[2]);
  717. tls_reg_write32(HR_CRYPTO_SHA1_DIGEST3, md->u.sha1.state[3]);
  718. tls_reg_write32(HR_CRYPTO_SHA1_DIGEST4, md->u.sha1.state[4]);
  719. g_crypto_ctx.gpsec_complete = 0;
  720. tls_reg_write32(HR_CRYPTO_SEC_CTRL, 0x1);//start crypto
  721. while (!g_crypto_ctx.gpsec_complete)
  722. {
  723. }
  724. g_crypto_ctx.gpsec_complete = 0;
  725. for (i = 0; i < 5; i++)
  726. {
  727. val = tls_reg_read32(HR_CRYPTO_SHA1_DIGEST0 + (4 * i));
  728. md->u.sha1.state[i] = val;
  729. }
  730. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  731. tls_crypto_sem_unlock();
  732. }
  733. /**
  734. * @brief This function initializes Message-Diggest context for usage in SHA1 algorithm, starts a new SHA1 operation and writes a new Digest Context.
  735. *
  736. * @param[in] md Pointer to the SHA1 Digest Context.
  737. *
  738. * @retval 0 success
  739. * @retval other failed
  740. *
  741. * @note None
  742. */
  743. void tls_crypto_sha1_init(psDigestContext_t *md)
  744. {
  745. md->u.sha1.state[0] = 0x67452301UL;
  746. md->u.sha1.state[1] = 0xefcdab89UL;
  747. md->u.sha1.state[2] = 0x98badcfeUL;
  748. md->u.sha1.state[3] = 0x10325476UL;
  749. md->u.sha1.state[4] = 0xc3d2e1f0UL;
  750. md->u.sha1.curlen = 0;
  751. #ifdef HAVE_NATIVE_INT64
  752. md->u.sha1.length = 0;
  753. #else
  754. md->u.sha1.lengthHi = 0;
  755. md->u.sha1.lengthLo = 0;
  756. #endif /* HAVE_NATIVE_INT64 */
  757. }
  758. /**
  759. * @brief Process a message block using SHA1 algorithm.
  760. * This function performs a SHA1 block update operation. It continues an SHA1 message-digest operation,
  761. * by processing InputLen-byte length message block pointed to by buf, and by updating the SHA1 context pointed to by md.
  762. * This function may be called as many times as necessary, so the message may be processed in blocks.
  763. *
  764. * @param[in] md Pointer to the SHA1 Digest Context.
  765. * @param[in] buf InputLen-byte length message block
  766. * @param[in] len The buf 's length
  767. *
  768. * @returnl None
  769. *
  770. * @note None
  771. */
  772. void tls_crypto_sha1_update(psDigestContext_t *md, const unsigned char *buf, u32 len)
  773. {
  774. u32 n;
  775. while (len > 0)
  776. {
  777. n = min(len, (64 - md->u.sha1.curlen));
  778. memcpy(md->u.sha1.buf + md->u.sha1.curlen, buf, (size_t)n);
  779. md->u.sha1.curlen += n;
  780. buf += n;
  781. len -= n;
  782. /* is 64 bytes full? */
  783. if (md->u.sha1.curlen == 64)
  784. {
  785. hd_sha1_compress(md);
  786. #ifdef HAVE_NATIVE_INT64
  787. md->u.sha1.length += 512;
  788. #else
  789. n = (md->u.sha1.lengthLo + 512) & 0xFFFFFFFFL;
  790. if (n < md->u.sha1.lengthLo)
  791. {
  792. md->u.sha1.lengthHi++;
  793. }
  794. md->u.sha1.lengthLo = n;
  795. #endif /* HAVE_NATIVE_INT64 */
  796. md->u.sha1.curlen = 0;
  797. }
  798. }
  799. }
  800. /**
  801. * @brief This function ends a SHA1 operation and produces a Message-Digest.
  802. * This function finalizes SHA1 algorithm, i.e. ends an SHA1 Message-Digest operation,
  803. * writing the Message-Digest in the 20-byte buffer pointed to by hash in according to the information stored in context.
  804. *
  805. * @param[in] md Pointer to the SHA1 Digest Context.
  806. * @param[in] hash Pointer to the Message-Digest
  807. *
  808. * @retval 20 success, return the hash size.
  809. * @retval <0 failed
  810. *
  811. * @note None
  812. */
  813. int tls_crypto_sha1_final(psDigestContext_t *md, unsigned char *hash)
  814. {
  815. s32 i;
  816. u32 val;
  817. #ifndef HAVE_NATIVE_INT64
  818. u32 n;
  819. #endif
  820. if (md->u.sha1.curlen >= sizeof(md->u.sha1.buf) || hash == NULL)
  821. {
  822. return ERR_ARG_FAIL;
  823. }
  824. /*
  825. increase the length of the message
  826. */
  827. #ifdef HAVE_NATIVE_INT64
  828. md->u.sha1.length += md->u.sha1.curlen << 3;
  829. #else
  830. n = (md->u.sha1.lengthLo + (md->u.sha1.curlen << 3)) & 0xFFFFFFFFL;
  831. if (n < md->u.sha1.lengthLo)
  832. {
  833. md->u.sha1.lengthHi++;
  834. }
  835. md->u.sha1.lengthHi += (md->u.sha1.curlen >> 29);
  836. md->u.sha1.lengthLo = n;
  837. #endif /* HAVE_NATIVE_INT64 */
  838. /*
  839. append the '1' bit
  840. */
  841. md->u.sha1.buf[md->u.sha1.curlen++] = (unsigned char)0x80;
  842. /*
  843. if the length is currently above 56 bytes we append zeros then compress.
  844. Then we can fall back to padding zeros and length encoding like normal.
  845. */
  846. if (md->u.sha1.curlen > 56)
  847. {
  848. while (md->u.sha1.curlen < 64)
  849. {
  850. md->u.sha1.buf[md->u.sha1.curlen++] = (unsigned char)0;
  851. }
  852. hd_sha1_compress(md);
  853. md->u.sha1.curlen = 0;
  854. }
  855. /*
  856. pad upto 56 bytes of zeroes
  857. */
  858. while (md->u.sha1.curlen < 56)
  859. {
  860. md->u.sha1.buf[md->u.sha1.curlen++] = (unsigned char)0;
  861. }
  862. /*
  863. store length
  864. */
  865. #ifdef HAVE_NATIVE_INT64
  866. STORE64H(md->u.sha1.length, md->u.sha1.buf + 56);
  867. #else
  868. STORE32H(md->u.sha1.lengthHi, md->u.sha1.buf + 56);
  869. STORE32H(md->u.sha1.lengthLo, md->u.sha1.buf + 60);
  870. #endif /* HAVE_NATIVE_INT64 */
  871. hd_sha1_compress(md);
  872. /*
  873. copy output
  874. */
  875. for (i = 0; i < 5; i++)
  876. {
  877. val = tls_reg_read32(HR_CRYPTO_SHA1_DIGEST0 + (4 * i));
  878. STORE32H(val, hash + (4 * i));
  879. }
  880. memset(md, 0x0, sizeof(psSha1_t));
  881. return SHA1_HASH_SIZE;
  882. }
  883. static void hd_md5_compress(psDigestContext_t *md)
  884. {
  885. unsigned int sec_cfg, val, i;
  886. tls_crypto_sem_lock();
  887. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  888. tls_reg_write32(HR_CRYPTO_SRC_ADDR, (unsigned int)md->u.md5.buf);
  889. sec_cfg = (CRYPTO_METHOD_MD5 << 16) | (64 & 0xFFFF);
  890. tls_reg_write32(HR_CRYPTO_SEC_CFG, sec_cfg);
  891. tls_reg_write32(HR_CRYPTO_SHA1_DIGEST0, md->u.md5.state[0]);
  892. tls_reg_write32(HR_CRYPTO_SHA1_DIGEST1, md->u.md5.state[1]);
  893. tls_reg_write32(HR_CRYPTO_SHA1_DIGEST2, md->u.md5.state[2]);
  894. tls_reg_write32(HR_CRYPTO_SHA1_DIGEST3, md->u.md5.state[3]);
  895. g_crypto_ctx.gpsec_complete = 0;
  896. tls_reg_write32(HR_CRYPTO_SEC_CTRL, 0x1);//start crypto
  897. while (!g_crypto_ctx.gpsec_complete)
  898. {
  899. }
  900. g_crypto_ctx.gpsec_complete = 0;
  901. for (i = 0; i < 4; i++)
  902. {
  903. val = tls_reg_read32(HR_CRYPTO_SHA1_DIGEST0 + (4 * i));
  904. md->u.md5.state[i] = val;
  905. }
  906. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_GPSEC);
  907. tls_crypto_sem_unlock();
  908. }
  909. /**
  910. * @brief This function initializes Message-Diggest context for usage in MD5 algorithm, starts a new MD5 operation and writes a new Digest Context.
  911. * This function begins a MD5 Message-Diggest Algorithm, i.e. fills the psDigestContext_t structure pointed to by md with necessary data.
  912. * MD5 is the algorithm which takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input.
  913. * It is conjectured that it is computationally infeasible to produce two messages having the same message digest,
  914. * or to produce any message having a given prespecified target message digest.
  915. *
  916. * @param[in] md MD5 Digest Context.
  917. *
  918. * @return None
  919. *
  920. * @note None
  921. */
  922. void tls_crypto_md5_init(psDigestContext_t *md)
  923. {
  924. md->u.md5.state[0] = 0x67452301UL;
  925. md->u.md5.state[1] = 0xefcdab89UL;
  926. md->u.md5.state[2] = 0x98badcfeUL;
  927. md->u.md5.state[3] = 0x10325476UL;
  928. md->u.md5.curlen = 0;
  929. #ifdef HAVE_NATIVE_INT64
  930. md->u.md5.length = 0;
  931. #else
  932. md->u.md5.lengthHi = 0;
  933. md->u.md5.lengthLo = 0;
  934. #endif /* HAVE_NATIVE_INT64 */
  935. }
  936. /**
  937. * @brief Process a message block using MD5 algorithm.
  938. * This function performs a MD5 block update operation. It continues an MD5 message-digest operation,
  939. * by processing InputLen-byte length message block pointed to by buf, and by updating the MD5 context pointed to by md.
  940. * This function may be called as many times as necessary, so the message may be processed in blocks.
  941. *
  942. * @param[in] md MD5 Digest Context.
  943. * @param[in] buf InputLen-byte length message block
  944. * @param[in] len The buf 's length
  945. *
  946. * @return None
  947. *
  948. * @note None
  949. */
  950. void tls_crypto_md5_update(psDigestContext_t *md, const unsigned char *buf, u32 len)
  951. {
  952. u32 n;
  953. while (len > 0)
  954. {
  955. n = min(len, (64 - md->u.md5.curlen));
  956. memcpy(md->u.md5.buf + md->u.md5.curlen, buf, (size_t)n);
  957. md->u.md5.curlen += n;
  958. buf += n;
  959. len -= n;
  960. /*
  961. is 64 bytes full?
  962. */
  963. if (md->u.md5.curlen == 64)
  964. {
  965. hd_md5_compress(md);
  966. #ifdef HAVE_NATIVE_INT64
  967. md->u.md5.length += 512;
  968. #else
  969. n = (md->u.md5.lengthLo + 512) & 0xFFFFFFFFL;
  970. if (n < md->u.md5.lengthLo)
  971. {
  972. md->u.md5.lengthHi++;
  973. }
  974. md->u.md5.lengthLo = n;
  975. #endif /* HAVE_NATIVE_INT64 */
  976. md->u.md5.curlen = 0;
  977. }
  978. }
  979. }
  980. /**
  981. * @brief This function ends a MD5 operation and produces a Message-Digest.
  982. * This function finalizes MD5 algorithm, i.e. ends an MD5 Message-Digest operation,
  983. * writing the Message-Digest in the 16-byte buffer pointed to by hash in according to the information stored in context.
  984. *
  985. * @param[in] md MD5 Digest Context.
  986. * @param[in] hash the Message-Digest
  987. *
  988. * @retval 16 success, return the hash size.
  989. * @retval <0 failed
  990. *
  991. * @note None
  992. */
  993. s32 tls_crypto_md5_final(psDigestContext_t *md, unsigned char *hash)
  994. {
  995. s32 i;
  996. u32 val;
  997. #ifndef HAVE_NATIVE_INT64
  998. u32 n;
  999. #endif
  1000. // psAssert(md != NULL);
  1001. if (hash == NULL)
  1002. {
  1003. CRYPTO_LOG("NULL hash storage passed to psMd5Final\n");
  1004. return PS_ARG_FAIL;
  1005. }
  1006. /*
  1007. increase the length of the message
  1008. */
  1009. #ifdef HAVE_NATIVE_INT64
  1010. md->u.md5.length += md->u.md5.curlen << 3;
  1011. #else
  1012. n = (md->u.md5.lengthLo + (md->u.md5.curlen << 3)) & 0xFFFFFFFFL;
  1013. if (n < md->u.md5.lengthLo)
  1014. {
  1015. md->u.md5.lengthHi++;
  1016. }
  1017. md->u.md5.lengthHi += (md->u.md5.curlen >> 29);
  1018. md->u.md5.lengthLo = n;
  1019. #endif /* HAVE_NATIVE_INT64 */
  1020. /*
  1021. append the '1' bit
  1022. */
  1023. md->u.md5.buf[md->u.md5.curlen++] = (unsigned char)0x80;
  1024. /*
  1025. if the length is currently above 56 bytes we append zeros then compress.
  1026. Then we can fall back to padding zeros and length encoding like normal.
  1027. */
  1028. if (md->u.md5.curlen > 56)
  1029. {
  1030. while (md->u.md5.curlen < 64)
  1031. {
  1032. md->u.md5.buf[md->u.md5.curlen++] = (unsigned char)0;
  1033. }
  1034. hd_md5_compress(md);
  1035. md->u.md5.curlen = 0;
  1036. }
  1037. /*
  1038. pad upto 56 bytes of zeroes
  1039. */
  1040. while (md->u.md5.curlen < 56)
  1041. {
  1042. md->u.md5.buf[md->u.md5.curlen++] = (unsigned char)0;
  1043. }
  1044. /*
  1045. store length
  1046. */
  1047. #ifdef HAVE_NATIVE_INT64
  1048. STORE64L(md->u.md5.length, md->u.md5.buf + 56);
  1049. #else
  1050. STORE32L(md->u.md5.lengthLo, md->u.md5.buf + 56);
  1051. STORE32L(md->u.md5.lengthHi, md->u.md5.buf + 60);
  1052. #endif /* HAVE_NATIVE_INT64 */
  1053. hd_md5_compress(md);
  1054. /*
  1055. copy output
  1056. */
  1057. for (i = 0; i < 4; i++)
  1058. {
  1059. val = tls_reg_read32(HR_CRYPTO_SHA1_DIGEST0 + (4 * i));
  1060. STORE32L(val, hash + (4 * i));
  1061. }
  1062. memset(md, 0x0, sizeof(psMd5_t));
  1063. return MD5_HASH_SIZE;
  1064. }
  1065. static void rsaMonMulSetLen(const u32 len)
  1066. {
  1067. RSAN = len;
  1068. }
  1069. static void rsaMonMulWriteMc(const u32 mc)
  1070. {
  1071. u32 val = 0;
  1072. RSAMC = mc;
  1073. val = RSAMC;
  1074. if(val == mc)
  1075. {
  1076. val = 1;
  1077. return;
  1078. }
  1079. }
  1080. static void rsaMonMulWriteA(const u32 *const in)
  1081. {
  1082. memcpy((u32 *)&RSAXBUF, in, RSAN * sizeof(u32));
  1083. }
  1084. static void rsaMonMulWriteB(const u32 *const in)
  1085. {
  1086. memcpy((u32 *)&RSAYBUF, in, RSAN * sizeof(u32));
  1087. }
  1088. static void rsaMonMulWriteM(const u32 *const in)
  1089. {
  1090. memcpy((u32 *)&RSAMBUF, in, RSAN * sizeof(u32));
  1091. }
  1092. static void rsaMonMulReadA(u32 *const in)
  1093. {
  1094. memcpy(in, (u32 *)&RSAXBUF, RSAN * sizeof(u32));
  1095. }
  1096. static void rsaMonMulReadB(u32 *const in)
  1097. {
  1098. memcpy(in, (u32 *)&RSAYBUF, RSAN * sizeof(u32));
  1099. }
  1100. static void rsaMonMulReadD(u32 *const in)
  1101. {
  1102. memcpy(in, (u32 *)&RSADBUF, RSAN * sizeof(u32));
  1103. }
  1104. static int rsaMulModRead(unsigned char w, hstm_int *a)
  1105. {
  1106. u32 in[64];
  1107. int err = 0;
  1108. memset(in, 0, 64 * sizeof(u32));
  1109. switch(w)
  1110. {
  1111. case 'A':
  1112. rsaMonMulReadA(in);
  1113. break;
  1114. case 'B':
  1115. rsaMonMulReadB(in);
  1116. break;
  1117. case 'D':
  1118. rsaMonMulReadD(in);
  1119. break;
  1120. }
  1121. pstm_reverse((unsigned char *)in, RSAN * sizeof(u32));
  1122. /* this a should be initialized outside. */
  1123. //if ((err = pstm_init_for_read_unsigned_bin(NULL, a, RSAN * sizeof(u32) + sizeof(hstm_int))) != ERR_CRY_OK){
  1124. // return err;
  1125. //}
  1126. if ((err = pstm_read_unsigned_bin(a, (unsigned char *)in, RSAN * sizeof(u32))) != ERR_CRY_OK)
  1127. {
  1128. pstm_clear(a);
  1129. return err;
  1130. }
  1131. return 0;
  1132. }
  1133. #if 0
  1134. static void rsaMulModDump(unsigned char w)
  1135. {
  1136. extern void dumpUint32(char *name, uint32_t* buffer, int len);
  1137. int addr = 0;
  1138. switch(w)
  1139. {
  1140. case 'A':
  1141. addr = 0;
  1142. break;
  1143. case 'B':
  1144. addr = 0x100;
  1145. break;
  1146. case 'D':
  1147. addr = 0x300;
  1148. break;
  1149. }
  1150. printf("%c", w);
  1151. dumpUint32(" Val:",((volatile u32*) (RSA_BASE_ADDRESS + addr )), RSAN);
  1152. }
  1153. #endif
  1154. static void rsaMulModWrite(unsigned char w, hstm_int *a)
  1155. {
  1156. u32 in[64];
  1157. memset(in, 0, 64 * sizeof(u32));
  1158. pstm_to_unsigned_bin_nr(NULL, a, (unsigned char *)in);
  1159. switch(w)
  1160. {
  1161. case 'A':
  1162. rsaMonMulWriteA(in);
  1163. break;
  1164. case 'B':
  1165. rsaMonMulWriteB(in);
  1166. break;
  1167. case 'M':
  1168. rsaMonMulWriteM(in);
  1169. break;
  1170. }
  1171. }
  1172. static void rsaMonMulAA(void)
  1173. {
  1174. g_crypto_ctx.rsa_complete = 0;
  1175. RSACON = 0x2c;
  1176. while (!g_crypto_ctx.rsa_complete)
  1177. {
  1178. }
  1179. g_crypto_ctx.rsa_complete = 0;
  1180. }
  1181. static void rsaMonMulDD(void)
  1182. {
  1183. g_crypto_ctx.rsa_complete = 0;
  1184. RSACON = 0x20;
  1185. while (!g_crypto_ctx.rsa_complete)
  1186. {
  1187. }
  1188. g_crypto_ctx.rsa_complete = 0;
  1189. }
  1190. static void rsaMonMulAB(void)
  1191. {
  1192. g_crypto_ctx.rsa_complete = 0;
  1193. RSACON = 0x24;
  1194. while (!g_crypto_ctx.rsa_complete)
  1195. {
  1196. }
  1197. g_crypto_ctx.rsa_complete = 0;
  1198. }
  1199. static void rsaMonMulBD(void)
  1200. {
  1201. g_crypto_ctx.rsa_complete = 0;
  1202. RSACON = 0x28;
  1203. while (!g_crypto_ctx.rsa_complete)
  1204. {
  1205. }
  1206. g_crypto_ctx.rsa_complete = 0;
  1207. }
  1208. /******************************************************************************
  1209. compute mc, s.t. mc * in = 0xffffffff
  1210. ******************************************************************************/
  1211. static void rsaCalMc(u32 *mc, const u32 in)
  1212. {
  1213. u32 y = 1;
  1214. u32 i = 31;
  1215. u32 left = 1;
  1216. u32 right = 0;
  1217. for(i = 31; i != 0; i--)
  1218. {
  1219. left <<= 1; /* 2^(i-1) */
  1220. right = (in * y) & left; /* (n*y) mod 2^i */
  1221. if( right )
  1222. {
  1223. y += left;
  1224. }
  1225. }
  1226. *mc = ~y + 1;
  1227. }
  1228. /**
  1229. * @brief This function implements the large module power multiplication algorithm.
  1230. * res = a**e (mod n)
  1231. *
  1232. * @param[in] a Pointer to a bignumber.
  1233. * @param[in] e Pointer to a bignumber.
  1234. * @param[in] n Pointer to a bignumber.
  1235. * @param[out] res Pointer to the result bignumber.
  1236. *
  1237. * @retval 0 success
  1238. * @retval other failed
  1239. *
  1240. * @note None
  1241. */
  1242. int tls_crypto_exptmod(hstm_int *a, hstm_int *e, hstm_int *n, hstm_int *res)
  1243. {
  1244. int i = 0;
  1245. u32 k = 0, mc = 0, dp0;
  1246. volatile u8 monmulFlag = 0;
  1247. hstm_int R, X, Y;
  1248. tls_open_peripheral_clock(TLS_PERIPHERAL_TYPE_RSA);
  1249. #ifndef CONFIG_KERNEL_NONE
  1250. tls_fls_sem_lock();
  1251. #endif
  1252. pstm_init(NULL, &X);
  1253. pstm_init(NULL, &Y);
  1254. pstm_init(NULL, &R);
  1255. k = pstm_count_bits(n);//n->used * DIGIT_BIT;//pstm_count_bits(n);
  1256. k = ((k / 32) + (k % 32 > 0 ? 1 : 0)) * 32;
  1257. #if 0
  1258. pstm_set(&Y, k);
  1259. pstm_set(&X, 2);
  1260. pstm_exptmod(NULL, &X, &Y, n, &R); //R = 2^k % n
  1261. #else
  1262. pstm_2expt(&X, (int16)k); //X = 2^k
  1263. pstm_mod(NULL, &X, n, &R); //R = 2^k % n
  1264. #endif
  1265. //pstm_set(&Y, 1);
  1266. pstm_mulmod(NULL, a, &R, n, &X); //X = A * R
  1267. pstm_copy(&R, &Y);
  1268. if(n->used > 1)
  1269. {
  1270. #if (DIGIT_BIT < 32)
  1271. dp0 = 0xFFFFFFFF & ((n->dp[0]) | (u32)(n->dp[1] << DIGIT_BIT));
  1272. #else
  1273. dp0 = (n->dp[0]);
  1274. #endif
  1275. }
  1276. else
  1277. dp0 = n->dp[0];
  1278. rsaCalMc(&mc, dp0);
  1279. k = pstm_count_bits(n);
  1280. rsaMonMulSetLen(k / 32 + (k % 32 == 0 ? 0 : 1));
  1281. rsaMonMulWriteMc(mc);
  1282. rsaMulModWrite('M', n);
  1283. rsaMulModWrite('B', &X);
  1284. rsaMulModWrite('A', &Y);
  1285. k = pstm_count_bits(e);
  1286. for(i = k - 1; i >= 0; i--)
  1287. {
  1288. //montMulMod(&Y, &Y, n, &Y);
  1289. //if(pstm_get_bit(e, i))
  1290. // montMulMod(&Y, &X, n, &Y);
  1291. if(monmulFlag == 0)
  1292. {
  1293. rsaMonMulAA();
  1294. monmulFlag = 1;
  1295. //rsaMulModDump('D');
  1296. }
  1297. else
  1298. {
  1299. rsaMonMulDD();
  1300. monmulFlag = 0;
  1301. //rsaMulModDump('A');
  1302. }
  1303. if(pstm_get_bit(e, i))
  1304. {
  1305. if(monmulFlag == 0)
  1306. {
  1307. rsaMonMulAB();
  1308. monmulFlag = 1;
  1309. //rsaMulModDump('D');
  1310. }
  1311. else
  1312. {
  1313. rsaMonMulBD();
  1314. monmulFlag = 0;
  1315. //rsaMulModDump('A');
  1316. }
  1317. }
  1318. }
  1319. pstm_set(&R, 1);
  1320. rsaMulModWrite('B', &R);
  1321. //montMulMod(&Y, &R, n, res);
  1322. if(monmulFlag == 0)
  1323. {
  1324. rsaMonMulAB();
  1325. rsaMulModRead('D', res);
  1326. }
  1327. else
  1328. {
  1329. rsaMonMulBD();
  1330. rsaMulModRead('A', res);
  1331. }
  1332. pstm_clamp(res);
  1333. pstm_clear(&X);
  1334. pstm_clear(&Y);
  1335. pstm_clear(&R);
  1336. #ifndef CONFIG_KERNEL_NONE
  1337. tls_fls_sem_unlock();
  1338. #endif
  1339. tls_close_peripheral_clock(TLS_PERIPHERAL_TYPE_RSA);
  1340. return 0;
  1341. }
  1342. /**
  1343. * @brief This function initializes the encryption module.
  1344. *
  1345. * @param None
  1346. *
  1347. * @return None
  1348. *
  1349. * @note None
  1350. */
  1351. int tls_crypto_init(void)
  1352. {
  1353. #ifndef CONFIG_KERNEL_NONE
  1354. int err = 0;
  1355. if(g_crypto_ctx.gpsec_lock != NULL)
  1356. {
  1357. return 0;
  1358. }
  1359. err = tls_os_sem_create(&g_crypto_ctx.gpsec_lock, 1);
  1360. if (err != TLS_OS_SUCCESS)
  1361. {
  1362. TLS_DBGPRT_ERR("create semaphore @gpsec_lock fail!\n");
  1363. return -1;
  1364. }
  1365. #endif
  1366. tls_irq_enable(RSA_IRQn);
  1367. tls_irq_enable(CRYPTION_IRQn);
  1368. return 0;
  1369. }
  1370. /**
  1371. * @brief This function is used to generate true random number seed.
  1372. *
  1373. * @param[in] None
  1374. *
  1375. * @retval random number
  1376. *
  1377. * @note None
  1378. */
  1379. unsigned int tls_random_seed_generation(void)
  1380. {
  1381. #if 0
  1382. extern void delay_cnt(int count);
  1383. unsigned int val;
  1384. unsigned int seed;
  1385. val = tls_reg_read32(HR_CRYPTO_TRNG_CR);
  1386. tls_reg_write32(HR_CRYPTO_TRNG_CR, val|(1 << TRNG_SEL));
  1387. delay_cnt(2000);
  1388. seed = tls_reg_read32(HR_CRYPTO_RNG_RESULT);
  1389. tls_reg_write32(HR_CRYPTO_TRNG_CR, val);
  1390. return seed;
  1391. #else
  1392. return csi_coret_get_value();
  1393. #endif
  1394. }