C code to clean up memory for openssl EVP_PKEY private keys

折月煮酒 提交于 2019-12-10 16:23:13

问题


I'm starting learn OpenSSL programming in C/C++. An issue I encountered is, how could I safely wipe out the memory for private keys?

For example, I may have code:

EVP_PKEY *private_key = PEM_read_bio_PrivateKey( bio, ,,,)
RSA *r = EVP_PKEY_get1_RSA( private_key);

I'd like to wipe out private_key from memory cleanly before using EVP_PKEY_free() to free it.

I'd appreciate for helps and/or your suggestions. Thanks.


回答1:


EVP_PKEY *private_key = PEM_read_bio_PrivateKey( bio, ,,,)

I'd like to wipe out private_key from memory cleanly before using EVP_PKEY_free to free it.

OpenSSL's EVP_PKEY_free wipes the private key for you. You don't have to do anything special.

RSA *r = EVP_PKEY_get1_RSA( private_key);

The get1 means the reference count was bumped and you effectively got your own copy of the object. A get0 means you got a pointer to an existing object, and you should not call free on it. Because of get1, you must call RSA_free on it to ensure it gets deleted. As with EVP_PKEY_free, RSA_free will wipe the key.

Please don't call memset. These are opaque structures, and you have to follow a number of pointers to correctly clear the sub-objects. A lot more fields have been hidden in OpenSSL 1.1.0, so its going to be more difficult to follow the pointers (if you wanted to). Also see Error: “invalid use of incomplete type ‘RSA {aka struct rsa_st}” in OpenSSL 1.1.0, Visual Studio and error C2027: use of undefined type 'rsa_st' in OpenSSL 1.1.0, EVP_get_cipherbyname and “undefined struct/union evp_cipher_st” in OpenSSL 1.1.0, etc.


Here's some additional reading you might be interested in:

  • Why does OPENSSL_cleanse look so complex and thread-unsafe?
  • Removing OPENSSL_cleanse from OpenSSL-1.0.1r

When functions like EVP_PKEY_free and RSA_free are called, they eventually end in a call to OPENSSL_cleanse before memory is returned to the operating system. In the case of an RSA private key, its called at leats 8 times to wipe the byte arrays associated with n, e, d, p, q, dp, dq, and invq.



来源:https://stackoverflow.com/questions/42868879/c-code-to-clean-up-memory-for-openssl-evp-pkey-private-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!