-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathopensslutils.pas
More file actions
2393 lines (2143 loc) · 71.1 KB
/
Copy pathopensslutils.pas
File metadata and controls
2393 lines (2143 loc) · 71.1 KB
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 OpenSSLUtils;
{$mode objfpc}{$H+}
interface
uses
windows, SysUtils, classes,dateutils,
libeay32,utils,inifiles,math;
procedure LoadSSL;
procedure FreeSSL;
function generate_rsa_key:boolean;
function generate_rsa_key_2:boolean;
function mkcert(filename:string;cn:string;privatekey:string='';read_password:string='';serial:string='';ca:boolean=false):boolean;
function mkreq(cn:string;keyfile,csrfile:string):boolean;
function signreq(filename:string;cert:string;read_password:string='';alt:string='';ca:boolean=false):boolean;
//function selfsign(filename:string;subject:string):boolean;
function set_password(filename,password:string):boolean;
function P7B2PEM(filename:string):boolean;
function PEM2P7B(filename:string):boolean;
function PFX2PEM(filename,export_pwd:string):boolean;
function PEM2PFX(export_pwd,privatekey,cert:string):boolean;
function PVTDER2PEM(filename:string):boolean;
function PVTPEM2DER(filename:string):boolean;
function X509DER2PEM(filename:string):boolean;
function X509PEM2DER(filename:string):boolean;
function print_cert(filename:string):boolean;
function print_private(filename:string;password:string=''):boolean;
function print_req(filename:string):boolean;
function Encrypt_Pub(sometext:string;var encrypted:string):boolean;
function Decrypt_Priv(ACryptedData:string):boolean;
function hash(algo:string;input:array of byte):boolean;
function crypt(algo,input:string;keystr:string='';ivstr:string='';enc:integer=1):boolean;
function list_ciphers:boolean;
function list_hashes:boolean;
function Base64Encode(message:array of byte):boolean;
function Base64Decode(message:string;utf16:boolean=false):boolean;
function getDN(pDn: pX509_NAME): String;
function getTime(asn1_time: pASN1_TIME): TDateTime;
function getSerialNumber(x509:px509): String;
function hextosomething(str:string):boolean;
implementation
type
ReadKeyChar = AnsiChar;
//ReadKeyChar = Byte;
PReadKeyChar = ^ReadKeyChar;
//OpenSSL_add_all_algorithms() is not needed for newer OpenSSL versions and is ignored
//The same applies to OpenSSL_add_all_ciphers() and OpenSSL_add_all_digests()
//This is not entirely accurate (at least not any more). OpenSSL_add_all_algorithms is not ignored, it is simply a macro wrapping a call to OPENSSL_init_crypto,
//see for example github.com/openssl/openssl/blob/…
procedure LoadSSL;
begin
OpenSSL_add_all_algorithms;
OpenSSL_add_all_ciphers;
OpenSSL_add_all_digests;
ERR_load_crypto_strings;
ERR_load_RSA_strings;
end;
procedure FreeSSL;
begin
EVP_cleanup;
ERR_free_strings;
end;
function BIO_ReadAnsiString(bp: PBIO): AnsiString;
var Buf: AnsiString;
a: TC_INT;
begin
Result := '';
SetLength(Buf, 512);
repeat
a := BIO_read(bp, @Buf[1], Length(Buf));
if a > 0 then
Result := Result + Copy(Buf, 1, a);
until a <= 0;
SetLength(Buf, 0);
end;
function LoadPEMFile(filePath: string): PBio;
var
{$IFNDEF MSWINDOWS}
LEncoding: TEncoding;
LOffset: Integer;
{$ENDIF}
Buffer: TBytes;
Stream: TStream;
begin
log('LoadPEMFile');
Stream := TFileStream.Create(filePath, fmOpenRead or fmShareDenyWrite);
try
SetLength(Buffer, Stream.size);
Stream.ReadBuffer(Buffer[0], Stream.size);
{$IFNDEF MSWINDOWS}
{On traite les problèmes d'encodage de flux sur les plateformes différentes de Windows}
LEncoding := nil;
LOffset := TEncoding.GetBufferEncoding(Buffer, LEncoding);
Buffer := LEncoding.Convert(LEncoding, TEncoding.UTF8, Buffer, LOffset,
Length(Buffer) - LOffset);
{$ENDIF}
Result := BIO_new_mem_buf(@Buffer[0], Length(Buffer));
finally
Stream.free;
end;
end;
function LoadCertPublicKey(filePath: string): PEVP_PKEY;
var
mem: PBIO;
FX509: pX509;
//Key: PEVP_PKEY;
x: pX509=nil;
begin
log('LoadCertPublicKey: '+filepath);
//KeyBuffer := LoadPEMFile(filepath);
//if KeyBuffer = nil then raise Exception.Create('Impossible de charger le buffer X509');
mem := BIO_new(BIO_s_file());
log('BIO_read_filename');
BIO_read_filename(mem, PAnsiChar(filePath));
try
FX509 := PEM_read_bio_X509(mem, x, nil, nil);
if not Assigned(FX509) then
raise Exception.Create('PEM_read_bio_X509 failed');
result := X509_get_pubkey(FX509);
finally
BIO_free(mem);
end;
end;
function LoadPublicKey(KeyFile: string) :pEVP_PKEY ;
var
mem: pBIO;
k: pEVP_PKEY;
rc:integer=0;
begin
log('LoadPublicKey: '+KeyFile);
k:=nil;
mem := BIO_new(BIO_s_file()); //BIO типа файл
log('BIO_read_filename');
rc:=BIO_read_filename(mem, PAnsiChar(KeyFile)); // чтение файла ключа в BIO
log(inttostr(rc));
try
log('PEM_read_bio_PUBKEY');
result := PEM_read_bio_PUBKEY(mem, k, nil, nil); //преобразование BIO в структуру pEVP_PKEY, третий параметр указан nil, означает для ключа не нужно запрашивать пароль
finally
BIO_free_all(mem);
end;
end;
function LoadPrivateKey(KeyFile: string;password:string='') :pEVP_PKEY;
var
mem: pBIO;
k: pEVP_PKEY;
begin
log('LoadPrivateKey: '+KeyFile);
k := nil;
mem := BIO_new(BIO_s_file());
BIO_read_filename(mem, PAnsiChar(KeyFile));
try
log('PEM_read_bio_PrivateKey');
if password=''
then result := PEM_read_bio_PrivateKey(mem, k, nil, nil)
else result := PEM_read_bio_PrivateKey(mem, k, nil, pchar(password));
finally
BIO_free_all(mem);
end;
end;
{
Importer une clé publique RSA
Un fichier au format PEM contenant une clé publique RSA
commence par —–BEGIN PUBLIC KEY—–
puis est suivi de la clé en Base64
et se termine par —–END PUBLIC KEY—–.
}
function RSAOpenSSLPublicKey(filePath: string): pRSA;
var
KeyBuffer: PBIO;
pkey: PEVP_PKEY;
x: pEVP_PKEY;
begin
log('FromOpenSSLPublicKey: '+filepath);
x:=nil;
KeyBuffer := LoadPEMFile(filePath);
if KeyBuffer = nil then
raise Exception.Create('Impossible de charger le buffer');
try
pkey := PEM_read_bio_PUBKEY(KeyBuffer, x, nil, nil);
if not Assigned(pkey) then
raise Exception.Create('Impossible de charger la clé publique');
try
Result := EVP_PKEY_get1_RSA(pkey);
if not Assigned(Result) then
raise Exception.Create('Impossible de charger la clé publique RSA');
finally
EVP_PKEY_free(pkey);
end;
finally
BIO_free(KeyBuffer);
end;
end;
{
Importer une clé privée RSA (chiffrée ou non)
Un fichier au format PEM contenant un clé privée RSA
commence par —–BEGIN PRIVATE KEY—– puis est suivi de la clé en Base64
et se termine par —–END PRIVATE KEY—–.
Si la clé est chiffrée, alors le fichier au format PEM
commence par —–BEGIN RSA PRIVATE KEY—– puis est suivi de Proc-Type: 4,ENCRYPTED.
Ensuite, il y a des informations sur l’algorithme utilisé pour chiffrer la clé (par exemple AES-128-CBC)
puis il y a la clé chiffrée, en Base64.
Enfin, le fichier se termine par —–END RSA PRIVATE KEY—–.
}
function RSAOpenSSLPrivateKey(filePath: string; pwd: String=''): pRSA;
var
KeyBuffer: PBio;
p: PReadKeyChar;
I: Integer;
x: pRSA;
begin
log('FromOpenSSLPrivateKey: '+filepath);
x:=nil;
KeyBuffer := LoadPEMFile(filePath);
if KeyBuffer = nil then
raise Exception.Create('cannot load buffer');
try
if pwd <> '' then
begin
p := GetMemory((length(pwd) + 1) * SizeOf(Char));
for I := 0 to length(pwd) - 1 do p[I] := ReadKeyChar(pwd[I+1]);
p[length(pwd)] := ReadKeyChar(#0);
end
else
p := nil; //password will be prompted
try
Result := PEM_read_bio_RSAPrivateKey(KeyBuffer, x, nil, p);
if not Assigned(Result) then
raise Exception.Create('cannot load private key');
finally
{On efface le mot de passe}
FillChar(p, SizeOf(p), 0);
FreeMem(p);
end;
finally
BIO_free(KeyBuffer);
end;
end;
{
Importer une clé publique RSA à partir d’un certificat X509
Un fichier au format PEM contenant un certificat X509
commence par —–BEGIN CERTIFICATE—– puis est suivi de la clé en Base64
et se termine par —–END CERTIFICATE—–.
}
function RSAOpenSSLCert(filePath: string): pRSA;
var
KeyBuffer: PBIO;
FX509: pX509;
Key: PEVP_PKEY;
x: pX509;
begin
log('FromOpenSSLCert: '+filepath);
x:=nil;
//KeyBuffer := LoadPEMFile(Buffer, Length(Buffer));
KeyBuffer := LoadPEMFile(filepath);
if KeyBuffer = nil then
raise Exception.Create('Impossible de charger le buffer X509');
try
FX509 := PEM_read_bio_X509(KeyBuffer, x, nil, nil);
if not Assigned(FX509) then
raise Exception.Create('Impossible de charger le certificat X509');
Key := X509_get_pubkey(FX509);
if not Assigned(Key) then
raise Exception.Create('Impossible de charger la clé publique X509');
try
Result := EVP_PKEY_get1_RSA(Key);
if not Assigned(Result) then
raise Exception.Create('Impossible de charger la clé publique RSA');
finally
EVP_PKEY_free(Key);
end;
finally
BIO_free(KeyBuffer);
end;
end;
function PEM2P7B(filename:string):boolean;
var
p7: pPKCS7=nil;
certs:pSTACK_OFX509 = nil;
bp:pBIO;
x509_cert:pX509=nil;
begin
result:=false;
log('PEM2P7B');
log('filename:'+filename);
bp := BIO_new_file(pchar(filename), 'r+');
log('PEM_read_bio_X509');
certs := sk_new_null();
while 1=1 do
begin
x509_cert := PEM_read_bio_X509(bp, nil, nil, nil);
if x509_cert =nil then break;
sk_push(certs, x509_cert);
end;
BIO_free(bp);
x509_cert :=sk_value(certs,0);
if x509_cert=nil then
begin
writeln('PEM_read_bio_X509 failed');
exit;
end;
//log('i2d_PKCS7_bio');
//result:=i2d_PKCS7_bio (bp,p7)<>-1; //der
//if result=false then writeln('i2d_X509_bio failed');
//https://www.openssl.org/docs/man1.0.2/man3/PKCS7_sign.html
//if signcert and pkey are NULL then a certificates only PKCS#7 structure is output.
p7 := PKCS7_sign(nil, nil, certs, nil, PKCS7_BINARY);
if p7=nil then writeln('PKCS7_sign failed');
//finalize the structure
log('PEM_write_bio_PKCS7');
bp := BIO_new_file(pchar(GetCurrentDir+'\'+changefileext(filename,'.p7b')), 'w+');
PEM_write_bio_PKCS7(bp,p7);
BIO_free(bp);
sk_free(certs);
result:=true;
end;
function P7B2PEM(filename:string):boolean;
var
bp:pBIO;
p7: pPKCS7;
i:byte;
begin
result:=false;
log('P7B2PEM');
log('filename:'+filename);
result:=false;
bp := BIO_new_file(pchar(filename), 'r+');
log('d2i_PKCS7_bio');
//decode
//p7:=d2i_PKCS7_bio(bp, nil); //d2i_PKCS7_bio expect a binary der PKCS7
p7:=PEM_read_bio_PKCS7(bp,nil,nil,nil); //if your input is in a pem format you should call PEM_read_bio_PKCS7 instead
BIO_free(bp);
if p7 = nil then exit;
//OBJ_obj2nid(p7^.type) should give us the type of p7b : NID_pkcs7_signed or NID_pkcs7_signedAndEnveloped
//sk_num should give us number of certs // if more than one we should sk_X509_shift or sk_X509_value(certs, i)
if (p7^.sign^.cert <> nil) then
begin
bp := BIO_new_file(pchar(GetCurrentDir+'\'+changefileext(filename,'.crt')), 'w+');
log('PEM_write_bio_X509');
for i:=0 to sk_num(p7^.sign^.cert) -1 do
begin
//PEM_write_bio_X509(bp,sk_X509_value(p7^.sign^.cert, 0));
PEM_write_bio_X509(bp,sk_value(p7^.sign^.cert, i));
end;
BIO_free(bp);
result:=true;
end;
end;
function PFX2PEM(filename,export_pwd:string):boolean;
const
PKCS12_R_MAC_VERIFY_FAILURE =113;
var
p12_cert:pPKCS12 = nil;
pkey:pEVP_PKEY=nil;
x509_cert:pX509=nil;
additional_certs:pSTACK_OFX509 = nil;
bp:pBIO;
err_reason:integer;
begin
result:=false;
log('Convert2PEM');
log('filename:'+filename);
result:=false;
bp := BIO_new_file(pchar(filename), 'r+');
log('d2i_PKCS12_bio');
//decode
p12_cert:=d2i_PKCS12_bio(bp, nil);
if p12_cert = nil then exit;
log('PKCS12_parse');
//this is the export password, not the private key password
err_reason:=PKCS12_parse(p12_cert, pchar(export_pwd), pkey, x509_cert, additional_certs);
//if err_reason<>0 then
log(inttostr(err_reason));
BIO_free(bp);
if err_reason =0 then exit;
//
bp := BIO_new_file(pchar(GetCurrentDir+'\'+changefileext(filename,'.crt')), 'w+');
log('PEM_write_bio_X509');
PEM_write_bio_X509(bp,x509_cert);
BIO_free(bp);
if pkey=nil then exit;
bp := BIO_new_file(pchar(GetCurrentDir+'\'+changefileext(filename,'.key')), 'w+');
log('PEM_write_bio_PrivateKey');
log('no password...');
//the private key will have no password
PEM_write_bio_PrivateKey(bp,pkey,nil{EVP_des_ede3_cbc()},nil,0,nil,nil);
BIO_free(bp);
//
if x509_cert<>nil then X509_free(x509_cert); x509_cert := nil;
if pkey<>nil then EVP_PKEY_free(pkey); pkey := nil;
ERR_clear_error();
PKCS12_free(p12_cert);
result:=true;
end;
function PEM2PFX(export_pwd,privatekey,cert:string):boolean;
var
err_reason:integer;
bp:pBIO=nil;
p12_cert:pPKCS12 = nil;
pkey:pEVP_PKEY = nil;
x509_cert:pX509 = nil;
certs:pSTACK_OFX509 = nil;
begin
result:=false;
log('Convert2PKCS12');
log('cert:'+cert);
log('privatekey:'+privatekey);
bp := BIO_new_file(pchar(privatekey), 'r+');
log('PEM_read_bio_PrivateKey');
//password will be prompted
pkey:=PEM_read_bio_PrivateKey(bp,nil,nil,nil);
BIO_free(bp);
if pkey=nil then
begin
writeln('PEM_read_bio_PrivateKey failed');
exit;
end;
bp := BIO_new_file(pchar(cert), 'r+');
log('PEM_read_bio_X509');
//x509_cert:=PEM_read_bio_X509(bp,nil,nil,nil);
certs := sk_new_null();
while 1=1 do
begin
x509_cert := PEM_read_bio_X509(bp, nil, nil, nil);
if x509_cert =nil then break;
sk_push(certs, x509_cert);
end;
BIO_free(bp);
x509_cert :=sk_value(certs,0);
if x509_cert=nil then
begin
writeln('PEM_read_bio_X509 failed');
exit;
end;
log('PKCS12_new');
p12_cert := PKCS12_new();
if p12_cert=nil then exit;
log('PKCS12_create');
p12_cert := PKCS12_create(pchar(export_pwd), nil, pkey, nil, certs, 0, 0, 0, 0, 0);
if p12_cert = nil then
begin
writeln('PKCS12_create failed, '+inttohex(ERR_peek_error,8));
//(SSL: error:0B080074:x509 certificate routines: X509_check_private_key:key values mismatch)
exit;
end;
log('i2d_PKCS12_bio');
bp := BIO_new_file(pchar(GetCurrentDir+'\'+changefileext(cert,'.pfx')), 'w+');
err_reason:=i2d_PKCS12_bio(bp, p12_cert);
BIO_free(bp);
if x509_cert<>nil then X509_free(x509_cert); x509_cert := nil;
if pkey<>nil then EVP_PKEY_free(pkey); pkey := nil;
ERR_clear_error();
PKCS12_free(p12_cert);
result:=err_reason<>0;
end;
function X509PEM2DER(filename:string):boolean;
var
x509_cert:pX509=nil;
bp:pBIO;
begin
result:=false;
log('X509PEM2DER');
log('filename:'+filename);
bp := BIO_new_file(pchar(filename), 'r+');
log('PEM_read_bio_X509');
x509_cert:=PEM_read_bio_X509(bp,nil,nil,nil);
BIO_free(bp);
if x509_cert=nil then
begin
writeln('PEM_read_bio_X509 failed');
exit;
end;
bp := BIO_new_file(pchar(GetCurrentDir+'\'+changefileext(filename,'.der')), 'w+');
result:= i2d_X509_bio (bp,x509_cert )<>-1;
if result=false then writeln('i2d_X509_bio failed');
BIO_free(bp);
end;
function X509DER2PEM(filename:string):boolean;
var
hfile_:thandle=thandle(-1);
mem_:array[0..8192-1] of char;
size_:dword=0;
//
pemX509Bio,bp:pBIO;
X509Key:pX509=nil;
begin
result:=false;
//
hfile_ := CreateFile(pchar(filename), GENERIC_READ , FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL, 0);
if hfile_=thandle(-1) then begin log('invalid handle',1);exit;end;
ReadFile (hfile_,mem_[0],sizeof(mem_),size_,nil);
closehandle(hfile_);
//
pemX509Bio := BIO_new(BIO_s_mem());
BIO_write(pemX509Bio, @mem_[0], size_);
BIO_flush(pemX509Bio);
X509Key := d2i_X509_bio (pemX509Bio, X509Key);
if X509Key=nil then exit;
//
bp := BIO_new_file(pchar(GetCurrentDir+'\'+changefileext(filename,'.crt')), 'w+');
log('PEM_write_bio_X509');
PEM_write_bio_X509 (bp,X509Key);
BIO_free(bp);
//
result:=true;
end;
function PVTDER2PEM(filename:string):boolean;
var
hfile_:thandle=thandle(-1);
mem_:array[0..8192-1] of char;
size_:dword=0;
//
pemPrivKeyBio,bp:pBIO;
privKey:pEVP_PKEY=nil;
begin
result:=false;
//
hfile_ := CreateFile(pchar(filename), GENERIC_READ , FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL, 0);
if hfile_=thandle(-1) then begin log('invalid handle',1);exit;end;
ReadFile (hfile_,mem_[0],sizeof(mem_),size_,nil);
closehandle(hfile_);
//
pemPrivKeyBio := BIO_new(BIO_s_mem());
BIO_write(pemPrivKeyBio, @mem_[0], size_);
BIO_flush(pemPrivKeyBio);
//BIO_read_filename easier?;
privKey := d2i_PrivateKey_bio(pemPrivKeyBio, privKey {nil?});
if privkey=nil then exit;
//
bp := BIO_new_file(pchar(GetCurrentDir+'\'+changefileext(filename,'.key')), 'w+');
log('PEM_write_bio_PrivateKey');
log('no password...');
//the private key will have no password
PEM_write_bio_PrivateKey(bp,privKey,nil{EVP_des_ede3_cbc()},nil,0,nil,nil);
BIO_free(bp);
//
result:=true;
end;
function PVTPEM2DER(filename:string):boolean;
var
p:pEVP_PKEY =nil;
bp:pBIO;
begin
result:=false;
log('PVTPEM2DER');
log('filename:'+filename);
p:=LoadPrivateKey(filename);
if p=nil then
begin
writeln('LoadPrivateKey failed');
exit;
end;
bp := BIO_new_file(pchar(GetCurrentDir+'\'+changefileext(filename,'.der')), 'w+');
result:= i2d_PrivateKey_bio (bp,p )<>-1;
if result=false then writeln('i2d_X509_bio failed');
BIO_free(bp);
end;
{
function selfsign(filename:string;subject:string):boolean;
var
x:pX509 = nil;
tmp:pX509_NAME=nil;
pkey:pEVP_PKEY = nil;
rsa:pRSA=nil;
bp:pBIO=nil;
begin
result:=false;
x := X509_new();
//OpenSSL provides the EVP_PKEY structure for storing an algorithm-independent private key in memory
log('EVP_PKEY_new');
pkey := EVP_PKEY_new();
//generate key
log('RSA_generate_key');
rsa := RSA_generate_key(
2048, //* number of bits for the key - 2048 is a sensible value */
RSA_F4, //* exponent - RSA_F4 is defined as 0x10001L */
nil, //* callback - can be NULL if we aren't displaying progress */
nil //* callback argument - not needed in this case */
);
//assign key to our struct
log('EVP_PKEY_assign_RSA');
EVP_PKEY_assign(pkey,EVP_PKEY_RSA,PCharacter(rsa));
X509_set_version(x, 2); //* version 3 certificate */
ASN1_INTEGER_set(X509_get_serialNumber(x),0);
X509_gmtime_adj(X509_get_notBefore(x), 0);
X509_gmtime_adj(X509_get_notAfter(x), 365 * 24 * 3600);
tmp := X509_get_subject_name(x);
X509_NAME_add_entry_by_txt(tmp, 'CN', MBSTRING_ASC, pchar(subject), -1, -1, 0);
X509_set_subject_name(x, tmp);
X509_set_pubkey(x, pkey);
X509_sign(x, pkey, EVP_sha256 ());
bp := BIO_new_file(pchar(ChangeFileExt (filename,'.key')), 'w+');
//PEM_write_bio_PrivateKey(bp,pkey,nil,nil,0,nil,nil);
//if you want a prompt for passphrase
log('PEM_write_bio_PrivateKey');
PEM_write_bio_PrivateKey(bp,pkey,EVP_des_ede3_cbc(),nil,0,nil,nil);
BIO_free(bp);
bp := BIO_new_file(pchar(filename), 'w+');
log('PEM_write_bio_X509');
PEM_write_bio_X509(bp,x);
BIO_free(bp);
result:=x<>nil;
if (x<>nil) then X509_free(x);
if (pkey<>nil) then EVP_PKEY_free(pkey);
end;
}
function name_add_entry(section:string;name:px509_name):boolean;
var
//
ini:TIniFile;
ident:tstrings;
s:string;
i:byte;
begin
log('name_add_entry');
result:=false;
if FileExists ('tinyssl.ini') then
begin
try
ini:=tinifile.Create ('tinyssl.ini');
ident:=tstringlist.Create ;
ini.ReadSection(section,ident) ;
for i:=0 to ident.count-1 do
begin
s:=ini.ReadString (section,ident[i],'');
log('X509_NAME_add_entry_by_txt');
X509_NAME_add_entry_by_txt(name, pchar(ident[i]), MBSTRING_ASC,pchar(s), -1, -1, 0);
end;
ident.Free ;
result:=true;
except
on e:exception do;
end;
end; //if FileExists ('tinyssl.ini') then
end;
function ini_readstring(section,ident:string):string;
var
//
ini:TIniFile;
begin
//log('ini_readstring');
result:='';
if FileExists ('tinyssl.ini') then
begin
try
ini:=tinifile.Create ('tinyssl.ini');
result:=ini.ReadString (section,ident,'');
except
on e:exception do;
end;
end; //if FileExists ('tinyssl.ini') then
end;
function add_ext(cert: PX509; nid: TC_INT; value: PAnsiChar): Boolean;
var ex: PX509_EXTENSION=nil;
ctx: X509V3_CTX;
begin
log('add_ext '+strpas(value));
Result := false;
ctx.db := nil;
log('X509V3_set_ctx');
X509V3_set_ctx(@ctx, cert, cert, nil, nil, 0);
log('X509V3_EXT_conf_nid');
ex := X509V3_EXT_conf_nid(nil, @ctx, nid, value);
if ex <> nil then
begin
log('X509_add_ext');
X509_add_ext(cert, ex, -1);
X509_EXTENSION_free(ex);
Result := True;
end;
end;
// sign cert
function do_X509_sign(cert:pX509; pkey:pEVP_PKEY;const md:pEVP_MD):integer;
var
rv:integer;
mctx:EVP_MD_CTX;
pkctx:pEVP_PKEY_CTX = nil;
begin
log('EVP_MD_CTX_init');
EVP_MD_CTX_init(@mctx);
log('EVP_DigestSignInit');
rv := EVP_DigestSignInit(@mctx, @pkctx, md, nil, pkey);
log('X509_sign_ctx');
if (rv > 0) then rv := X509_sign_ctx(cert, @mctx);
log('EVP_MD_CTX_cleanup');
EVP_MD_CTX_cleanup(@mctx);
if rv > 0 then result:= 1 else result:= 0;
end;
function hash_pubkey(x509_cert:pX509):boolean;
const
X509V3_ADD_DEFAULT =0;
var
ret:integer = 0;
rsa:pRSA=nil;
digest:array[0..63] of byte;
size,i:cardinal;
subjectKeyIdentifier:pASN1_OCTET_STRING;
bin:pointer;
begin
result:=false;
rsa:=EVP_PKEY_get1_RSA(X509_get_pubkey (x509_cert));
//Writeln('BN_bn2hex E: ', BN_bn2hex(rsa^.e ));
bin:=getmem(BN_num_bytes(rsa^.e));
BN_bn2bin(rsa^.e,bin);
//X509_pubkey_digest(x509, EVP_sha1(), pubkey_hash, &len); // not in openssl 1.x
ret:=evp_digest(bin , BN_num_bytes(rsa^.e),@digest[0],@size,EVP_sha1(),nil);
if ret=1 then
begin
//write('hash sha1:');
//for i:=0 to size -1 do write(inttohex(digest[i],2));
//writeln;
subjectKeyIdentifier := ASN1_OCTET_STRING_new;
ASN1_OCTET_STRING_set(subjectKeyIdentifier, @digest[0], SHA_DIGEST_LENGTH);
log('X509_add1_ext_i2d');
X509_add1_ext_i2d(x509_cert, NID_subject_key_identifier, subjectKeyIdentifier, 0, X509V3_ADD_DEFAULT);
ASN1_OCTET_STRING_free(subjectKeyIdentifier);
result:=true;
end;
end;
//the private key of the resulting cert is the request.key
function signreq(filename:string;cert:string;read_password:string='';alt:string='';ca:boolean=false):boolean;
const
LN_commonName= 'commonName';
//NID_commonName= 13;
X509V3_ADD_DEFAULT =0;
var
ret:integer = 0;
pkey:PEVP_PKEY=nil;
pktmp:PEVP_PKEY=nil;
rsa:pRSA=nil;
cert_rsa:pRSA=nil;
x509_ca:pX509=nil;
x509_cert:pX509=nil;
X509_REQ:pX509_REQ=nil;
bp:pBIO;
serial:integer = 1;
days:long = 365 * 24 * 3600; // 1 year
subject:pX509_NAME = nil;
tmpname:pX509_NAME = nil;
//test
cert_entry:pX509_NAME_ENTRY=nil;
entryData:pASN1_STRING;
cn:ppansichar;
//
value:string;
digest:array[0..63] of byte;
size,i:cardinal;
subjectKeyIdentifier:pASN1_OCTET_STRING;
bin:pointer;
label free_all;
begin
log('signreq');
log('filename:'+filename);
log('cert:'+cert);
result:=false;
// load ca
bp := BIO_new_file(pchar(cert), 'r+');
log('PEM_read_bio_X509');
x509_ca:=PEM_read_bio_X509(bp,nil,nil,nil);
BIO_free(bp);
if x509_ca=nil then goto free_all;
//loadCAPrivateKey
try
//rsa:=RSAOpenSSLPrivateKey(ChangeFileExt (cert,'.key'),read_password);
pkey:=LoadPrivateKey (ChangeFileExt (cert,'.key'),read_password);
if pkey=nil then exception.Create ('pkey is nul');
except
on e:exception do begin log(e.message,1);exit;end;
end; //try
//generate key
{
log('EVP_PKEY_new');
pkey := EVP_PKEY_new();
log('EVP_PKEY_assign_RSA');
EVP_PKEY_assign(pkey,EVP_PKEY_RSA,PCharacter(rsa));
}
// load X509 Req
bp := BIO_new_file(pchar(filename), 'r+');
log('PEM_read_bio_X509_REQ');
X509_REQ := PEM_read_bio_X509_REQ(bp, nil, nil, nil);
BIO_free(bp);
if X509_REQ=nil then goto free_all;
//
x509_cert := X509_new();
// set version to X509 v3 certificate
log('X509_set_version');
X509_set_version(x509_cert,2);
// set serial
log('X509_get_serialNumber');
ASN1_INTEGER_set(X509_get_serialNumber(x509_cert), serial);
// set issuer name frome ca
log('X509_set_issuer_name');
X509_set_issuer_name(x509_cert, X509_get_subject_name(x509_ca ));
//test ok
{
cert_entry := X509_NAME_get_entry(X509_get_subject_name(x509_ca ),X509_NAME_get_index_by_NID(X509_get_subject_name(x509_ca ), NID_commonName, 0));
entryData := X509_NAME_ENTRY_get_data( cert_entry );
ASN1_STRING_to_UTF8(CN, entryData);
writeln(strpas(cn^));
}
// set time
X509_gmtime_adj(X509_get_notBefore(x509_cert), 0);
X509_gmtime_adj(X509_get_notAfter(x509_cert), days);
//log('X509_NAME_add_entry_by_txt');
//X509_NAME_add_entry_by_txt(subject, 'CN', MBSTRING_ASC,pchar('localhost'), -1, -1, 0);
log('X509_set_subject_name'); //from req -> CN
X509_set_subject_name(x509_cert, X509_REQ_get_subject_name(X509_REQ));
//X509_NAME_add_entry_by_NID(X509_get_subject_name(X509_cert), NID_pkcs9_emailAddress, MBSTRING_ASC, pchar('me@domain.com'), -1, -1, 0);
// set pubkey from req
pktmp := X509_REQ_get_pubkey(X509_REQ);
log('X509_set_pubkey');
ret := X509_set_pubkey(x509_cert, pktmp);
EVP_PKEY_free(pktmp);
//
if ca=true then add_ext(x509_cert, NID_basic_constraints, 'critical,CA:true');
if alt<>'' then add_ext(x509_cert, NID_subject_alt_name,pchar(alt)); //'DNS:localhost'
//add_ext(x509_cert, NID_friendlyName,pchar('toto'));
//rfc 5280 - key_usage
value:=ini_readstring('req_ext','key_usage');
if value<>'' then add_ext(x509_cert, NID_key_usage, pchar(value)); //'critical,digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment'
value:=ini_readstring('req_ext','subject_key_identifier');
//if value<>'' then add_ext(x509_cert, NID_subject_key_identifier, pchar(value)); //'hash'
if value='hash' then hash_pubkey (x509_cert);
//not ready, see https://github.com/warmlab/study/blob/master/openssl/x509.c
//value:=ini_readstring('req_ext','authority_key_identifier');
//if value<>'' then add_ext(x509_cert, NID_authority_key_identifier, pchar(value)); //'keyid:always,issuer:always'
value:=ini_readstring('req_ext','ext_key_usage');
if value<>'' then add_ext(x509_cert, NID_ext_key_usage, pchar(value)); //'critical, clientAuth, serverAuth'
//do_X509_sign;
log('do_X509_sign');
do_X509_sign(x509_cert, pkey, EVP_sha256 ());
//or simpler?
//X509_sign(x509_cert, pkey,EVP_sha256());
//
{
cert_rsa := EVP_PKEY_get1_RSA(pkey);
bp := BIO_new_file(pchar('signed.key'), 'w+');
log('PEM_write_bio_RSAPrivateKey');
PEM_write_bio_RSAPrivateKey(bp, cert_rsa,nil {EVP_des_ede3_cbc}, nil, 0, nil, nil);
BIO_free(bp);
RSA_free(cert_rsa);
}
{
bp := BIO_new_file(pchar('signed.key'), 'w+');
log('PEM_write_bio_PrivateKey');
PEM_write_bio_PrivateKey(bp,pkey,EVP_des_ede3_cbc(),nil,0,nil,nil);
BIO_free(bp);
}
//save cert
bp := BIO_new_file(pchar(ChangeFileExt (filename,'.crt') ), 'w+');
log('PEM_write_bio_X509');
PEM_write_bio_X509(bp,x509_cert);
BIO_free(bp);
//
free_all:
X509_free(x509_cert);
//BIO_free_all(out);
X509_REQ_free(X509_REQ);
X509_free(x509_ca);
EVP_PKEY_free(pkey);
result:= ret = 1;
end;
{
PEM Format
Most CAs (Certificate Authority) provide certificates in PEM format in Base64 ASCII encoded files.
The certificate file types can be .pem, .crt, .cer, or .key.
The .pem file can include the server certificate, the intermediate certificate and the private key in a single file.
The server certificate and intermediate certificate can also be in a separate .crt or .cer file.
The private key can be in a .key file.
PKCS#12 Format
The PKCS#12 certificates are in binary form, contained in .pfx or .p12 files.
The PKCS#12 can store the server certificate, the intermediate certificate and the private key in a single .pfx file with password protection.
These certificates are mainly used on the Windows platform.
}
//openssl pkcs12 -inkey priv.key -in cert.crt -export -out cert.pfx
//openssl pkcs12 -in INFILE.p12 -out OUTFILE.crt -nodes -> no encrypted private key
//openssl pkcs12 -in INFILE.p12 -out OUTFILE.crt -> encrypted private key
//openssl pkcs12 -in INFILE.p12 -out OUTFILE.key -nodes -nocerts -> private key only
//openssl pkcs12 -in INFILE.p12 -out OUTFILE.crt -nokeys -> cert only
function mkcert(filename:string;cn:string;privatekey:string='';read_password:string='';serial:string='';ca:boolean=false):boolean;
var
pkey:PEVP_PKEY=nil;
rsa:pRSA=nil;
x509:pX509=nil;
name:pX509_NAME=nil;
hfile:thandle=thandle(-1);
f:file;
bp:pBIO;
ret:integer;
days:long = 5 * 365 * 24 * 3600; // 5 years
//
bc:pBASIC_CONSTRAINTS;
iserial:integer=1;
asn1:pASN1_INTEGER =nil;
p:pBIGNUM=nil;
ctx:pBN_CTX=nil ;
//
value:string;
begin
log('mkCAcert');
log('filename:'+filename);
log('cn:'+cn);
log('privatekey:'+privatekey);
result:=false;