User Guide: rsa.h

From Crypto++ Wiki
Jump to: navigation, search

rsa.h

The classes actually defined in rsa.h, RSAFunction and InvertibleRSAFunction, are basic classes that envelop a plain RSA public key and private key, respectively. The classes support directly RSA computation through methods ApplyFunction() (the public-key operation) and CalculateInverse() (the private-key operation). You should only use these methods directly if you know what you are doing, and are applying appropriate padding.

More commonly, you will want to use typedefs RSAES_OAEP_SHA_Decryptor, RSAES_OAEP_SHA_Encryptor, RSASSA_PKCS1v15_SHA_Signer, RSASSA_PKCS1v15_SHA_Verifier, and other typedefs of the same sort also defined in rsa.h. The classes identified by these typedefs are derived from an array of base classes declared in pubkey.h. The various RSA Encryptor/Decryptor/Signer/Verifier typedef'ed classes will be easiest to use if you remember that they all ultimately inherit either from PK_FixedLengthEncryptor, PK_FixedLengthDecryptor, PK_Signer or PK_Verifier, all of them declared in cryptlib.h.

Examples

Generate an RSA keypair and save it:

#include <crypto++/rsa.h>
#include <crypto++/osrng.h>
#include <crypto++/base64.h>
#include <crypto++/files.h>
using namespace CryptoPP;
int main()
{
 
 // InvertibleRSAFunction is used directly only because the private key
 // won't actually be used to perform any cryptographic operation;
 // otherwise, an appropriate typedef'ed type from rsa.h would have been used.
 AutoSeededRandomPool rng;
 InvertibleRSAFunction privkey;
 privkey.Initialize(rng, 1024);
 
 // With the current version of Crypto++, MessageEnd() needs to be called
 // explicitly because Base64Encoder doesn't flush its buffer on destruction.
 Base64Encoder privkeysink(new FileSink("c:\\privkey.txt"));
 privkey.DEREncode(privkeysink);
 privkeysink.MessageEnd();
 
 // Suppose we want to store the public key separately,
 // possibly because we will be sending the public key to a third party.
 RSAFunction pubkey(privkey);
 
 Base64Encoder pubkeysink(new FileSink("c:\\pubkey.txt"));
 pubkey.DEREncode(pubkeysink);
 pubkeysink.MessageEnd();
}

Load a private key and sign a file:

void Sign()
{
   string strContents = "A message to be signed";
   //FileSource("tobesigned.dat", true, new StringSink(strContents));
   
   AutoSeededRandomPool rng;
   
   //Read private key
   CryptoPP::ByteQueue bytes;
   FileSource file("privkey.txt", true, new Base64Decoder);
   file.TransferTo(bytes);
   bytes.MessageEnd();
   RSA::PrivateKey privateKey;
   privateKey.Load(bytes);
   
   //Sign message
   RSASSA_PKCS1v15_SHA_Signer privkey(privateKey);
   SecByteBlock sbbSignature(privkey.SignatureLength());
   privkey.SignMessage(
       rng,
       (byte const*) strContents.data(),
       strContents.size(),
       sbbSignature);
   
   //Save result
   FileSink sink("signed.dat");
   sink.Put((byte const*) strContents.data(), strContents.size());
   FileSink sinksig("sig.dat");
   sinksig.Put(sbbSignature, sbbSignature.size());
}

Verify a signed file

void Verify()
{
   //Read public key
   CryptoPP::ByteQueue bytes;
   FileSource file("pubkey.txt", true, new Base64Decoder);
   file.TransferTo(bytes);
   bytes.MessageEnd();
   RSA::PublicKey pubKey;
   pubKey.Load(bytes);
   
   RSASSA_PKCS1v15_SHA_Verifier verifier(pubKey);

   //Read signed message
   string signedTxt;
   FileSource("signed.dat", true, new StringSink(signedTxt));
   string sig;
   FileSource("sig.dat", true, new StringSink(sig));

   string combined(signedTxt);
   combined.append(sig);

   //Verify signature
   try
   {
       StringSource(combined, true,
           new SignatureVerificationFilter(
               verifier, NULL,
               SignatureVerificationFilter::THROW_EXCEPTION
          )
       );
       cout << "Signature OK" << endl;
   }
   catch(SignatureVerificationFilter::SignatureVerificationFailed &err)
   {
       cout << err.what() << endl;
   }

}


Load a public key and encrypt a short string using RSA:

 string strShortString =
     "Must be shorter than the size of the RSA key minus OAEP decoration.";
 
 RSAES_OAEP_SHA_Encryptor pubkey(
     FileSource("c:\\pubkey.txt", true,
         new Base64Decoder)));
 
 // Cannot use std::string for buffer;
 // its internal storage might not be contiguous
 SecByteBlock sbbCipherText(pubkey.CipherTextLength(strShortString.size()));
 
 AutoSeededRandomPool rng;
 pubkey.Encrypt(
     rng,
     (byte const*) strShortString.data(),
     strShortString.size(),
     sbbCipherText.Begin());

 FileSink("c:\\encrypted.dat").Put(sbbCipherText.Begin(), sbbCipherText.Size());

To find other topics in the User Guide, visit Category:User Guide.