3 import java.security.*;
\r
4 import javax.crypto.*;
\r
7 public static void main (String[] args) throws NoSuchAlgorithmException,
\r
9 InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,
\r
11 BadPaddingException, NoSuchPaddingException {
\r
13 /* Generate a RSA key pair */
\r
15 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
\r
16 SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
\r
18 keyGen.initialize(512, random);
\r
20 KeyPair pair = keyGen.generateKeyPair();
\r
21 PrivateKey priv = pair.getPrivate();
\r
22 PublicKey pub = pair.getPublic();
\r
23 //System.out.println("Public is" + pub);
\r
24 //System.out.println("Private is" + priv);
\r
26 /* Create the cipher */
\r
27 Cipher rsaCipher = Cipher.getInstance("RSA");
\r
28 rsaCipher.init(Cipher.ENCRYPT_MODE, pub);
\r
31 byte[] cleartext = "This is Bilal".getBytes();
\r
32 System.out.println("the original cleartext is: " + new String(cleartext));
\r
33 //System.out.println("the original cleartext is: " + cleartext);
\r
35 // Encrypt the cleartext
\r
36 byte[] ciphertext = null;
\r
37 ciphertext = rsaCipher.doFinal(cleartext);
\r
38 //byte[] ciphertext = rsaCipher.doFinal(cleartext);
\r
39 //String ciphertext = rsaCipher.doFinal(cleartext);
\r
40 System.out.println("the encrypted text is: " + new String(ciphertext));
\r
42 // Initialize the same cipher for decryption
\r
43 rsaCipher.init(Cipher.DECRYPT_MODE, priv);
\r
45 // Decrypt the ciphertext
\r
46 byte[] cleartext1 = rsaCipher.doFinal(ciphertext);
\r
47 //String cleartext1 = rsaCipher.doFinal(ciphertext);
\r
48 System.out.println("the final cleartext is: " + new String(cleartext1));
\r
49 //System.out.println("the final cleartext is: " + cleartext1);
\r