首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在.NET中散列SecureString

在.NET中散列SecureString
EN

Stack Overflow用户
提问于 2013-01-12 20:33:14
回答 3查看 6.4K关注 0票数 24

在.NET中,我们有SecureString类,在您尝试使用它之前,它是非常好的,至于(例如)散列字符串,您需要明文。我在这里尝试编写了一个函数,它将对SecureString进行散列,给定一个散列函数,该函数接受一个字节数组并输出一个字节数组。

代码语言:javascript
复制
private static byte[] HashSecureString(SecureString ss, Func<byte[], byte[]> hash)
{
    // Convert the SecureString to a BSTR
    IntPtr bstr = Marshal.SecureStringToBSTR(ss);

    // BSTR contains the length of the string in bytes in an
    // Int32 stored in the 4 bytes prior to the BSTR pointer
    int length = Marshal.ReadInt32(bstr, -4);

    // Allocate a byte array to copy the string into
    byte[] bytes = new byte[length];

    // Copy the BSTR to the byte array
    Marshal.Copy(bstr, bytes, 0, length);

    // Immediately destroy the BSTR as we don't need it any more
    Marshal.ZeroFreeBSTR(bstr);

    // Hash the byte array
    byte[] hashed = hash(bytes);

    // Destroy the plaintext copy in the byte array
    for (int i = 0; i < length; i++) { bytes[i] = 0; }

    // Return the hash
    return hashed;
}

我相信这将正确地散列字符串,并在函数返回时正确地从内存中擦除明文的任何副本,假设所提供的散列函数表现良好,并且不会对输入进行任何不擦除自身的复制。我是不是漏掉了什么?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14293344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档