Skip to content

Commit

Permalink
let mormot.crypt.ecc use the new PKCS#8 functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Arnaud Bouchez committed Nov 24, 2023
1 parent e94da6a commit 2f4ffda
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 29 deletions.
34 changes: 6 additions & 28 deletions src/crypt/mormot.crypt.ecc.pas
Original file line number Diff line number Diff line change
Expand Up @@ -2152,8 +2152,7 @@ function DerToEcc(der: PByteArray; derlen: PtrInt; out pub: TEccPublicKey): bool

function PemDerRawToEcc(const pem: RawUtf8; out priv: TEccPrivateKey): boolean; overload;
var
der, oid, oct, key: RawByteString;
pos, posoct, vt: integer;
der, key: RawByteString;
begin
der := PemToDer(pem); // return input if not PEM (assume was DER)
result := DerToEcc(pointer(der), length(der), priv);
Expand All @@ -2166,28 +2165,14 @@ function PemDerRawToEcc(const pem: RawUtf8; out priv: TEccPrivateKey): boolean;
else
begin
// decode prime256v1 PKCS#8 PrivateKeyInfo as generated by OpenSSL
pos := 1;
posoct := 1;
if (AsnNext(pos, der) = ASN1_SEQ) and
(AsnNextInteger(pos, der, vt) = 0) and // version
(vt = ASN1_INT) and
(AsnNext(pos, der) = ASN1_SEQ) and // privateKeyAlgorithm
(AsnNext(pos, der, @oid) = ASN1_OBJID) and
(oid = ASN1_OID_X962_PUBLICKEY) and // ecPublicKey
(AsnNext(pos, der, @oid) = ASN1_OBJID) and
(oid = CKA_OID[ckaEcc256]) and // prime256v1
(AsnNextRaw(pos, der, oct) = ASN1_OCTSTR) and // privateKey
(AsnNext(posoct, oct) = ASN1_SEQ) and
(AsnNext(posoct, oct) = ASN1_INT) and
(AsnNextRaw(posoct, oct, key) = ASN1_OCTSTR) and
(length(key) = SizeOf(priv)) then
key := SeqToEccPrivKey(ckaEcc256, der);
if length(key) = SizeOf(priv) then
begin
priv := PEccPrivateKey(key)^;
result := true;
end;
end;
FillZero(der); // anti-forensic protection of the private key
FillZero(oct);
FillZero(key);
end;

Expand Down Expand Up @@ -5412,7 +5397,7 @@ destructor TCryptPrivateKeyEcc.Destroy;

function TCryptPrivateKeyEcc.ToDer: RawByteString;
var
rawecc, oct: RawByteString;
rawecc: RawByteString;
begin
if self = nil then
result := ''
Expand All @@ -5422,16 +5407,9 @@ function TCryptPrivateKeyEcc.ToDer: RawByteString;
begin
// EccToDer() raw encoding is not standard as PEM -> use PKCS#8 format
FastSetRawByteString(rawecc, @fEcc, SizeOf(fEcc));
oct := AsnSafeOct([Asn(1),
Asn(ASN1_OCTSTR, [rawecc])]);
FillZero(rawecc);
// see PemDerRawToEcc() secp256r1/prime256v1 PKCS#8 PrivateKeyInfo
result := AsnSeq([
Asn(0), // version
CkaToSeq(ckaEcc256),
oct
]);
FillZero(oct);
result := EccPrivKeyToSeq(ckaEcc256, rawecc);
FillZero(rawecc);
end;
end;

Expand Down
2 changes: 1 addition & 1 deletion src/mormot.commit.inc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
'2.1.6308'
'2.1.6309'

0 comments on commit 2f4ffda

Please sign in to comment.