资源描述
RSA实现数字签名
数字签名,就是只有信息的发送者才能产生的别人无法伪造的一段数字串,这段数字串同时也是对信息的发送者发送信息真实性的一个有效证明。
主要功能
保证信息传输的完整性、发送者的身份认证、防止交易中的抵赖发生。
数字签名技术是将摘要信息用发送者的私钥加密,与原文一起传送给接收者。接收者只有用发送者的公钥才能解密被加密的摘要信息,然后用HASH函数对收到的原文产生一个摘要信息,与解密的摘要信息对比。如果相同,则说明收到的信息是完整的,在传输过程中没有被修改,否则说明信息被修改过,因此数字签名能够验证信息的完整性。
数字签名是个加密的过程,数字签名验证是个解密的过程。
数字签名签名过程
“发送报文时,发送方用一个哈希函数从报文文本中生成报文摘要,然后用自己的私人密钥对这个摘要进行加密,这个加密后的摘要将作为报文的数字签名和报文一起发送给接收方,接收方首先用与发送方一样的哈希函数从接收到的原始报文中计算出报文摘要,接着再用发送方的公用密钥来对报文附加的数字签名进行解密,如果这两个摘要相同、那么接收方就能确认该数字签名是发送方的。
数字签名有两种功效:一是能确定消息确实是由发送方签名并发出来的,因为别人假冒不了发送方的签名。二是数字签名能确定消息的完整性。因为数字签名的特点是它代表了文件的特征,文件如果发生改变,数字摘要的值也将发生变化。不同的文件将得到不同的数字摘要。 一次数字签名涉及到一个哈希函数、发送者的公钥、发送者的私钥。”
数字签名:
发送方用自己的密钥对报文X进行Encrypt(编码)运算,生成不可读取的密文Dsk,然后将Dsk传送给接收方,接收方为了核实签名,用发送方的公用密钥进行Decrypt(解码)运算,还原报文。
我自己看了crypto++的文档,利用文档给的rsa签名的示例代码自己做了一个小程序,代码示例如下:
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include "md5.h"
#include<iostream>
#include "pssr.h"
#include <hex.h>
#include "rsa.h"
#include "osrng.h"
using namespace CryptoPP;
#pragma comment(lib, "cryptlib.lib")
using namespace std;
bool md5(const string &src, string &digest)
{
Weak::MD5 md5;
StringSource(src, true,
new HashFilter(md5,
new HexEncoder(new StringSink(digest))
)
);
return true;
}
int main()
{
try
{
////////////////////////////////////////////////
// Generate keys
AutoSeededRandomPool rng;
InvertibleRSAFunction parameters;
parameters.GenerateRandomWithKeySize(rng, 1024);
RSA::PrivateKey privateKey(parameters);
RSA::PublicKey publicKey(parameters);
// Message
string message;// = "Yoda said, Do or Do Not. There is not try.";
string signature,md5_message;
cout << "请输入要签名的内容:";
cin >> message;
cout << endl;
md5(message, md5_message);
cout <<"将信息哈希为摘要:"<<endl<<endl<< md5_message << endl << endl;
////////////////////////////////////////////////
// Sign and Encode
RSASS<PSS, SHA1>::Signer signer(privateKey);
StringSource(md5_message, true,
new SignerFilter(rng, signer,
new StringSink(signature)
) // SignerFilter
); // StringSource
cout << signature << endl<<endl<<endl;
////////////////////////////////////////////////
// Verify and Recover
RSASS<PSS, SHA1>::Verifier verifier(publicKey);
StringSource(md5_message + signature, true,
new SignatureVerificationFilter(
verifier, NULL,
SignatureVerificationFilter::THROW_EXCEPTION
) // SignatureVerificationFilter
); // StringSource
cout << "Verified signature on message" << endl;
} // try
catch (CryptoPP::Exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
展开阅读全文