unit uSecurityCrypto;

interface

uses
  Winapi.Windows, System.SysUtils, System.Classes, System.Hash, System.NetEncoding;

type
  TDBConnectionConfig = record
    Host: string;
    Port: Integer;
    Database: string;
    Username: string;
    Password: string;
    VendorLib: string;
    InactivityMinutes: Integer;
    PrivacyMaskDefault: Boolean;
    class function CreateDefault(const ABaseDir: string): TDBConnectionConfig; static;
  end;

  TSecurityCrypto = class
  private
    const
      FILE_MAGIC: array[0..7] of Byte = ($53, $4E, $54, $53, $45, $43, $30, $31); // 'SNTSEC01'
      APP_ENTROPY: string = 'SANTIAS_SALUD_RGPD_AES_DPAPI_2026_KEY_V1';
      LEGACY_XOR_EMPTY_HEX: string = '634F5059524947485400655A455155';
      LEGACY_XOR_ASCII_KEY: AnsiString = 'Copyright Ezequ';
    class function DeriveKeyStream(const ASalt: TBytes; ASize: Integer): TBytes; static;
    class function DPAPIProtect(const AData: TBytes): TBytes; static;
    class function DPAPIUnprotect(const AData: TBytes): TBytes; static;
    class function HexToBytes(const AHex: string): TBytes; static;
  public
    class procedure SaveEncryptedConfig(const AFilePath: string; const AConfig: TDBConnectionConfig); static;
    class function LoadEncryptedConfig(const AFilePath: string; out AConfig: TDBConnectionConfig; const ABaseDir: string): Boolean; static;
    class function GetFileSHA256Hex(const AFilePath: string): string; static;

    class function DecryptLegacyPassword(const AHexContras: string): string; static;
    class function HashPasswordSHA256(const APlainPassword: string): string; static;
    class function VerifyDoctorPassword(const AInputPassword, AStoredContras: string): Boolean; static;

    class function MaskDNI(const ADNI: string; AMaskEnabled: Boolean): string; static;
    class function MaskPhone(const APhone: string; AMaskEnabled: Boolean): string; static;
    class function RtfToPlainText(const ARtf: string): string; static;
  end;

implementation

type
  DATA_BLOB = record
    cbData: DWORD;
    pbData: PByte;
  end;
  PDATA_BLOB = ^DATA_BLOB;

const
  CRYPTPROTECT_UI_FORBIDDEN = $1;

function CryptProtectData(pDataIn: PDATA_BLOB; szDataDescr: LPCWSTR;
  pOptionalEntropy: PDATA_BLOB; pvReserved: Pointer; pPromptStruct: Pointer;
  dwFlags: DWORD; pDataOut: PDATA_BLOB): BOOL; stdcall; external 'Crypt32.dll';

function CryptUnprotectData(pDataIn: PDATA_BLOB; ppszDataDescr: Pointer;
  pOptionalEntropy: PDATA_BLOB; pvReserved: Pointer; pPromptStruct: Pointer;
  dwFlags: DWORD; pDataOut: PDATA_BLOB): BOOL; stdcall; external 'Crypt32.dll';

{ TDBConnectionConfig }

class function TDBConnectionConfig.CreateDefault(const ABaseDir: string): TDBConnectionConfig;
begin
  Result.Host := '127.0.0.1';
  Result.Port := 3306;
  Result.Database := 'santias';
  Result.Username := 'root';
  Result.Password := '';
  Result.VendorLib := IncludeTrailingPathDelimiter(ABaseDir) + 'libmysql.dll';
  Result.InactivityMinutes := 10;
  Result.PrivacyMaskDefault := False;
end;

{ TSecurityCrypto }

class function TSecurityCrypto.DeriveKeyStream(const ASalt: TBytes; ASize: Integer): TBytes;
var
  LMasterKey, LBlock, LInput: TBytes;
  LSecretBytes: TBytes;
  I, LOffset, LCopyLen: Integer;
  LCounter: Cardinal;
