Click here to download all the source files.
|
public static void generatePrimeNumbers() { p = new BigInteger( primeSize, 10, new Random() ) ; do { q = new BigInteger( primeSize, 10, new Random() ) ; } while( q.compareTo( p ) == 0 ) ; } |
Choose a number, E, less than N and relatively prime to ( p - 1 ) * ( q - 1 ), which means E and ( p - 1 ) * ( q - 1 ) have no common factors except 1. In other words, E is coprime to and less than ( p - 1 ) * ( q - 1 ).
Find another number D such that ( E * D - 1 ) is divisible by ( p - 1 ) * ( q - 1 ). The value of D can be obtained by computing the inverse of E mod ( p - 1 ) * ( q - 1 ). This gives a value for D such that E * D = 1 mod ( p - 1 ) * ( q - 1 ).
The values E and D are called the public and private exponents, respectively.
The public key is the pair (N, E) which will be published. The private key is the pair (N, D) which will be kept private.
The factors p and q may be destroyed or kept with the private key.
|
public static void generatePublicPrivateKeys() { // N = p * q N = p.multiply( q ) ; // r = ( p - 1 ) * ( q - 1 ) r = p.subtract( BigInteger.valueOf( 1 ) ) ; r = r.multiply( q.subtract( BigInteger.valueOf( 1 ) ) ) ; // Choose E, coprime to and less than r do { E = new BigInteger( 2 * primeSize, new Random() ) ; } while( ( E.compareTo( r ) != -1 ) || ( E.gcd( r ).compareTo( BigInteger.valueOf( 1 ) ) != 0 ) ) ; // Compute D, the inverse of E mod r D = E.modInverse( r ) ; } |
Suppose Alice wants to send a message M (Plaintext) to Bob. Alice creates the ciphertext C by exponentiating: C = ME mod N, where E and N are Bob's public key. She sends C (Ciphertext) to Bob.
|
public static BigInteger[] encrypt( String message ) { int i ; byte[] temp = new byte[1] ; byte[] digits = message.getBytes() ; BigInteger[] bigdigits = new BigInteger[digits.length] ; for( i = 0 ; i < bigdigits.length ; i++ ) { temp[0] = digits[i] ; bigdigits[i] = new BigInteger( temp ) ; } BigInteger[] encrypted = new BigInteger[bigdigits.length] ; for( i = 0 ; i < bigdigits.length ; i++ ) encrypted[i] = bigdigits[i].modPow( E, N ) ; return( encrypted ) ; } |
|
public static String decrypt( BigInteger[] encrypted ) { int i ; BigInteger[] decrypted = new BigInteger[encrypted.length] ; for( i = 0 ; i < decrypted.length ; i++ ) decrypted[i] = encrypted[i].modPow( D, N ) ; char[] charArray = new char[decrypted.length] ; for( i = 0 ; i < charArray.length ; i++ ) charArray[i] = (char) ( decrypted[i].intValue() ) ; return( new String( charArray ) ) ; } |
Copyright� 2002 by Chue Wai Lian
Last updated on Sunday, 06 January 2002
Please send all mails to [email protected] or [email protected]