【发布时间】:2017-01-03 01:56:05
【问题描述】:
我是编程和网络安全的新手。我正在尝试为我的课业实现 RSA 算法,但我没有得到正确的输出,所以请帮助我,它在解密时没有给出相同的纯文本。
以下是我的代码
import java.security.*;
import java.lang.*;
import java.math.*;
public class RSAalgo
{
BigInteger p,q,n,d,e,ph,t;
SecureRandom r;
public RSAalgo()
{
r=new SecureRandom();
p=new BigInteger(512,100,r);
q=new BigInteger(512,100,r);
System.out.println("\n RSA ALGO");
System.out.println("\n Prime No P : "+p.intValue());
System.out.println("\n Prime no Q : "+q.intValue());
n=p.multiply(q);
ph=(p.subtract(new BigInteger("1")));
e = new BigInteger("2");
while((ph.gcd(e).intValue()>1)||(e.compareTo(ph)!=-1))
e=e.add(new BigInteger("1"));
d=e.modInverse(ph);
System.out.println("public key = "+n.intValue()+", "+e.intValue());
System.out.println("Private key = "+n.intValue()+", "+d.intValue());
BigInteger msg=new BigInteger("21");
System.out.println("Message is "+msg);
BigInteger enmsg=encrypt(msg,e,n);
System.out.println("Encrypted message is "+enmsg.intValue());
BigInteger demsg=decrypt(enmsg,d,n);
System.out.println("Decrypted message is "+demsg.intValue());
}
BigInteger encrypt(BigInteger msg,BigInteger e, BigInteger n)
{
return msg.modPow(e,n);
}
BigInteger decrypt(BigInteger msg,BigInteger d, BigInteger n)
{
return msg.modPow(d,n);
}
public static void main(String args[])
{
new RSAalgo();
}
}
输入:21
加密的味精和解密的味精每次都是随机的
【问题讨论】:
-
请补充信息:你给了什么输入;以及它的输出;否则会发生什么?并花了几分钟更好地缩进/格式化您的代码,使其更易于阅读。
-
如何确保 p 和 q 是素数?
-
r=new SecureRandom(); p=new BigInteger(512,100,r); q=new BigInteger(512,100,r);生成素数
-
你错了。我在下面发布一个答案,有很多错误
标签: java algorithm encryption rsa