001    package railo.runtime.crypt;
002    
003    import java.security.InvalidKeyException;
004    import java.security.Key;
005    import java.security.NoSuchAlgorithmException;
006    
007    import javax.crypto.BadPaddingException;
008    import javax.crypto.Cipher;
009    import javax.crypto.IllegalBlockSizeException;
010    import javax.crypto.NoSuchPaddingException;
011    import javax.crypto.spec.SecretKeySpec;
012    
013    import railo.runtime.coder.Coder;
014    import railo.runtime.coder.CoderException;
015    
016       /**
017       * This program generates a AES key, retrieves its raw bytes, and
018       * then reinstantiates a AES key from the key bytes.
019       * The reinstantiated key is used to initialize a AES cipher for
020       * encryption and decryption.
021       */
022    
023       public class Cryptor {
024    
025            public static byte[] encrypt(String type, String key, String message) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
026                    return encrypt(type, key, message.getBytes());
027            }
028            public static byte[] encrypt(String type, String key, byte[] message) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
029                    type=type.toUpperCase();
030                    Key k = new SecretKeySpec( decodeKey(key), type );
031            Cipher c = Cipher.getInstance(type);
032            c.init( Cipher.ENCRYPT_MODE, k );
033            return c.doFinal(message);
034            }
035    
036    
037    
038            public static byte[] decrypt(String type, String key, String message) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
039            return decrypt(type, key, message.getBytes());
040            }
041            public static byte[] decrypt(String type, String key, byte[] message) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
042                    type=type.toUpperCase();
043                    
044                    Cipher c = Cipher.getInstance(type);
045            Key k = new SecretKeySpec( decodeKey(key), type );
046            c.init( Cipher.DECRYPT_MODE, k );
047            return c.doFinal(message);
048            }
049            
050    
051    
052            private static byte[] decodeKey(String key) {
053                    try {
054                            return Coder.decode(Coder.ENCODING_BASE64, key);
055                    }
056                    catch (CoderException e) {
057                            return key.getBytes();
058                    }
059            }
060    }