RSA key generation based on Crypto++/cryptopp, RSA encryption, decryption, RSA signature, verification

Source: Internet
Author: User
Tags base64 decrypt hash asymmetric encryption

Reproduced in http://www.xdty.org/1678

In the project you need to add a registration function, think of using RSA Asymmetric encryption method. Third-party libraries such as OpenSSL were compared, and Cryptopp was used.

1. source File Collation
You can get the source files of the library in http://www.cryptopp.com/, and then archive the files again after extracting them. The header file is placed in the Include folder and the CPP is placed in the SRC directory. All test-related CPP and non-CPP and H files are also removed. Copy the Cryptopp directory to the project directory
2. Join the project
Add a new filter to the VS2010 project, named Cryptopp, and add the sub filter include and SRC. Import the H file under include into the Include and import the CPP under SRC to the SRC filter.

3. Compiling
Open src, select all CPP files, change the properties, and modify the precompiled header to PCH.H. The VC + + path of the project is updated to add include and SRC.


Compile the project, if you compile but modify the error.
4. Generate RSA public key, private key, save to file after Base64 encoding
Some header files need to be imported:


#include "iterhash.h"
#include "files.h"
#include "rsa.h"
#include "randpool.h"
#include "hex.h"
#include "base64.h"
#include "osrng.h"

void Ckeycontroller::generatersakey (unsigned int keylength, CString decfilename, CString encfilename, CString Seed)
{
    Randompool randpool;
    Randpool.put ((BYTE *) seed. GetBuffer (seed. GetLength ()), seed. GetLength ());

    Rsaes_oaep_sha_decryptor Decrypt (Randpool, keylength);
    Hexencoder Decfile (New Base64encoder (New Filesink (Decfilename.getbuffer ())));

    Decrypt. Derencode (decfile);
    Decfile.messageend ();

    Rsaes_oaep_sha_encryptor Encrypt (decrypt);
    Hexencoder Encfile (New Base64encoder (New Filesink (Encfilename.getbuffer ())));
    Encrypt. Derencode (encfile);

    Encfile.messageend ();

    return;
}
Randompool & Ckeycontroller::globalrng ()
{
    static randompool Randompool;
    return randompool;
}

5. Encrypt a string by generating a public key file

CString ckeycontroller::rsaencryptstring (CString encfilename, CString seed, CString message)
{
    string encstring;
    Filesource Encfile (Encfilename.getbuffer (Encfilename.getlength ()), True, new Base64decoder (New Stringsink (encString )) );
    Hexdecoder decoder;
    Decoder. Put ((byte*) encstring.c_str (), encstring.size ());
    Decoder. Messageend ();

    Rsaes_oaep_sha_encryptor Enc;
    Enc. AccessKey (). Load (decoder);

    Randompool Randpool;
    Randpool.put ((BYTE *) seed. GetBuffer (seed. GetLength ()), seed. GetLength ());

    string result;
    Stringsource (C2S (message), True, new Pk_encryptorfilter (Randpool, ENC, new Hexencoder (new Stringsink (result)));

    Return CString (Result.c_str ());
}

6. Decrypting a string with the generated private key file

CString ckeycontroller::rsadecryptstring (CString decfilename, CString ciphertext)
{
    string decstring;
    Filesource Decfile (Decfilename.getbuffer (Decfilename.getlength ()), True, new Base64decoder (New Stringsink (decString )) );
    Hexdecoder decoder;
    Decoder. Put ((byte*) decstring.c_str (), decstring.size ());
    Decoder. Messageend ();

    Rsaes_oaep_sha_decryptor Dec;
    Dec. AccessKey (). Load (decoder);

    string result;
    Stringsource (C2s (ciphertext), True, new Hexdecoder (New Pk_decryptorfilter (GLOBALRNG (), Dec, new Stringsink (Result)))) ;

    Return CString (Result.c_str ());
}

7. Signing with a private key

CString ckeycontroller::signmessage (const std::string& privatekeyfilename, const std::string& message)
{
    std::string signedmessage = "";
    string encstring;
    Filesource Privfile (Privatekeyfilename.c_str (), True, new Base64decoder (New Stringsink (encstring)));
    Rsassa_pkcs1v15_sha_signer Priv;

    Hexdecoder decoder;
    Decoder. Put ((byte*) encstring.c_str (), encstring.size ());
    Decoder. Messageend ();

    Priv. AccessKey (). Load (decoder);

    Autoseededrandompool rng;
    Stringsource S1 (message, True, new Signerfilter (RNG, Priv, New Hexencoder (New Stringsink (Signedmessage)));
   
    Return CString (Signedmessage.c_str ());
}

8. Verifying the signature with the public key

BOOL Ckeycontroller::verifysignature (const std::string& publickeyfilename, const std::string& message, const
    std::string& signedmessage) {string decstring;
    Filesource Pubfile (Publickeyfilename.c_str (), True, new Base64decoder (New Stringsink (decstring)));

    Rsassa_pkcs1v15_sha_verifier Pub;
    Hexdecoder decoder; Decoder.
    Put ((byte*) decstring.c_str (), decstring.size ()); Decoder.

    Messageend (); Pub. AccessKey ().

    Load (decoder);
    Stringsource Signaturefile (Signedmessage, True, new Hexdecoder); if (signaturefile.maxretrievable ()! = Pub.

    Signaturelength ()) {throw std::string ("Signature Size Problem");} Secbyteblock Signature (pub.
    Signaturelength ());

    Signaturefile.get (signature, signature.size ());
    Verifierfilter *verifierfilter = new Verifierfilter (pub); Verifierfilter->put (signature, Pub.
    Signaturelength ());

    Stringsource s (message, True, Verifierfilter);
return Verifierfilter->getlastresult (); }

9. Test function calls

void Ckeycontroller::testrsa ()
{
    CString Encryptkey = _t ("key.pub");
    CString Decryptkey = _t ("Key.pri");
    CString seed = _t ("seed");

    Generatersakey (1024x768, Decryptkey, Encryptkey, seed);

    CString message = _t ("X3BA-9NSF-8N9Q-UWQC-U7FX-AZZF-JAJW");

    CString encryptedtext = rsaencryptstring (Encryptkey, seed, message);

    CString Decryptedtext = rsadecryptstring (Decryptkey, encryptedtext);
   
    CString signedmessage = signmessage ("Key.pri", C2s (Decryptedtext));

    BOOL verified = verifysignature ("Key.pub", C2s (Message), C2s (Signedmessage));
}

10. Tool functions such as Base64 transcoding, string conversion

std::string ckeycontroller::encodebase64 (String message)
{
    string encode;
    Stringsource (Message, True, new Base64encoder (new Stringsink (encode)));
    return encode;
}

std::string Ckeycontroller::D ecodeBase64 (String message)
{
    string decode;
    Stringsource (Message, True, new Base64decoder (New Stringsink (decode)));
    return decode;
}

CString ckeycontroller::hashstring (CString message)
{
    string digest;
    SHA256 Hash;
    Stringsource foo (C2S (message), True, new Hashfilter (hash, new Hexencoder (New Stringsink (Digest)));
    Return CString (Digest.c_str ());
}

CString ckeycontroller::hashfile (CString fileName)
{
    string digest;
    SHA256 Hash;
    Filesource (FileName, True, new Hashfilter (hash, new Hexencoder (New Stringsink (Digest)));
    Return CString (Digest.c_str ());
}

std::string C2s (CString &cs)
{
    CT2CA pszconvertedansistring (CS);
    std::string strstd (pszconvertedansistring);
    return strstd;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.