1
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 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
44 kpg.initialize(512); 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}