This repository has been archived by the owner on Aug 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
mp_rsa.pas
1893 lines (1673 loc) · 60.2 KB
/
mp_rsa.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit mp_rsa;
{MP functions for basic RSA based public-key cryptography}
interface
{$i STD.INC}
uses
mp_types;
{$i mp_conf.inc}
(*************************************************************************
DESCRIPTION : MP functions for basic RSA based public-key cryptography
REQUIREMENTS : BP7, D1-D7/D9-D10/D12/D17-D18, FPC, VP
EXTERNAL DATA : (mp_types)
MEMORY USAGE : heap
DISPLAY MODE : ---
REMARK : In order to keep MPArith (relative) small and modular the
RSA sign/verify operations do not call the actual hash
functions. The user has to supply a hash algorithm ID
and externally calculated hash digests.
REFERENCES : [1] LibTomMath 0.30+ by Tom St Denis
[2] MPI by M.J. Fromberger
- RFC 2313 - PKCS #1: RSA Encryption Version 1.5 and
- RFC 3447 - PKCS #1: RSA Encryption Version 2.1 available
online from http://tools.ietf.org/html/rfc2313 and
http://tools.ietf.org/html/rfc3447
[30] J. v. zur Gathen, J. Gerhard, Modern computer algebra, 2nd ed., 2003
https://cosec.bit.uni-bonn.de/science/mca/
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.0.01 10.11.05 W.Ehrhardt Initial version: working pkcs1v15_decrypt a la MPI
0.0.02 12.11.05 we EME-PKCS1-v1_5 decoding with $00, $02 ...
0.0.03 12.11.05 we Working pkcs1v15_encrypt
0.0.04 13.11.05 we nonzero random padding, more error checking
0.0.05 13.11.05 we max lengths in more uniform parameter lists
0.0.06 19.11.05 we mp_rsa_keygen1, RSA_MINSIZE
0.0.07 20.11.05 we mp_rsa_keygen1: changed pt_3mod4 to pt_normal
0.0.08 11.08.06 we Avoid FPC warnings: mp_pkcs1v15_encrypt, mp_pkcs1v15_decrypt
0.0.09 12.11.07 we Fix memory leak(s) if MPC_HaltOnError is not defined
1.6.00 22.05.08 we TPrivateKey, mp_rsa_keygen2, mp_rsa_init/clear/calc_private
1.6.01 23.05.08 we mp_rsadp2
1.6.02 25.05.08 we mp_i2pchar
1.6.03 01.06.08 we mp_rsa_calc_npq, mp_pkcs1v15_decrypt2, mp_rsa_calc_d
1.7.00 30.06.08 we correct exception strings in mp_rsa_calc_npq
1.9.00 29.11.08 we mp_rsa_calc_nd, fix silly "fillchar(buf^" bug
1.9.01 02.12.08 we Uses BTypes: char8, pchar8
1.9.02 13.12.08 we mp_rsa_recover_pq
1.9.03 23.12.08 we mp_rsa_recover_pq uses s_mp_mca_alg1816
1.9.04 06.01.09 we Uses BTypes moved to implementation
1.10.00 21.01.09 we changes related to (s)mp_divrem
1.10.01 10.02.09 we mp_rsa_recover_pq2
1.12.00 20.06.09 we updated RFC URL(s)
1.12.01 28.06.09 we improved mp_rsa_calc_npq
1.12.03 29.07.09 we Increased trace level in mp_rsa_calc_npq
1.13.00 10.08.09 we mp_rsa_wiener
1.16.00 06.06.10 we ensure |p-q| is not too small in mp_rsa_calc_npq
1.17.00 27.12.10 we Sign/verify functions
1.17.01 31.12.10 we mp_pkcs1v15_emsa_encode: SHA224 and RIPEMD-160
1.17.02 01.01.11 we Fix wrong byte in RFC4880 SHA224 algorithm identifier
1.23.00 24.09.12 we s_mp_mca_alg1816 from mp_numth
1.33.00 09.06.15 we moved some mp_clear[x] into success blocks
1.34.00 08.05.17 we update some broken links
**************************************************************************)
(*-------------------------------------------------------------------------
This code uses material/ideas from the following 3rd party libraries:
- LibTomMath 0.30+ by Tom St Denis
- MPI 1.8.6 by Michael J. Fromberger
See the file '3rdparty.mpa' for the licenses.
----------------------------------------------------------------------------*)
(*---------------------------------------------------------------------------
Acknowledgement
RFCs 2313/3447 are based on contributions of RSA Laboratories.
RSA Security Inc. requests that the PKCS references are identified as
"RSA Security Inc. PKCS #1 v1.5" and "RSA Security Inc. PKCS #1 v2.1".
----------------------------------------------------------------------------*)
(*-------------------------------------------------------------------------
(C) Copyright 2005-2017 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
const
RSA_MINSIZE = 11; {minimum octet size of modulus}
type
TPrivateKey = record {RSA private key record with CRT coefficients}
p,q : mp_int; {primes with n=p*q }
dp : mp_int; {dp = e^-1 mod (p-1)}
dq : mp_int; {dq = e^-1 mod (q-1)}
qinv : mp_int; {qinv = q^-1 mod p }
end;
type
TSSAHash = (SA_MD2, SA_MD5, SA_RMD160, SA_SHA1, SA_SHA224, SA_SHA256, SA_SHA384, SA_SHA512);
{Valid hash algorithms for RSA signature schemes. Only the hash}
{digests and algorithm identifiers are used, not the actual hash}
{functions, i.e. the digests have to be calculated externally. }
procedure mp_i2osp(const x: mp_int; outp: pointer; len: word);
{-Convert a nonnegative mp_int to an octet string of a specified length}
procedure mp_i2pchar(const x: mp_int; outp: pointer; len: word);
{-Convert a nonnegative mp_int to a pchar with a specified max length}
procedure mp_os2ip(inp: pointer; ilen: word; var x: mp_int);
{-Convert an octet string of length ilen to a nonnegative mp_int}
function mp_pkcs1v15_decode(em, msg: pointer; emlen: word; var mlen: word): boolean;
{-EME-PKCS1-v1_5 decoding; true if decoding is successful, false otherwise}
procedure mp_pkcs1v15_decrypt(const d, n: mp_int; ctp,ptp: pointer; clen,pmax: word; var plen: word);
{-Decrypt a message using RSA and EME-PKCS1-v1_5 padding}
procedure mp_pkcs1v15_decrypt2(const prk: TPrivateKey; const n: mp_int; ctp,ptp: pointer; clen,pmax: word; var plen: word);
{-Decrypt a message using RSA/CRT and EME-PKCS1-v1_5 padding}
function mp_pkcs1v15_emsa_encode(AHash: TSSAHash; hdp, smp: pointer; hlen, slen: word): boolean;
{-EMSA-PKCS1-v1_5 encoding; true if encoding is successful, false otherwise}
function mp_pkcs1v15_encode(msg, em: pointer; mlen, emlen: word; rnd: byte): boolean;
{-EME-PKCS1-v1_5 encoding; true if encoding is successful, false otherwise}
procedure mp_pkcs1v15_encrypt(const e, n: mp_int; rnd: byte; ptp,ctp: pointer; plen,cmax: word; var clen: word);
{-Encrypt a message using RSA and EME-PKCS1-v1_5 padding}
function mp_pkcs1v15_maxlen(const n: mp_int): word;
{-Maximum message length for RSA modulus n using PKCS1-v1_5 encoding}
procedure mp_pkcs1v15_sign(const d, n: mp_int; AHash: TSSAHash; hdp,smp: pointer; hlen,smax: word; var slen: word);
{-Sign a hash digest using RSA and EMSA-PKCS1-v1_5 encoding}
procedure mp_pkcs1v15_sign2(const prk: TPrivateKey; const n: mp_int; AHash: TSSAHash;
hdp,smp: pointer; hlen,smax: word; var slen: word);
{-Sign a hash digest using RSA/CRT and EMSA-PKCS1-v1_5 encoding}
function mp_pkcs1v15_verify(const e, n: mp_int; AHash: TSSAHash; hdp,smp: pointer; hlen,slen: word): boolean;
{-Signature verification operation}
procedure mp_rsadp(const c, d, n: mp_int; var m: mp_int);
{-Basic RSA decryption operation, m=c^d mod n.}
procedure mp_rsadp2(const c: mp_int; const prk: TPrivateKey; var m: mp_int);
{-Basic RSA decryption operation for private key CRT record.}
procedure mp_rsaep(const m, e, n: mp_int; var c: mp_int);
{-Basic RSA encryption operation, c=m^e mod n.}
procedure mp_rsasp(const m, d, n: mp_int; var s: mp_int);
{-Basic RSA signature primitive, s=m^d mod n.}
procedure mp_rsasp2(const m: mp_int; const prk: TPrivateKey; var s: mp_int);
{-Basic RSA signature primitive for private key CRT record.}
procedure mp_rsavp(const s, e, n: mp_int; var m: mp_int);
{-Basic RSA verification operation, m=s^e mod n.}
procedure mp_rsa_calc_d(const e: mp_int; const prk: TPrivateKey; var d: mp_int);
{-Get RSA decryption exponent d from private key record and encryption exponent e}
procedure mp_rsa_calc_nd(const e,p,q: mp_int; var n,d: mp_int);
{-Calculate n,d from e,p,q}
procedure mp_rsa_calc_npq(const e: mp_int; osize: word; var n,p,q: mp_int);
{-Generate RSA primes p,q; q<p, n=p*q, osize: octet size of n;}
{ e: public key encryption exponent, e odd and greater than 2}
procedure mp_rsa_calc_private(const e, p, q: mp_int; var prk: TPrivateKey);
{-Calculate remaining fields of private RSA/CRT key from e,p,q}
procedure mp_rsa_clear_private(var prk: TPrivateKey);
{-Clear fields of private RSA/CRT key}
procedure mp_rsa_init_private(var prk: TPrivateKey);
{-Initialize fields of private RSA/CRT key}
procedure mp_rsa_keygen1(const e: mp_int; osize: word; var d, n: mp_int);
{-Basic RSA private key pair (n, d) generation; osize: octet size of n;}
{ e: public key encryption exponent, e odd and greater than 2}
procedure mp_rsa_keygen2(const e: mp_int; osize: word; var n: mp_int; var prk: TPrivateKey);
{-Generate private RSA/CRT key prk and modulus n; osize: octet size of n;}
{ e: public key encryption exponent, e odd and greater than 2}
procedure mp_rsa_recover_pq(const n,e,d: mp_int; var p,q: mp_int; var fail: boolean);
{-Try to recover p,q from n,e,d. Assumes n=p*q with odd primes p,q and}
{ e*d=1 mod lcm(p-1,q-1). Fail=true if no success or if e*d is even.}
procedure mp_rsa_recover_pq2(const n,e,dp: mp_int; var p,q: mp_int; var fail: boolean);
{-Try to recover p,q from n,e,dp (dp is CRT exponent of p). Assumes n=p*q}
{ with odd primes p,q. Fail=true if no success or if e*dp is even.}
procedure mp_rsa_wiener(const e,n: mp_int; var p,q,d: mp_int; var fail: boolean);
{-Wiener's attack on small RSA secret exponents: Recover p,q,d from e,n.}
{ Assumes n=p*q with odd primes p>q, e*d=1 mod lcm(p-1,q-1). Fail=true if}
{ no success: typically if bitsize(d) > bitsize(n)/4. If e is given and}
{ d is calculated, usually d will be 'large' and cannot be recovered. }
procedure s_mp_mca_alg1816(const n,L: mp_int; k:integer; var p: mp_int; var fail: boolean);
{-Try to find a factor p of a squarefree odd integer n>5, with L a multiple}
{ of lambda(n) [lambda: Carmichael function] and a confidence parameter k.}
{ Fail=true, if no success (e.g. n is prime), n is even, n<=5, or L is odd.}
implementation
uses
BTypes, mp_base, mp_prng, mp_modul, mp_numth;
type
TByteArr = packed array[0..65519] of byte; {Helper types}
PByteArr = ^TByteArr;
{---------------------------------------------------------------------------}
function mp_pkcs1v15_maxlen(const n: mp_int): word;
{-Maximum message length for RSA modulus n using PKCS1-v1_5 encoding}
var
modlen: word;
begin
{MPC_ArgCheck in mp_unsigned_bin_size or deeper}
modlen := mp_unsigned_bin_size(n);
{at least RSA_MINSIZE bytes are required for EME-PKCS1-v1_5 padding}
if modlen<RSA_MINSIZE then mp_pkcs1v15_maxlen := 0
else mp_pkcs1v15_maxlen := modlen-RSA_MINSIZE;
end;
{---------------------------------------------------------------------------}
procedure mp_i2osp(const x: mp_int; outp: pointer; len: word);
{-Convert a nonnegative mp_int to an octet string of a specified length}
var
lx,l0: word;
begin
{MPC_ArgCheck in mp_unsigned_bin_size or deeper}
lx := mp_unsigned_bin_size(x);
if lx>len then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXRange.Create('mp_i2osp: x too large"');
{$else}
RunError(MP_RTE_RANGE);
{$endif}
{$else}
set_mp_error(MP_RANGE);
exit;
{$endif}
end;
l0 := len-lx;
{zero "leading digits"}
fillchar(outp^,l0,0);
inc(Ptr2Inc(outp),l0);
{$ifopt X-} l0 := {$endif} mp_to_unsigned_bin_n(x,outp^,lx);
end;
{---------------------------------------------------------------------------}
procedure mp_i2pchar(const x: mp_int; outp: pointer; len: word);
{-Convert a nonnegative mp_int to a pchar with a specified max length}
var
lx,l0: word;
begin
{MPC_ArgCheck in mp_unsigned_bin_size or deeper}
lx := mp_unsigned_bin_size(x);
if lx+1>len then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXRange.Create('mp_i2pchar: x too large"');
{$else}
RunError(MP_RTE_RANGE);
{$endif}
{$else}
set_mp_error(MP_RANGE);
exit;
{$endif}
end;
l0 := mp_to_unsigned_bin_n(x,outp^,lx);
if l0<len then begin
inc(Ptr2Inc(outp),l0);
pchar8(outp)^ := #0;
end;
end;
{---------------------------------------------------------------------------}
procedure mp_os2ip(inp: pointer; ilen: word; var x: mp_int);
{-Convert an octet string of length ilen to a nonnegative mp_int}
begin
{MPC_ArgCheck in mp_read_unsigned_bin}
mp_read_unsigned_bin(x, inp^, ilen);
end;
{---------------------------------------------------------------------------}
function mp_pkcs1v15_decode(em, msg: pointer; emlen: word; var mlen: word): boolean;
{-EME-PKCS1-v1_5 decoding; true if decoding is successful, false otherwise}
{ em - encoded message
emlen - length of encoded message, in bytes
msg - decode message (may be same as em)
mlen - length of decoded msg}
var
ep: PByteArr absolute em;
ip: word;
res: boolean;
begin
{EME-PKCS1-v1_5 decoding: Separate the encoded message EM into an
octet string PS consisting of nonzero octets and a message M as
EM = 0x00 || 0x02 || PS || 0x00 || MSG.
If the first octet of EM does not have hexadecimal value 0x00, if the
second octet of EM does not have hexadecimal value 0x02, if there is
no octet with hexadecimal value 0x00 to separate PS from M, or if the
length of PS is less than 8 octets, output "decryption error".
Note: Care shall be taken to ensure that an opponent cannot distinguish
the different error conditions, whether by error message or timing.
Otherwise an opponent may be able to obtain useful information about
the decryption of the ciphertext C. WE note: This is partly achieved
by running through the entire code without error exit.}
res := true;
{check min length and starting bytes}
if emlen<RSA_MINSIZE then res := false;
if ep^[0]<>$00 then res := false;
if ep^[1]<>$02 then res := false;
{look for zero separator}
ip := 2;
while ip<emlen do begin
if ep^[ip]=0 then break;
inc(ip);
end;
{position of zero separator must be >= 10 and < emlen}
if (ip=emlen) or (ip<10) then res := false;
{copy msg}
mlen := 0;
if emlen > (ip + 1) then begin
mlen := emlen - (ip + 1);
move(ep^[ip+1],msg^,mlen);
end
else res := false;
mp_pkcs1v15_decode := res;
end;
{---------------------------------------------------------------------------}
procedure mp_pkcs1v15_decrypt(const d, n: mp_int; ctp,ptp: pointer; clen,pmax: word; var plen: word);
{-Decrypt a message using RSA and EME-PKCS1-v1_5 padding}
{ n,d - RSA private key pair (n, d) = (modulus, exponent)
ctp - input message (ciphertext)
ptp - pointer to buffer holding decrypted plaintext
clen - length of input message, in bytes
pmax - max. length of plaintext buffer
plen - length of plaintext, in bytes}
var
k: word;
c: mp_int;
buf: pointer;
begin
if mp_error<>MP_OKAY then exit;
{$ifdef MPC_ArgCheck}
{check d here; n checked in mp_unsigned_bin_size}
if mp_not_init(d) then begin
{$ifdef MPC_HaltOnArgCheck}
{$ifdef MPC_UseExceptions}
raise MPXNotInit.Create('mp_pkcs1v15_decrypt');
{$else}
RunError(MP_RTE_NOTINIT);
{$endif}
{$else}
set_mp_error(MP_NOTINIT);
exit;
{$endif}
end;
{$endif}
{get size of modulus n in bytes}
k := mp_unsigned_bin_size(n);
if clen<>k then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXUndef.Create('mp_pkcs1v15_decrypt: clen <> k');
{$else}
RunError(MP_RTE_OTHER);
{$endif}
{$endif}
set_mp_error(MP_UNDEF);
exit;
end;
if pmax<k then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXUndef.Create('mp_pkcs1v15_decrypt: pmax < k');
{$else}
RunError(MP_RTE_OTHER);
{$endif}
{$endif}
set_mp_error(MP_UNDEF);
exit;
end;
{get local memory for encoded message}
buf := mp_getmem(clen);
if buf=nil then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXMemory.Create('mp_pkcs1v15_decrypt: buf=nil');
{$else}
RunError(MP_RTE_MEM);
{$endif}
{$else}
set_mp_error(MP_MEM);
exit;
{$endif}
end;
{initialize ciphertext mp_int representative}
mp_init(c);
if mp_error=MP_OKAY then begin
{convert ciphertext to mp_int representative}
mp_os2ip(ctp, clen, c);
{apply the RSADP decryption primitive to the ciphertext representative c}
mp_rsadp(c, d, n, c);
{Convert the message representative to an encoded message}
mp_i2osp(c, buf, k);
{EME-PKCS1-v1_5 decoding buf -> ptp}
if not mp_pkcs1v15_decode(buf, ptp, k, plen) then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXUndef.Create('mp_pkcs1v15_decrypt: decode error');
{$else}
RunError(MP_RTE_OTHER);
{$endif}
{$endif}
set_mp_error(MP_UNDEF);
end;
mp_clear(c);
end;
fillchar(buf^,clen,0);
mp_freemem(buf, clen);
end;
{---------------------------------------------------------------------------}
procedure mp_pkcs1v15_decrypt2(const prk: TPrivateKey; const n: mp_int; ctp,ptp: pointer; clen,pmax: word; var plen: word);
{-Decrypt a message using RSA/CRT and EME-PKCS1-v1_5 padding}
{ prk,n - private key CRT record and modulus
ctp - input message (ciphertext)
ptp - pointer to buffer holding decrypted plaintext
clen - length of input message, in bytes
pmax - max. length of plaintext buffer
plen - length of plaintext, in bytes}
var
k: word;
c: mp_int;
buf: pointer;
begin
if mp_error<>MP_OKAY then exit;
{Init check n in mp_unsigned_bin_size or below}
{get size of modulus n in bytes}
k := mp_unsigned_bin_size(n);
if clen<>k then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXUndef.Create('mp_pkcs1v15_decrypt2: clen <> k');
{$else}
RunError(MP_RTE_OTHER);
{$endif}
{$endif}
set_mp_error(MP_UNDEF);
exit;
end;
if pmax<k then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXUndef.Create('mp_pkcs1v15_decrypt2: pmax < k');
{$else}
RunError(MP_RTE_OTHER);
{$endif}
{$endif}
set_mp_error(MP_UNDEF);
exit;
end;
{get local memory for encoded message}
buf := mp_getmem(clen);
if buf=nil then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXMemory.Create('mp_pkcs1v15_decrypt2: buf=nil');
{$else}
RunError(MP_RTE_MEM);
{$endif}
{$else}
set_mp_error(MP_MEM);
exit;
{$endif}
end;
{initialize ciphertext mp_int representative}
mp_init(c);
if mp_error=MP_OKAY then begin
{convert ciphertext to mp_int representative}
mp_os2ip(ctp, clen, c);
{apply the RSADP decryption primitive to the ciphertext representative c}
mp_rsadp2(c, prk, c);
{Convert the message representative to an encoded message}
mp_i2osp(c, buf, k);
{EME-PKCS1-v1_5 decoding buf -> ptp}
if not mp_pkcs1v15_decode(buf, ptp, k, plen) then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXUndef.Create('mp_pkcs1v15_decrypt2: decode error');
{$else}
RunError(MP_RTE_OTHER);
{$endif}
{$endif}
set_mp_error(MP_UNDEF);
end;
mp_clear(c);
end;
fillchar(buf^,clen,0);
mp_freemem(buf, clen);
end;
{---------------------------------------------------------------------------}
function mp_pkcs1v15_encode(msg, em: pointer; mlen, emlen: word; rnd: byte): boolean;
{-EME-PKCS1-v1_5 encoding; true if encoding is successful, false otherwise}
{ msg - plaintext message
mlen - length of plaintext message
em - encoded message
emlen - length of encoded message, in bytes, will be padded
rnd - pad byte, if pad=0 use bytes generated with mp_random_byte}
var
i,ip: word;
ep: PByteArr absolute em;
rb: byte;
begin
if mlen>emlen-RSA_MINSIZE then mp_pkcs1v15_encode := false
else begin
{EME-PKCS1-v1_5 encoding:
Generate an octet string PS of length emLen - mLen - 3 consisting
of pseudo-randomly generated nonzero octets. The length of PS
will be at least eight octets.
Concatenate PS, the message MSG, and other padding to form an
encoded message EM of length k octets as
EM = 0x00 || 0x02 || PS || 0x00 || MSG.
WE-Note: First 0 byte makes mp_int representative less than modulus}
{insert starting bytes}
ep^[0] := $00;
ep^[1] := $02;
{calculate padding offset. Note: mlen<=emlen-RSA_MINSIZE -> ip>=RSA_MINSIZE}
ip := emlen-mlen;
{insert padding bytes}
for i:=2 to ip-2 do begin
if rnd<>0 then ep^[i] := rnd
else begin
{generate random nonzero padding bytes}
repeat
rb := mp_random_byte;
until rb<>0;
ep^[i] := rb;
end;
end;
{insert zero separator}
ep^[ip-1] := 0;
move(msg^,ep^[ip],mlen);
mp_pkcs1v15_encode := true;
end;
end;
{---------------------------------------------------------------------------}
procedure mp_pkcs1v15_encrypt(const e, n: mp_int; rnd: byte; ptp,ctp: pointer; plen,cmax: word; var clen: word);
{-Encrypt a message using RSA and EME-PKCS1-v1_5 padding}
{ n,e - recipient's RSA public key pair (n, e) = (modulus, exponent)
rnd - padding byte, if 0 mp_random_byte is used
ptp - input message (plaintext)
ctp - output message (ciphertext)
plen - length of buffer holding plaintext, in bytes
cmax - max length of ciphertext buffer
clen - length of output message, in bytes}
var
k: word;
c: mp_int;
buf: pointer;
begin
if mp_error<>MP_OKAY then exit;
{$ifdef MPC_ArgCheck}
{check e here; n checked in mp_unsigned_bin_size}
if mp_not_init(e) then begin
{$ifdef MPC_HaltOnArgCheck}
{$ifdef MPC_UseExceptions}
raise MPXNotInit.Create('mp_pkcs1v15_encrypt');
{$else}
RunError(MP_RTE_NOTINIT);
{$endif}
{$else}
set_mp_error(MP_NOTINIT);
exit;
{$endif}
end;
{$endif}
{get size of modulus n in bytes}
k := mp_unsigned_bin_size(n);
if cmax<k then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXUndef.Create('mp_pkcs1v15_encrypt: cmax < k');
{$else}
RunError(MP_RTE_OTHER);
{$endif}
{$endif}
set_mp_error(MP_UNDEF);
exit;
end;
clen := k;
{get local memory for encoded message}
buf := mp_getmem(clen);
if buf=nil then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXMemory.Create('mp_pkcs1v15_encrypt: buf=nil');
{$else}
RunError(MP_RTE_MEM);
{$endif}
{$else}
set_mp_error(MP_MEM);
exit;
{$endif}
end;
{initialize ciphertext mp_int representative}
mp_init(c);
if mp_error=MP_OKAY then begin
{-EME-PKCS1-v1_5 encoding ptp -> buf}
if not mp_pkcs1v15_encode(ptp, buf, plen, k, rnd) then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXUndef.Create('mp_pkcs1v15_encrypt: encode error');
{$else}
RunError(MP_RTE_OTHER);
{$endif}
{$endif}
set_mp_error(MP_UNDEF);
end
else begin
{Convert the encoded message EM to mp_int representative c}
mp_os2ip(buf, k, c);
{Apply the RSAEP encryption primitive to the message representative c}
mp_rsaep(c, e, n, c);
{Convert the ciphertext representative c to octet string}
mp_i2osp(c, ctp, clen);
end;
mp_clear(c);
end;
fillchar(buf^,clen,0);
mp_freemem(buf, clen);
end;
{---------------------------------------------------------------------------}
procedure mp_rsadp(const c, d, n: mp_int; var m: mp_int);
{-Basic RSA decryption operation, m=c^d mod n.}
{ c : ciphertext representative, an integer between 0 and n - 1.
n,d : RSA private key pair (n, d) = (modulus, exponent).
m : message representative, an integer between 0 and n - 1.}
begin
if mp_error<>MP_OKAY then exit;
{$ifdef MPC_ArgCheck}
{check c,n here; d,m are checked in mp_exptmod}
if mp_not_init(c) or mp_not_init(n) then begin
{$ifdef MPC_HaltOnArgCheck}
{$ifdef MPC_UseExceptions}
raise MPXNotInit.Create('mp_rsadp');
{$else}
RunError(MP_RTE_NOTINIT);
{$endif}
{$else}
set_mp_error(MP_NOTINIT);
exit;
{$endif}
end;
{$endif}
{Insure that ciphertext representative is in range of modulus}
if (c.sign=MP_NEG) or (mp_cmp(c, n)<>MP_LT) then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXRange.Create('mp_rsadp: ciphertext representative out of range');
{$else}
RunError(MP_RTE_RANGE);
{$endif}
{$else}
set_mp_error(MP_RANGE);
exit;
{$endif}
end;
mp_exptmod(c, d, n, m);
end;
{---------------------------------------------------------------------------}
procedure mp_rsadp2(const c: mp_int; const prk: TPrivateKey; var m: mp_int);
{-Basic RSA decryption operation for private key CRT record.}
{ c : ciphertext representative, an integer between 0 and n - 1. Note
that this condition will be checked only approximately.
prk : RSA private key CRT record.
m : message representative, an integer between 0 and n - 1.}
var
t: mp_int;
begin
if mp_error<>MP_OKAY then exit;
{$ifdef MPC_ArgCheck}
{check c,n here; d,m are checked in mp_exptmod}
if mp_not_init(c) or mp_not_init(m) or mp_not_init(prk.p) or mp_not_init(prk.q)
or mp_not_init(prk.dp) or mp_not_init(prk.dq) or mp_not_init(prk.qinv)
then begin
{$ifdef MPC_HaltOnArgCheck}
{$ifdef MPC_UseExceptions}
raise MPXNotInit.Create('mp_rsadp2');
{$else}
RunError(MP_RTE_NOTINIT);
{$endif}
{$else}
set_mp_error(MP_NOTINIT);
exit;
{$endif}
end;
{$endif}
{Insure that ciphertext representative is in range of modulus}
if (c.sign=MP_NEG) or (mp_bitsize(c) > (mp_bitsize(prk.p)+mp_bitsize(prk.q))) then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXRange.Create('mp_rsadp2: ciphertext representative out of range');
{$else}
RunError(MP_RTE_RANGE);
{$endif}
{$else}
set_mp_error(MP_RANGE);
exit;
{$endif}
end;
mp_init(t);
if mp_error=MP_OKAY then with prk do begin
{no need to reduce c mod p/q, will be done implicitly in mp_exptmod}
{m1 = c^dp mod p}
mp_exptmod(c,dp,p,t);
{m2 = c^dq mod q}
mp_exptmod(c,dq,q,m);
{h = (m1-m2)*qinv mod p}
mp_submod(t,m,p,t);
mp_mulmod(t,qinv,p,t);
{m = m2+q*h}
mp_mul(q,t,t);
mp_add(t,m,m);
mp_clear(t);
end;
end;
{---------------------------------------------------------------------------}
procedure mp_rsaep(const m, e, n: mp_int; var c: mp_int);
{-Basic RSA encryption operation, c=m^e mod n.}
{ m : message representative, an integer between 0 and n - 1.
n,e : RSA public key pair (n, e) = (modulus, exponent).
c : ciphertext representative, an integer between 0 and n - 1.}
begin
if mp_error<>MP_OKAY then exit;
{$ifdef MPC_ArgCheck}
{check m,n here; d,m are checked in mp_exptmod}
if mp_not_init(m) or mp_not_init(n) then begin
{$ifdef MPC_HaltOnArgCheck}
{$ifdef MPC_UseExceptions}
raise MPXNotInit.Create('mp_rsaep');
{$else}
RunError(MP_RTE_NOTINIT);
{$endif}
{$else}
set_mp_error(MP_NOTINIT);
exit;
{$endif}
end;
{$endif}
{Insure that message representative is in range of modulus}
if (m.sign=MP_NEG) or (mp_cmp(m, n)<>MP_LT) then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXRange.Create('mp_rsaep: message representative out of range');
{$else}
RunError(MP_RTE_RANGE);
{$endif}
{$else}
set_mp_error(MP_RANGE);
exit;
{$endif}
end;
mp_exptmod(m, e, n, c);
end;
{---------------------------------------------------------------------------}
procedure mp_rsa_calc_d(const e: mp_int; const prk: TPrivateKey; var d: mp_int);
{-Get RSA decryption exponent d from private key record and encryption exponent e}
var
p,q: mp_int;
begin
if mp_error<>MP_OKAY then exit;
{$ifdef MPC_ArgCheck}
if mp_not_init(e) or mp_not_init(d) or mp_not_init(prk.p) or mp_not_init(prk.q)
or mp_not_init(prk.dp) or mp_not_init(prk.dq) or mp_not_init(prk.qinv)
then begin
{$ifdef MPC_HaltOnArgCheck}
{$ifdef MPC_UseExceptions}
raise MPXNotInit.Create('mp_rsa_calc_d');
{$else}
RunError(MP_RTE_NOTINIT);
{$endif}
{$else}
set_mp_error(MP_NOTINIT);
exit;
{$endif}
end;
{$endif}
mp_init2(p,q);
if mp_error=MP_OKAY then begin
{now calculate d := e^-1 mod lcm(p-1, q-1)}
mp_sub_d(prk.p,1,p);
mp_sub_d(prk.q,1,q);
mp_lcm(p,q,d);
mp_invmod(e,d,d);
mp_clear2(p,q);
end;
end;
{---------------------------------------------------------------------------}
procedure mp_rsa_calc_nd(const e,p,q: mp_int; var n,d: mp_int);
{-Calculate n,d from e,p,q}
var
p1,q1: mp_int;
begin
if mp_error<>MP_OKAY then exit;
{$ifdef MPC_ArgCheck}
if mp_not_init(e) or mp_not_init(d) or mp_not_init(n) or mp_not_init(p) or mp_not_init(q) then begin
{$ifdef MPC_HaltOnArgCheck}
{$ifdef MPC_UseExceptions}
raise MPXNotInit.Create('mp_rsa_calc_nd');
{$else}
RunError(MP_RTE_NOTINIT);
{$endif}
{$else}
set_mp_error(MP_NOTINIT);
exit;
{$endif}
end;
{$endif}
mp_init2(p1,q1);
if mp_error=MP_OKAY then begin
mp_sub_d(p,1,p1);
mp_sub_d(q,1,q1);
{n := p*q}
mp_mul(p,q,n);
{d := e^-1 mod lcm(p-1, q-1)}
mp_lcm(p1,q1,d);
mp_invmod(e,d,d);
mp_clear2(p1,q1);
end;
end;
{---------------------------------------------------------------------------}
procedure mp_rsa_calc_npq(const e: mp_int; osize: word; var n,p,q: mp_int);
{-Generate RSA primes p,q; q<p, n=p*q, osize: octet size of n;}
{ e: public key encryption exponent, e odd and greater than 2}
var
t: mp_int;
s3,s4,s8: word;
f: mp_digit;
const
fmaxs = mp_digit(MP_DIGIT_MAX and $3FF);
begin
if mp_error<>MP_OKAY then exit;
{$ifdef MPC_ArgCheck}
if mp_not_init(e) or mp_not_init(n) or mp_not_init(p) or mp_not_init(q) then begin
{$ifdef MPC_HaltOnArgCheck}
{$ifdef MPC_UseExceptions}
raise MPXNotInit.Create('mp_rsa_calc_npq');
{$else}
RunError(MP_RTE_NOTINIT);
{$endif}
{$else}
set_mp_error(MP_NOTINIT);
exit;
{$endif}
end;
{$endif}
{check if e is odd and greater than 2}
if mp_iseven(e) or (mp_cmp_d(e,3)=MP_LT) then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXBadArg.Create('mp_rsa_calc_npq: e is even or <3');
{$else}
RunError(MP_RTE_BADARG);
{$endif}
{$else}
set_mp_error(MP_BADARG);
exit;
{$endif}
end;
{check requested octet size of n}
if osize<RSA_MINSIZE then begin
{$ifdef MPC_HaltOnError}
{$ifdef MPC_UseExceptions}
raise MPXBadArg.Create('mp_rsa_calc_npq: osize < RSA_MINSIZE');
{$else}
RunError(MP_RTE_BADARG);
{$endif}
{$else}
set_mp_error(MP_BADARG);
exit;
{$endif}
end;
mp_init(t);
if mp_error=MP_OKAY then begin
{bit size of p and q = 1/2 bit size of n = 4*osize}
s3 := 3*osize;
s4 := 4*osize;
s8 := s4+s4;
{generate p with gcd(p-1,e)=1}
repeat
if mp_error<>MP_OKAY then begin
mp_clear(t);
exit;
end;
mp_rand_bits(p,s4);
p.pdigits^[0] := p.pdigits^[0] or 1;