/** *

COMP3441/9441 Assignment 2 Example Code

*

Session 2, 2003

* @author Halvard Skogsrud */ import java.security.*; import java.security.Security.*; import java.security.interfaces.*; import javax.crypto.* ; public class Test { /** * The message we want to encrypt */ public static final String CLEARTEXT = "Hello world"; /** *

This method does the following:

*
    *
  1. Adds the Cryptix provider to JCE
  2. *
  3. Generates an RSA key pair
  4. *
  5. Initializes the RSA cipher
  6. *
  7. Encrypts a string using RSA
  8. *
  9. Decrypts the encrypted string
  10. *
*/ public static void main (String[] args) { try { // add our open-source provider, which can do RSA encryption Security.addProvider(new cryptix.jce.provider.CryptixCrypto()); // just print some information on the crypto provider package Provider cryptix = Security.getProvider("CryptixCrypto"); System.out.println(cryptix.getName() + " " + cryptix.getVersion()); System.out.println(cryptix.getInfo()); // create an RSA key pair generator object KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); // set the key size to the desired number of bits (max 2048) gen.initialize(512); // generate the RSA key pair KeyPair pair = gen.generateKeyPair(); // extract the public and private keys RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate(); // initialize the RSA cipher in ECB mode Cipher c = Cipher.getInstance("RSA/ECB/PKCS#1"); // set the cipher to do encryption c.init(Cipher.ENCRYPT_MODE, publicKey); // encrypt the sample string byte[] ciphertext = c.doFinal(CLEARTEXT.getBytes()); // set the cipher to do decryption c.init(Cipher.DECRYPT_MODE, privateKey); // decrypt the encrypted sample string byte[] decryptedText = c.doFinal(ciphertext); // print out the strings System.out.println("Original string: " + CLEARTEXT); System.out.println("Encrypted string: " + new String(ciphertext)); System.out.println("Decrypted string: " + new String(decryptedText)); } catch (Throwable t) { t.printStackTrace(); } } }