import java.security.*;

/**
 * <p>Example 1 exercises the KeyPairGenerator & Signature
 *    classes.
 *    
 *    An RSA key pair is generated, and used to sign a message
 *    using the MD5withRSA signature algorithm. The signature
 *    is then verified.
 */
public class Example1
{
  public static void main(String args[])
  {
    try
    {
      System.out.println("Seeding random number generator ...");
      SecureRandom rand = new SecureRandom();
      rand.nextInt();
  
      // We want RSA keys of key length = 1024 bits
      KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
      kpg.initialize(1024, rand);
  
      System.out.println("Generating keys ...");
      KeyPair kp = kpg.generateKeyPair();
      PrivateKey priv = kp.getPrivate();
      PublicKey pub = kp.getPublic();
  
      // We want to use MD5withRSA
      Signature signature = Signature.getInstance("MD5withRSA");
  
      // Initialize for signing
      signature.initSign(priv);
      
      // Data to be signed  
      byte[] data = "Hello, world!".getBytes();
  
      // Sign it and returns signature bytes
      signature.update(data);
      byte[] sigBytes = signature.sign();
  
      // Initialize for verification
      signature.initVerify(pub);
  
      // Verify signature
      signature.update(data);
      boolean isVerified = signature.verify(sigBytes);
  
      System.out.println("Signature verifies: " + isVerified);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}  
