SecureStringtoByteC#我的目标是使用CryptoStream将这些字节写入文件,并且此类的Write方法接受byte[]输入,因此我想将SecureString转换为byte[]以便我可以使用CryptoStream。编辑:我不想使用字符串,因为它破坏了我从原始答案修改的SecureString以处理unicodeIntPtrunmanagedBytes=Marshal.SecureStringToGlobalAllocUnicode(password);byte[]bValue=null;try{byte*byteArray=(byte*)unmanagedBytes.GetPointer();//找到字符串的结尾byte*pEnd=byteArray;字符c='';做{byteb1=*pEnd++;字节b2=*pEnd++;c='';c=(char)(b1假设您想使用字节数组并在完成后立即删除它,您应该封装整个操作以便它自行清理:publicstaticTProcess(thisSecureStringsrc,Funcfunc){IntPtrbstr=IntPtr.Zero;byte[]workArray=null;GCHandlehandle=GCHandle.Alloc(workArray,GCHandleType.Pinned);try{/***PLAINTEXTEXPOSUREBEGINSHERE***/bstr=Marshal.SecureStringToBSTR(src);unsafe{byte*bstrBytes=(byte*)bstr;workArray=newbyte[src.Length*2];for(inti=0;i这是用例的样子:privatebyte[]GetHash(SecureStringpassword){using(varh=newSHA256Cng())//或您选择的散列{returnpassword.Process(h.ComputeHash);}}没有混乱,没有大惊小怪,内存中没有留下明文。请记住,传递给func()的字节数组包含明文的原始Unicode表示,这对于大多数加密应用程序来说应该不是问题。按照这个,http://www.microsoft.com/indonesia/msdn/credmgmt.aspx,您可以将其编组为普通C#字符串,然后将其转换为字节数组:staticstringSecureStringToString(SecureStringvalue){strings;IntPtrp=Marshal.SecureStringToBSTR(值);尝试{s=Marshal.PtrToStringBSTR(p);}最后{Marshal.FreeBSTR(p);}返回;或者根据这个答案,HowtoconvertSecureStringtoSystem.String?,您可以在IntPtr上使用Marshal.ReadByte和Marshal.ReadInt16来获取您需要的内容。以上就是C#学习教程:SecureStringtoByteC#分享的全部内容。如果对您有用,需要了解更多C#学习教程,希望您多多关注---本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
