我正在尝试使用rsa加密当前日期和时间,并使用此密文输入另一个应用程序来验证用户。
这是代码。我是java的noobie所以我从互联网上复制了它并且对它做了一些改动。
计划 -
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Scanner;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class RSA3
{
public BigInteger n, d, e;
private int bitlen = 16;
/** Create an instance that can both encrypt and decrypt. */
public RSA3(int bits)
{
bitlen = bits;
SecureRandom r = new SecureRandom();
Scanner in = new Scanner(System.in);
String number1, number2;
System.out.println("Enter first number");
number1 = in.nextLine();
System.out.println("Enter second number");
number2 = in.nextLine();
BigInteger p = new BigInteger(number1);
BigInteger q = new BigInteger(number2);
//BigInteger p = new BigInteger(bitlen / 2,100,r);
//BigInteger q = new BigInteger(bitlen / 2,100,r);
n = p.multiply(q);
System.out.println("\n n="+n);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
System.out.println("\n m="+m);
e = new BigInteger("3");
while (m.gcd(e).intValue() > 1)
{
e = e.add(new BigInteger("2"));
}
System.out.println("\n e="+e);
d = e.modInverse(m);
System.out.println("\n d="+d);
}
/** Encrypt the given plaintext message. */
public synchronized BigInteger encrypt(BigInteger message)
{System.out.println("\n 2nd enc");
return message.modPow(e, n);
}
/** Decrypt the given ciphertext message. */
public synchronized BigInteger decrypt(BigInteger message)
{System.out.println("\n2nd dec");
return message.modPow(d, n);
}
/** Trivial test program. */
public static void main(String[] args)
{
RSA3 rsa = new RSA3(1024);
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
String text1 = dateFormat.format(date);
System.out.println("Plaintext: " + text1);
BigInteger plaintext = new BigInteger(text1.getBytes());
BigInteger ciphertext = rsa.encrypt(plaintext);
System.out.println("Ciphertext: " + ciphertext);
plaintext = rsa.decrypt(ciphertext);
String text2 = new String(plaintext.toByteArray());
System.out.println("Plaintext: " + text2);
}
}
如果我为p& q来自用户,就像我在代码中所做的那样。密文有问题。 但如果我选择BigInteger(bitlen / 2,100,r);它工作正常。 但每次密文生成都是新的随机数。我不想这样 我想要p&我个人的选择
我想我已经搞砸了某个地方的biginteger。 如果有任何其他方法我可以告诉我。
我在这里找不到逻辑错误 请帮忙 谢谢