-1

我想使用CryptUnprotectData& CryptProtectDatain Crypt32.dll

我的代码是:

unit Unit1;

interface

uses   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type   TForm1 = class(TForm)
    btn1: TButton;
    btn2: TButton;
    edt1: TEdit;
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);   private
    { Private declarations }   public
    { Public declarations }   end;

var   Form1: TForm1; const CRYPTPROTECT_LOCAL_MACHINE = 4 ;

type   TLargeByteArray = array [0..Pred(MaxInt)] of byte;   PLargeByteArray = ^TLargeByteArray;

  _CRYPTOAPI_BLOB = packed record
    cbData: DWORD;
    pbData: PByte;   end;   TCryptoApiBlob     = _CRYPTOAPI_BLOB;   PCrypyoApiBlob     = ^TCryptoApiBlob;   CRYPT_INTEGER_BLOB =
_CRYPTOAPI_BLOB;   PCRYPT_INTEGER_BLOB = ^CRYPT_INTEGER_BLOB;   CRYPT_UINT_BLOB    = _CRYPTOAPI_BLOB;   PCRYPT_UINT_BLOB   = ^CRYPT_INTEGER_BLOB;   CRYPT_OBJID_BLOB   = _CRYPTOAPI_BLOB;   PCRYPT_OBJID_BLOB  = ^CRYPT_INTEGER_BLOB;   CERT_NAME_BLOB     =
_CRYPTOAPI_BLOB;   PCERT_NAME_BLOB    = ^CRYPT_INTEGER_BLOB;   CERT_RDN_VALUE_BLOB = _CRYPTOAPI_BLOB;   PCERT_RDN_VALUE_BLOB = ^CRYPT_INTEGER_BLOB;   CERT_BLOB          = _CRYPTOAPI_BLOB;   PCERT_BLOB         = ^CRYPT_INTEGER_BLOB;   CRL_BLOB           =
_CRYPTOAPI_BLOB;   PCRL_BLOB          = ^CRYPT_INTEGER_BLOB;   DATA_BLOB          = _CRYPTOAPI_BLOB;   PDATA_BLOB         = ^CRYPT_INTEGER_BLOB;   CRYPT_DATA_BLOB    = _CRYPTOAPI_BLOB;   PCRYPT_DATA_BLOB   = ^CRYPT_INTEGER_BLOB;   CRYPT_HASH_BLOB    =
_CRYPTOAPI_BLOB;   PCRYPT_HASH_BLOB   = ^CRYPT_INTEGER_BLOB;   CRYPT_DIGEST_BLOB  = _CRYPTOAPI_BLOB;   PCRYPT_DIGEST_BLOB = ^CRYPT_INTEGER_BLOB;   CRYPT_DER_BLOB     = _CRYPTOAPI_BLOB;   PCRYPT_DER_BLOB    = ^CRYPT_INTEGER_BLOB;   CRYPT_ATTR_BLOB    =
_CRYPTOAPI_BLOB;   PCRYPT_ATTR_BLOB   = ^CRYPT_INTEGER_BLOB;

type   _CRYPTPROTECT_PROMPTSTRUCT = packed record
    cbSize:        DWORD;
    dwPromptFlags: DWORD;
    hwndApp:       HWND;
    szPrompt:      LPCWSTR;   end;   TCryptProtectPromptStruct  = _CRYPTPROTECT_PROMPTSTRUCT;   PCryptProtectPromptStruct  = ^TCryptProtectPromptStruct;   CRYPTPROTECT_PROMPTSTRUCT  =
_CRYPTPROTECT_PROMPTSTRUCT;   PCRYPTPROTECT_PROMPTSTRUCT = ^_CRYPTPROTECT_PROMPTSTRUCT;

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

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

implementation {$R *.DFM}

procedure FreeDataBlob(var Data: DATA_BLOB); begin   if Assigned(Data.pbData) then
    LocalFree(HLOCAL(Data.pbData));   FillChar(Data, SizeOf(DATA_BLOB), 0); end;

function GetDataBlobText(Data: DATA_BLOB): string; begin   if (Data.cbData > 0) and Assigned(Data.pbData) then
    SetString(Result, PChar(Data.pbData), Data.cbData)   else
    SetLength(Result, 0); end;

function SetDataBlobText(Text: string; var Data: DATA_BLOB): boolean; begin   FillChar(Data, SizeOf(DATA_BLOB), 0);   if (Length(Text) > 0) then   begin
    Data.pbData := Pointer(LocalAlloc(LPTR, Succ(Length(Text))));
    if Assigned(Data.pbData) then
    begin
      StrPCopy(PChar(Data.pbData), Text);
      Data.cbData := Length(Text);
      Result := True;
    end
    else
      Result := False;   end   else
    Result := True; end;






{============================================     }

