1 package org.kuali.mobility.security.util;
2 import java.security.InvalidKeyException;
3 import java.security.NoSuchAlgorithmException;
4 import java.util.List;
5 import java.util.Properties;
6
7 import javax.crypto.BadPaddingException;
8 import javax.crypto.Cipher;
9 import javax.crypto.IllegalBlockSizeException;
10 import javax.crypto.NoSuchPaddingException;
11 import javax.crypto.spec.SecretKeySpec;
12
13 import org.apache.commons.codec.binary.Base64;
14 import org.apache.log4j.Logger;
15
16 public class EncryptionUtil implements EncryptionConstants{
17
18 private static final Logger LOGGER = Logger.getLogger(EncryptionUtil.class);
19
20 private SecretKeySpec keySpec;
21 private Cipher encryptionCipher, decryptionCipher;
22
23 private String encodedKey;
24 private String algorithm;
25
26 Properties kmeProperties;
27
28
29
30
31
32
33
34
35
36 public EncryptionUtil(Properties properties) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
37 algorithm = properties.getProperty(ENCRYPTION_ALGORITHM);
38 if(algorithm == null){
39 throw new RuntimeException("No encryption algorithm provided");
40 }
41
42 encodedKey = properties.getProperty(ENCRYPTION_KEY);
43
44 this.kmeProperties = properties;
45
46 keySpec = new SecretKeySpec(Base64.decodeBase64(encodedKey),algorithm);
47
48 encryptionCipher = Cipher.getInstance(algorithm);
49 decryptionCipher = Cipher.getInstance(algorithm);
50
51 encryptionCipher.init(Cipher.ENCRYPT_MODE, keySpec);
52 decryptionCipher.init(Cipher.DECRYPT_MODE, keySpec);
53
54 }
55
56 public synchronized String encrypt(String value) throws IllegalBlockSizeException, BadPaddingException{
57 byte[] encryptedBytes = encryptionCipher.doFinal(value.getBytes());
58 return Base64.encodeBase64String(encryptedBytes);
59 }
60
61 public synchronized String decrypt(String value) throws IllegalBlockSizeException, BadPaddingException{
62 byte[] decodedBytes = Base64.decodeBase64(value);
63 byte[] decryptedBytes = decryptionCipher.doFinal(decodedBytes);
64 return new String(decryptedBytes);
65 }
66
67 public Properties encryptProperties(List<String> propertyNames) throws IllegalBlockSizeException, BadPaddingException{
68 Properties encryptedProperties = new Properties();
69
70 for(String property : propertyNames){
71 String encryptedValue = encrypt(kmeProperties.getProperty(property));
72 encryptedProperties.put(property,encryptedValue);
73 LOGGER.info(property + "=" + encryptedValue);
74 }
75
76 return encryptedProperties;
77 }
78 }