📄 publickey.java
字号:
package rsa;
import java.math.BigInteger;
import java.io.*;
import java.util.*;
/** class to represent a public key */
public class publicKey implements Serializable
{
/** size of block of bytes to encrypt in a single go */
final static int BLOCKSIZE = 8;
public BigInteger N;
public BigInteger E;
/** constructor */
public publicKey(BigInteger _N, BigInteger _E)
{
N = _N;
E = _E;
}
/** encrypts an entire string */
public ArrayList encrypt(String plaintext)
{
// declare array of BigIntegers that is the ciphertext
ArrayList ciphertext = new ArrayList();
// declare stringbuffer to hold the bits in each block of bytes being encrypted
StringBuffer bits = new StringBuffer();
// loop through each character
for (int i = 1; i <= plaintext.length(); i++)
{
// convert the character to a string of bits
String charAsBits = Integer.toBinaryString((int)plaintext.charAt(i-1));
// pad to 16 bits (Unicode)
while (charAsBits.length() < 16)
charAsBits = "0" + charAsBits;
// add to the main string of bits for this block
bits.append(charAsBits);
// if we have reached the blocksize, encrypt this block using RSA and reset the string of bits
if (i % BLOCKSIZE == 0)
{
BigInteger binaryValueBigInt = new BigInteger(bits.toString(), 2);
ciphertext.add(binaryValueBigInt.modPow(E, N));
bits.setLength(0);
}
}
// if there is a partially completed block of bits, encrypt these
if (bits.length() > 0)
{
BigInteger binaryValueBigInt = new BigInteger(bits.toString(), 2);
ciphertext.add(binaryValueBigInt.modPow(E, N));
}
return ciphertext;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -