📄 rsaimp.java
字号:
package cpe5021;
import java.math.BigInteger;
import java.util.Scanner;
import sun.security.util.BigInt;
public class RsaImp {
private final static BigInteger ONE = new BigInteger("1");
private BigInteger privateKey;
private BigInteger publicKey;
private BigInteger modulus;
RsaImp(int N) {
Modules modules = new Modules();
BigInteger p = modules.getRandomPrime(N);
BigInteger q = new BigInteger("0");
do {
q = modules.getRandomPrime(N);
}while (p.equals(q)||!GCD(p,q).equals(BigInteger.ONE));
BigInteger phi = (p.subtract(ONE)).multiply(q.subtract(ONE));
modulus = p.multiply(q);
publicKey = modules.getRandomPrime(16);
privateKey = publicKey.modInverse(phi);
}
BigInteger encrypt(BigInteger message) {
return message.modPow(publicKey, modulus);
}
BigInteger decrypt(BigInteger encrypted) {
return encrypted.modPow(privateKey, modulus);
}
BigInteger signature(BigInteger message){
return message.modPow(privateKey, modulus);
}
BigInteger revert(BigInteger signatured){
return signatured.modPow(publicKey, modulus);
}
public BigInteger GCD(BigInteger a, BigInteger b)
{
if (b.equals(BigInteger.ZERO)) return a;
return GCD(b,a.mod(b));
}
public static void main(String[] args) {
System.out.print("Please type in key size: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
System.out.print("Please type in messages: ");
Scanner s = new Scanner(System.in);
String m = s.nextLine();
RsaImp key = new RsaImp(num);
byte[] bytes = m.getBytes();
BigInteger message = new BigInteger(bytes);
BigInteger encrypt = key.encrypt(message);
BigInteger decrypt = key.decrypt(encrypt);
BigInteger signature = key.signature(message);
BigInteger revert = key.revert(signature);
byte[] en = encrypt.toByteArray();
byte[] de = decrypt.toByteArray();
byte[] si = signature.toByteArray();
byte[] re = revert.toByteArray();
String enm = new String(en);
String dem = new String(de);
String sim = new String(si);
String rem = new String(re);
System.out.println("encrpyted = " + enm);
System.out.println("decrypted = " + dem);
System.out.println("signatured = " + sim);
System.out.println("reverted signature = " + rem);
BigInteger msgHashCode= BigInteger.valueOf(m.hashCode());
msgHashCode = msgHashCode.abs();
BigInteger siMsgHashCode= key.signature(msgHashCode);
BigInteger reMsgHasCode = key.revert(siMsgHashCode);
System.out.println("Messages Hash Code: " + msgHashCode);
System.out.println("Signtured Hash Code: " + siMsgHashCode);
System.out.println("Reverted Hash Code: " + reMsgHasCode);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -