如果您的问题只是让用户不必每次都输入密码,那么您应该知道 Windows 已经有密码存储系统。
如果您转到Control Panel -> Credential Manager。从那里您正在寻找Windows Credentials -> Generic Credentials。
从那里您可以看到存储远程桌面密码等内容的位置相同:
公开此功能的 API 是CredRead
、CredWrite
和CredDelete
。
我将它们包含在三个函数中:
function CredReadGenericCredentials(const Target: UnicodeString; var Username, Password: UnicodeString): Boolean;
function CredWriteGenericCredentials(const Target, Username, Password: UnicodeString): Boolean;
function CredDeleteGenericCredentials(const Target: UnicodeString): Boolean;
目标是识别凭证的事物。我通常使用应用程序名称。
String target = ExtractFilename(ParamStr(0)); //e.g. 'Contoso.exe'
那么它很简单:
CredWriteGenericCredentials(ExtractFilename(ParamStr(0)), username, password);
然后,您可以在凭据管理器中看到它们:
当您想读回它们时:
CredReadGenericCredentials(ExtractFilename(ParamStr(0)), {var}username, {var}password);
有额外的 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;
写入存储的凭据:
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;
然后删除:
function CredDeleteGenericCredentials(const Target: UnicodeString): Boolean;
begin
Result := CredDelete(Target, CRED_TYPE_GENERIC);
end;
CredRead 是 CryptProtectData 的包装器
需要注意的是 CredWrite/CredRead 内部使用CryptProtectData
.
- 它也只是选择将凭据存储在您的某个地方
- 它还提供了一个 UI 供用户查看、管理,甚至手动输入和更改保存的凭据
使用CryptProtectData
你自己的区别在于你只得到一个 blob。您可以将其存储在某个地方,然后再检索它。
这是很好的包装器CryptProtectData
和CryptUnprotectData
存储密码时:
function EncryptString(const Plaintext: UnicodeString; const AdditionalEntropy: UnicodeString): TBytes;
function DecryptString(const Blob: TBytes; const AdditionalEntropy: UnicodeString): UnicodeString;
这很容易使用:
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;
真正的胆子是:
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;
并解密:
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;