SecureString的为byte [] C# [英] SecureString to Byte[] C#

查看:278
本文介绍了SecureString的为byte [] C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何得到一个字节[] 相当于 SecureString的(这是我从一个获得 PasswordBox )?

How would I get a byte[] equivalent of a SecureString (which I get from a PasswordBox)?

我的目标是使用的CryptoStream 到一个文件中写入这些字节,而该类的方法需要一个字节[] 输入,所以我要转换的 SecureString的字节[] 这样我就可以使用了的CryptoStream

My objective is to write these bytes using a CryptoStream to a file, and the Write method of that class takes a byte[] input, so I want to convert the SecureString to the byte[] so I can use in with a CryptoStream.

编辑:我不想用字符串,因为它违背了一个 SecureString的

I don't want to use string as it defeats the point of having a SecureString

推荐答案

我从的原来的答复处理的unicode

I modified from the original answer to handle 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<length;++i)
    {
        // Work with data in byte array as necessary, via pointers, here
        bValue[i] = *(byteArray + i);
    }
}
finally
{
    // This will completely remove the data from memory
    Marshal.ZeroFreeGlobalAllocUnicode(unmanagedBytes);
}

这篇关于SecureString的为byte [] C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