简体   繁体   中英

C code to clean up memory for openssl EVP_PKEY private keys

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.

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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM