-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
web3.crypto.pas
189 lines (159 loc) · 7.07 KB
/
web3.crypto.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
{******************************************************************************}
{ }
{ Delphereum }
{ }
{ Copyright(c) 2018 Stefan van As <svanas@runbox.com> }
{ Github Repository <https://github.com/svanas/delphereum> }
{ }
{ Distributed under GNU AGPL v3.0 with Commons Clause }
{ }
{ This program is free software: you can redistribute it and/or modify }
{ it under the terms of the GNU Affero General Public License as published }
{ by the Free Software Foundation, either version 3 of the License, or }
{ (at your option) any later version. }
{ }
{ This program is distributed in the hope that it will be useful, }
{ but WITHOUT ANY WARRANTY; without even the implied warranty of }
{ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the }
{ GNU Affero General Public License for more details. }
{ }
{ You should have received a copy of the GNU Affero General Public License }
{ along with this program. If not, see <https://www.gnu.org/licenses/> }
{ }
{******************************************************************************}
unit web3.crypto;
{$I web3.inc}
interface
uses
// Delphi
System.SysUtils,
System.TypInfo,
// CryptoLib4Pascal
ClpBigInteger,
ClpBigIntegers,
ClpCryptoLibTypes,
ClpCustomNamedCurves,
ClpECDomainParameters,
ClpECDsaSigner,
ClpECKeyGenerationParameters,
ClpECKeyPairGenerator,
ClpECPrivateKeyParameters,
ClpIAsymmetricCipherKeyPair,
ClpIECC,
ClpIECDomainParameters,
ClpIECKeyGenerationParameters,
ClpIECKeyPairGenerator,
ClpIECPrivateKeyParameters,
ClpIECPublicKeyParameters,
ClpISecureRandom,
ClpIX9ECParameters,
ClpIX9ECParametersHolder,
ClpSecureRandom;
type
TKeyType = (SECP256K1, SECP384R1, SECP521R1, SECT283K1);
type
TKeyTypeHelper = record helper for TKeyType
function GetCurve: IX9ECParameters;
end;
type
TECDsaSignature = record
r : TBigInteger;
s : TBigInteger;
rec: TBigInteger;
end;
type
TECDsaSignerEx = class(TECDsaSigner)
public
function GenerateSignature(const aKeyType: TKeyType; const msg: TCryptoLibByteArray): TECDsaSignature; reintroduce;
end;
function privateKeyFromByteArray(const algorithm: string; const aKeyType: TKeyType; const aPrivKey: TBytes): IECPrivateKeyParameters;
function publicKeyFromPrivateKey(const aPrivKey: IECPrivateKeyParameters): IECPublicKeyParameters;
function publicKeyToByteArray(const aPubKey: IECPublicKeyParameters): TBytes;
function compressPublicKey(const aPubKey: IECPublicKeyParameters): TBytes;
function generatePrivateKey(const algorithm: string; const aKeyType: TKeyType): IECPrivateKeyParameters;
implementation
function TKeyTypeHelper.GetCurve: IX9ECParameters;
begin
const curveName = GetEnumName(TypeInfo(TKeyType), Ord(Self));
Result := TCustomNamedCurves.GetByName(curveName);
end;
function privateKeyFromByteArray(const algorithm: string; const aKeyType: TKeyType; const aPrivKey: TBytes): IECPrivateKeyParameters;
begin
const curve : IX9ECParameters = aKeyType.GetCurve;
const domain: IECDomainParameters = TECDomainParameters.Create(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed);
const privD = TBigInteger.Create(1, aPrivKey);
Result := TECPrivateKeyParameters.Create(algorithm, privD, domain);
end;
function publicKeyFromPrivateKey(const aPrivKey: IECPrivateKeyParameters): IECPublicKeyParameters;
begin
Result := TECKeyPairGenerator.GetCorrespondingPublicKey(aPrivKey);
end;
function publicKeyToByteArray(const aPubKey: IECPublicKeyParameters): TBytes;
begin
Result := TBigIntegers.BigIntegerToBytes(aPubKey.Q.AffineXCoord.ToBigInteger, 32)
+ TBigIntegers.BigIntegerToBytes(aPubKey.Q.AffineYCoord.ToBigInteger, 32);
end;
function compressPublicKey(const aPubKey: IECPublicKeyParameters): TBytes;
begin
if aPubKey.Q.AffineYCoord.ToBigInteger.IsEven then
Result := [2]
else
Result := [3];
Result := Result + TBigIntegers.BigIntegerToBytes(aPubKey.Q.AffineXCoord.ToBigInteger, 32);
end;
function generatePrivateKey(const algorithm: string; const aKeyType: TKeyType): IECPrivateKeyParameters;
begin
const secureRandom: ISecureRandom = TSecureRandom.Create;
const customCurve : IX9ECParameters = aKeyType.GetCurve;
const domainParams: IECDomainParameters = TECDomainParameters.Create(customCurve.Curve,
customCurve.G, customCurve.N, customCurve.H, customCurve.GetSeed);
const keyPairGenerator: IECKeyPairGenerator = TECKeyPairGenerator.Create(algorithm);
const keyGenParams: IECKeyGenerationParameters = TECKeyGenerationParameters.Create(domainParams, secureRandom);
keyPairGenerator.Init(keyGenParams);
const keyPair: IAsymmetricCipherKeyPair = keyPairGenerator.GenerateKeyPair;
Result := keyPair.Private as IECPrivateKeyParameters;
end;
{ TECDsaSignerEx }
function TECDsaSignerEx.GenerateSignature(const aKeyType: TKeyType; const msg: TCryptoLibByteArray): TECDsaSignature;
function curveOrder: TBigInteger;
begin
Result := aKeyType.GetCurve.Curve.Order;
end;
function isLowS(const s: TBigInteger): Boolean;
begin
const halfCurveOrder = curveOrder.ShiftRight(1);
Result := s.CompareTo(halfCurveOrder) <= 0;
end;
procedure makeCanonical(var aSignature: TECDsaSignature);
begin
if not isLowS(aSignature.s) then
aSignature.s := curveOrder.Subtract(aSignature.s);
end;
begin
const ec: IECDomainParameters = Fkey.parameters;
const n = ec.n;
const e = CalculateE(n, msg);
const d = (Fkey as IECPrivateKeyParameters).d;
if FkCalculator.IsDeterministic then
FkCalculator.Init(n, d, msg)
else
FkCalculator.Init(n, Frandom);
const base: IECMultiplier = CreateBasePointMultiplier;
var p: IECPoint;
repeat // Generate s
var k: TBigInteger;
repeat // Generate r
k := FkCalculator.NextK;
p := base.Multiply(ec.G, k).Normalize;
Result.r := p.AffineXCoord.ToBigInteger.&Mod(n);
until not(Result.r.SignValue = 0);
Result.s := k.ModInverse(n).Multiply(e.Add(d.Multiply(Result.r))).&Mod(n);
until not(Result.s.SignValue = 0);
// https://ethereum.stackexchange.com/questions/42455/during-ecdsa-signing-how-do-i-generate-the-recovery-id
Result.rec := p.AffineYCoord.ToBigInteger.&And(TBigInteger.One);
if Result.s.CompareTo(n.Divide(TBigInteger.Two)) = 1 then
Result.rec := Result.rec.&Xor(TBigInteger.One);
// https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#Low_S_values_in_signatures
makeCanonical(Result);
end;
end.