function EncryptPassword(Password: string): string; var   DataIn: DATA_BLOB;   dwFlags: DWORD;   DataOut: PDATA_BLOB;   I: Integer;   P: PByte; begin   Result := '';   DataIn.cbData := Length(Password);   DataIn.pbData := Pointer(PChar(Password));   dwFlags := CRYPTPROTECT_LOCAL_MACHINE;   if CryptProtectData(@DataIn, 'Password', nil, nil, nil, dwFlags, DataOut) then   begin
    P := DataOut.pbData;
    I := DataOut.cbData;
    Result := IntToHex(I, 8);
    while (I > 0) do
    begin
      Dec(I);
      Result := Result + IntToHex(P^, 2);
      Inc(P);
    end;
    LocalFree(Cardinal(DataOut.pbData));   end; end;

function DecryptPassword(Password: string): string; var   DataIn: DATA_BLOB;   dwFlags: DWORD;   DataOut: PDATA_BLOB;   I, J: Integer;   P: PByte;   DataDescr: LPWSTR; begin   Result := '';   if (Length(Password) > 0) then   begin
    DataIn.cbData := StrToIntDef('$' + Copy(Password, 1, 8), 0);
    if (DataIn.cbData > 0) then
    begin
      GetMem(DataIn.pbData, DataIn.cbData);
      I := DataIn.cbData;
      J := 9;
      P := DataIn.pbData;
      while (I > 0) and (J < Length(Password)) do
      begin
        Dec(I);
        P^ := StrToInt('$' + Copy(Password, J, 2));
        Inc(P);
        Inc(J, 2);
      end;
      dwFlags := CRYPTPROTECT_LOCAL_MACHINE;
      if CryptUnprotectData(@DataIn, DataDescr, nil, nil, nil, dwFlags, DataOut) then
      begin
        Result := Copy(string(DataOut.pbData), 0, DataOut.cbData);
        LocalFree(Cardinal(DataOut.pbData));
      end;
    end;   end; end;

procedure TForm1.btn1Click(Sender: TObject); var   DataIn:  DATA_BLOB; DataOut: DATA_BLOB;   DataCheck: DATA_BLOB;   lpwszDesc: PWideChar; begin   FillChar(DataIn, SizeOf(DATA_BLOB), 0);   FillChar(DataOut, SizeOf(DATA_BLOB), 0);   FillChar(DataCheck, SizeOf(DATA_BLOB), 0);   if SetDataBlobText('Hello world this is a test!', DataIn) then   begin
    try
      if CryptProtectData(@DataIn, PWideChar(WideString('Hello Test')), nil, nil, nil, 0, @DataOut) then
      begin
        MessageBox(0, PChar(GetDataBlobText(DataOut)), PChar(Format('%d bytes returned', [DataOut.cbData])), MB_OK or MB_ICONINFORMATION);
        try
          if CryptUnprotectData(@DataOut, lpwszDesc, nil, nil, nil, 0, @DataCheck) then
          begin
            try
              MessageBox(0, PChar(GetDataBlobText(DataCheck)), PChar(string(WideString(lpwszDesc))), MB_OK or MB_ICONINFORMATION);
            finally
              LocalFree(HLOCAL(lpwszDesc));
              FreeDataBlob(DataCheck);
            end;
          end;
        finally
          FreeDataBlob(DataIn);
        end;
      end;
    finally
      FreeDataBlob(DataIn);
    end;   end;

end;

procedure TForm1.btn2Click(Sender: TObject); begin   ShowMessage(DecryptPassword(edt1.Text)); end;

end.

但我在 2 个按钮中有错误,无法获得真正的字符串。

btn1 错误:

---------------------------
Project1
---------------------------
Access violation at address 76F2E23E in module 'ntdll.dll'. Read of address 22481A56.
---------------------------
OK   
---------------------------

btn2 解密后显示 null 并向我显示此错误:

---------------------------
Project1
---------------------------
Access violation at address 00000000. Read of address 00000000.
---------------------------
OK   
---------------------------

有什么问题?

4

2 回答 2

3

您的代码已格式化,因此几乎无法阅读和分析。如果它的格式更好,那么我认为您会得到更全面的答案。这是我能看到的:

  1. 记录不应打包。
  2. 第二个参数CryptUnprotectData不应是 var 参数。通过使其成为var参数,您可以强制自己传递它。由于您不想使用它,因此应将其声明为指向的指针,PWideChar以便您可以选择不使用它。
  3. btn1Click你没有分配任何东西给lpwszDesc. 更重要的是,您将其传递给LocalFree.
  4. 您使用的是 Unicode Delphi,因此没有理由在WideString这里使用。只需将string已经是 UTF-16 的 . 转换为PWideChar.
  5. 您不允许SizeOf(Char)在 Unicode Delphi 中为 2 的事实。所以你的处理是cbData错误的。
  6. DecryptPassword将一个未初始化的指针传递给CryptUnprotectData.
  7. DecryptPassword泄漏分配的内存GetMem
  8. 我真的不知道DecryptPassword试图做什么,但它显然已经坏了。我无法解决它,因为我不知道你的目标是什么。

但是,我敢肯定还有更多问题。我有一些一般性的建议给你。问题中的代码太多。您应该尽可能多地删除。您应该制作尽可能小的SSCCE。这应该是一个简单的控制台应用程序。代码的格式应该是可读的,最好不要使用水平滚动。这对您的帮助和对我们的帮助一样多。

