首页
学习
活动
专区
工具
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

回答 3

Stack Overflow用户

发布于 2015-04-17 20:12:28

总是有可能使用非托管CryptoApiCNG函数。请记住,SecureString的设计考虑到了一个非托管消费者,该消费者可以完全控制内存管理。

如果你想坚持使用C#,你应该固定临时数组,以防止GC在你有机会清理它之前移动它:

代码语言:javascript
复制
private static byte[] HashSecureString(SecureString input, Func<byte[], byte[]> hash)
{
    var bstr = Marshal.SecureStringToBSTR(input);
    var length = Marshal.ReadInt32(bstr, -4);
    var bytes = new byte[length];

    var bytesPin = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    try {
        Marshal.Copy(bstr, bytes, 0, length);
        Marshal.ZeroFreeBSTR(bstr);

        return hash(bytes);
    } finally {
        for (var i = 0; i < bytes.Length; i++) { 
            bytes[i] = 0; 
        }

        bytesPin.Free();
    }
}
票数 5
EN

Stack Overflow用户

发布于 2013-01-12 21:27:53

作为对Hans答案的补充,这里有一个如何实现hasher的建议。Hans建议将指向非托管字符串的指针传递给哈希函数,但这意味着客户端代码(=哈希函数)需要处理非托管内存。这并不理想。

另一方面,您可以将回调替换为以下接口的实例:

代码语言:javascript
复制
interface Hasher {
    void Reinitialize();
    void AddByte(byte b);
    byte[] Result { get; }
}

这样,hasher (尽管它变得稍微复杂一些)可以完全在托管区域中实现,而不会泄露安全信息。然后,您的HashSecureString将如下所示:

代码语言:javascript
复制
private static byte[] HashSecureString(SecureString ss, Hasher hasher) {
    IntPtr bstr = Marshal.SecureStringToBSTR(ss);
    try {
        int length = Marshal.ReadInt32(bstr, -4);

        hasher.Reinitialize();

        for (int i = 0; i < length; i++)
            hasher.AddByte(Marshal.ReadByte(bstr, i));

        return hasher.Result;
    }
    finally {
        Marshal.ZeroFreeBSTR(bstr);
    }
}

请注意finally块,以确保非托管内存已清零,无论哈希器实例做什么恶作剧。

下面是一个简单(但不是很有用)的Hasher实现来说明该接口:

代码语言:javascript
复制
sealed class SingleByteXor : Hasher {
    private readonly byte[] data = new byte[1];

    public void Reinitialize() {
        data[0] = 0;
    }

    public void AddByte(byte b) {
        data[0] ^= b;
    }

    public byte[] Result {
        get { return data; }
    }
}
票数 3
EN

Stack Overflow用户

发布于 2014-01-09 05:43:26

作为进一步的补充,您可以不将提供的逻辑@KonradRudolph和@HansPassant包装到自定义Stream实现中吗?

这将允许您使用HashAlgorithm.ComputeHash(Stream)方法,该方法将保持接口处于托管状态(尽管需要您及时处理流)。

当然,由HashAlgorithm实现决定一次有多少数据进入内存(当然,这就是引用源的用途!)

只是一个想法..。

代码语言:javascript
复制
public class SecureStringStream : Stream
{
    public override bool CanRead { get { return true; } }
    public override bool CanWrite { get { return false; } }
    public override bool CanSeek { get { return false; } }

    public override long Position
    {
        get { return _pos; }
        set { throw new NotSupportedException(); }
    }

    public override void Flush() { throw new NotSupportedException(); }
    public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
    public override void SetLength(long value) { throw new NotSupportedException(); }
    public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }

    private readonly IntPtr _bstr = IntPtr.Zero;
    private readonly int _length;
    private int _pos;

    public SecureStringStream(SecureString str)
    {
        if (str == null) throw new ArgumentNullException("str");
        _bstr = Marshal.SecureStringToBSTR(str);

        try
        {
            _length = Marshal.ReadInt32(_bstr, -4);
            _pos = 0;
        }
        catch
        {
            if (_bstr != IntPtr.Zero) Marshal.ZeroFreeBSTR(_bstr);
            throw;
        }
    }

    public override long Length { get { return _length; } }

    public override int Read(byte[] buffer, int offset, int count)
    {
        if (buffer == null) throw new ArgumentNullException("buffer");
        if (offset < 0) throw new ArgumentOutOfRangeException("offset");
        if (count < 0) throw new ArgumentOutOfRangeException("count");
        if (offset + count > buffer.Length) throw new ArgumentException("offset + count > buffer");

        if (count > 0 && _pos++ < _length) 
        {
            buffer[offset] = Marshal.ReadByte(_bstr, _pos++);
            return 1;
        }
        else return 0;
    }

    protected override void Dispose(bool disposing)
    {
        try { if (_bstr != IntPtr.Zero) Marshal.ZeroFreeBSTR(_bstr); }
        finally { base.Dispose(disposing); }
    }
}

void RunMe()
{
    using (SecureString s = new SecureString())
    {
        foreach (char c in "jimbobmcgee") s.AppendChar(c);
        s.MakeReadOnly();

        using (SecureStringStream ss = new SecureStringStream(s))
        using (HashAlgorithm h = MD5.Create())
        {
            Console.WriteLine(Convert.ToBase64String(h.ComputeHash(ss)));
        }
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14293344

复制
相关文章

相似问题

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