/*
 * Silly tests with Java crypto
 *
 */
import java.math.*;
import java.security.*;
import java.security.interfaces.*;

//import org.bouncycastle.crypto.*;

public class Testje {

    static SecureRandom random = new SecureRandom();
    static private int RSAlength = 1024;

    public static void main (String[] args) throws Exception {
	System.out.println("==== Hash test");
	// Alternatives "MD5" or "SHA1"
	MessageDigest mdHash = MessageDigest.getInstance( "MD5" );
	String s = "Hash thjs string";
	// Feed the Byte Array containing the string to the hash
	mdHash.update(s.getBytes());   
	// Compute the hash
	byte[] raw = mdHash.digest();   
	System.out.println("Hash value of string \"" + s + "\" is\n" + 
			   new BigInteger(raw) + 
			   "\nwith " + raw.length + " bytes length.");

	KeyPairGenerator RSAkeyGen = KeyPairGenerator.getInstance("RSA");
	RSAkeyGen.initialize(RSAlength);
	KeyPair RSAkeypair = RSAkeyGen.generateKeyPair();
	RSAPublicKey RSApubkey = (RSAPublicKey)RSAkeypair.getPublic();
	BigInteger RSAmod = RSApubkey.getModulus();
 	BigInteger E = RSApubkey.getPublicExponent();
 	RSAPrivateCrtKey RSAprivkey = (RSAPrivateCrtKey)RSAkeypair.getPrivate();
 	BigInteger P = RSAprivkey.getPrimeP();
 	BigInteger Q = RSAprivkey.getPrimeQ();
 	BigInteger EulerMod = 
	    P.subtract(BigInteger.ONE).multiply(Q.subtract(BigInteger.ONE));
 	BigInteger D = RSAprivkey.getPrivateExponent();
	System.out.println("==== RSA test\n" +
			   "RSA key check works: " +
			   RSAmod.equals(P.multiply(Q)));
	System.out.format("Public key modulus (N) %d and exponent (E) %d\n", 
			  RSAmod, E);
	System.out.println("Private key exponent (D): " + D);
	System.out.println("Product of E and D is: " +
			   E.multiply(D).mod(EulerMod));
 	// 
 	BigInteger message = new BigInteger(RSAlength-1, random);
	System.out.println("===\nEncryption by hand test of message : " + 
			   message);
 	BigInteger enc = message.modPow(E, RSAmod);
 	// System.out.println("Encrypted: " + enc);
 	BigInteger dec = enc.modPow(D, RSAmod);
 	System.out.println("Encryption-Decryption test " +
 			   ((message.equals(dec) ? "succeeded" : "failed")));
    }

}