begin
  LSecretBytes := TEncoding.UTF8.GetBytes(APP_ENTROPY);
  LMasterKey := LSecretBytes + ASalt;
  // 2048 rondas SHA-256 con salt para derivar clave maestra de 256 bits
  for I := 1 to 2048 do
    LMasterKey := THashSHA2.GetHMACAsBytes(LMasterKey, ASalt, SHA256);

  SetLength(Result, ASize);
  LOffset := 0;
  LCounter := 1;
  while LOffset < ASize do
  begin
    SetLength(LInput, Length(ASalt) + SizeOf(Cardinal));
    if Length(ASalt) > 0 then
      Move(ASalt[0], LInput[0], Length(ASalt));
    Move(LCounter, LInput[Length(ASalt)], SizeOf(Cardinal));
    LBlock := THashSHA2.GetHMACAsBytes(LInput, LMasterKey, SHA256);
    LCopyLen := Length(LBlock);
    if LOffset + LCopyLen > ASize then
      LCopyLen := ASize - LOffset;
    Move(LBlock[0], Result[LOffset], LCopyLen);
    Inc(LOffset, LCopyLen);
    Inc(LCounter);
  end;
end;

class function TSecurityCrypto.DPAPIProtect(const AData: TBytes): TBytes;
var
  LInBlob, LOutBlob, LEntropyBlob: DATA_BLOB;
  LEntropyBytes: TBytes;
begin
  if Length(AData) = 0 then
    Exit(nil);
  LEntropyBytes := TEncoding.UTF8.GetBytes(APP_ENTROPY);
  LInBlob.cbData := Length(AData);
  LInBlob.pbData := @AData[0];
  LEntropyBlob.cbData := Length(LEntropyBytes);
  LEntropyBlob.pbData := @LEntropyBytes[0];
  FillChar(LOutBlob, SizeOf(LOutBlob), 0);
  if CryptProtectData(@LInBlob, 'SantiasSaludConfig', @LEntropyBlob, nil, nil,
    CRYPTPROTECT_UI_FORBIDDEN, @LOutBlob) then
  begin
    try
      SetLength(Result, LOutBlob.cbData);
      if LOutBlob.cbData > 0 then
        Move(LOutBlob.pbData^, Result[0], LOutBlob.cbData);
    finally
      LocalFree(HLOCAL(LOutBlob.pbData));
    end;
  end
  else
    Result := AData;
end;

class function TSecurityCrypto.DPAPIUnprotect(const AData: TBytes): TBytes;
var
  LInBlob, LOutBlob, LEntropyBlob: DATA_BLOB;
  LEntropyBytes: TBytes;
begin
  if Length(AData) = 0 then
    Exit(nil);
  LEntropyBytes := TEncoding.UTF8.GetBytes(APP_ENTROPY);
  LInBlob.cbData := Length(AData);
  LInBlob.pbData := @AData[0];
  LEntropyBlob.cbData := Length(LEntropyBytes);
  LEntropyBlob.pbData := @LEntropyBytes[0];
  FillChar(LOutBlob, SizeOf(LOutBlob), 0);
  if CryptUnprotectData(@LInBlob, nil, @LEntropyBlob, nil, nil,
    CRYPTPROTECT_UI_FORBIDDEN, @LOutBlob) then
  begin
    try
      SetLength(Result, LOutBlob.cbData);
      if LOutBlob.cbData > 0 then
        Move(LOutBlob.pbData^, Result[0], LOutBlob.cbData);
    finally
      LocalFree(HLOCAL(LOutBlob.pbData));
    end;
  end
  else
    Result := nil;
end;

class procedure TSecurityCrypto.SaveEncryptedConfig(const AFilePath: string;
  const AConfig: TDBConnectionConfig);
var
  LList: TStringList;
  LPlainBytes, LSalt, LKeyStream, LCipherBytes, LDPAPIBytes, LHmac, LFinal: TBytes;
  I, LLen: Integer;
  LGuid: TGUID;
  LStream: TFileStream;
