如何安全地清除std :: string? [英] how does one securely clear std::string?

查看:190
本文介绍了如何安全地清除std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在std :: string中存储敏感数据(例如:密码)?

How does one store sensitive data (ex: passwords) in std::string?

我有一个应用程序提示用户输入密码,并在连接设置过程中将其传递给下游服务器。我想在连接建立后安全地清除密码值。

I have an application which prompts the user for a password and passes it to a downstream server during connection setup. I want to securely clear the password value after the connection has been established.

如果我将密码存储为 char * array,我可以使用像 SecureZeroMemory 这样的API来摆脱来自过程存储器的敏感数据。但是,我想避免在我的代码中的字符数组,并寻找类似的std :: string?

If I store the password as a char * array, I can use APIs like SecureZeroMemory to get rid of the sensitive data from the process memory. However, I want to avoid char arrays in my code and am looking for something similar for std::string?

预先感谢您的时间。

推荐答案

基于给定的答案这里,我写了一个分配器来安全地清除内存。

Based on the answer given here, I wrote an allocator to securely zero memory.

#include <string>
#include <windows.h>

namespace secure
{
  template <class T> class allocator : public std::allocator<T>
  {
  public:

    template<class U> struct rebind { typedef allocator<U> other; };
    allocator() throw() {}
    allocator(const allocator &) throw() {}
    template <class U> allocator(const allocator<U>&) throw() {}

    void deallocate(pointer p, size_type num)
    {
      SecureZeroMemory((void *)p, num);
      std::allocator<T>::deallocate(p, num);
    }
  };

  typedef std::basic_string<char, std::char_traits<char>, allocator<char> > string;
}

int main()
{
  {
    secure::string bar("bar");
    secure::string longbar("baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar");
  }
}

但是,事实证明, c $ c> std :: string 被实现,可能的是,分配器甚至不被调用小的值。在我的代码中,例如, deallocate 甚至不被调用的字符串 bar (在Visual Studio) 。

However, it turns out, depending on how std::string is implemented, it is possible that the allocator isn't even invoked for small values. In my code, for example, the deallocate doesn't even get called for the string bar (on Visual Studio).

答案是,我们不能使用std :: string存储敏感数据。当然,我们可以选择写一个新的类来处理用例,但我特别感兴趣使用 std :: string 定义。

The answer, then, is that we cannot use std::string to store sensitive data. Of course, we have the option to write a new class that handles the use case, but I was specifically interested in using std::string as defined.

感谢大家的帮助!

这篇关于如何安全地清除std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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