📄 privatekey.java
字号:
package rsa;
import java.io.*;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.*;
/** class to represent a private key */
public class privateKey
{
/** probability when generating prime numbers for RSA key */
public static int PRIME_PROBABILITY = 100;
/** value of 1 */
final static BigInteger ONE = BigInteger.valueOf(1);
public BigInteger P;
public BigInteger Q;
public BigInteger PQ;
public BigInteger E;
public BigInteger N;
public BigInteger D;
/** constructor - pass in two prime numbers and a value for E */
public privateKey(BigInteger _P, BigInteger _Q, BigInteger _E)
{
P = _P;
Q = _Q;
E = _E;
N = P.multiply(Q);
PQ = P.subtract(ONE).multiply(Q.subtract(ONE));
D = E.modInverse(PQ);
}
/** constructor that generates two massive prime numbers and E automatically */
public privateKey(int bitSize)
{
// create secure random number generator
SecureRandom sr = new SecureRandom();
// generate random prime numbers
do
{
P = new BigInteger(bitSize / 2, PRIME_PROBABILITY, sr);
do
{
Q = new BigInteger(bitSize / 2, PRIME_PROBABILITY, sr);
} while (P.compareTo(Q) == 0);
E = new BigInteger(bitSize / 4, PRIME_PROBABILITY, sr);
PQ = P.subtract(ONE).multiply(Q.subtract(ONE));
N = P.multiply(Q);
}
while (N.bitLength() != bitSize || E.gcd(PQ).compareTo(ONE) !=0); // ensure E is relatively prime to PQ
// N = P.multiply(Q);
//System.out.println("N bitlength=" + N.bitLength());
D = E.modInverse(PQ);
}
/** decrypts an entire string */
public String decrypt(ArrayList ciphertext)
{
// declare the returned plaintext
StringBuffer plaintext = new StringBuffer();
// loop through each BigInteger in the array
for (int i = 1; i <= ciphertext.size(); i++)
{
// get the next BigInteger
BigInteger c = (BigInteger)ciphertext.get(i-1);
// decrypt it using RSA
BigInteger plainTextNum = c.modPow(D, N);
// get this number as a string of bits
String bits = plainTextNum.toString(2);
// pad to ensure the string contains a multiple of 16 bits (Unicode)
while (bits.length() % 16 != 0)
bits = "0" + bits;
// convert each set of 16 bits to a character, add to the plaintext, then delete from the stringbuffer
for (int j = 0; j < bits.length(); j += 16)
plaintext.append((char)Integer.parseInt(bits.substring(j, j+16), 2));
}
return plaintext.toString();
}
/** returns the public key for this private key */
public publicKey getPublicKey()
{
return new publicKey(N, E);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -