프로그래밍/델파이

Crypt32의 CryptProtectData, CryptUnprotectData 사용 예

채윤아빠 2011. 4. 11. 11:21
728x90
반응형
윈도우즈에서 데이터 암호화 저장에 자주 이용하는 Crypt32.dll 내에 CryptProtectData, CryptUnprotectData 두 함수를 사용한 암호화 및 복호화 예제입니다.

먼저 아래와 같은 구조체 및 함수들을 선언하여 줍니다.
type
  _CRYPTOAPI_BLOB = record
    cbData: DWORD;
    pbData: PBYTE;
  end;
  {$EXTERNALSYM _CRYPTOAPI_BLOB}

  DATA_BLOB = _CRYPTOAPI_BLOB;
  {$EXTERNALSYM DATA_BLOB}
  PDATA_BLOB = ^DATA_BLOB;
  {$EXTERNALSYM PDATA_BLOB}

  PCRYPTPROTECT_PROMPTSTRUCT = ^CRYPTPROTECT_PROMPTSTRUCT;
  {$EXTERNALSYM PCRYPTPROTECT_PROMPTSTRUCT}
  _CRYPTPROTECT_PROMPTSTRUCT = record
    cbSize: DWORD;
    dwPromptFlags: DWORD;
    hwndApp: HWND;
    szPrompt: LPCWSTR;
  end;
  {$EXTERNALSYM _CRYPTPROTECT_PROMPTSTRUCT}
  CRYPTPROTECT_PROMPTSTRUCT = _CRYPTPROTECT_PROMPTSTRUCT;
  {$EXTERNALSYM CRYPTPROTECT_PROMPTSTRUCT}

const
  CRYPTPROTECT_LOCAL_MACHINE = $4;
  {$EXTERNALSYM CRYPTPROTECT_LOCAL_MACHINE}

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

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


그리고 아래와 같이 사용하면 됩니다.
procedure TForm1.Button1Click(Sender: TObject);
const
  DEMO_STRING = 'Hello world of data protection.';
var
  DataIn: DATA_BLOB;
  DataOut: DATA_BLOB;
  DataVerify: DATA_BLOB;

  pDescrOut: PWideChar;
begin
  DataIn.pbData := PByte(PAnsiChar(DEMO_STRING));
  DataIn.cbData := Length(DEMO_STRING)+1;

  if CryptProtectData(@DataIn, PWideChar('This is the description string.'),
      nil, nil, nil, 0, @DataOut) then
  begin
    ShowMessage('The encryption phase worked.');
    pDescrOut := nil;
    if CryptUnprotectData(@DataOut, @pDescrOut, nil, nil, nil, 0, @DataVerify) then
    begin
      ShowMessage('The decrypted data is: ' + AnsiString(PAnsiChar(DataVerify.pbData)));
      ShowMessage('The description of the data was: ' + UnicodeString(pDescrOut));

      LocalFree(Cardinal(DataVerify.pbData));
      LocalFree(Cardinal(pDescrOut));
    end
    else
      ShowMessage('Decryption error!');
    LocalFree(cardinal(DataOut.pbData));
  end
  else
    ShowMessage('Encryption error!');
end;