C++ RSA程序仅在一定范围内对数字进行加密和解密
如果我给出p=61,q=53的样本输入,如果我给这个特殊素数集一个介于1和21之间的消息值,我的程序成功地将消息加密并解密回正确的原始消息。但如果我输入p=61,q=53,消息值大于21,则无法将消息解密回正确的原始消息 不仅仅是这些特殊的素数集合。对于任何一对素数,只有一定范围的消息值被正确加密和解密。那为什么呢?有人能建议如何解决这个问题吗C++ RSA程序仅在一定范围内对数字进行加密和解密,c++,encryption,cryptography,C++,Encryption,Cryptography,如果我给出p=61,q=53的样本输入,如果我给这个特殊素数集一个介于1和21之间的消息值,我的程序成功地将消息加密并解密回正确的原始消息。但如果我输入p=61,q=53,消息值大于21,则无法将消息解密回正确的原始消息 不仅仅是这些特殊的素数集合。对于任何一对素数,只有一定范围的消息值被正确加密和解密。那为什么呢?有人能建议如何解决这个问题吗 class RSA { private: long int p,q; long int msg,cipherMsg,plainM
class RSA
{
private:
long int p,q;
long int msg,cipherMsg,plainMsg;
long int n,totient;
long int publicKey,privateKey;
public:
RSA();
void ComputeKeys(long int p1,long int p2,long long int message);
void EncryptMessage();
void DecryptMessage();
};
RSA :: RSA()
{
p=0;q=0;
n=0;totient=0;
publicKey=0;privateKey=0;
msg=0;cipherMsg=0;plainMsg=0;
}
void RSA :: EncryptMessage()
{
int y=1;
cout<<"Encrypting Message....."<<endl;
for(long int i=1;i<=publicKey;i++)
{
y=y*msg;
}
msg=y;
cout<<"m^e:"<<msg<<endl;
cipherMsg= msg%n;
cout<<"Encryption Complete!"<<endl;
cout<<"Cipher Message:"<<cipherMsg<<endl;
}
void RSA :: DecryptMessage()
{
long int y= 1,tmp;
cout<<"Decrypting Message...."<<endl;
for(long int i=1;i<=privateKey;i++)
{
y=y*cipherMsg;
tmp=y;
y=fmod(y,n);
}
cout<<"c^d:"<<tmp<<endl;
plainMsg=y;
cout<<"Decryption Complete!"<<endl;
cout<<"Original Message:"<<plainMsg<<endl;
}
int main()
{
RSA obj;
cout<<"\t------RSA Cryptography------"<<endl;
obj.ComputeKeys(61,53,21);
return 0;
}
类RSA
{
私人:
长整数p,q;
长int msg、ciphersg、plainMsg;
长int n,toticent;
长整数公钥、私钥;
公众:
RSA();
无效计算键(长整数p1、长整数p2、长整数消息);
void EncryptMessage();
无效消息();
};
RSA::RSA()
{
p=0;q=0;
n=0;ToClient=0;
公钥=0;私钥=0;
msg=0;ciphersg=0;plainMsg=0;
}
void RSA::EncryptMessage()
{
int y=1;
cout对我来说,这看起来像是整数溢出。现在,你正在计算xy,并且只有当你完成时,才将结果取为mod m
您通常希望利用这样一个事实,即您可以在过程中的每一步取模数,以最小化避免溢出所需的大小
模块化电源功能的代码可以如下所示:
template <class T>
T mul_mod(T a, T b, T m) {
if (m == 0) return a * b;
T r = T();
while (a > 0) {
if (a & 1)
if ((r += b) > m) r %= m;
a >>= 1;
if ((b <<= 1) > m) b %= m;
}
return r;
}
template <class T>
T pow_mod(T a, T n, T m) {
T r = 1;
while (n > 0) {
if (n & 1)
r = mul_mod(r, a, m);
a = mul_mod(a, a, m);
n >>= 1;
}
return r;
}
模板
T mul_mod(ta,tb,tm){
如果(m==0)返回a*b;
tr=T();
而(a>0){
如果(a&1)
如果((r+=b)>m)r%=m;
a>>=1;
如果((b0){
如果(n&1)
r=多个模态(r,a,m);
a=多模态(a,a,m);
n>>=1;
}
返回r;
}
根据您使用的类型和值,这仍然可能溢出,但对于给定的类型,它将为比原始版本大得多的值生成正确的结果
还要注意的是,这会通过重复平方提高到一个幂,这使得它在处理较大的数字时更加实用(基本上,它是O(logn)而不是O(N),N=模)
我在中发布了一个更完整的实现。您所说的有问题的值是函数ComputeKeys
的输入,您不想发布该函数。您希望得到什么样的帮助?我们不知道该函数的功能。我所看到的只是一个构造函数,其中所有内容都初始化为零。在我看来,除了t在整数上使用fmod
。这太疯狂了。为什么要使用fmod
?如果y
或m
超过53位的值,这很可能会导致问题。而且m^e
对于任何大于微小值的公钥都会产生较大的值,对于c^d
。