在Windows中存储密码的安全方式

The*_*ude 12 delphi encryption password-protection delphi-2010

我正在尝试保护包含敏感信息的本地数据库(类似于这个问题,仅适用于delphi 2010)

我正在使用DISQLite组件,它支持AES加密,但我仍然需要保护我用来解密和读取数据库的密码.

我最初的想法是生成一个随机密码,使用像DPAPI(CryptProtectDataCryptUnprotectDataCrypt32.dll中找到的函数)之类的东西存储它,但我找不到任何关于Delphi的例子

我的问题是:如何安全地存储随机生成的密码?或者,假设DPAPI之路是安全的,我如何在Delphi中实现这个DPAPI?

iPa*_*h ツ 18

最好使用Windows的DPAPI.它比使用其他方法更安全:

  • CryptProtectData/CryptProtectMemory
  • CryptUnprotectData/CryptUnprotectMemory

CryptProtectMemory/CryptUnprotectMemory提供更多灵活性:

  • CRYPTPROTECTMEMORY_SAME_PROCESS:只有您的进程可以解密您的数据
  • CRYPTPROTECTMEMORY_CROSS_PROCESS:任何进程都可以解析您的数据
  • CRYPTPROTECTMEMORY_SAME_LOGON:只有在同一用户和同一会话中运行的进程才能解密数据

优点:

  1. 无需钥匙 - Windows为您做到了
  2. 细粒度控制:每个进程/每个会话/每个登录/每台机器
  3. CryptProtectData存在于Windows 2000及更高版本中
  4. DPAPI Windows比使用你写的"安全"相关代码更安全,我和相信Random()的人绝对随机返回数字:)事实上,微软在安全领域拥有数十年的经验,拥有遭受过最多攻击的操作系统: O)

缺点:

  1. 在CRYPTPROTECTMEMORY_SAME_PROCESS的情况下,一个*可以在您的进程中注入一个新线程,该线程可以解密您的数据
  2. 如果有人重置用户密码(不更改),您将无法解密数据
  3. 在CRYPTPROTECTMEMORY_SAME_LOGON的情况下:如果用户*运行被黑客攻击的进程,它可以解密您的数据
  4. 如果您使用CRYPTPROTECT_LOCAL_MACHINE - 该计算机上的每个用户*都可以解密数据.这就是为什么不建议在.RDP文件中保存密码的原因
  5. 已知的问题

注意: "每个用户"都是具有使用DPAPI的工具或技能的用户

无论如何 - 你有一个选择.

请注意,@ David-Heffernan是对的 - 计算机上存储的任何内容都可以解密 - 从内存中读取,在进程中注入线程等.

另一方面......为什么我们不让饼干的生活变得更难?:)

经验法则:使用后清除包含敏感数据的所有缓冲区.这不会使事情变得非常安全,但会降低内存中包含敏感数据的可能性.当然这并没有解决其他主要问题:其他Delphi组件如何处理传递给他们的敏感数据:)

JEDI的安全库具有面向对象的DPAPI方法.JEDI项目还包含DPAPI(JWA IIRC)的已翻译窗口标题

更新:这是使用DPAPI的示例代码(使用JEDI API):

Uses SysUtils, jwaWinCrypt, jwaWinBase, jwaWinType;

function dpApiProtectData(var fpDataIn: tBytes): tBytes;
var
  dataIn,               // Input buffer (clear-text/data)
  dataOut: DATA_BLOB;   // Output buffer (encrypted)
begin
  // Initializing variables
  dataOut.cbData := 0;
  dataOut.pbData := nil;

  dataIn.cbData := length(fpDataIn); // How much data (in bytes) we want to encrypt
  dataIn.pbData := @fpDataIn[0];     // Pointer to the data itself - the address of the first element of the input byte array

  if not CryptProtectData(@dataIn, nil, nil, nil, nil, 0, @dataOut) then
    RaiseLastOSError; // Bad things happen sometimes

  // Copy the encrypted bytes to RESULT variable
  setLength(result, dataOut.cbData);
  move(dataOut.pbData^, result[0], dataOut.cbData);
  LocalFree(HLOCAL(dataOut.pbData));                  // http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261(v=vs.85).aspx