关键是您正在寻找错误。如果您将代码简化为尽可能简单,那么需要检查的就更少了。如果代码可见且布局整齐,则更容易检查。

与正确获取特定细节一样,了解如何使代码可读和简洁的一般原则在这里更为重要。

因此,只是为了向您展示我的意思,这是您将原始帖子转换为 SSCCE,并修复了一些错误:

program SO17823083;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, Winapi.Windows;

const
  CRYPTPROTECT_LOCAL_MACHINE = 4;

type
  TLargeByteArray = array [0 .. Pred(MaxInt)] of byte;
  PLargeByteArray = ^TLargeByteArray;

  _CRYPTOAPI_BLOB = record
    cbData: DWORD;
    pbData: PByte;
  end;

  DATA_BLOB = _CRYPTOAPI_BLOB;
  PDATA_BLOB = ^DATA_BLOB;

type
  _CRYPTPROTECT_PROMPTSTRUCT = record
    cbSize: DWORD;
    dwPromptFlags: DWORD;
    hwndApp: HWND;
    szPrompt: PWideChar;
  end;

  CRYPTPROTECT_PROMPTSTRUCT = _CRYPTPROTECT_PROMPTSTRUCT;
  PCRYPTPROTECT_PROMPTSTRUCT = ^CRYPTPROTECT_PROMPTSTRUCT;

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

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

procedure FreeDataBlob(var Data: DATA_BLOB);
begin
  if Assigned(Data.pbData) then
    LocalFree(HLOCAL(Data.pbData));
  FillChar(Data, SizeOf(DATA_BLOB), 0);
end;

function GetDataBlobText(Data: DATA_BLOB): string;
begin
  SetString(Result, PChar(Data.pbData), Data.cbData div SizeOf(Char))
end;

function SetDataBlobText(const Text: string; var Data: DATA_BLOB): boolean;
begin
  FillChar(Data, SizeOf(DATA_BLOB), 0);
  if Length(Text) > 0 then
  begin
    Data.cbData := SizeOf(Char)*Length(Text);
    Data.pbData := Pointer(LocalAlloc(LPTR, Data.cbData));
    if Assigned(Data.pbData) then
    begin
      Move(Pointer(Text)^, Data.pbData^, Data.cbData);
      Result := True;
    end
    else
      Result := False;
  end
  else
    Result := True;
end;

function DecryptPassword(Password: string): string;
var
  DataIn: DATA_BLOB;
  dwFlags: DWORD;
  DataOut: DATA_BLOB;
  I, J: Integer;
  P: PByte;
begin
  Result := '';
  if (Length(Password) > 0) then
  begin
    DataIn.cbData := StrToIntDef('$' + Copy(Password, 1, 8), 0);
    if (DataIn.cbData > 0) then
    begin
      GetMem(DataIn.pbData, DataIn.cbData);
      I := DataIn.cbData;
      J := 9;
      P := DataIn.pbData;
      while (I > 0) and (J < Length(Password)) do
      begin
        Dec(I);
        P^ := StrToInt('$' + Copy(Password, J, 2));
        Inc(P);
        Inc(J, 2);
      end;
      dwFlags := CRYPTPROTECT_LOCAL_MACHINE;
      if CryptUnprotectData(@DataIn, nil, nil, nil, nil, dwFlags, @DataOut)
      then
      begin
        Result := GetDataBlobText(DataOut);
        LocalFree(Cardinal(DataOut.pbData));
      end;
      FreeMem(DataIn.pbData);
    end;
  end;
end;

procedure Test1;
var
  DataIn: DATA_BLOB;
  DataOut: DATA_BLOB;
  DataCheck: DATA_BLOB;
begin
  if SetDataBlobText('Hello world this is a test!', DataIn) then
  begin
    try
      if CryptProtectData(@DataIn, PChar('Hello Test'), nil,
        nil, nil, 0, @DataOut) then
      begin
        Writeln(GetDataBlobText(DataOut));
        Writeln(Format('%d bytes returned', [DataOut.cbData]));
        try
          if CryptUnprotectData(@DataOut, nil, nil, nil, nil, 0,
            @DataCheck) then
          begin
            try
              Writeln(GetDataBlobText(DataCheck));
            finally
              FreeDataBlob(DataCheck);
            end;
          end;
        finally
          FreeDataBlob(DataIn);
        end;
      end;
    finally
      FreeDataBlob(DataIn);
    end;
  end;
end;

procedure Test2;
begin
  Writeln(DecryptPassword('1111'));
end;

begin
  try
    Test1;
    Test2;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

我使用 Delphi IDE 的代码格式化功能将代码以可读的方式布局。我将它转换为控制台应用程序,以便您拥有一个包含整个程序的文件。

这个版本至少会运行并且不会引发访问冲突。现在由你来决定它是否真正做你想做的事情。

于 2013-07-24T06:14:18.687 回答
2

首先使用Jedi Apilib而不是转换自己(JwaWinCrypt),因为它们已经过验证和时间考验。

在我的博客上有一小段示例代码。

于 2013-07-24T06:12:33.943 回答