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
| unit SLTOpenSslSignerTools;
interface
uses System.SysUtils,
IdSSLOpenSSL, IdSSLOpenSSLHeaders, IdThreadSafe;
type
{ Forward class declarations }
TSLTPEMKeyLoader = class;
TSLTPEMKey = class;
TSLTSignatureVerificator = class;
TSLTSignatureGenerator = class;
{ Exception class declarations }
ESLTPEMKeyException = class(Exception);
ESLTPEMKeyLoaderException = class(ESLTPEMKeyException);
ESLTSignatureVerificatorException = class(ESLTPEMKeyException);
ESLTSignatureGeneratorException = class(ESLTPEMKeyException);
{ TSLTPEMKeyLoader }
TSLTPEMKeyLoader = class(TObject)
private
class var FOpenSSLSharedLibraryCryptoLoaded: TIdThreadSafeBoolean;
class var FOpenSSLSharedLibraryCryptoFunctions: record
PEM_read_bio_PUBKEY : function(bp: PBio; x: PPEVP_PKEY; cb: ppem_password_cb; u: pointer): PEVP_PKEY; cdecl;
end;
public
type
PPEMInput = PBIO; // Basic I/O - PEM = Privacy Enhanced eMail
PPublicKey = PEVP_PKEY; // EVP = The Digital EnVeloPe library, provides a high-level interface to cryptographic functions.
PPublicKeyRSA = PRSA;
PPrivateKey = PEVP_PKEY; // EVP = The Digital EnVeloPe library, provides a high-level interface to cryptographic functions.
PPrivateKeyRSA = PRSA;
public
class function InitOpenSSL(): Boolean;
class procedure FinalizeOpenSSL();
class function OpenPEM(const APEMContent: TBytes; out APEMInput: PPEMInput): Boolean;
class procedure ClosePEM(var APEMInput: PPEMInput);
class function OpenPublicKey(const APEMInput: PPEMInput; out APublicKey: PPublicKey): Boolean;
class procedure ClosePublicKey(var APublicKey: PPublicKey);
class function OpenPublicKeyRSA(const APublicKey: PPublicKey; out APublicKeyRSA: PPublicKeyRSA): Boolean;
class procedure ClosePublicKeyRSA(var APublicKeyRSA: PPublicKeyRSA);
class function OpenPrivateKey(const APEMInput: PPEMInput; const APWDContent: TBytes; out APrivateKey: PPrivateKey): Boolean;
class procedure ClosePrivateKey(var APrivateKey: PPrivateKey);
class function OpenPrivateKeyRSA(const APEMInput: PPEMInput; const APWDContent: TBytes; out APrivateKeyRSA: PPrivateKeyRSA): Boolean;
class procedure ClosePrivateKeyRSA(var APrivateKeyRSA: PPrivateKeyRSA);
class function CreatePWDPointer(const APWDContent: TBytes): PByte;
class procedure FreePWDPointer(var APWDPointer: PByte);
class function InDebugMode(): Boolean; inline;
class procedure OutputDebugError(); inline;
public
class constructor Create();
class destructor Destroy();
end;
{ TSLTPEMKeySide }
TSLTPEMKeySide = (ksPublic, ksPrivate);
{ TSLTPEMKey }
TSLTPEMKey = class(TObject)
private
type
TPublicKeyRec = record
Key: TSLTPEMKeyLoader.PPublicKey;
RSA: TSLTPEMKeyLoader.PPublicKeyRSA;
end;
TPrivateKeyRec = record
Key: TSLTPEMKeyLoader.PPrivateKey;
end;
TKeyRec = record
case Side: TSLTPEMKeySide of
ksPublic: (PublicKey: TPublicKeyRec);
ksPrivate: (PrivateKey: TPublicKeyRec);
end;
private
FContent: TKeyRec;
public
constructor Create(const APEMContent: TBytes; ASide: TSLTPEMKeySide; const APWDContent: TBytes = nil);
destructor Destroy(); override;
end;
{ TSLTSignatureDigestMethod }
TSLTSignatureDigestMethod = (sdmSha1, smdSha256);
{ TSLTSignatureVerificator }
TSLTSignatureVerificator = class(TObject)
public
class function Verify(AKey: TSLTPEMKey; const AData: string; const ASignature: string; ADigestMethod: TSLTSignatureDigestMethod = sdmSha1): Boolean;
end;
{ TSLTSignatureGenerator }
TSLTSignatureGenerator = class(TObject)
public
class function Sign(AKey: TSLTPEMKey; const AData: string; out ASignature: string; ADigestMethod: TSLTSignatureDigestMethod = sdmSha1): Boolean;
end;
implementation
uses Winapi.Windows, System.NetEncoding;
{ TSLTPEMKeyLoader }
//------------------------------------------------------------------------------
class constructor TSLTPEMKeyLoader.Create;
begin
FOpenSSLSharedLibraryCryptoLoaded := TIdThreadSafeBoolean.Create();
end;
//------------------------------------------------------------------------------
class destructor TSLTPEMKeyLoader.Destroy();
begin
FinalizeOpenSSL();
FreeAndNil(FOpenSSLSharedLibraryCryptoLoaded);
end;
//------------------------------------------------------------------------------
class function TSLTPEMKeyLoader.InitOpenSSL(): Boolean;
begin
FOpenSSLSharedLibraryCryptoLoaded.Lock();
try
Result := FOpenSSLSharedLibraryCryptoLoaded.Value;
if not Result then
begin
if IdSSLOpenSSL.LoadOpenSSLLibrary() then
begin
FOpenSSLSharedLibraryCryptoFunctions.PEM_read_bio_PUBKEY := GetProcAddress(IdSSLOpenSSLHeaders.GetCryptLibHandle, PChar('PEM_read_bio_PUBKEY'));
Result := Assigned(FOpenSSLSharedLibraryCryptoFunctions.PEM_read_bio_PUBKEY);
end;
FOpenSSLSharedLibraryCryptoLoaded.Value := Result;
end;
finally
FOpenSSLSharedLibraryCryptoLoaded.Unlock();
end;
end;
//------------------------------------------------------------------------------
class procedure TSLTPEMKeyLoader.FinalizeOpenSSL();
begin
FOpenSSLSharedLibraryCryptoFunctions.PEM_read_bio_PUBKEY := nil;
FOpenSSLSharedLibraryCryptoLoaded.Value := False;
end;
//------------------------------------------------------------------------------
class function TSLTPEMKeyLoader.InDebugMode(): Boolean;
begin
{$IFDEF DEBUG}
{$WARN SYMBOL_PLATFORM OFF}
Result := DebugHook <> 0;
{$WARN SYMBOL_PLATFORM ON}
{$ELSE DEBUG}
Result := False;
{$ENDIF DEBUG}
end;
//------------------------------------------------------------------------------
class function TSLTPEMKeyLoader.OpenPEM(const APEMContent: TBytes; out APEMInput: PPEMInput): Boolean;
begin
APEMInput := IdSSLOpenSSLHeaders.BIO_new_mem_buf(APEMContent, Length(APEMContent));
Result := Assigned(APEMInput);
end;
//------------------------------------------------------------------------------
class procedure TSLTPEMKeyLoader.ClosePEM(var APEMInput: PPEMInput);
begin
if Assigned(APEMInput) then
begin
BIO_free(APEMInput);
APEMInput := nil;
end;
end;
//------------------------------------------------------------------------------
class function TSLTPEMKeyLoader.OpenPublicKey(const APEMInput: PPEMInput; out APublicKey: PPublicKey): Boolean;
begin
// -----BEGIN PUBLIC KEY-----
// ...
// -----END PUBLIC KEY-----
APublicKey := FOpenSSLSharedLibraryCryptoFunctions.PEM_read_bio_PUBKEY(APEMInput, nil, nil, nil);
Result := Assigned(APublicKey);
if not Result then
OutputDebugError();
end;
//------------------------------------------------------------------------------
class procedure TSLTPEMKeyLoader.ClosePublicKey(var APublicKey: PPublicKey);
begin
if Assigned(APublicKey) then
begin
IdSSLOpenSSLHeaders.EVP_PKEY_free(APublicKey);
APublicKey := nil;
end;
end;
//------------------------------------------------------------------------------
class function TSLTPEMKeyLoader.OpenPublicKeyRSA(const APublicKey: PPublicKey; out APublicKeyRSA: PPublicKeyRSA): Boolean;
begin
APublicKeyRSA := IdSSLOpenSSLHeaders.EVP_PKEY_get1_RSA(APublicKey);
Result := Assigned(APublicKeyRSA);
if not Result then
OutputDebugError();
end;
//------------------------------------------------------------------------------
class procedure TSLTPEMKeyLoader.ClosePublicKeyRSA(var APublicKeyRSA: PPublicKeyRSA);
begin
if Assigned(APublicKeyRSA) then
begin
IdSSLOpenSSLHeaders.RSA_free(APublicKeyRSA);
APublicKeyRSA := nil;
end;
end;
//------------------------------------------------------------------------------
class function TSLTPEMKeyLoader.OpenPrivateKey(const APEMInput: PPEMInput; const APWDContent: TBytes; out APrivateKey: PPrivateKey): Boolean;
var
u: PByte;
begin
// https://www.openssl.org/docs/man1.1.1/man3/PEM_read_bio_PrivateKey.html
u := CreatePWDPointer(APWDContent);
try
// -----BEGIN ENCRYPTED PRIVATE KEY-----
// ...
// -----END ENCRYPTED PRIVATE KEY-----
APrivateKey := IdSSLOpenSSLHeaders.PEM_read_bio_PrivateKey(APEMInput, nil, nil, u);
Result := Assigned(APrivateKey);
if not Result then
OutputDebugError();
finally
FreePWDPointer(u);
end;
end;
//------------------------------------------------------------------------------
class procedure TSLTPEMKeyLoader.ClosePrivateKey(var APrivateKey: PPrivateKey);
begin
if Assigned(APrivateKey) then
begin
IdSSLOpenSSLHeaders.EVP_PKEY_free(APrivateKey);
APrivateKey := nil;
end;
end;
//------------------------------------------------------------------------------
class function TSLTPEMKeyLoader.OpenPrivateKeyRSA(const APEMInput: PPEMInput; const APWDContent: TBytes; out APrivateKeyRSA: PPrivateKeyRSA): Boolean;
var
u: PByte;
begin
// https://www.openssl.org/docs/man1.1.1/man3/PEM_read_bio_RSAPrivateKey.html
u := CreatePWDPointer(APWDContent);
try
// Ce n'est pas ce type de clé privée pour le moment
// -----BEGIN RSA PRIVATE KEY-----
// Proc-Type: 4,ENCRYPTED
// DEK-Info: AES-128-CBC,...
// ...
// -----END RSA PRIVATE KEY-----
APrivateKeyRSA := IdSSLOpenSSLHeaders.PEM_read_bio_RSAPrivateKey(APEMInput, nil, nil, u);
Result := Assigned(APrivateKeyRSA);
if not Result then
OutputDebugError();
finally
FreePWDPointer(u);
end;
end;
//------------------------------------------------------------------------------
class procedure TSLTPEMKeyLoader.ClosePrivateKeyRSA(var APrivateKeyRSA: PPrivateKeyRSA);
begin
if Assigned(APrivateKeyRSA) then
begin
IdSSLOpenSSLHeaders.RSA_free(APrivateKeyRSA);
APrivateKeyRSA := nil;
end;
end;
//------------------------------------------------------------------------------
class function TSLTPEMKeyLoader.CreatePWDPointer(const APWDContent: TBytes): PByte;
var
k: Integer;
begin
k := Length(APWDContent);
if k > 0 then
begin
GetMem(Result, k + 1);
Move(APWDContent[0], Result^, k);
Result[k] := 0;
end
else
Result := nil;
end;
//------------------------------------------------------------------------------
class procedure TSLTPEMKeyLoader.FreePWDPointer(var APWDPointer: PByte);
begin
if Assigned(APWDPointer) then
begin
FreeMem(APWDPointer);
APWDPointer := nil;
end;
end;
//------------------------------------------------------------------------------
class procedure TSLTPEMKeyLoader.OutputDebugError();
var
ErrorMsg: AnsiString;
begin
if InDebugMode() then
begin
SetLength(ErrorMsg, 255);
IdSSLOpenSSLHeaders.ERR_error_string(IdSSLOpenSSLHeaders.ERR_get_error(), PAnsiChar(ErrorMsg));
OutputDebugStringA(PAnsiChar(ErrorMsg));
end;
end;
{ TSLTPEMKey }
//------------------------------------------------------------------------------
constructor TSLTPEMKey.Create(const APEMContent: TBytes; ASide: TSLTPEMKeySide; const APWDContent: TBytes = nil);
var
PEMInput: TSLTPEMKeyLoader.PPEMInput;
tmpKey: PEVP_PKEY;
tmpRSA: PRSA;
begin
inherited Create();
FContent.Side := ASide;
// https://delphi.developpez.com/tutoriels/rsa/#LIV
TSLTPEMKeyLoader.InitOpenSSL();
(* Extraction de la Clé
* PBIO_new_mem_buf pour ouvrir le binaire ici d'un contenu d'un fichier PEM
* PPEM_read_bio_PUBKEY pour extraire la clé publique (fonction chargée manuellement)
* PEVP_PKEY_get1_RSA pour vérifier que la clé publique est bien de type RSA
* PBIO_free, EVP_PKEY_free, RSA_free sont respectivement les fonctions de libération pour chaque fonction ci-dessus
*)
if TSLTPEMKeyLoader.OpenPEM(APEMContent, PEMInput) then
begin
try
case FContent.Side of
ksPublic :
if TSLTPEMKeyLoader.OpenPublicKey(PEMInput, tmpKey) then
begin
try
if TSLTPEMKeyLoader.OpenPublicKeyRSA(tmpKey, tmpRSA) then
begin
try
FContent.PublicKey.Key := tmpKey;
FContent.PublicKey.RSA := tmpRSA;
tmpKey := nil;
tmpRSA := nil;
finally
TSLTPEMKeyLoader.ClosePublicKeyRSA(tmpRSA);
end;
end
else
raise Exception.Create('RSA Public Key is not loaded !');
finally
TSLTPEMKeyLoader.ClosePublicKey(tmpKey);
end;
end
else
raise Exception.Create('Public Key is not loaded !');
ksPrivate :
if TSLTPEMKeyLoader.OpenPrivateKey(PEMInput, APWDContent, tmpKey) then
begin
try
FContent.PrivateKey.Key := tmpKey;
tmpKey := nil;
finally
TSLTPEMKeyLoader.ClosePrivateKey(tmpKey);
end;
end
else
raise Exception.Create('Private Key is not loaded !');
end;
finally
TSLTPEMKeyLoader.ClosePEM(PEMInput);
end;
end
else
raise ESLTPEMKeyLoaderException.Create('PEM content buffer is not loaded !');
end;
//------------------------------------------------------------------------------
destructor TSLTPEMKey.Destroy();
begin
case FContent.Side of
ksPublic :
begin
TSLTPEMKeyLoader.ClosePublicKeyRSA(FContent.PublicKey.RSA);
TSLTPEMKeyLoader.ClosePublicKey(FContent.PublicKey.Key);
end;
ksPrivate :
begin
TSLTPEMKeyLoader.ClosePrivateKey(FContent.PrivateKey.Key);
end;
end;
inherited Destroy();
end;
{ TSLTSignatureVerificator }
//------------------------------------------------------------------------------
class function TSLTSignatureVerificator.Verify(AKey: TSLTPEMKey; const AData: string; const ASignature: string; ADigestMethod: TSLTSignatureDigestMethod = sdmSha1): Boolean;
var
IOLayer: PBIO;
EVPContext : pEVP_MD_CTX;
MethodProc: PEVP_MD;
LData: TBytes;
LSignature: TBytes;
begin
(* Utilisation de la Clé et Verification de la Signature :
* EVP_sha1() est la méthode utilisée en phase avec le PHP openssl_sign OPENSSL_ALGO_SHA1.
* BIO_new pour ouvrir un espace de travail
* BIO_get_md_ctx pour récupérer un contexte d'execution
* EVP_DigestVerifyInit affecte au contexte en cours la méthode utilisé (sha1) et la clé issue de PEM_read_bio_PUBKEY
* EVP_DigestVerifyUpdate affecte au contexte en cours la donnée qui a été utilisé comme $data dans openssl_sign .
- Un débat sur l'encodage de cette chaine pose problème, en CS c'est ASCII mais je devine qu'il faut utiliser UTF8 à la place mais du coup c'est n'est plus iso-fonctionnalité
* EVP_DigestVerifyFinal vérifie la signature &$signature issue de openssl_sign en commençant comme en CS par récupérer le binaire à partir d'un décodage de Base64
* BIO_reset, remet à zéro les valeurs transmises au contexte
* BIO_free fermer l'espace de travail
*)
case ADigestMethod of
sdmSha1: MethodProc := IdSSLOpenSSLHeaders.EVP_sha1;
smdSha256: MethodProc := IdSSLOpenSSLHeaders.EVP_sha256;
else
raise ESLTSignatureVerificatorException.Create('Method not supported or not approuved.');
end;
IOLayer := IdSSLOpenSSLHeaders.BIO_new(IdSSLOpenSSLHeaders.BIO_f_md());
try
IdSSLOpenSSLHeaders.BIO_get_md_ctx(IOLayer, @EVPContext);
try
IdSSLOpenSSLHeaders.EVP_DigestVerifyInit(EVPContext, nil, MethodProc, nil, AKey.FContent.PublicKey.Key);
LData := TEncoding.UTF8.GetBytes(AData); // ASCII en C# et corrigé en UTF8 pour être plus conforme au PHP
IdSSLOpenSSLHeaders.EVP_DigestVerifyUpdate(EVPContext, @LData[0], Length(LData));
// https://www.openssl.org/docs/man1.1.1/man3/EVP_DigestVerifyFinal.html
// https://www.openssl.org/docs/man3.0/man3/EVP_DigestVerifyFinal.html
LSignature := TNetEncoding.Base64.DecodeStringToBytes(ASignature);
Result := LongBool(IdSSLOpenSSLHeaders.EVP_DigestVerifyFinal(EVPContext, PAnsiChar(@LSignature[0]), Length(LSignature)));
finally
IdSSLOpenSSLHeaders.BIO_reset(IOLayer);
end;
finally
IdSSLOpenSSLHeaders.BIO_free(IOLayer);
end;
end;
{ TSLTSignatureGenerator }
//------------------------------------------------------------------------------
class function TSLTSignatureGenerator.Sign(AKey: TSLTPEMKey; const AData: string; out ASignature: string; ADigestMethod: TSLTSignatureDigestMethod = sdmSha1): Boolean;
var
IOLayer: PBIO;
EVPContext : pEVP_MD_CTX;
MethodProc: PEVP_MD;
LData: TBytes;
LSignature: TBytes;
Len: SIZE_T;
begin
Result := False;
case ADigestMethod of
sdmSha1: MethodProc := IdSSLOpenSSLHeaders.EVP_sha1;
smdSha256: MethodProc := IdSSLOpenSSLHeaders.EVP_sha256;
else
raise ESLTSignatureVerificatorException.Create('Method not supported or not approuved.');
end;
IOLayer := IdSSLOpenSSLHeaders.BIO_new(IdSSLOpenSSLHeaders.BIO_f_md());
try
// Normalement EVP_MD_CTX_new devrait créer le Contexte mais la DLL contient une fonction proche EVP_MD_CTX_create qui n'est pas déclaré dans IdSSLOpenSSLHeaders
// Cet autre méthode fonctionne pour obtenir un nouveau contexte en utilisant un nouvel espace de travail complet.
IdSSLOpenSSLHeaders.BIO_get_md_ctx(IOLayer, @EVPContext);
try
IdSSLOpenSSLHeaders.EVP_DigestSignInit(EVPContext, nil, MethodProc, nil, AKey.FContent.PrivateKey.Key);
LData := TEncoding.UTF8.GetBytes(AData); // ASCII en C# et corrigé en UTF8 pour être plus conforme au PHP
IdSSLOpenSSLHeaders.EVP_DigestSignUpdate(EVPContext, @LData[0], Length(LData));
// https://www.openssl.org/docs/man1.1.1/man3/EVP_DigestSignFinal.html
if LongBool(IdSSLOpenSSLHeaders.EVP_DigestSignFinal(EVPContext, nil, @Len)) then
begin
SetLength(LSignature, Len);
Result := LongBool(IdSSLOpenSSLHeaders.EVP_DigestSignFinal(EVPContext, PAnsiChar(@LSignature[0]), @Len));
if Result then
with TBase64Encoding.Create(0) do
try
ASignature := EncodeBytesToString(LSignature);
finally
Free();
end;
end;
finally
IdSSLOpenSSLHeaders.BIO_reset(IOLayer); // EVP_MD_CTX_destroy
end;
finally
IdSSLOpenSSLHeaders.BIO_free(IOLayer);
end;
end;
end. |
Partager