//  fillChar(fpDataIn[0], length(fpDataIn), #0);  // Eventually erase input buffer i.e. not to leave sensitive data in memory
end;

function dpApiUnprotectData(fpDataIn: tBytes): tBytes;
var
  dataIn,               // Input buffer (clear-text/data)
  dataOut: DATA_BLOB;   // Output buffer (encrypted)
begin
  dataOut.cbData := 0;
  dataOut.pbData := nil;

  dataIn.cbData := length(fpDataIn);
  dataIn.pbData := @fpDataIn[0];

  if not CryptUnprotectData(
    @dataIn,  
    nil, 
    nil, 
    nil, 
    nil, 
    0,         // Possible flags: http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261%28v=vs.85%29.aspx 
               // 0 (zero) means only the user that encrypted the data will be able to decrypt it
    @dataOut
  ) then
    RaiseLastOSError;

  setLength(result, dataOut.cbData);                  // Copy decrypted bytes in the RESULT variable
  move(dataOut.pbData^, result[0], dataOut.cbData);   
  LocalFree(HLOCAL(dataOut.pbData));                  // http://msdn.microsoft.com/en-us/library/windows/desktop/aa380882%28v=vs.85%29.aspx
end;

procedure testDpApi;
var
  bytesClearTextIn,       // Holds input bytes
  bytesClearTextOut,      // Holds output bytes
  bytesEncrypted: tBytes; // Holds the resulting encrypted bytes
  strIn, strOut: string;  // Input / Output strings
begin

  // *** ENCRYPT STRING TO BYTE ARRAY
  strIn := 'Some Secret Data Here';

  // Copy string contents to bytesClearTextIn
  // NB: this works for STRING type only!!! (AnsiString / UnicodeString)
  setLength(bytesClearTextIn, length(strIn) * sizeOf(char));
  move(strIn[1], bytesClearTextIn[0], length(strIn) * sizeOf(char));

  bytesEncrypted := dpApiProtectData(bytesClearTextIn);     // Encrypt data

  // *** DECRYPT BYTE ARRAY TO STRING
  bytesClearTextOut := dpApiUnprotectData(bytesEncrypted);  // Decrypt data

  // Copy decrypted bytes (bytesClearTextOut) to the output string variable
  // NB: this works for STRING type only!!! (AnsiString / UnicodeString)    
  setLength(strOut, length(bytesClearTextOut) div sizeOf(char));
  move(bytesClearTextOut[0], strOut[1], length(bytesClearTextOut));

  assert(strOut = strIn, 'Boom!');  // Boom should never booom :)

end;
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 该示例是使用CryptProtectData/CryptUnprotectData的轻量级版本;
  • 加密是面向字节的,所以更容易使用tBytes(tBytes = byte of array);
  • 如果输入和输出字符串是UTF8String,则删除"*sizeOf(char)",因为UTF8String的char只有1个字节
  • CryptProtectMemory/CryptUnProtectMemory的使用类似

  • 警告:“CryptProtectMemory”是确定性的,这意味着它容易受到频率分析的影响。(即,如果相同的数据在内存中的多个位置被加密,它们将产生相同的密文,因此攻击者将能够知道它们是相同的东西,这可能会泄漏信息。) (2认同)

Ian*_*oyd 5

如果您的问题只是为了使用户不必每次都输入密码,您应该知道Windows已经有密码存储系统.

如果您转到控制面板 - > 凭据管理器.从那里,您正在寻找Windows凭据 - > 通用凭据.

从那里你可以看到存储远程桌面密码之类的地方是相同的:

在此输入图像描述

暴露此功能的API CredRead,CredWriteCredDelete.

我将它们包含在三个功能中:

function CredReadGenericCredentials(const Target: UnicodeString; var Username, Password: UnicodeString): Boolean;
function CredWriteGenericCredentials(const Target, Username, Password: UnicodeString): Boolean;
function CredDeleteGenericCredentials(const Target: UnicodeString): Boolean;
Run Code Online (Sandbox Code Playgroud)

