【发布时间】:2020-03-19 05:38:03
【问题描述】:
我正在编写一个关于 MANET(移动自组织网络)中的 AODV 路由协议的项目,我的目标之一是在协议数据包之一的字段中添加数字签名。
我正在使用 NS3 来模拟基于 C++ 的网络。对于签名,我使用的是 Crypto++ 的 RSA 库。基本上,一个节点生成一个公钥和私钥对来对数据包进行签名,将其公钥包含在数据包中,然后将其发送到另一个节点。然后接收节点使用数据包中提供的公钥来验证签名。数据包中的公钥被编码为具有std::string 数据类型的十六进制字符串。
我已经确认公钥是正确的,问题仅在于从十六进制格式解码公钥字符串。
这些是我用来生成密钥对、签名和验证的函数 (我从http://marko-editor.com/articles/cryptopp_sign_string/ 得到这些):
struct KeyPairHex {
std::string publicKey;
std::string privateKey;
};
KeyPairHex
RoutingProtocol::RsaGenerateHexKeyPair(unsigned int aKeySize) {
KeyPairHex keyPair;
// PGP Random Pool-like generator
AutoSeededRandomPool rng;
// generate keys
RSA::PrivateKey privateKey;
privateKey.GenerateRandomWithKeySize(rng, aKeySize);
RSA::PublicKey publicKey(privateKey);
// save keys
publicKey.Save( HexEncoder(
new StringSink(keyPair.publicKey)).Ref());
privateKey.Save(HexEncoder(
new StringSink(keyPair.privateKey)).Ref());
return keyPair;
}
std::string
RoutingProtocol::RsaSignString(const std::string &aPrivateKeyStrHex,
const std::string &aMessage) {
// decode and load private key (using pipeline)
RSA::PrivateKey privateKey;
privateKey.Load(StringSource(aPrivateKeyStrHex, true,
new HexDecoder()).Ref());
// sign message
std::string signature;
RSASS<PKCS1v15, SHA>::Signer signer(privateKey);
AutoSeededRandomPool rng;
StringSource ss(aMessage, true,
new SignerFilter(rng, signer,
new HexEncoder(
new StringSink(signature))));
return signature;
}
bool
RoutingProtocol::RsaVerifyString(const std::string &aPublicKeyStrHex,
const std::string &aMessage,
const std::string &aSignatureStrHex) {
// decode and load public key (using pipeline)
RSA::PublicKey publicKey;
publicKey.Load(StringSource(aPublicKeyStrHex, true,
new HexDecoder()).Ref());
// decode signature
std::string decodedSignature;
StringSource ss(aSignatureStrHex, true,
new HexDecoder(
new StringSink(decodedSignature)));
// verify message
bool result = false;
RSASS<PKCS1v15, SHA>::Verifier verifier(publicKey);
StringSource ss2(decodedSignature + aMessage, true,
new SignatureVerificationFilter(verifier,
new ArraySink((byte*)&result, sizeof(result))));
return result;
}
我使用的密钥大小为 384。这是公钥:
304A300D06092A864886F70D01010105000339003036023100CC112A0E007C6329F813BC96498AFE
DF580EE4F708C2A923F6C6257FA4CC5FE2BA711C75CDE02036839E67C9B62720B3020111
签名邮件没有问题。但是,从字符串中加载密钥时,我不断收到错误消息。
我得到的错误是:
terminate called after throwing instance of 'BerDecodeErr' what(): BER decode error
【问题讨论】:
标签: c++ rsa digital-signature crypto++