-
-
Notifications
You must be signed in to change notification settings - Fork 973
/
Copy pathECDSA.pas
409 lines (341 loc) · 11.9 KB
/
ECDSA.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
unit ECDSA;
{
Inno Setup
Copyright (C) 1997-2025 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
ECDSA-P256 signing, verification, and key generation, based on CNG (BCrypt)
}
interface
uses
Windows, SysUtils;
type
TECDSAInt256 = array[0..31] of Byte;
TECDSAPublicKey = packed record
Public_x: TECDSAInt256;
Public_y: TECDSAInt256;
procedure Clear;
end;
TECDSAPrivateKey = packed record
PublicKey: TECDSAPublicKey;
Private_d: TECDSAInt256;
procedure Clear;
end;
TECDSASignature = packed record
Sig_r: TECDSAInt256;
Sig_s: TECDSAInt256;
procedure Clear;
end;
TECDSAKey = class
private
FAlgorithmHandle: THandle; { BCRYPT_ALG_HANDLE }
FKeyHandle: THandle; { BCRYPT_KEY_HANDLE }
class procedure CheckStatus(const AFunctionName: String;
const AStatus: NTSTATUS); static;
procedure KeyHandleRequired;
public
constructor Create;
destructor Destroy; override;
procedure DestroyKey;
procedure ExportPrivateKey(out APrivateKey: TECDSAPrivateKey);
procedure ExportPublicKey(out APublicKey: TECDSAPublicKey);
procedure GenerateKeyPair;
procedure ImportPrivateKey([ref] const APrivateKey: TECDSAPrivateKey);
procedure ImportPublicKey([ref] const APublicKey: TECDSAPublicKey);
procedure SignHash(const AHash: array of Byte;
out ASignature: TECDSASignature);
function VerifySignature(const AHash: array of Byte;
const ASignature: TECDSASignature): Boolean;
end;
EECDSAError = class(Exception);
implementation
type
BCRYPT_ALG_HANDLE = type THandle;
BCRYPT_KEY_HANDLE = type THandle;
BCRYPT_ECCKEY_BLOB = record
dwMagic: ULONG;
cbKey: ULONG;
end;
const
BCRYPT_ECDSA_P256_ALGORITHM = 'ECDSA_P256';
BCRYPT_ECCPRIVATE_BLOB = 'ECCPRIVATEBLOB';
BCRYPT_ECCPUBLIC_BLOB = 'ECCPUBLICBLOB';
BCRYPT_ECDSA_PRIVATE_P256_MAGIC = $32534345;
BCRYPT_ECDSA_PUBLIC_P256_MAGIC = $31534345;
STATUS_INVALID_SIGNATURE = NTSTATUS($C000A000);
var
BCryptFunctionsInitialized: BOOL;
BCryptCloseAlgorithmProvider: function(hAlgorithm: BCRYPT_ALG_HANDLE;
dwFlags: ULONG): NTSTATUS;
stdcall;
BCryptDestroyKey: function(hKey: BCRYPT_KEY_HANDLE): NTSTATUS;
stdcall;
BCryptExportKey: function(hKey: BCRYPT_KEY_HANDLE; hExportKey: BCRYPT_KEY_HANDLE;
pszBlobType: LPCWSTR; var pbOutput; cbOutput: ULONG; out pcbResult: ULONG;
dwFlags: ULONG): NTSTATUS;
stdcall;
BCryptFinalizeKeyPair: function(hKey: BCRYPT_KEY_HANDLE; dwFlags: ULONG): NTSTATUS;
stdcall;
BCryptGenerateKeyPair: function(hAlgorithm: BCRYPT_ALG_HANDLE;
out phKey: BCRYPT_KEY_HANDLE; dwLength: ULONG; dwFlags: ULONG): NTSTATUS;
stdcall;
BCryptImportKeyPair: function(hAlgorithm: BCRYPT_ALG_HANDLE;
hImportKey: BCRYPT_KEY_HANDLE; pszBlobType: LPCWSTR;
out phKey: BCRYPT_KEY_HANDLE; const pbInput; cbInput: ULONG;
dwFlags: ULONG): NTSTATUS;
stdcall;
BCryptOpenAlgorithmProvider: function(out phAlgorithm: BCRYPT_ALG_HANDLE;
pszAlgId: LPCWSTR; pszImplementation: LPCWSTR; dwFlags: ULONG): NTSTATUS;
stdcall;
BCryptSignHash: function(hKey: BCRYPT_KEY_HANDLE; pPaddingInfo: Pointer;
const pbInput; cbInput: ULONG; var pbOutput; cbOutput: ULONG;
out pcbResult: ULONG; dwFlags: ULONG): NTSTATUS;
stdcall;
BCryptVerifySignature: function(hKey: BCRYPT_KEY_HANDLE; pPaddingInfo: Pointer;
const pbHash; cbHash: ULONG; const pbSignature; cbSignature: ULONG;
dwFlags: ULONG): NTSTATUS;
stdcall;
type
{ ECDSA-P256 key blob formats specific to BCrypt }
TBCryptPrivateKeyBlob = record
Header: BCRYPT_ECCKEY_BLOB;
Public_x: TECDSAInt256;
Public_y: TECDSAInt256;
Private_d: TECDSAInt256;
procedure Clear;
end;
TBCryptPublicKeyBlob = record
Header: BCRYPT_ECCKEY_BLOB;
Public_x: TECDSAInt256;
Public_y: TECDSAInt256;
procedure Clear;
end;
procedure InitBCryptFunctions;
var
M: HMODULE;
procedure InitFunc(out AProc: Pointer; const AProcName: PAnsiChar);
begin
AProc := GetProcAddress(M, AProcName);
if not Assigned(AProc) then
raise EECDSAError.CreateFmt('Failed to get address of %s in bcrypt.dll',
[AProcName]);
end;
var
SystemDir: array[0..MAX_PATH-1] of Char;
begin
if BCryptFunctionsInitialized then begin
MemoryBarrier;
Exit;
end;
GetSystemDirectory(SystemDir, SizeOf(SystemDir) div SizeOf(SystemDir[0]));
M := LoadLibrary(PChar(SystemDir + '\bcrypt.dll'));
if M = 0 then
raise EECDSAError.Create('Failed to load bcrypt.dll');
InitFunc(@BCryptCloseAlgorithmProvider, 'BCryptCloseAlgorithmProvider');
InitFunc(@BCryptDestroyKey, 'BCryptDestroyKey');
InitFunc(@BCryptExportKey, 'BCryptExportKey');
InitFunc(@BCryptFinalizeKeyPair, 'BCryptFinalizeKeyPair');
InitFunc(@BCryptGenerateKeyPair, 'BCryptGenerateKeyPair');
InitFunc(@BCryptImportKeyPair, 'BCryptImportKeyPair');
InitFunc(@BCryptOpenAlgorithmProvider, 'BCryptOpenAlgorithmProvider');
InitFunc(@BCryptSignHash, 'BCryptSignHash');
InitFunc(@BCryptVerifySignature, 'BCryptVerifySignature');
MemoryBarrier;
BCryptFunctionsInitialized := True;
end;
{ TBCryptPrivateKeyBlob }
procedure TBCryptPrivateKeyBlob.Clear;
begin
FillChar(Self, SizeOf(Self), 0);
end;
{ TBCryptPublicKeyBlob }
procedure TBCryptPublicKeyBlob.Clear;
begin
FillChar(Self, SizeOf(Self), 0);
end;
{ TECDSAPublicKey }
procedure TECDSAPublicKey.Clear;
begin
FillChar(Self, SizeOf(Self), 0);
end;
{ TECDSAPrivateKey }
procedure TECDSAPrivateKey.Clear;
begin
FillChar(Self, SizeOf(Self), 0);
end;
{ TECDSASignature }
procedure TECDSASignature.Clear;
begin
FillChar(Self, SizeOf(Self), 0);
end;
{ TECDSAKey }
constructor TECDSAKey.Create;
begin
inherited;
InitBCryptFunctions;
var LAlgorithmHandle: BCRYPT_ALG_HANDLE;
CheckStatus('BCryptOpenAlgorithmProvider',
BCryptOpenAlgorithmProvider(LAlgorithmHandle, BCRYPT_ECDSA_P256_ALGORITHM,
nil, 0));
FAlgorithmHandle := LAlgorithmHandle; { assign only on success }
end;
destructor TECDSAKey.Destroy;
begin
DestroyKey;
if FAlgorithmHandle <> 0 then
BCryptCloseAlgorithmProvider(FAlgorithmHandle, 0);
inherited;
end;
class procedure TECDSAKey.CheckStatus(const AFunctionName: String;
const AStatus: NTSTATUS);
begin
if AStatus <> 0 then
raise EECDSAError.CreateFmt('%s failed with error code 0x%x',
[AFunctionName, AStatus]);
end;
procedure TECDSAKey.DestroyKey;
begin
const H = FKeyHandle;
if H <> 0 then begin
FKeyHandle := 0;
BCryptDestroyKey(H);
end;
end;
procedure TECDSAKey.ExportPrivateKey(out APrivateKey: TECDSAPrivateKey);
begin
KeyHandleRequired;
var KeyBlob: TBCryptPrivateKeyBlob;
{ Initially clear KeyBlob just to make it easier to verify that
BCryptExportKey overwrites the entire record }
KeyBlob.Clear;
try
var ResultSize: ULONG;
CheckStatus('BCryptExportKey',
BCryptExportKey(FKeyHandle, 0, BCRYPT_ECCPRIVATE_BLOB, KeyBlob,
SizeOf(KeyBlob), ResultSize, 0));
if ResultSize <> SizeOf(KeyBlob) then
raise EECDSAError.Create('BCryptExportKey result invalid (1)');
if KeyBlob.Header.dwMagic <> BCRYPT_ECDSA_PRIVATE_P256_MAGIC then
raise EECDSAError.Create('BCryptExportKey result invalid (2)');
if KeyBlob.Header.cbKey <> SizeOf(KeyBlob.Public_x) then
raise EECDSAError.Create('BCryptExportKey result invalid (3)');
APrivateKey.PublicKey.Public_x := KeyBlob.Public_x;
APrivateKey.PublicKey.Public_y := KeyBlob.Public_y;
APrivateKey.Private_d := KeyBlob.Private_d;
finally
{ Security: don't leave copy of private key on the stack }
KeyBlob.Clear;
end;
end;
procedure TECDSAKey.ExportPublicKey(out APublicKey: TECDSAPublicKey);
begin
KeyHandleRequired;
var KeyBlob: TBCryptPublicKeyBlob;
{ Initially clear KeyBlob just to make it easier to verify that
BCryptExportKey overwrites the entire record }
KeyBlob.Clear;
try
var ResultSize: ULONG;
CheckStatus('BCryptExportKey',
BCryptExportKey(FKeyHandle, 0, BCRYPT_ECCPUBLIC_BLOB, KeyBlob,
SizeOf(KeyBlob), ResultSize, 0));
if ResultSize <> SizeOf(KeyBlob) then
raise EECDSAError.Create('BCryptExportKey result invalid (1)');
if KeyBlob.Header.dwMagic <> BCRYPT_ECDSA_PUBLIC_P256_MAGIC then
raise EECDSAError.Create('BCryptExportKey result invalid (2)');
if KeyBlob.Header.cbKey <> SizeOf(KeyBlob.Public_x) then
raise EECDSAError.Create('BCryptExportKey result invalid (3)');
APublicKey.Public_x := KeyBlob.Public_x;
APublicKey.Public_y := KeyBlob.Public_y;
finally
{ There's no private key, but clear anyway for consistency }
KeyBlob.Clear;
end;
end;
procedure TECDSAKey.GenerateKeyPair;
begin
DestroyKey;
var LKeyHandle: BCRYPT_KEY_HANDLE;
CheckStatus('BCryptGenerateKeyPair',
BCryptGenerateKeyPair(FAlgorithmHandle, LKeyHandle, 256, 0));
try
CheckStatus('BCryptFinalizeKeyPair',
BCryptFinalizeKeyPair(LKeyHandle, 0));
except
BCryptDestroyKey(LKeyHandle);
raise;
end;
FKeyHandle := LKeyHandle; { assign only on success }
end;
procedure TECDSAKey.ImportPrivateKey([ref] const APrivateKey: TECDSAPrivateKey);
begin
DestroyKey;
var KeyBlob: TBCryptPrivateKeyBlob;
try
KeyBlob.Header.dwMagic := BCRYPT_ECDSA_PRIVATE_P256_MAGIC;
KeyBlob.Header.cbKey := SizeOf(KeyBlob.Public_x);
KeyBlob.Public_x := APrivateKey.PublicKey.Public_x;
KeyBlob.Public_y := APrivateKey.PublicKey.Public_y;
KeyBlob.Private_d := APrivateKey.Private_d;
var LKeyHandle: BCRYPT_KEY_HANDLE;
CheckStatus('BCryptImportKeyPair',
BCryptImportKeyPair(FAlgorithmHandle, 0, BCRYPT_ECCPRIVATE_BLOB,
LKeyHandle, KeyBlob, SizeOf(KeyBlob), 0));
FKeyHandle := LKeyHandle; { assign only on success }
finally
{ Security: don't leave copy of private key on the stack }
KeyBlob.Clear;
end;
end;
procedure TECDSAKey.ImportPublicKey([ref] const APublicKey: TECDSAPublicKey);
begin
DestroyKey;
var KeyBlob: TBCryptPublicKeyBlob;
try
KeyBlob.Header.dwMagic := BCRYPT_ECDSA_PUBLIC_P256_MAGIC;
KeyBlob.Header.cbKey := SizeOf(KeyBlob.Public_x);
KeyBlob.Public_x := APublicKey.Public_x;
KeyBlob.Public_y := APublicKey.Public_y;
var LKeyHandle: BCRYPT_KEY_HANDLE;
CheckStatus('BCryptImportKeyPair',
BCryptImportKeyPair(FAlgorithmHandle, 0, BCRYPT_ECCPUBLIC_BLOB,
LKeyHandle, KeyBlob, SizeOf(KeyBlob), 0));
FKeyHandle := LKeyHandle; { assign only on success }
finally
{ There's no private key, but clear anyway for consistency }
KeyBlob.Clear;
end;
end;
procedure TECDSAKey.KeyHandleRequired;
begin
if FKeyHandle = 0 then
raise EECDSAError.Create('No key has been assigned');
end;
procedure TECDSAKey.SignHash(const AHash: array of Byte;
out ASignature: TECDSASignature);
begin
KeyHandleRequired;
{ Initially clear ASignature just to make it easier to verify that
BCryptSignHash overwrites the entire record }
ASignature.Clear;
var ResultSize: ULONG;
CheckStatus('BCryptSignHash',
BCryptSignHash(FKeyHandle, nil, AHash[0], ULONG(Length(AHash)), ASignature,
SizeOf(ASignature), ResultSize, 0));
if ResultSize <> SizeOf(ASignature) then
raise EECDSAError.Create('BCryptSignHash result size invalid');
end;
function TECDSAKey.VerifySignature(const AHash: array of Byte;
const ASignature: TECDSASignature): Boolean;
begin
KeyHandleRequired;
const Status = BCryptVerifySignature(FKeyHandle, nil, AHash[0],
ULONG(Length(AHash)), ASignature, SizeOf(ASignature), 0);
if Status = STATUS_INVALID_SIGNATURE then
Result := False
else begin
CheckStatus('BCryptVerifySignature', Status);
Result := True;
end;
end;
end.