目标是确定credentails的东西.我通常使用应用程序名称.

String target = ExtractFilename(ParamStr(0)); //e.g. 'Contoso.exe'
Run Code Online (Sandbox Code Playgroud)

那么它只是简单地说:

CredWriteGenericCredentials(ExtractFilename(ParamStr(0)), username, password);
Run Code Online (Sandbox Code Playgroud)

然后,您可以在凭据管理器中查看它们:

在此输入图像描述

当你想要阅读它们时:

CredReadGenericCredentials(ExtractFilename(ParamStr(0)), {var}username, {var}password);
Run Code Online (Sandbox Code Playgroud)

有一个额外的UI工作,你必须:

  • 检测到没有存储的凭据,并提示用户输入凭据
  • 检测到保存的用户名/密码不起作用并提示输入新的/正确的凭据,尝试连接并保存新的正确凭据

读取存储的凭证:

function CredReadGenericCredentials(const Target: UnicodeString; var Username, Password: UnicodeString): Boolean;
var
    credential: PCREDENTIALW;
    le: DWORD;
    s: string;
begin
    Result := False;

    credential := nil;
    if not CredReadW(Target, CRED_TYPE_GENERIC, 0, {var}credential) then
    begin
        le := GetLastError;
        s := 'Could not get "'+Target+'" generic credentials: '+SysErrorMessage(le)+' '+IntToStr(le);
        OutputDebugString(PChar(s));
        Exit;
    end;

    try
        username := Credential.UserName;
        password := WideCharToWideString(PWideChar(Credential.CredentialBlob), Credential.CredentialBlobSize div 2); //By convention blobs that contain strings do not have a trailing NULL.
    finally
        CredFree(Credential);
    end;

    Result := True;
end;
Run Code Online (Sandbox Code Playgroud)

编写存储的凭证:

function CredWriteGenericCredentials(const Target, Username, Password: UnicodeString): Boolean;
var
    persistType: DWORD;
    Credentials: CREDENTIALW;
    le: DWORD;
    s: string;
begin
    ZeroMemory(@Credentials, SizeOf(Credentials));
    Credentials.TargetName := PWideChar(Target); //cannot be longer than CRED_MAX_GENERIC_TARGET_NAME_LENGTH (32767) characters. Recommended format "Company_Target"
    Credentials.Type_ := CRED_TYPE_GENERIC;
    Credentials.UserName := PWideChar(Username);
    Credentials.Persist := CRED_PERSIST_LOCAL_MACHINE;
    Credentials.CredentialBlob := PByte(Password);
    Credentials.CredentialBlobSize := 2*(Length(Password)); //By convention no trailing null. Cannot be longer than CRED_MAX_CREDENTIAL_BLOB_SIZE (512) bytes
    Credentials.UserName := PWideChar(Username);
    Result := CredWriteW(Credentials, 0);
    end;
end;
Run Code Online (Sandbox Code Playgroud)

然后删除:

function CredDeleteGenericCredentials(const Target: UnicodeString): Boolean;
begin
    Result := CredDelete(Target, CRED_TYPE_GENERIC);
end;
Run Code Online (Sandbox Code Playgroud)

CredRead是CryptProtectData的包装器

应该注意CredWrite/CredRead内部使用CryptProtectData.

  • 它还选择在某个地方为您存储凭据
  • 它还为用户提供了一个用户界面,可以查看,管理甚至手动输入和更改已保存的凭据

使用CryptProtectData自己的不同之处在于你只获得了一个blob.由您决定将其存储在某个地方,并在以后检索它.

这里有很好的包装器CryptProtectDataCryptUnprotectData存储密码时:

function EncryptString(const Plaintext: UnicodeString; const AdditionalEntropy: UnicodeString): TBytes;
function DecryptString(const Blob: TBytes; const AdditionalEntropy: UnicodeString): UnicodeString;
Run Code Online (Sandbox Code Playgroud)

这很容易使用:

procedure TForm1.TestStringEncryption;
var
    encryptedBlob: TBytes;
    plainText: UnicodeString;
