宝峰科技

 找回密码
 注册

QQ登录

只需一步,快速开始

智能终端设备维修查询系统注册会员邮箱认证须知!
查看: 2224|回复: 0

[VC界面库] C语言RSA算法源代码

[复制链接]
  • TA的每日心情
    开心
    2024-12-9 18:45
  • 签到天数: 124 天

    [LV.7]常住居民III

    admin 发表于 2010-5-23 14:17:30 | 显示全部楼层 |阅读模式

    欢迎您注册加入!这里有您将更精采!

    您需要 登录 才可以下载或查看,没有账号?注册

    x

    1. /* c code
    2. Header source file: rsa.h
    3. */
    4. /**
    5. * \file rsa.h
    6. */
    7. #ifndef XYSSL_RSA_H
    8. #define XYSSL_RSA_H
    9. #include "xyssl/bignum.h"
    10. #define XYSSL_ERR_RSA_BAD_INPUT_DATA -0x0400
    11. #define XYSSL_ERR_RSA_INVALID_PADDING -0x0410
    12. #define XYSSL_ERR_RSA_KEY_GEN_FAILED -0x0420
    13. #define XYSSL_ERR_RSA_KEY_CHECK_FAILED -0x0430
    14. #define XYSSL_ERR_RSA_PUBLIC_FAILED -0x0440
    15. #define XYSSL_ERR_RSA_PRIVATE_FAILED -0x0450
    16. #define XYSSL_ERR_RSA_VERIFY_FAILED -0x0460
    17. /*
    18. * PKCS#1 constants
    19. */
    20. #define RSA_RAW 0
    21. #define RSA_MD2 2
    22. #define RSA_MD4 3
    23. #define RSA_MD5 4
    24. #define RSA_SHA1 5
    25. #define RSA_SHA256 6
    26. #define RSA_PUBLIC 0
    27. #define RSA_PRIVATE 1
    28. #define RSA_PKCS_V15 0
    29. #define RSA_PKCS_V21 1
    30. #define RSA_SIGN 1
    31. #define RSA_CRYPT 2
    32. /*
    33. * DigestInfo ::= SEQUENCE {
    34. * digestAlgorithm DigestAlgorithmIdentifier,
    35. * digest Digest }
    36. *
    37. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
    38. *
    39. * Digest ::= OCTET STRING
    40. */
    41. #define ASN1_HASH_MDX \
    42. "\x30\x20\x30\x0C\x06\x08\x2A\x86\x48" \
    43. "\x86\xF7\x0D\x02\x00\x05\x00\x04\x10"
    44. #define ASN1_HASH_SHA1 \
    45. "\x30\x21\x30\x09\x06\x05\x2B\x0E\x03" \
    46. "\x02\x1A\x05\x00\x04\x14"
    47. /**
    48. * \brief RSA context structure
    49. */
    50. typedef struct
    51. {
    52. int ver; /*!< always 0 */
    53. int len; /*!< size(N) in chars */
    54. mpi N; /*!< public modulus */
    55. mpi E; /*!< public exponent */
    56. mpi D; /*!< private exponent */
    57. mpi P; /*!< 1st prime factor */
    58. mpi Q; /*!< 2nd prime factor */
    59. mpi DP; /*!< D % (P - 1) */
    60. mpi DQ; /*!< D % (Q - 1) */
    61. mpi QP; /*!< 1 / (Q % P) */
    62. mpi RN; /*!< cached R^2 mod N */
    63. mpi RP; /*!< cached R^2 mod P */
    64. mpi RQ; /*!< cached R^2 mod Q */
    65. int padding; /*!< 1.5 or OAEP/PSS */
    66. int hash_id; /*!< hash identifier */
    67. int (*f_rng)(void *); /*!< RNG function */
    68. void *p_rng; /*!< RNG parameter */
    69. }
    70. rsa_context;
    71. #ifdef __cplusplus
    72. extern "C" {
    73. #endif
    74. /**
    75. * \brief Initialize an RSA context
    76. *
    77. * \param ctx RSA context to be initialized
    78. * \param padding RSA_PKCS_V15 or RSA_PKCS_V21
    79. * \param hash_id RSA_PKCS_V21 hash identifier
    80. * \param f_rng RNG function
    81. * \param p_rng RNG parameter
    82. *
    83. * \note The hash_id parameter is actually ignored
    84. * when using RSA_PKCS_V15 padding.
    85. *
    86. * \note Currently (xyssl-0.8), RSA_PKCS_V21 padding
    87. * is not supported.
    88. */
    89. void rsa_init( rsa_context *ctx,
    90. int padding,
    91. int hash_id,
    92. int (*f_rng)(void *),
    93. void *p_rng );
    94. /**
    95. * \brief Generate an RSA keypair
    96. *
    97. * \param ctx RSA context that will hold the key
    98. * \param nbits size of the public key in bits
    99. * \param exponent public exponent (e.g., 65537)
    100. *
    101. * \note rsa_init() must be called beforehand to setup
    102. * the RSA context (especially f_rng and p_rng).
    103. *
    104. * \return 0 if successful, or an XYSSL_ERR_RSA_XXX error code
    105. */
    106. int rsa_gen_key( rsa_context *ctx, int nbits, int exponent );
    107. /**
    108. * \brief Check a public RSA key
    109. *
    110. * \param ctx RSA context to be checked
    111. *
    112. * \return 0 if successful, or an XYSSL_ERR_RSA_XXX error code
    113. */
    114. int rsa_check_pubkey( rsa_context *ctx );
    115. /**
    116. * \brief Check a private RSA key
    117. *
    118. * \param ctx RSA context to be checked
    119. *
    120. * \return 0 if successful, or an XYSSL_ERR_RSA_XXX error code
    121. */
    122. int rsa_check_privkey( rsa_context *ctx );
    123. /**
    124. * \brief Do an RSA public key operation
    125. *
    126. * \param ctx RSA context
    127. * \param input input buffer
    128. * \param output output buffer
    129. *
    130. * \return 0 if successful, or an XYSSL_ERR_RSA_XXX error code
    131. *
    132. * \note This function does NOT take care of message
    133. * padding. Also, be sure to set input[0] = 0.
    134. *
    135. * \note The input and output buffers must be large
    136. * enough (eg. 128 bytes if RSA-1024 is used).
    137. */
    138. int rsa_public( rsa_context *ctx,
    139. unsigned char *input,
    140. unsigned char *output );
    141. /**
    142. * \brief Do an RSA private key operation
    143. *
    144. * \param ctx RSA context
    145. * \param input input buffer
    146. * \param output output buffer
    147. *
    148. * \return 0 if successful, or an XYSSL_ERR_RSA_XXX error code
    149. *
    150. * \note The input and output buffers must be large
    151. * enough (eg. 128 bytes if RSA-1024 is used).
    152. */
    153. int rsa_private( rsa_context *ctx,
    154. unsigned char *input,
    155. unsigned char *output );
    156. /**
    157. * \brief Add the message padding, then do an RSA operation
    158. *
    159. * \param ctx RSA context
    160. * \param mode RSA_PUBLIC or RSA_PRIVATE
    161. * \param ilen contains the the plaintext length
    162. * \param input buffer holding the data to be encrypted
    163. * \param output buffer that will hold the ciphertext
    164. *
    165. * \return 0 if successful, or an XYSSL_ERR_RSA_XXX error code
    166. *
    167. * \note The output buffer must be as large as the size
    168. * of ctx->N (eg. 128 bytes if RSA-1024 is used).
    169. */
    170. int rsa_pkcs1_encrypt( rsa_context *ctx,
    171. int mode, int ilen,
    172. unsigned char *input,
    173. unsigned char *output );
    174. /**
    175. * \brief Do an RSA operation, then remove the message padding
    176. *
    177. * \param ctx RSA context
    178. * \param mode RSA_PUBLIC or RSA_PRIVATE
    179. * \param input buffer holding the encrypted data
    180. * \param output buffer that will hold the plaintext
    181. * \param olen will contain the plaintext length
    182. *
    183. * \return 0 if successful, or an XYSSL_ERR_RSA_XXX error code
    184. *
    185. * \note The output buffer must be as large as the size
    186. * of ctx->N (eg. 128 bytes if RSA-1024 is used).
    187. */
    188. int rsa_pkcs1_decrypt( rsa_context *ctx,
    189. int mode, int *olen,
    190. unsigned char *input,
    191. unsigned char *output );
    192. /**
    193. * \brief Do a private RSA to sign a message digest
    194. *
    195. * \param ctx RSA context
    196. * \param mode RSA_PUBLIC or RSA_PRIVATE
    197. * \param hash_id RSA_RAW, RSA_MD{2,4,5} or RSA_SHA{1,256}
    198. * \param hashlen message digest length (for RSA_RAW only)
    199. * \param hash buffer holding the message digest
    200. * \param sig buffer that will hold the ciphertext
    201. *
    202. * \return 0 if the signing operation was successful,
    203. * or an XYSSL_ERR_RSA_XXX error code
    204. *
    205. * \note The "sig" buffer must be as large as the size
    206. * of ctx->N (eg. 128 bytes if RSA-1024 is used).
    207. */
    208. int rsa_pkcs1_sign( rsa_context *ctx,
    209. int mode,
    210. int hash_id,
    211. int hashlen,
    212. unsigned char *hash,
    213. unsigned char *sig );
    214. /**
    215. * \brief Do a public RSA and check the message digest
    216. *
    217. * \param ctx points to an RSA public key
    218. * \param mode RSA_PUBLIC or RSA_PRIVATE
    219. * \param hash_id RSA_RAW, RSA_MD{2,4,5} or RSA_SHA{1,256}
    220. * \param hashlen message digest length (for RSA_RAW only)
    221. * \param hash buffer holding the message digest
    222. * \param sig buffer holding the ciphertext
    223. *
    224. * \return 0 if the verify operation was successful,
    225. * or an XYSSL_ERR_RSA_XXX error code
    226. *
    227. * \note The "sig" buffer must be as large as the size
    228. * of ctx->N (eg. 128 bytes if RSA-1024 is used).
    229. */
    230. int rsa_pkcs1_verify( rsa_context *ctx,
    231. int mode,
    232. int hash_id,
    233. int hashlen,
    234. unsigned char *hash,
    235. unsigned char *sig );
    236. /**
    237. * \brief Free the components of an RSA key
    238. */
    239. void rsa_free( rsa_context *ctx );
    240. /**
    241. * \brief Checkup routine
    242. *
    243. * \return 0 if successful, or 1 if the test failed
    244. */
    245. int rsa_self_test( int verbose );
    246. #ifdef __cplusplus
    247. }
    248. #endif
    249. #endif /* rsa.h */C source file: rsa.c
    250. /*
    251. * The RSA public-key cryptosystem
    252. *
    253. * Copyright (C) 2006-2007 Christophe Devine
    254. *
    255. * This library is free software; you can redistribute it and/or
    256. * modify it under the terms of the GNU Lesser General Public
    257. * License, version 2.1 as published by the Free Software Foundation.
    258. *
    259. * This library is distributed in the hope that it will be useful,
    260. * but WITHOUT ANY WARRANTY; without even the implied warranty of
    261. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    262. * Lesser General Public License for more details.
    263. *
    264. * You should have received a copy of the GNU Lesser General Public
    265. * License along with this library; if not, write to the Free Software
    266. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    267. * MA 02110-1301 USA
    268. */
    269. /*
    270. * RSA was designed by Ron Rivest, Adi Shamir and Len Adleman.
    271. *
    272. * http://theory.lcs.mit.edu/~rivest/rsapaper.pdf
    273. * http://www.cacr.math.uwaterloo.ca/hac/about/chap8.pdf
    274. */
    275. #include "xyssl/config.h"
    276. #if defined(XYSSL_RSA_C)
    277. #include "xyssl/rsa.h"
    278. #include <stdlib.h>
    279. #include <string.h>
    280. #include <stdio.h>
    281. /*
    282. * Initialize an RSA context
    283. */
    284. void rsa_init( rsa_context *ctx,
    285. int padding,
    286. int hash_id,
    287. int (*f_rng)(void *),
    288. void *p_rng )
    289. {
    290. memset( ctx, 0, sizeof( rsa_context ) );
    291. ctx->padding = padding;
    292. ctx->hash_id = hash_id;
    293. ctx->f_rng = f_rng;
    294. ctx->p_rng = p_rng;
    295. }
    296. #if defined(XYSSL_GENPRIME)
    297. /*
    298. * Generate an RSA keypair
    299. */
    300. int rsa_gen_key( rsa_context *ctx, int nbits, int exponent )
    301. {
    302. int ret;
    303. mpi P1, Q1, H, G;
    304. if( ctx->f_rng == NULL || nbits < 128 || exponent < 3 )
    305. return( XYSSL_ERR_RSA_BAD_INPUT_DATA );
    306. mpi_init( &P1, &Q1, &H, &G, NULL );
    307. /*
    308. * find primes P and Q with Q < P so that:
    309. * GCD( E, (P-1)*(Q-1) ) == 1
    310. */
    311. MPI_CHK( mpi_lset( &ctx->E, exponent ) );
    312. nbits >>= 1;
    313. do
    314. {
    315. MPI_CHK( mpi_gen_prime( &ctx->P, nbits, 0,
    316. ctx->f_rng, ctx->p_rng ) );
    317. MPI_CHK( mpi_gen_prime( &ctx->Q, nbits, 0,
    318. ctx->f_rng, ctx->p_rng ) );
    319. if( mpi_cmp_mpi( &ctx->P, &ctx->Q ) < 0 )
    320. mpi_swap( &ctx->P, &ctx->Q );
    321. if( mpi_cmp_mpi( &ctx->P, &ctx->Q ) == 0 )
    322. continue;
    323. MPI_CHK( mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) );
    324. MPI_CHK( mpi_sub_int( &P1, &ctx->P, 1 ) );
    325. MPI_CHK( mpi_sub_int( &Q1, &ctx->Q, 1 ) );
    326. MPI_CHK( mpi_mul_mpi( &H, &P1, &Q1 ) );
    327. MPI_CHK( mpi_gcd( &G, &ctx->E, &H ) );
    328. }
    329. while( mpi_cmp_int( &G, 1 ) != 0 );
    330. /*
    331. * D = E^-1 mod ((P-1)*(Q-1))
    332. * DP = D mod (P - 1)
    333. * DQ = D mod (Q - 1)
    334. * QP = Q^-1 mod P
    335. */
    336. MPI_CHK( mpi_inv_mod( &ctx->D , &ctx->E, &H ) );
    337. MPI_CHK( mpi_mod_mpi( &ctx->DP, &ctx->D, &P1 ) );
    338. MPI_CHK( mpi_mod_mpi( &ctx->DQ, &ctx->D, &Q1 ) );
    339. MPI_CHK( mpi_inv_mod( &ctx->QP, &ctx->Q, &ctx->P ) );
    340. ctx->len = ( mpi_msb( &ctx->N ) + 7 ) >> 3;
    341. cleanup:
    342. mpi_free( &G, &H, &Q1, &P1, NULL );
    343. if( ret != 0 )
    344. {
    345. rsa_free( ctx );
    346. return( XYSSL_ERR_RSA_KEY_GEN_FAILED | ret );
    347. }
    348. return( 0 );
    349. }
    350. #endif
    351. /*
    352. * Check a public RSA key
    353. */
    354. int rsa_check_pubkey( rsa_context *ctx )
    355. {
    356. if( ( ctx->N.p[0] & 1 ) == 0 ||
    357. ( ctx->E.p[0] & 1 ) == 0 )
    358. return( XYSSL_ERR_RSA_KEY_CHECK_FAILED );
    359. if( mpi_msb( &ctx->N ) < 128 ||
    360. mpi_msb( &ctx->N ) > 4096 )
    361. return( XYSSL_ERR_RSA_KEY_CHECK_FAILED );
    362. if( mpi_msb( &ctx->E ) < 2 ||
    363. mpi_msb( &ctx->E ) > 64 )
    364. return( XYSSL_ERR_RSA_KEY_CHECK_FAILED );
    365. return( 0 );
    366. }
    367. /*
    368. * Check a private RSA key
    369. */
    370. int rsa_check_privkey( rsa_context *ctx )
    371. {
    372. int ret;
    373. mpi TN, P1, Q1, H, G;
    374. if( ( ret = rsa_check_pubkey( ctx ) ) != 0 )
    375. return( ret );
    376. mpi_init( &TN, &P1, &Q1, &H, &G, NULL );
    377. MPI_CHK( mpi_mul_mpi( &TN, &ctx->P, &ctx->Q ) );
    378. MPI_CHK( mpi_sub_int( &P1, &ctx->P, 1 ) );
    379. MPI_CHK( mpi_sub_int( &Q1, &ctx->Q, 1 ) );
    380. MPI_CHK( mpi_mul_mpi( &H, &P1, &Q1 ) );
    381. MPI_CHK( mpi_gcd( &G, &ctx->E, &H ) );
    382. if( mpi_cmp_mpi( &TN, &ctx->N ) == 0 &&
    383. mpi_cmp_int( &G, 1 ) == 0 )
    384. {
    385. mpi_free( &TN, &P1, &Q1, &H, &G, NULL );
    386. return( 0 );
    387. }
    388. cleanup:
    389. mpi_free( &TN, &P1, &Q1, &H, &G, NULL );
    390. return( XYSSL_ERR_RSA_KEY_CHECK_FAILED | ret );
    391. }
    392. /*
    393. * Do an RSA public key operation
    394. */
    395. int rsa_public( rsa_context *ctx,
    396. unsigned char *input,
    397. unsigned char *output )
    398. {
    399. int ret, olen;
    400. mpi T;
    401. mpi_init( &T, NULL );
    402. MPI_CHK( mpi_read_binary( &T, input, ctx->len ) );
    403. if( mpi_cmp_mpi( &T, &ctx->N ) >= 0 )
    404. {
    405. mpi_free( &T, NULL );
    406. return( XYSSL_ERR_RSA_BAD_INPUT_DATA );
    407. }
    408. olen = ctx->len;
    409. MPI_CHK( mpi_exp_mod( &T, &T, &ctx->E, &ctx->N, &ctx->RN ) );
    410. MPI_CHK( mpi_write_binary( &T, output, olen ) );
    411. cleanup:
    412. mpi_free( &T, NULL );
    413. if( ret != 0 )
    414. return( XYSSL_ERR_RSA_PUBLIC_FAILED | ret );
    415. return( 0 );
    416. }
    417. /*
    418. * Do an RSA private key operation
    419. */
    420. int rsa_private( rsa_context *ctx,
    421. unsigned char *input,
    422. unsigned char *output )
    423. {
    424. int ret, olen;
    425. mpi T, T1, T2;
    426. mpi_init( &T, &T1, &T2, NULL );
    427. MPI_CHK( mpi_read_binary( &T, input, ctx->len ) );
    428. if( mpi_cmp_mpi( &T, &ctx->N ) >= 0 )
    429. {
    430. mpi_free( &T, NULL );
    431. return( XYSSL_ERR_RSA_BAD_INPUT_DATA );
    432. }
    433. #if 0
    434. MPI_CHK( mpi_exp_mod( &T, &T, &ctx->D, &ctx->N, &ctx->RN ) );
    435. #else
    436. /*
    437. * faster decryption using the CRT
    438. *
    439. * T1 = input ^ dP mod P
    440. * T2 = input ^ dQ mod Q
    441. */
    442. MPI_CHK( mpi_exp_mod( &T1, &T, &ctx->DP, &ctx->P, &ctx->RP ) );
    443. MPI_CHK( mpi_exp_mod( &T2, &T, &ctx->DQ, &ctx->Q, &ctx->RQ ) );
    444. /*
    445. * T = (T1 - T2) * (Q^-1 mod P) mod P
    446. */
    447. MPI_CHK( mpi_sub_mpi( &T, &T1, &T2 ) );
    448. MPI_CHK( mpi_mul_mpi( &T1, &T, &ctx->QP ) );
    449. MPI_CHK( mpi_mod_mpi( &T, &T1, &ctx->P ) );
    450. /*
    451. * output = T2 + T * Q
    452. */
    453. MPI_CHK( mpi_mul_mpi( &T1, &T, &ctx->Q ) );
    454. MPI_CHK( mpi_add_mpi( &T, &T2, &T1 ) );
    455. #endif
    456. olen = ctx->len;
    457. MPI_CHK( mpi_write_binary( &T, output, olen ) );
    458. cleanup:
    459. mpi_free( &T, &T1, &T2, NULL );
    460. if( ret != 0 )
    461. return( XYSSL_ERR_RSA_PRIVATE_FAILED | ret );
    462. return( 0 );
    463. }
    464. /*
    465. * Add the message padding, then do an RSA operation
    466. */
    467. int rsa_pkcs1_encrypt( rsa_context *ctx,
    468. int mode, int ilen,
    469. unsigned char *input,
    470. unsigned char *output )
    471. {
    472. int nb_pad, olen;
    473. unsigned char *p = output;
    474. olen = ctx->len;
    475. switch( ctx->padding )
    476. {
    477. case RSA_PKCS_V15:
    478. if( ilen < 0 || olen < ilen + 11 )
    479. return( XYSSL_ERR_RSA_BAD_INPUT_DATA );
    480. nb_pad = olen - 3 - ilen;
    481. *p++ = 0;
    482. *p++ = RSA_CRYPT;
    483. while( nb_pad-- > 0 )
    484. {
    485. do {
    486. *p = (unsigned char) rand();
    487. } while( *p == 0 );
    488. p++;
    489. }
    490. *p++ = 0;
    491. memcpy( p, input, ilen );
    492. break;
    493. default:
    494. return( XYSSL_ERR_RSA_INVALID_PADDING );
    495. }
    496. return( ( mode == RSA_PUBLIC )
    497. ? rsa_public( ctx, output, output )
    498. : rsa_private( ctx, output, output ) );
    499. }
    500. /*
    501. * Do an RSA operation, then remove the message padding
    502. */
    503. int rsa_pkcs1_decrypt( rsa_context *ctx,
    504. int mode, int *olen,
    505. unsigned char *input,
    506. unsigned char *output )
    507. {
    508. int ret, ilen;
    509. unsigned char *p;
    510. unsigned char buf[512];
    511. ilen = ctx->len;
    512. if( ilen < 16 || ilen > (int) sizeof( buf ) )
    513. return( XYSSL_ERR_RSA_BAD_INPUT_DATA );
    514. ret = ( mode == RSA_PUBLIC )
    515. ? rsa_public( ctx, input, buf )
    516. : rsa_private( ctx, input, buf );
    517. if( ret != 0 )
    518. return( ret );
    519. p = buf;
    520. switch( ctx->padding )
    521. {
    522. case RSA_PKCS_V15:
    523. if( *p++ != 0 || *p++ != RSA_CRYPT )
    524. return( XYSSL_ERR_RSA_INVALID_PADDING );
    525. while( *p != 0 )
    526. {
    527. if( p >= buf + ilen - 1 )
    528. return( XYSSL_ERR_RSA_INVALID_PADDING );
    529. p++;
    530. }
    531. p++;
    532. break;
    533. default:
    534. return( XYSSL_ERR_RSA_INVALID_PADDING );
    535. }
    536. *olen = ilen - (int)(p - buf);
    537. memcpy( output, p, *olen );
    538. return( 0 );
    539. }
    540. /*
    541. * Do an RSA operation to sign the message digest
    542. */
    543. int rsa_pkcs1_sign( rsa_context *ctx,
    544. int mode,
    545. int hash_id,
    546. int hashlen,
    547. unsigned char *hash,
    548. unsigned char *sig )
    549. {
    550. int nb_pad, olen;
    551. unsigned char *p = sig;
    552. olen = ctx->len;
    553. switch( ctx->padding )
    554. {
    555. case RSA_PKCS_V15:
    556. switch( hash_id )
    557. {
    558. case RSA_RAW:
    559. nb_pad = olen - 3 - hashlen;
    560. break;
    561. case RSA_MD2:
    562. case RSA_MD4:
    563. case RSA_MD5:
    564. nb_pad = olen - 3 - 34;
    565. break;
    566. case RSA_SHA1:
    567. nb_pad = olen - 3 - 35;
    568. break;
    569. default:
    570. return( XYSSL_ERR_RSA_BAD_INPUT_DATA );
    571. }
    572. if( nb_pad < 8 )
    573. return( XYSSL_ERR_RSA_BAD_INPUT_DATA );
    574. *p++ = 0;
    575. *p++ = RSA_SIGN;
    576. memset( p, 0xFF, nb_pad );
    577. p += nb_pad;
    578. *p++ = 0;
    579. break;
    580. default:
    581. return( XYSSL_ERR_RSA_INVALID_PADDING );
    582. }
    583. switch( hash_id )
    584. {
    585. case RSA_RAW:
    586. memcpy( p, hash, hashlen );
    587. break;
    588. case RSA_MD2:
    589. memcpy( p, ASN1_HASH_MDX, 18 );
    590. memcpy( p + 18, hash, 16 );
    591. p[13] = 2; break;
    592. case RSA_MD4:
    593. memcpy( p, ASN1_HASH_MDX, 18 );
    594. memcpy( p + 18, hash, 16 );
    595. p[13] = 4; break;
    596. case RSA_MD5:
    597. memcpy( p, ASN1_HASH_MDX, 18 );
    598. memcpy( p + 18, hash, 16 );
    599. p[13] = 5; break;
    600. case RSA_SHA1:
    601. memcpy( p, ASN1_HASH_SHA1, 15 );
    602. memcpy( p + 15, hash, 20 );
    603. break;
    604. default:
    605. return( XYSSL_ERR_RSA_BAD_INPUT_DATA );
    606. }
    607. return( ( mode == RSA_PUBLIC )
    608. ? rsa_public( ctx, sig, sig )
    609. : rsa_private( ctx, sig, sig ) );
    610. }
    611. /*
    612. * Do an RSA operation and check the message digest
    613. */
    614. int rsa_pkcs1_verify( rsa_context *ctx,
    615. int mode,
    616. int hash_id,
    617. int hashlen,
    618. unsigned char *hash,
    619. unsigned char *sig )
    620. {
    621. int ret, len, siglen;
    622. unsigned char *p, c;
    623. unsigned char buf[512];
    624. siglen = ctx->len;
    625. if( siglen < 16 || siglen > (int) sizeof( buf ) )
    626. return( XYSSL_ERR_RSA_BAD_INPUT_DATA );
    627. ret = ( mode == RSA_PUBLIC )
    628. ? rsa_public( ctx, sig, buf )
    629. : rsa_private( ctx, sig, buf );
    630. if( ret != 0 )
    631. return( ret );
    632. p = buf;
    633. switch( ctx->padding )
    634. {
    635. case RSA_PKCS_V15:
    636. if( *p++ != 0 || *p++ != RSA_SIGN )
    637. return( XYSSL_ERR_RSA_INVALID_PADDING );
    638. while( *p != 0 )
    639. {
    640. if( p >= buf + siglen - 1 || *p != 0xFF )
    641. return( XYSSL_ERR_RSA_INVALID_PADDING );
    642. p++;
    643. }
    644. p++;
    645. break;
    646. default:
    647. return( XYSSL_ERR_RSA_INVALID_PADDING );
    648. }
    649. len = siglen - (int)( p - buf );
    650. if( len == 34 )
    651. {
    652. c = p[13];
    653. p[13] = 0;
    654. if( memcmp( p, ASN1_HASH_MDX, 18 ) != 0 )
    655. return( XYSSL_ERR_RSA_VERIFY_FAILED );
    656. if( ( c == 2 && hash_id == RSA_MD2 ) ||
    657. ( c == 4 && hash_id == RSA_MD4 ) ||
    658. ( c == 5 && hash_id == RSA_MD5 ) )
    659. {
    660. if( memcmp( p + 18, hash, 16 ) == 0 )
    661. return( 0 );
    662. else
    663. return( XYSSL_ERR_RSA_VERIFY_FAILED );
    664. }
    665. }
    666. if( len == 35 && hash_id == RSA_SHA1 )
    667. {
    668. if( memcmp( p, ASN1_HASH_SHA1, 15 ) == 0 &&
    669. memcmp( p + 15, hash, 20 ) == 0 )
    670. return( 0 );
    671. else
    672. return( XYSSL_ERR_RSA_VERIFY_FAILED );
    673. }
    674. if( len == hashlen && hash_id == RSA_RAW )
    675. {
    676. if( memcmp( p, hash, hashlen ) == 0 )
    677. return( 0 );
    678. else
    679. return( XYSSL_ERR_RSA_VERIFY_FAILED );
    680. }
    681. return( XYSSL_ERR_RSA_INVALID_PADDING );
    682. }
    683. /*
    684. * Free the components of an RSA key
    685. */
    686. void rsa_free( rsa_context *ctx )
    687. {
    688. mpi_free( &ctx->RQ, &ctx->RP, &ctx->RN,
    689. &ctx->QP, &ctx->DQ, &ctx->DP,
    690. &ctx->Q, &ctx->P, &ctx->D,
    691. &ctx->E, &ctx->N, NULL );
    692. }
    693. #if defined(XYSSL_SELF_TEST)
    694. #include "xyssl/sha1.h"
    695. /*
    696. * Example RSA-1024 keypair, for test purposes
    697. */
    698. #define KEY_LEN 128
    699. #define RSA_N "9292758453063D803DD603D5E777D788" \
    700. "8ED1D5BF35786190FA2F23EBC0848AEA" \
    701. "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
    702. "7130B9CED7ACDF54CFC7555AC14EEBAB" \
    703. "93A89813FBF3C4F8066D2D800F7C38A8" \
    704. "1AE31942917403FF4946B0A83D3D3E05" \
    705. "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
    706. "5E94BB77B07507233A0BC7BAC8F90F79"
    707. #define RSA_E "10001"
    708. #define RSA_D "24BF6185468786FDD303083D25E64EFC" \
    709. "66CA472BC44D253102F8B4A9D3BFA750" \
    710. "91386C0077937FE33FA3252D28855837" \
    711. "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
    712. "DF79C5CE07EE72C7F123142198164234" \
    713. "CABB724CF78B8173B9F880FC86322407" \
    714. "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
    715. "071513A1E85B5DFA031F21ECAE91A34D"
    716. #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
    717. "2C01CAD19EA484A87EA4377637E75500" \
    718. "FCB2005C5C7DD6EC4AC023CDA285D796" \
    719. "C3D9E75E1EFC42488BB4F1D13AC30A57"
    720. #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \
    721. "E211C2B9E5DB1ED0BF61D0D9899620F4" \
    722. "910E4168387E3C30AA1E00C339A79508" \
    723. "8452DD96A9A5EA5D9DCA68DA636032AF"
    724. #define RSA_DP "C1ACF567564274FB07A0BBAD5D26E298" \
    725. "3C94D22288ACD763FD8E5600ED4A702D" \
    726. "F84198A5F06C2E72236AE490C93F07F8" \
    727. "3CC559CD27BC2D1CA488811730BB5725"
    728. #define RSA_DQ "4959CBF6F8FEF750AEE6977C155579C7" \
    729. "D8AAEA56749EA28623272E4F7D0592AF" \
    730. "7C1F1313CAC9471B5C523BFE592F517B" \
    731. "407A1BD76C164B93DA2D32A383E58357"
    732. #define RSA_QP "9AE7FBC99546432DF71896FC239EADAE" \
    733. "F38D18D2B2F0E2DD275AA977E2BF4411" \
    734. "F5A3B2A5D33605AEBBCCBA7FEB9F2D2F" \
    735. "A74206CEC169D74BF5A8C50D6F48EA08"
    736. #define PT_LEN 24
    737. #define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
    738. "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
    739. /*
    740. * Checkup routine
    741. */
    742. int rsa_self_test( int verbose )
    743. {
    744. int len;
    745. rsa_context rsa;
    746. unsigned char sha1sum[20];
    747. unsigned char rsa_plaintext[PT_LEN];
    748. unsigned char rsa_decrypted[PT_LEN];
    749. unsigned char rsa_ciphertext[KEY_LEN];
    750. memset( &rsa, 0, sizeof( rsa_context ) );
    751. rsa.len = KEY_LEN;
    752. mpi_read_string( &rsa.N , 16, RSA_N );
    753. mpi_read_string( &rsa.E , 16, RSA_E );
    754. mpi_read_string( &rsa.D , 16, RSA_D );
    755. mpi_read_string( &rsa.P , 16, RSA_P );
    756. mpi_read_string( &rsa.Q , 16, RSA_Q );
    757. mpi_read_string( &rsa.DP, 16, RSA_DP );
    758. mpi_read_string( &rsa.DQ, 16, RSA_DQ );
    759. mpi_read_string( &rsa.QP, 16, RSA_QP );
    760. if( verbose != 0 )
    761. printf( " RSA key validation: " );
    762. if( rsa_check_pubkey( &rsa ) != 0 ||
    763. rsa_check_privkey( &rsa ) != 0 )
    764. {
    765. if( verbose != 0 )
    766. printf( "failed\n" );
    767. return( 1 );
    768. }
    769. if( verbose != 0 )
    770. printf( "passed\n PKCS#1 encryption : " );
    771. memcpy( rsa_plaintext, RSA_PT, PT_LEN );
    772. if( rsa_pkcs1_encrypt( &rsa, RSA_PUBLIC, PT_LEN,
    773. rsa_plaintext, rsa_ciphertext ) != 0 )
    774. {
    775. if( verbose != 0 )
    776. printf( "failed\n" );
    777. return( 1 );
    778. }
    779. if( verbose != 0 )
    780. printf( "passed\n PKCS#1 decryption : " );
    781. if( rsa_pkcs1_decrypt( &rsa, RSA_PRIVATE, &len,
    782. rsa_ciphertext, rsa_decrypted ) != 0 )
    783. {
    784. if( verbose != 0 )
    785. printf( "failed\n" );
    786. return( 1 );
    787. }
    788. if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 )
    789. {
    790. if( verbose != 0 )
    791. printf( "failed\n" );
    792. return( 1 );
    793. }
    794. if( verbose != 0 )
    795. printf( "passed\n PKCS#1 data sign : " );
    796. sha1( rsa_plaintext, PT_LEN, sha1sum );
    797. if( rsa_pkcs1_sign( &rsa, RSA_PRIVATE, RSA_SHA1, 20,
    798. sha1sum, rsa_ciphertext ) != 0 )
    799. {
    800. if( verbose != 0 )
    801. printf( "failed\n" );
    802. return( 1 );
    803. }
    804. if( verbose != 0 )
    805. printf( "passed\n PKCS#1 sig. verify: " );
    806. if( rsa_pkcs1_verify( &rsa, RSA_PUBLIC, RSA_SHA1, 20,
    807. sha1sum, rsa_ciphertext ) != 0 )
    808. {
    809. if( verbose != 0 )
    810. printf( "failed\n" );
    811. return( 1 );
    812. }
    813. if( verbose != 0 )
    814. printf( "passed\n\n" );
    815. rsa_free( &rsa );
    816. return( 0 );
    817. }
    818. #endif
    819. #endif[edit] java code
    820. // RSAPublicKey: RSA public key
    821. import java.math.*; // for BigInteger
    822. public class RSAPublicKey {
    823. public BigInteger n; // public modulus
    824. public BigInteger e = new BigInteger("3"); // encryption exponent
    825. public String userName; // attach name to each public/private key pair
    826. public RSAPublicKey(String name) {
    827. userName = name;
    828. }
    829. // setN: to give n a value in case only have public key
    830. public void setN(BigInteger newN) {
    831. n = newN;
    832. }
    833. // getN: provide n
    834. public BigInteger getN() {
    835. return n;
    836. }
    837. // RSAEncrypt: just raise m to power e (3) mod n
    838. public BigInteger RSAEncrypt(BigInteger m) {
    839. return m.modPow(e, n);
    840. }
    841. // RSAVerify: same as encryption, since RSA is symmetric
    842. public BigInteger RSAVerify(BigInteger s) {
    843. return s.modPow(e, n);
    844. }
    845. }
    846. // RSAPrivateKey: RSA private key
    847. import java.math.*; // for BigInteger
    848. import java.util.*; // for Random
    849. public class RSAPrivateKey extends RSAPublicKey{
    850. private final BigInteger TWO = new BigInteger("2");
    851. private final BigInteger THREE = new BigInteger("3");
    852. private BigInteger p; // first prime
    853. private BigInteger q; // second prime
    854. private BigInteger d; // decryption exponent
    855. public RSAPrivateKey(int size, Random rnd, String name) {
    856. super(name); generateKeyPair(size, rnd);
    857. }
    858. public void generateKeyPair(int size, Random rnd) { // size = n in bits
    859. // want sizes of primes close, but not too close. Here 10-20 bits apart.
    860. int size1 = size/2;
    861. int size2 = size1;
    862. int offset1 = (int)(5.0*(rnd.nextDouble()) + 5.0);
    863. int offset2 = -offset1;
    864. if (rnd.nextDouble() < 0.5) {
    865. offset1 = -offset1; offset2 = -offset2;
    866. }
    867. size1 += offset1; size2 += offset2;
    868. // generate two random primes, so that p*q = n has size bits
    869. BigInteger p1 = new BigInteger(size1, rnd); // random int
    870. p = nextPrime(p1);
    871. BigInteger pM1 = p.subtract(BigInteger.ONE);
    872. BigInteger q1 = new BigInteger(size2, rnd);
    873. q = nextPrime(q1);
    874. BigInteger qM1 = q.subtract(BigInteger.ONE);
    875. n = p.multiply(q);
    876. BigInteger phiN = pM1.multiply(qM1); // (p-1)*(q-1)
    877. BigInteger e = THREE;
    878. d = e.modInverse(phiN);
    879. }
    880. // nextPrime: next prime p after x, with p-1 and 3 relatively prime
    881. public BigInteger nextPrime(BigInteger x) {
    882. if ((x.remainder(TWO)).equals(BigInteger.ZERO))
    883. x = x.add(BigInteger.ONE);
    884. while(true) {
    885. BigInteger xM1 = x.subtract(BigInteger.ONE);
    886. if (!(xM1.remainder(THREE)).equals(BigInteger.ZERO))
    887. if (x.isProbablePrime(10)) break;
    888. x = x.add(TWO);
    889. }
    890. return x;
    891. }
    892. // RSADecrypt: decryption function
    893. public BigInteger RSADecrypt(BigInteger c) {
    894. return c.modPow(d, n);
    895. }
    896. // RSASign: same as decryption for RSA (since it is a symmetric PKC)
    897. public BigInteger RSASign(BigInteger m) {
    898. return m.modPow(d, n);
    899. }
    900. public BigInteger RSASignAndEncrypt(BigInteger m, RSAPublicKey other) {
    901. // two ways to go, depending on sizes of n and other.getN()
    902. if (n.compareTo(other.getN()) > 0)
    903. return RSASign(other.RSAEncrypt(m));
    904. else
    905. return other.RSAEncrypt(RSASign(m));
    906. }
    907. public BigInteger RSADecryptAndVerify(BigInteger c,
    908. RSAPrivateKey other) {
    909. // two ways to go, depending on sizes of n and other.getN()
    910. if (n.compareTo(other.getN()) > 0)
    911. return other.RSAVerify(RSADecrypt(c));
    912. else
    913. return RSADecrypt(other.RSAVerify(c));
    914. }
    915. }
    916. --------------------------------------------------------------------------------
    917. // RSATest: Test RSA Implementation
    918. import java.math.*; // for BigInteger
    919. import java.util.*; // for Random
    920. public class RSATest {
    921. public static void main(String[] args) {
    922. Random rnd = new Random();
    923. BigInteger m, m1, m2, m3, c, s, s1;
    924. RSAPrivateKey alice = new RSAPrivateKey(1024, rnd, "Alice");
    925. RSAPrivateKey bob = new RSAPrivateKey(1024, rnd, "Bob ");
    926. m = new BigInteger(
    927. "1234567890987654321012345678909876543210" +
    928. "1234567890987654321012345678909876543210" +
    929. "1234567890987654321012345678909876543210" +
    930. "1234567890987654321012345678909876543210" +
    931. "1234567890987654321012345678909876543210" +
    932. "1234567890987654321012345678909876543210");
    933. System.out.println("Message m:\n" + m + "\n");
    934. System.out.println("ALICE ENCRYPTS m FOR BOB; BOB DECRYPTS IT:");
    935. c = bob.RSAEncrypt(m); // Using Bob's public key
    936. System.out.println("Message encrypted with Bob's public key:\n" +
    937. c + "\n");
    938. m1 = bob.RSADecrypt(c); // Using Bob's private key
    939. System.out.println("Original message back, decrypted:\n" + m1 + "\n");
    940. System.out.println("ALICE SIGNS m FOR BOB; BOB VERIFIES SIGNATURE:");
    941. s = alice.RSASign(m); // Using Alice's private key
    942. System.out.println("Message signed with Alice's private key:\n" +
    943. c + "\n");
    944. m2 = alice.RSAVerify(s); // Using Alice's public key
    945. System.out.println("Original message back, verified:\n" + m2 + "\n");
    946. System.out.println("BOB SIGNS AND ENCRYPTS m FOR ALICE;" +
    947. "\n ALICE VERIFIES SIGNATURE AND DECRYPTS:");
    948. c = bob.RSASignAndEncrypt(m, alice);
    949. System.out.println("Message signed and encrypted," +
    950. "\n using Bob's secret key and Alice's public key:\n" + c + "\n");
    951. m3 = alice.RSADecryptAndVerify(c, bob);
    952. System.out.println("Original message back, verified and decrypted," +
    953. "\n using Alice's secret key and Bob's public key:\n" + m1);
    954. }
    955. }
    复制代码
    您需要登录后才可以回帖 登录 | 注册

    本版积分规则

    免责声明

    本站中所有被研究的素材与信息全部来源于互联网,版权争议与本站无关。本站所发布的任何软件编程开发或软件的逆向分析文章、逆向分析视频、补丁、注册机和注册信息,仅限用于学习和研究软件安全的目的。全体用户必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。学习编程开发技术或逆向分析技术是为了更好的完善软件可能存在的不安全因素,提升软件安全意识。所以您如果喜欢某程序,请购买注册正版软件,获得正版优质服务!不得将上述内容私自传播、销售或者用于商业用途!否则,一切后果请用户自负!

    QQ|Archiver|手机版|小黑屋|联系我们|宝峰科技 ( 滇公网安备 53050202000040号 | 滇ICP备09007156号-2 )

    Copyright © 2001-2023 Discuz! Team. GMT+8, 2025-5-8 18:02 , File On Powered by Discuz! X3.49

    快速回复 返回顶部 返回列表