View Javadoc

1   /*
2    * EL4J, the Extension Library for the J2EE, adds incremental enhancements to
3    * the spring framework, http://el4j.sf.net
4    * Copyright (C) 2005 by ELCA Informatique SA, Av. de la Harpe 22-24,
5    * 1000 Lausanne, Switzerland, http://www.elca.ch
6    *
7    * EL4J is published under the GNU Lesser General Public License (LGPL)
8    * Version 2.1. See http://www.gnu.org/licenses/
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13   * GNU Lesser General Public License for more details.
14   *
15   * For alternative licensing, please contact info@elca.ch
16   */
17  package ch.elca.el4j.services.security.encryption;
18  
19  import java.util.Arrays;
20  
21  import javax.crypto.Cipher;
22  import javax.crypto.KeyGenerator;
23  import javax.crypto.SecretKey;
24  import javax.crypto.spec.SecretKeySpec;
25  
26  import org.slf4j.Logger;
27  import org.slf4j.LoggerFactory;
28  
29  import org.apache.commons.codec.binary.Base64;
30  
31  
32  /**
33   * This class can be used to en/decrypt Strings using the AES algorithm.
34   *
35   * @svnLink $Revision: 4010 $;$Date: 2009-12-01 10:59:54 +0100 (Di, 01. Dez 2009) $;$Author: jonasha $;$URL: https://el4j.svn.sourceforge.net/svnroot/el4j/branches/el4j_3_1/el4j/framework/modules/security/src/main/java/ch/elca/el4j/services/security/encryption/AESCipher.java $
36   *
37   * @author Stefan Wismer (SWI)
38   */
39  public class AESCipher {
40  	/**
41  	 * The prefix of encrypted messages.
42  	 */
43  	private static final String PREFIX = "{AES-128}";
44  	
45  	/**
46  	 * The logger.
47  	 */
48  	private static Logger s_logger = LoggerFactory.getLogger(AESCipher.class);
49  	
50  	/**
51  	 * Cipher used for encryption.
52  	 */
53  	private Cipher m_cipherEncypt;
54  	
55  	/**
56  	 * Cipher used for decryption.
57  	 */
58  	private Cipher m_cipherDecypt;
59  	
60  	/**
61  	 * @param base64encodedKey    a 128 bit AES key (base64 encoded) to use for en/decryption
62  	 */
63  	public AESCipher(String base64encodedKey) {
64  		try {
65  			byte[] key = Base64.decodeBase64(base64encodedKey.getBytes());
66  			SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
67  			
68  			m_cipherEncypt = Cipher.getInstance("AES");
69  			m_cipherEncypt.init(Cipher.ENCRYPT_MODE, skeySpec);
70  			
71  			m_cipherDecypt = Cipher.getInstance("AES");
72  			m_cipherDecypt.init(Cipher.DECRYPT_MODE, skeySpec);
73  		} catch (Exception e) {
74  			s_logger.error("Error creating AESCipher", e);
75  		}
76  	}
77  	
78  	/**
79  	 * @param plainText    plain text
80  	 * @return             encrypted text
81  	 */
82  	public String encrypt(String plainText) {
83  		try {
84  			return PREFIX + new String(Base64.encodeBase64(m_cipherEncypt.doFinal(plainText.getBytes())));
85  		} catch (Exception e) {
86  			s_logger.error("Error while encrypting text", e);
87  			return null;
88  		}
89  	}
90  	
91  	/**
92  	 * @param encryptedText    encrypted text
93  	 * @return                decrypted text
94  	 */
95  	public String decrypt(String encryptedText) {
96  		try {
97  			if (encryptedText.startsWith(PREFIX)) {
98  				return new String(m_cipherDecypt.doFinal(
99  						Base64.decodeBase64(encryptedText.substring(PREFIX.length()).getBytes())));
100 			} else {
101 				s_logger.error("Error while decrypting text: encyptedText does not start with " + PREFIX);
102 				return encryptedText;
103 			}
104 		} catch (Exception e) {
105 			s_logger.error("Error while decrypting text", e);
106 			return null;
107 		}
108 	}
109 
110 	/**
111 	 * @param args          (no arguments expected)
112 	 * @throws Exception
113 	 */
114 	public static void main(String[] args) throws Exception {
115 
116 		KeyGenerator kgen = KeyGenerator.getInstance("AES");
117 		kgen.init(128); // 192 and 256 bits may not be available
118 
119 		// Generate the secret key specs.
120 		SecretKey skey = kgen.generateKey();
121 		byte[] raw = skey.getEncoded();
122 
123 		System.out.println("Generated AES-128 key:" + Arrays.toString(Base64.encodeBase64(raw)));
124 	}
125 
126 }