begin
  LList := TStringList.Create;
  try
    LList.Values['Host'] := Trim(AConfig.Host);
    LList.Values['Port'] := IntToStr(AConfig.Port);
    LList.Values['Database'] := Trim(AConfig.Database);
    LList.Values['Username'] := Trim(AConfig.Username);
    LList.Values['Password'] := AConfig.Password;
    LList.Values['VendorLib'] := Trim(AConfig.VendorLib);
    LList.Values['InactivityMinutes'] := IntToStr(AConfig.InactivityMinutes);
    if AConfig.PrivacyMaskDefault then
      LList.Values['PrivacyMaskDefault'] := '1'
    else
      LList.Values['PrivacyMaskDefault'] := '0';
    LPlainBytes := TEncoding.UTF8.GetBytes(LList.Text);
  finally
    LList.Free;
  end;

  CreateGUID(LGuid);
  SetLength(LSalt, 16);
  Move(LGuid, LSalt[0], 16);

  LKeyStream := DeriveKeyStream(LSalt, Length(LPlainBytes));
  SetLength(LCipherBytes, Length(LPlainBytes));
  for I := 0 to High(LPlainBytes) do
    LCipherBytes[I] := LPlainBytes[I] xor LKeyStream[I];

  LDPAPIBytes := DPAPIProtect(LCipherBytes);
  LHmac := THashSHA2.GetHMACAsBytes(LSalt + LDPAPIBytes, TEncoding.UTF8.GetBytes(APP_ENTROPY), SHA256);

  LLen := Length(LDPAPIBytes);
  SetLength(LFinal, 8 + 16 + 32 + 4 + LLen);
  Move(FILE_MAGIC[0], LFinal[0], 8);
  Move(LSalt[0], LFinal[8], 16);
  Move(LHmac[0], LFinal[24], 32);
  Move(LLen, LFinal[56], 4);
  if LLen > 0 then
    Move(LDPAPIBytes[0], LFinal[60], LLen);

  ForceDirectories(ExtractFilePath(AFilePath));
  LStream := TFileStream.Create(AFilePath, fmCreate or fmShareExclusive);
  try
    LStream.WriteBuffer(LFinal[0], Length(LFinal));
  finally
    LStream.Free;
  end;
end;

class function TSecurityCrypto.LoadEncryptedConfig(const AFilePath: string;
  out AConfig: TDBConnectionConfig; const ABaseDir: string): Boolean;
var
  LStream: TFileStream;
  LAll, LSalt, LStoredHmac, LCalcHmac, LDPAPIBytes, LCipherBytes, LKeyStream, LPlainBytes: TBytes;
  LLen, I: Integer;
  LList: TStringList;
begin
  AConfig := TDBConnectionConfig.CreateDefault(ABaseDir);
  if not FileExists(AFilePath) then
    Exit(False);

  try
    LStream := TFileStream.Create(AFilePath, fmOpenRead or fmShareDenyWrite);
    try
      if LStream.Size < 64 then
        Exit(False);
      SetLength(LAll, LStream.Size);
      LStream.ReadBuffer(LAll[0], Length(LAll));
    finally
      LStream.Free;
    end;

    for I := 0 to 7 do
      if LAll[I] <> FILE_MAGIC[I] then
        Exit(False);

    SetLength(LSalt, 16);
    Move(LAll[8], LSalt[0], 16);
    SetLength(LStoredHmac, 32);
    Move(LAll[24], LStoredHmac[0], 32);
    Move(LAll[56], LLen, 4);

    if (LLen <= 0) or (60 + LLen > Length(LAll)) then
      Exit(False);

    SetLength(LDPAPIBytes, LLen);
    Move(LAll[60], LDPAPIBytes[0], LLen);

    LCalcHmac := THashSHA2.GetHMACAsBytes(LSalt + LDPAPIBytes, TEncoding.UTF8.GetBytes(APP_ENTROPY), SHA256);
    for I := 0 to 31 do
      if LStoredHmac[I] <> LCalcHmac[I] then
        Exit(False);

    LCipherBytes := DPAPIUnprotect(LDPAPIBytes);
    if Length(LCipherBytes) = 0 then
      Exit(False);

    LKeyStream := DeriveKeyStream(LSalt, Length(LCipherBytes));
    SetLength(LPlainBytes, Length(LCipherBytes));
    for I := 0 to High(LCipherBytes) do
      LPlainBytes[I] := LCipherBytes[I] xor LKeyStream[I];

    LList := TStringList.Create;
    try
      LList.Text := TEncoding.UTF8.GetString(LPlainBytes);
      if LList.Values['Host'] <> '' then
        AConfig.Host := LList.Values['Host'];
      AConfig.Port := StrToIntDef(LList.Values['Port'], 3306);
      if LList.Values['Database'] <> '' then
        AConfig.Database := LList.Values['Database'];
      if LList.Values['Username'] <> '' then
        AConfig.Username := LList.Values['Username'];
      AConfig.Password := LList.Values['Password'];
      if LList.Values['VendorLib'] <> '' then
        AConfig.VendorLib := LList.Values['VendorLib'];
      AConfig.InactivityMinutes := StrToIntDef(LList.Values['InactivityMinutes'], 10);
      AConfig.PrivacyMaskDefault := LList.Values['PrivacyMaskDefault'] = '1';
    finally
      LList.Free;
    end;
    Result := True;
  except
    Result := False;
  end;
