我正在尝试将加密密码保存到 Windows 凭据管理器,以下代码可以正常读取,并且我可以生成正确加密的字符串,但是密码的加密形式永远不会保留。
为了完整起见,我需要加密密码,因为客户端应用程序需要此密码(Office 2010)。如果我通过 Office 2010 保存密码,我就可以正确读取它。
凭证结构
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Credential
{
public UInt32 flags;
public UInt32 type;
public string targetName;
public string comment;
public System.Runtime.InteropServices.ComTypes.FILETIME lastWritten;
public UInt32 credentialBlobSize;
public IntPtr credentialBlob;
public UInt32 persist;
public UInt32 attributeCount;
public IntPtr credAttribute;
public string targetAlias;
public string userName;
}
读:
IntPtr credPtr;
if (!Win32.CredRead(target, settings.Type, 0, out credPtr))
{
Trace.TraceError("Could not find a credential with the given target name");
return;
}
var passwordBytes = new byte[blobSize];
Marshal.Copy(blob, passwordBytes, 0, (int)blobSize);
var decrypted = ProtectedData.Unprotect(passwordBytes, null, DataProtectionScope.CurrentUser);
return Encoding.Unicode.GetString(decrypted);
写:
var bytes = Encoding.Unicode.GetBytes(password);
var encypted = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);
//construct and set all the other properties on Credential...
credential.credentialBlobSize = (uint)bytes.Length;
credential.credentialBlob = GetPtrToArray(bytes);
if (!Win32.CredWrite(ref credential, 0))
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
GetPtrToArray
private static IntPtr GetPtrToArray(byte[] bytes)
{
var handle = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, handle, bytes.Length);
return handle;
}
我尝试过的事情是:
- 更改
credentialBlob
为字节 [],这将在 CredentialRead 期间因 PtrToStructure 中的编组错误而失败 - 更改
credentialBlob
为字符串,并在解密之前使用 Unicode.GetBytes() ,这会产生一个 2 个字符的字符串,假定是IntPtr
我认为问题在于共享 byte[] 的内存,即生成IntPtr
用于CredWrite()
. 之后尝试读取凭据时,blobSize
andblob
都是 0(即指向 blob 的空 ptr)。
为了完整起见,这是从 .net 4.6.1 代码库运行的,我可以Marshal.StringToCoTaskMemUni(password)
毫无问题地存储未加密的字符串(使用 )。
你能帮我吗?