3 import java.security.*;
\r
4 import javax.crypto.*;
\r
7 private final static BigInteger one = new BigInteger("1");
\r
8 private final static SecureRandom random = new SecureRandom();
\r
10 private BigInteger privateKey;
\r
11 private BigInteger publicKey;
\r
12 private BigInteger modulus;
\r
14 // generate an N-bit (roughly) public and private key
\r
16 BigInteger p = BigInteger.probablePrime(N/2, random);
\r
17 BigInteger q = BigInteger.probablePrime(N/2, random);
\r
18 BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));
\r
20 modulus = p.multiply(q);
\r
21 publicKey = new BigInteger("65537"); // common value in practice = 2^16 + 1
\r
22 privateKey = publicKey.modInverse(phi);
\r
26 BigInteger encrypt(BigInteger message) {
\r
27 return message.modPow(publicKey, modulus);
\r
30 BigInteger decrypt(BigInteger encrypted) {
\r
31 return encrypted.modPow(privateKey, modulus);
\r
34 public String toString() {
\r
36 s += "public = " + publicKey + "\n";
\r
37 s += "private = " + privateKey + "\n";
\r
38 s += "modulus = " + modulus;
\r
42 public static void main(String[] args) {
\r
43 MyKeyPair kp = new MyKeyPair(128);
\r
44 System.out.println(key);
\r
46 // create random message, encrypt and decrypt
\r
47 //BigInteger message = new BigInteger(127, random);
\r
49 //// create message by converting string to integer
\r
51 byte[] bytes = s.getBytes();
\r
52 BigInteger message = new BigInteger(bytes);
\r
54 BigInteger encrypt = kp.encrypt(message);
\r
55 BigInteger decrypt = kp.decrypt(encrypt);
\r
56 System.out.println("message = " + message);
\r
57 System.out.println("encrpyted = " + encrypt);
\r
58 System.out.println("decrypted = " + new String(decrypt.toByteArray()));
\r