const
    Salt = 'Salt doesn''t have to be secret; just different from the next application';
begin
    encryptedBlob := EncryptString('correct battery horse staple', Salt);

    plainText := DecryptString(encryptedBlob, salt);

    if plainText <> 'correct battery horse staple' then
        raise Exception.Create('String encryption self-test failed');
end;
Run Code Online (Sandbox Code Playgroud)

实际的胆量是:

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

const
    CRYPTPROTECT_UI_FORBIDDEN = $1;

function CryptProtectData(const DataIn: DATA_BLOB; szDataDescr: PWideChar; OptionalEntropy: PDATA_BLOB; Reserved: Pointer; PromptStruct: Pointer{PCRYPTPROTECT_PROMPTSTRUCT}; dwFlags: DWORD; var DataOut: DATA_BLOB): BOOL; stdcall; external 'Crypt32.dll' name 'CryptProtectData';
function CryptUnprotectData(const DataIn: DATA_BLOB; szDataDescr: PPWideChar; OptionalEntropy: PDATA_BLOB; Reserved: Pointer; PromptStruct: Pointer{PCRYPTPROTECT_PROMPTSTRUCT}; dwFlags: DWORD; var DataOut: DATA_BLOB): Bool; stdcall; external 'Crypt32.dll' name 'CryptUnprotectData';

function EncryptString(const Plaintext: UnicodeString; const AdditionalEntropy: UnicodeString): TBytes;
var
    blobIn: DATA_BLOB;
    blobOut: DATA_BLOB;
    entropyBlob: DATA_BLOB;
    pEntropy: Pointer;
    bRes: Boolean;
begin
    blobIn.pbData := Pointer(PlainText);
    blobIn.cbData := Length(PlainText)*SizeOf(WideChar);

    if AdditionalEntropy <> '' then
    begin
        entropyBlob.pbData := Pointer(AdditionalEntropy);
        entropyBlob.cbData := Length(AdditionalEntropy)*SizeOf(WideChar);
        pEntropy := @entropyBlob;
    end
    else
        pEntropy := nil;

    bRes := CryptProtectData(
            blobIn,
            nil, //data description (PWideChar)
            pentropy, //optional entropy (PDATA_BLOB)
            nil, //reserved
            nil, //prompt struct
            CRYPTPROTECT_UI_FORBIDDEN, //flags
            {var}blobOut);
    if not bRes then
        RaiseLastOSError;

    //Move output blob into resulting TBytes
    SetLength(Result, blobOut.cbData);
    Move(blobOut.pbData^, Result[0], blobOut.cbData);

    // When you have finished using the DATA_BLOB structure, free its pbData member by calling the LocalFree function
    LocalFree(HLOCAL(blobOut.pbData));
end;
Run Code Online (Sandbox Code Playgroud)

并解密:

function DecryptString(const blob: TBytes; const AdditionalEntropy: UnicodeString): UnicodeString;
var
    dataIn: DATA_BLOB;
    entropyBlob: DATA_BLOB;
    pentropy: PDATA_BLOB;
    dataOut: DATA_BLOB;
    bRes: BOOL;
begin
    dataIn.pbData := Pointer(blob);
    dataIn.cbData := Length(blob);

    if AdditionalEntropy <> '' then
    begin
        entropyBlob.pbData := Pointer(AdditionalEntropy);
        entropyBlob.cbData := Length(AdditionalEntropy)*SizeOf(WideChar);
        pentropy := @entropyBlob;
    end
    else
        pentropy := nil;

    bRes := CryptUnprotectData(
            DataIn,
            nil, //data description (PWideChar)
            pentropy, //optional entropy (PDATA_BLOB)
            nil, //reserved
            nil, //prompt struct
            CRYPTPROTECT_UI_FORBIDDEN,
            {var}dataOut);
    if not bRes then
        RaiseLastOSError;

    SetLength(Result, dataOut.cbData div 2);
    Move(dataOut.pbData^, Result[1], dataOut.cbData);
    LocalFree(HLOCAL(DataOut.pbData));
end;
Run Code Online (Sandbox Code Playgroud)