《ASCE1885的信息安全》のCrypto++用户手册のrsa.h

来源:互联网 发布:淘宝卖家快递费最低 编辑:程序博客网 时间:2024/05/16 07:41

Crypto++用户手册のrsa.h

RSA加解密相关的类都是在rsa.h头文件中定义的。其中类RSAFunction和类InvertibleRSAFunction是分别封装了RSA公钥和私钥信息的基础类,这两个类支持直接通过函数ApplyFunction (公钥操作)和函数CalculateInverse(私钥操作)进行RSA的计算。我们只有在完全清楚自己的操作的情况下,同时使用正确

补位(padding),才能直接使用这两个函数。

一般情况下,我们更多使用的是rsa.h中通过typedef定义的类型:

typedef RSAES<OAEP<SHA> >::Decryptor RSAES_OAEP_SHA_Decryptor;

typedef RSAES<OAEP<SHA> >::Encryptor RSAES_OAEP_SHA_Encryptor;

 

typedef RSASS<PKCS1v15, SHA>::Signer RSASSA_PKCS1v15_SHA_Signer;

typedef RSASS<PKCS1v15, SHA>::Verifier RSASSA_PKCS1v15_SHA_Verifier;

.

由这些类型定义的类是从pubkey.h文件中的基类派生而来的,各种的RSA Encryptor/Decryptor/Signer/Verifier类型定义使用起来会很简单,只要我们记住它们最终是从定义在cryptlib.h文件中的PK_FixedLengthEncryptor, PK_FixedLengthDecryptor, PK_Signer PK_Verifier继承而来就行了。

 

下面来看几个实例吧:

1)生成RSA密钥对并保存之:

// 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(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();

 

2)加载私钥,并用它对文件进行签名:

string strContents;

 FileSource("c://tobesigned.dat", true,

     new StringSink(strContents));

 

 RSASSA_PKCS1v15_SHA_Signer privkey(

     FileSource("c://privkey.txt", true,

         new Base64Decoder)));

 

 SecByteBlock sbbSignature(privkey.SignatureLength());

 

 AutoSeededRandomPool rng;

 privkey.SignMessage(

     rng,

     (byte const*) strContents.data(),

     strContents.size(),

     sbbSignature.Begin());

 

 FileSink sink("c://signed.dat");

 sink.Put((byte const*) strContents.data(), strContents.size());

 sink.Put(sbbSignature.Begin(), sbbSignature.Size());

 

3)加载公钥,并用它对一短字符串进行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());

 

 

 

原创粉丝点击