windows 当安全性不是问题时,有什么理由使用 SecureZeroMemory() 而不是 memset() 或 ZeroMemory() 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2012602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:42:09  来源:igfitidea点击:

Any reason to use SecureZeroMemory() instead of memset() or ZeroMemory() when security is not an issue?

c++windowslanguage-agnosticvisual-c++initialization

提问by sharptooth

This MSND articlesays SecureZeroMemory()is good for cases when sensitive data stored in memory for a while should be for sure overwritten as soon as possible when no longer needed. Answers to this SO questionexplain why this can make a difference.

这MSND文章SecureZeroMemory()是良好的情况下,当存储在内存中的一个,而敏感数据应尽快为确保覆盖时,不再需要。这个 SO 问题的答案解释了为什么这会有所作为。

Now is there any sence in using SecureZeroMemory()for initializing just every memory block? For example in one project I see code like the following:

现在仅SecureZeroMemory()用于初始化每个内存块有什么意义吗?例如,在一个项目中,我看到如下代码:

ICONINFO ii; 
::SecureZeroMemory(&ii, sizeof(ICONINFO)); 
if (::GetIconInfo(hIcon, &ii)) 
{
    //do stuff, then 
    //release bitmaps 
    if(ii.hbmMask) 
        ::DeleteObject(ii.hbmMask); 
    if(ii.hbmColor) 
        ::DeleteObject(ii.hbmColor); 
} 

why use SecureZeroMemory()here instead of ZeroMemory(), memset()or value initialization? I mean if the compiler decides initialization is unnecessary and wants to optimize it out - why would I enforce it? Is there any reason to use SecureZeroMemory()here?

为什么SecureZeroMemory()在这里使用而不是ZeroMemory(),memset()或值初始化?我的意思是如果编译器决定初始化是不必要的并且想要优化它 - 我为什么要强制执行它?有什么理由在SecureZeroMemory()这里使用吗?

回答by Dmitry

SecureZeroMemory is neveroptimized-away by a compiler. That is important if you need to worry about the contents of your memory to be cleaned, say if it contains very sensitive user info, e.g. banking software, passwords, etc. Obviously if there's no need for you to worry about such things, you can use any other way of cleaning memory buffers or not cleaning at all if it's not necessary.

SecureZeroMemory永远不会被编译器优化掉。如果您需要担心要清理的内存内容,例如它是否包含非常敏感的用户信息,例如银行软件、密码等,这很重要。显然,如果您不需要担心这些事情,您可以如果没有必要,请使用任何其他方式清理内存缓冲区或根本不清理。

回答by Hans Passant

It makes no sense to use SecureZeroMemory to initialize an icon info structure. It can only overwrite bytes on the stack frame that should have been securely erased elsewhere. That horse already escaped the barn. It doesn't even make sense to initialize it at all, the return value of GetIconInfo() tells you that it got initialized.

使用 SecureZeroMemory 初始化图标信息结构毫无意义。它只能覆盖堆栈帧上本应在其他地方安全擦除的字节。那匹马已经逃出了谷仓。甚至根本没有初始化它的意义,GetIconInfo() 的返回值告诉您它已初始化。

SecureZeroMemory() only makes sense aftermemory was filled with secure data.

SecureZeroMemory() 仅内存充满安全数据后才有意义。