end;

class function TSecurityCrypto.GetFileSHA256Hex(const AFilePath: string): string;
begin
  if FileExists(AFilePath) then
    Result := UpperCase(THashSHA2.GetHashStringFromFile(AFilePath, SHA256))
  else
    Result := '(Archivo aún no generado)';
end;

class function TSecurityCrypto.HexToBytes(const AHex: string): TBytes;
var
  I, LLen: Integer;
begin
  LLen := Length(AHex) div 2;
  SetLength(Result, LLen);
  for I := 0 to LLen - 1 do
    Result[I] := StrToIntDef('$' + Copy(AHex, I * 2 + 1, 2), 0);
end;

class function TSecurityCrypto.DecryptLegacyPassword(const AHexContras: string): string;
var
  LCipher, LEmptyKey: TBytes;
  I: Integer;
  B, K: Byte;
  LRes: AnsiString;
begin
  Result := '';
  if Length(Trim(AHexContras)) <> 30 then
    Exit(Trim(AHexContras));
  LCipher := HexToBytes(Trim(AHexContras));
  LEmptyKey := HexToBytes(LEGACY_XOR_EMPTY_HEX);
  LRes := '';
  for I := 0 to 14 do
  begin
    if LCipher[I] = LEmptyKey[I] then
      Break;
    K := Byte(LEGACY_XOR_ASCII_KEY[I + 1]);
    B := (LCipher[I] xor K) xor $20;
    if B = 0 then
      Break;
    LRes := LRes + AnsiChar(B);
  end;
  Result := string(LRes);
end;

class function TSecurityCrypto.HashPasswordSHA256(const APlainPassword: string): string;
var
  LGuid: TGUID;
  LSalt, LHash: string;
begin
  CreateGUID(LGuid);
  LSalt := Copy(THashSHA2.GetHashString(GUIDToString(LGuid), SHA256), 1, 8);
  LHash := Copy(THashSHA2.GetHashString(LSalt + ':' + UpperCase(Trim(APlainPassword)) + ':' + APP_ENTROPY, SHA256), 1, 18);
  // Cabe exactamente en CHAR(30): 'S$' (2) + Salt (8) + '$' (1) + Hash (18) = 29 chars
  Result := UpperCase('S$' + LSalt + '$' + LHash);
end;

class function TSecurityCrypto.VerifyDoctorPassword(const AInputPassword, AStoredContras: string): Boolean;
var
  LStored, LSalt, LExpected, LLegacyPlain: string;
begin
  LStored := Trim(AStoredContras);
  if (LStored = '') or SameText(LStored, LEGACY_XOR_EMPTY_HEX) then
    Exit(Trim(AInputPassword) = '');

  if Copy(LStored, 1, 2) = 'S$' then
  begin
    LSalt := Copy(LStored, 3, 8);
    LExpected := UpperCase('S$' + LSalt + '$' +
      Copy(THashSHA2.GetHashString(LowerCase(LSalt) + ':' + UpperCase(Trim(AInputPassword)) + ':' + APP_ENTROPY, SHA256), 1, 18));
    Result := SameText(LStored, LExpected);
  end
  else
  begin
    LLegacyPlain := DecryptLegacyPassword(LStored);
    Result := SameText(Trim(AInputPassword), Trim(LLegacyPlain));
  end;
