1 /*
2  * @(#) $Id: AsymmetricCipherTest.java,v 1.2 2003/07/08 08:13:52 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10import java.security.KeyPairGenerator;
11import java.security.KeyPair;
12import java.security.PublicKey;
13import java.security.PrivateKey;
14import javax.crypto.Cipher;
15import javax.crypto.IllegalBlockSizeException;
16import javax.crypto.NoSuchPaddingException;
17import javax.crypto.BadPaddingException;
18import java.security.SignatureException;
19import java.security.NoSuchAlgorithmException;
20import java.security.InvalidKeyException;
21import java.security.InvalidAlgorithmParameterException;
22
23public class AsymmetricCipherTest {
24    private static byte[] encrypt(byte[] inpBytes, PublicKey key, String xform) throws
25            NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException,
26            NoSuchPaddingException, BadPaddingException, InvalidAlgorithmParameterException {
27        Cipher cipher = Cipher.getInstance(xform);
28        cipher.init(Cipher.ENCRYPT_MODE, key);
29        return cipher.doFinal(inpBytes);
30    }
31    private static byte[] decrypt(byte[] inpBytes, PrivateKey key, String xform) throws
32            NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException,
33            NoSuchPaddingException, BadPaddingException, InvalidAlgorithmParameterException{
34        Cipher cipher = Cipher.getInstance(xform);
35        cipher.init(Cipher.DECRYPT_MODE, key);
36        return cipher.doFinal(inpBytes);
37    }
38
39    public static void main(String[] unused) throws Exception {
40        String xform = "RSA/NONE/PKCS1PADDING";
41        int keysize = 56;
42        // Generate a key-pair
43        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
44        kpg.initialize(512); // 512 is the keysize.
45        KeyPair kp = kpg.generateKeyPair();
46        PublicKey pubk = kp.getPublic();
47        PrivateKey prvk = kp.getPrivate();
48
49        byte[] dataBytes = "J2EE Security for Servlets, EJBs and Web Services".getBytes();
50
51        byte[] encBytes = encrypt(dataBytes, pubk, xform);
52        byte[] decBytes = decrypt(encBytes, prvk, xform);
53
54        boolean expected = java.util.Arrays.equals(dataBytes, decBytes);
55        System.out.println("Test " + (expected ? "SUCCEEDED!" : "FAILED!"));
56    }
57}