SecureString到Byte C#

我如何得到一个相当于SecureStringbyte[] (我从PasswordBox获得)?

我的目标是使用CryptoStream将这些字节写入文件,并且该类的Write方法接受byte[]输入,因此我想将SecureString转换为byte[]以便我可以使用CryptoStream

编辑:我不想使用string因为它击败了拥有SecureString的点

我从原来的答案修改为处理unicode

 IntPtr unmanagedBytes = Marshal.SecureStringToGlobalAllocUnicode(password); byte[] bValue = null; try { byte* byteArray = (byte*)unmanagedBytes.GetPointer(); // Find the end of the string byte* pEnd = byteArray; char c='\0'; do { byte b1=*pEnd++; byte b2=*pEnd++; c = '\0'; c= (char)(b1 << 8); c += (char)b2; }while (c != '\0'); // Length is effectively the difference here (note we're 2 past end) int length = (int)((pEnd - byteArray) - 2); bValue = new byte[length]; for (int i=0;i 

假设你想要使用字节数组并在完成后立即删除它,你应该封装整个操作,以便它自己清理:

 public static T Process(this SecureString src, Func func) { IntPtr bstr = IntPtr.Zero; byte[] workArray = null; GCHandle handle = GCHandle.Alloc(workArray, GCHandleType.Pinned); try { /*** PLAINTEXT EXPOSURE BEGINS HERE ***/ bstr = Marshal.SecureStringToBSTR(src); unsafe { byte* bstrBytes = (byte*)bstr; workArray = new byte[src.Length * 2]; for (int i = 0; i < workArray.Length; i++) workArray[i] = *bstrBytes++; } return func(workArray); } finally { if (workArray != null) for (int i = 0; i < workArray.Length; i++) workArray[i] = 0; handle.Free(); if (bstr != IntPtr.Zero) Marshal.ZeroFreeBSTR(bstr); /*** PLAINTEXT EXPOSURE ENDS HERE ***/ } } 

以下是用例的外观:

 private byte[] GetHash(SecureString password) { using (var h = new SHA256Cng()) // or your hash of choice { return password.Process(h.ComputeHash); } } 

没有muss,没有大惊小怪,没有明文留在内存中。

请记住,传递给func()的字节数组包含明文的原始Unicode呈现,这对于大多数加密应用程序来说应该不是问题。

按此, http://www.microsoft.com/indonesia/msdn/credmgmt.aspx ,您可以将其编组为库存C#字符串,然后将其转换为字节数组:

 static string SecureStringToString( SecureString value ) { string s ; IntPtr p = Marshal.SecureStringToBSTR( value ); try { s = Marshal.PtrToStringBSTR( p ) ; } finally { Marshal.FreeBSTR( p ) ; } return s ; } 

或者根据这个答案, 如何将SecureString转换为System.String? ,你可以在IntPtr上使用Marshal.ReadByteMarshal.ReadInt16来获得你需要的东西。