C/C++ encrypt/decrypt with public key
I'm looking for two functions conceptually similar to these:
// returns the encrypted text
string encrypt( string public_key, string pass_phrase, string text );
// returns the original text
stri开发者_开发技巧ng decrypt( string private_key, string pass_phrase, string encrypted_text );
where string
could be a char*
, a std::string
or something easily convertible to those two. And where public_key
and private_key
can be basically anything, from keys generated with some commands (gpg/ssl stuff or whatever), to keys generated with other simple functions.
I've looked into a few cryptography libraries (libgcrypt, libgpgme, openssl ...), but it doesn't look easy at all to implement such functions with those libraries: they require a non-superficial knowledge about asymmetric encryption and a lot of code.
Anyway this task doesn't seem uncommon. How can I implement the two functions above?
Unfortunately, encryption always requires a non-superficial knowledge of the algorithms involved. It is hard to get right. The "Handbook of Applied Cryptography" is a relatively readable guide to the various algorithms available so it's probably worth a look.
You could also try cryptlib. It seems to have a well-layered design that gives you sensible defaults for a lot of parameters so you can hopefully get started without having to worry too much about the details.
When someone asks for easy encryption, I can only recommend KeyCzar.
It not only provides a clean interface in several languages (that can use the same keys) but also mechanisms to handle key rotations and the like.
And of course, safe defaults for the algorithms implemented so that you don't have to worry about the technical details.
Really, the better easy & safe combination I've seen so far.
Assuming you don’t need something platform agnostic, Cryptography Next Generation (CNG) is a relatively new cryptography API on Windows and is surprisingly intuitive and easy to use. I wrote an article that includes examples of all the main cryptographic operations you’re likely to need in typical applications. The sample code for the article also provides a complete working example for these operations using the Visual C++ compiler.
http://msdn.microsoft.com/en-us/magazine/cc163389.aspx
To treat public and private keys as strings you could simply use Base64 or a similar encoding.
精彩评论