eccrypto.h提供了基于椭圆曲线加密操作的一系列模板类,将这些类设计成模板主要的原因是有两种类型椭圆曲线。因此,类EC2N(ec2n.h)代表的是基于GF(2n)的椭圆曲线算法;而类ECP(ecp.h)代表的是基于GF(p)的椭圆曲线算法。
椭圆曲线的参数保存在模板类ECParameters中,参数能够以多种方式初始化;但是其中一个更实用的用法是使用函数LoadRecommendedParameters(),它提供了建议参数之一,定义在oids.h中。
下面看几个实例代码:
1)生成一个EC2N密钥对,并保存之:
// ECPrivateKey is used directly only because the private key
// won't actually be used to perform any cryptographic operation.
AutoSeededRandomPool rng;
ECPrivateKey privkey(rng, ASN1::sect233k1);
Base64Encoder privkeysink(new FileSink("c://privkey.txt"));
privkey.DEREncode(privkeysink);
privkeysink.MessageEnd(); // Need to flush Base64Encoder's buffer
// Suppose we want to store the public key separately,
// possibly because we will be sending the public key to a third party.
ECPublicKey pubkey(privkey);
Base64Encoder pubkeysink(new FileSink("c://pubkey.txt"));
pubkey.DEREncode(pubkeysink);
pubkeysink.MessageEnd(); // Need to flush Base64Encoder's buffer
2)加载公钥,并加密一个文件:
string sContents;
FileSource("c://tobesigned.dat", true,
new StringSink(sContents));
ECEncryptor 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(sContents.size()));
// ECIES encryption is nice because it handles the entire encryption
// process internally, regardless of the length of input data.
// We don't have to generate a symmetric session key and encrypt
// with it separately.
AutoSeededRandomPool rng;
pubkey.Encrypt(
rng,
(byte const*) sContents.data(),
sContents.size(),
sbbCipherText.Begin());
FileSink("c://encrypted.dat").Put(sbbCipherText.Begin(), sbbCipherText.Size());