我将如何从字符串/字节数组或任何其他容器加载私钥/公钥
How would I load a Private / Public Key from a string / byte array or any other container
是否可以将RSA私钥/公钥存储在源中,例如在byte[]
或string
或任何其他container
中,并使用此密钥进行加密/解密?
文件中的解码函数如下所示:
void Decode(const string& filename, BufferedTransformation& bt)
{
// http://www.cryptopp.com/docs/ref/class_file_source.html
FileSource file(filename.c_str(), true /*pumpAll*/);
file.TransferTo(bt);
bt.MessageEnd();
}
这从文件加载密钥,这不是我想要的。
我知道这必须是可能的,因为我可以用AutoSeededRandomPool
创建密钥。
我只是不知道如何使用现有的。
也许我在文档中忽略了这一部分。
密钥和格式和 Crypto++ RSA Cryptography 页面可能会感兴趣。
如果要生成如下所示的 RSA 参数:
AutoSeededRandomPool rng;
InvertibleRSAFunction params;
params.GenerateRandomWithKeySize(rng, 2048);
您可以使用 InvertibleRSAFunction
的 DEREncode
和 BERDecode
方法分别对所有参数进行编码和解码:
{
FileSink output("rsaparams.dat");
params.DEREncode(output);
}
InvertibleRSAFunction params2;
{
FileSource input("rsaparams.dat", true);
params2.BERDecode(input);
}
要分别对私有和公共材料进行编码/解码,请在RSA::PrivateKey
和RSA::PublicKey
对象本身上使用DEREncode
和BERDecode
方法:
// Initialize keys from generated params
RSA::PrivateKey rsaPrivate(params);
RSA::PublicKey rsaPublic(params);
// Write keys to file
{
FileSink output("rsaprivate.dat");
rsaPrivate.DEREncode(output);
}
{
FileSink output("rsapublic.dat");
rsaPublic.DEREncode(output);
}
// Read keys from file into new objects
RSA::PrivateKey rsaPrivate2;
RSA::PublicKey rsaPublic2;
{
FileSource input("rsaprivate.dat", true);
rsaPrivate2.BERDecode(input);
}
{
FileSource input("rsapublic.dat", true);
rsaPublic2.BERDecode(input);
}
FileSource
和 FileSink
只是可以使用的示例源和接收器对象。编码/解码例程将BufferedTransformation
对象作为参数,因此您可以使用该接口的任何其他合适实现。
例如,ArraySink
可用于将数据写入您提供的内存缓冲区,StringSource
(也称为 ArraySource
)可用于从缓冲区读取。
下面是一些代码,显示了使用 ArraySink
和 ArraySource
通过std::vector<byte>
来往返私钥材料:
RSA::PrivateKey rsaPrivate(params);
std::vector<byte> buffer(8192 /* buffer size */);
ArraySink arraySink(&buffer[0], buffer.size());
rsaPrivate.DEREncode(arraySink);
// Initialize variable with the encoded key material
// (excluding unwritten bytes at the end of our buffer object)
std::vector<byte> rsaPrivateMaterial(
&buffer[0],
&buffer[0] + arraySink.TotalPutLength());
RSA::PrivateKey rsaPrivate2;
ArraySource arraySource(
&rsaPrivateMaterial[0],
rsaPrivateMaterial.size(),
true);
rsaPrivate2.BERDecode(arraySource);
(另请参阅@jww的答案,以获取通过使用ByteQueue
避免固定大小缓冲区的示例)。
另一个示例使用 std::string
存储密钥材料并使用 StringSink
类写入此材料,这避免了一些缓冲区管理(字符串将自动调整大小以匹配编码的数据量)。请注意,即使它位于 std::string
对象中,这仍然是二进制数据。
RSA::PrivateKey rsaPrivate(params);
std::string rsaPrivateMaterial;
StringSink stringSink(rsaPrivateMaterial);
rsaPrivate.DEREncode(stringSink);
RSA::PrivateKey rsaPrivate2;
StringSource stringSource(rsaPrivateMaterial, true);
rsaPrivate2.BERDecode(stringSource);
或者,如果要自己控制格式,可以使用InvertibleRSAFunction
对象或密钥对象的方法提取各个参数(如上面的"Crypto++ RSA 加密"链接所示),并使用它来提取值以您自己的格式进行存储:
const Integer& n = params.GetModulus();
const Integer& p = params.GetPrime1();
const Integer& q = params.GetPrime2();
const Integer& d = params.GetPrivateExponent();
const Integer& e = params.GetPublicExponent();
然后,当从文件或容器中读取时,通过使用相应的 setter 方法(SetModulus()
、SetPrime1()
等),可以将这些实例还原到新的 InvertibleRSAFunction
或 RSA::*Key
实例。
我将如何从字符串/字节数组或任何其他容器加载私钥/公钥
Crypto++ 库内置了对 std:strings
的支持。但其他C++容器将更加棘手。 ArraySource
是在Crypto++ 5.6中添加的,但它只是StringSource
的一个typedef
。
如果您使用的是敏感材料,那么您还应该考虑使用 SecByteBlock
.当析构函数运行时,它将擦除或归零敏感材料。
和字符串源(加载)
string spki = ...;
StringSource ss(spki, true /*pumpAll*/);
RSA::PublicKey publicKey;
publicKey.Load(ss);
矢量和数组源(加载)
vector<byte> spki = ...;
ArraySource as(&spki[0], spki.length(), true /*pumpAll*/);
RSA::PublicKey publicKey;
publicKey.Load(as);
字符串和字符串接收器(保存)
string spki;
StringSink ss(spki);
RSA::PublicKey publicKey(...);
publicKey.Save(ss);
矢量(保存)
请参阅下面的代码。
下面是保存到std::vector
和从加载的示例。您必须使用中间ByteQueue
进行保存,因为您无法轻松创建VectorSink
。
AutoSeededRandomPool prng;
RSA::PrivateKey pk1, pk2;
pk1.Initialize(prng, 1024);
ByteQueue queue;
pk1.Save(queue);
vector<byte> spki;
spki.resize(queue.MaxRetrievable());
ArraySink as1(&spki[0], spki.size());
queue.CopyTo(as1);
ArraySource as2(&spki[0], spki.size(), true);
pk2.Load(as2);
bool valid = pk2.Validate(prng, 3);
if(valid)
cout << "Validated private key" << endl;
else
cout << "Failed to validate private key" << endl;
我们没有显式VectorSink
,并且由于对traits_type::char_type
的隐式期望,我们无法轻易创建一个。例如:
using CryptoPP::StringSinkTemplate;
typedef StringSinkTemplate< std::vector<byte> > VectorSink;
In file included from cryptopp-test.cpp:65:
In file included from /usr/local/include/cryptopp/files.h:5:
/usr/local/include/cryptopp/filters.h:590:22: error: no member named
'traits_type' in 'std::vector<unsigned char, std::allocator<unsigned char>
>'
typedef typename T::traits_type::char_type char_type;
~~~^
cryptopp-test.cpp:243:20: note: in instantiation of template class
'CryptoPP::StringSinkTemplate<std::vector<unsigned char,
std::allocator<unsigned char> > >' requested here
VectorSink vs(spki);
您可以创建VectorSource
并VectorSink
,它只需要一些工作。您可以通过查看 filters.h 和 filters.cpp 中的StringSource
和StringSink
源代码来了解所涉及的工作。
如果按如下方式创建 DSA 密钥,则最终将得到两个文件,一个包含私钥,另一个包含公钥。
void CreateDsaKeys(std::string folder)
{
AutoSeededRandomPool rng;
// Generate Private Key
DSA::PrivateKey privateKey;
privateKey.GenerateRandomWithKeySize(rng, 1024);
// Generate Public Key
DSA::PublicKey publicKey;
publicKey.AssignFrom(privateKey);
if (!privateKey.Validate(rng, 3) || !publicKey.Validate(rng, 3))
{
throw runtime_error("DSA key generation failed");
}
std::string publicPath = folder + "/publickey.txt";
std::string privatePath = folder + "/privatekey.txt";
SaveHexPublicKey(publicPath, publicKey);
SaveHexPrivateKey(privatePath, privateKey);
}
将这两个文件的内容复制到源代码中,并将它们放入字符串中:
std::string publickey("308201B73082012C...F752BB791");
std::字符串私钥("3082014C0201003...0B8E805D83E9708");
然后,您可以使用 HexDecoder 将字符串转换为字节,并使用以下字节创建公钥和私钥:
bool LoadDsaKeysFromStringsAndTest()
{
AutoSeededRandomPool rng;
HexDecoder decoderPublic;
decoderPublic.Put((byte*)publickey.data(), publickey.size());
decoderPublic.MessageEnd();
HexDecoder decoderPrivate;
decoderPrivate.Put((byte*)privatekey.data(), privatekey.size());
decoderPrivate.MessageEnd();
DSA::PublicKey publicKey;
publicKey.Load(decoderPublic);
DSA::PrivateKey privateKey;
privateKey.Load(decoderPrivate);
string message = "DSA Signature";
string signature;
try {
DSA::Signer signer( privateKey );
StringSource ss1( message, true,
new SignerFilter( rng, signer,
new StringSink( signature )
) // SignerFilter
); // StringSource
bool result = false;
DSA::Verifier verifier1( publicKey );
StringSource ss(message+signature, true,
new SignatureVerificationFilter(verifier1,
new ArraySink((uint8_t*)&result, sizeof(result)),
SignatureVerificationFilter::PUT_RESULT | SignatureVerificationFilter::SIGNATURE_AT_END)
);
return result;
}
catch(const CryptoPP::Exception& e)
{
std::cerr << e.what() << std::endl;
}
return false;
}
这些是保存密钥所需的其他例程
void Save(const string& filename, const BufferedTransformation& bt)
{
FileSink file(filename.c_str());
bt.CopyTo(file);
file.MessageEnd();
}
void SaveHex(const string& filename, const BufferedTransformation& bt)
{
HexEncoder encoder;
bt.CopyTo(encoder);
encoder.MessageEnd();
Save(filename, encoder);
}
void SaveHexPrivateKey(const string& filename, const PrivateKey& key)
{
ByteQueue queue;
key.Save(queue);
SaveHex(filename, queue);
}
void SaveHexPublicKey(const string& filename, const PublicKey& key)
{
ByteQueue queue;
key.Save(queue);
SaveHex(filename, queue);
}
我将如何从字符串/字节数组或加载私钥/公钥或 任何其他容器
//Create Cryptopp StringSource From Std::string
std::string PublicKeyString = "<Your key as std::string value>";
CryptoPP::StringSource PKeyStringSource(PublicKeyString, true);
CryptoPP::RSA::PublicKey publicKey;
publicKey.Load(PKeyStringSource);
不过,我不确定cryptopp是否支持CryptoPP::StringSource的本机容器。但我相信,将容器存储为 std::vector> 这应该可以达到这里的目的。
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么 c++ 中的 main() 函数不采用除 int 和 void 之外的任何其他返回类型
- 为什么当我没有变量或其他任何命名的东西时"no match for 'operator==' "错误?
- 如何在不进行任何其他修改的情况下"pretty print" C++的XML字符串?
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 如何对 int 变量应用验证,使其仅接受整数数据,并且在任何其他数据的情况下不会出错?
- GLSL 计算着色器 使用查找表设置缓冲区会导致不写入任何数据,与其他数据设置相同的缓冲区有效
- 如何计算该程序的复杂性?是否有任何其他复杂性较低的解决方案
- C const在函数声明中以及其他任何地方的anmpersand的右侧
- 如何使用"std::multimap"或任何其他容器对多个值进行排序?
- 如何在任何其他全局变量或静态变量之前创建/构造类实例
- SSO在STD :: String以外的任何其他标准库容器中使用
- 程序在C++ Tutor中执行时有效,但在其他任何地方都不起作用
- 避免重复变量类型:Return type Resolver、C++11 auto、..其他任何东西
- 强制仅在某些代码中使用的特定构造函数,而不是其他任何地方
- 除了在类和程序之前,函数是否需要在其他任何地方声明?
- Ifstream不会读取整数或其他任何东西
- 3摄像机捕获与视频输入或其他任何东西
- 模板中的构造函数不同:一个用于字符串,另一个用于其他任何东西