end;

class function TSecurityCrypto.MaskDNI(const ADNI: string; AMaskEnabled: Boolean): string;
var
  S: string;
begin
  S := Trim(ADNI);
  if (not AMaskEnabled) or (Length(S) <= 4) then
    Exit(S);
  Result := '***' + Copy(S, Length(S) - 3, 3) + '*';
end;

class function TSecurityCrypto.MaskPhone(const APhone: string; AMaskEnabled: Boolean): string;
var
  S: string;
begin
  S := Trim(APhone);
  if (not AMaskEnabled) or (Length(S) <= 3) then
    Exit(S);
  Result := '******' + Copy(S, Length(S) - 2, 3);
end;

class function TSecurityCrypto.RtfToPlainText(const ARtf: string): string;
var
  S: string;
  I, N, LBraceDepth, LSkipDepth, LHexVal: Integer;
  C: Char;
  LCmd: string;
  LSB: TStringBuilder;
begin
  S := Trim(ARtf);
  if not S.StartsWith('{\rtf', True) then
    Exit(ARtf);

  LSB := TStringBuilder.Create;
  try
    I := 1;
    N := Length(S);
    LBraceDepth := 0;
    LSkipDepth := 0;
    while I <= N do
    begin
      C := S[I];
      if C = '{' then
      begin
        Inc(LBraceDepth);
        // Detectar grupos de cabecera RTF ({\fonttbl, {\colortbl, {\stylesheet, {\info, {\*)
        if (I + 1 <= N) and (S[I + 1] = '\') then
        begin
          LCmd := LowerCase(Copy(S, I + 1, 12));
          if LCmd.StartsWith('\fonttbl') or LCmd.StartsWith('\colortbl') or
             LCmd.StartsWith('\stylesheet') or LCmd.StartsWith('\info') or
             LCmd.StartsWith('\*') then
          begin
            if LSkipDepth = 0 then
              LSkipDepth := LBraceDepth;
          end;
        end;
        Inc(I);
      end
      else if C = '}' then
      begin
        if LBraceDepth = LSkipDepth then
          LSkipDepth := 0;
        Dec(LBraceDepth);
        Inc(I);
      end
      else if LSkipDepth > 0 then
      begin
        Inc(I);
      end
      else if C = '\' then
      begin
        Inc(I);
        if I > N then Break;
        if S[I] = '''' then
        begin
          // Escape hexadecimal \'xx en Windows-1252
          if I + 2 <= N then
          begin
            LHexVal := StrToIntDef('$' + Copy(S, I + 1, 2), 32);
            LSB.Append(Char(LHexVal));
            Inc(I, 3);
          end
          else
            Inc(I);
        end
        else if CharInSet(S[I], ['\', '{', '}']) then
        begin
          LSB.Append(S[I]);
          Inc(I);
        end
        else
        begin
          LCmd := '';
          while (I <= N) and CharInSet(S[I], ['a'..'z', 'A'..'Z']) do
          begin
            LCmd := LCmd + S[I];
            Inc(I);
          end;
          while (I <= N) and CharInSet(S[I], ['-', '0'..'9']) do
            Inc(I);
          if (I <= N) and (S[I] = ' ') then
            Inc(I);
          LCmd := LowerCase(LCmd);
          if (LCmd = 'par') or (LCmd = 'line') then
            LSB.AppendLine
          else if LCmd = 'tab' then
            LSB.Append(#9);
        end;
      end
      else if CharInSet(C, [#13, #10]) then
      begin
        Inc(I);
      end
      else
      begin
        LSB.Append(C);
        Inc(I);
      end;
    end;
    Result := Trim(LSB.ToString);
  finally
    LSB.Free;
  end;
end;

end.
