1 package fr.in2p3.jsaga.adaptor.security;
2
3 import javax.crypto.Cipher;
4 import javax.crypto.KeyGenerator;
5 import javax.crypto.spec.SecretKeySpec;
6
7 import org.apache.commons.codec.binary.Base64;
8
9 import java.io.File;
10 import java.io.FileOutputStream;
11 import java.security.Key;
12
13
14
15
16
17
18
19
20
21
22
23
24
25 public class PasswordEncrypterSingleton extends PasswordAbstract {
26 private static final int EXPIRY_DATE_POSITION = 12;
27 private static final int KEY_SIZE = 128;
28
29
30
31
32
33 public PasswordEncrypterSingleton(String keyalias, int lifetime) throws Exception {
34 super();
35
36
37 KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
38 keyGenerator.init(KEY_SIZE);
39 Key key = keyGenerator.generateKey();
40
41
42 byte[] rawKey = key.getEncoded();
43 int expiryDate = getExpiryDate(lifetime);
44 setBytes(rawKey, EXPIRY_DATE_POSITION, expiryDate);
45 m_key = new SecretKeySpec(rawKey, ALGORITHM);
46
47
48 File keystoreFile = PasswordAbstract.KEYSTORE_FILE;
49 m_keystore.setKeyEntry(keyalias, m_key, m_keypass, null);
50 m_keystore.store(new FileOutputStream(keystoreFile), m_storepass);
51 }
52
53 public String encrypt(String uncrypted) throws Exception {
54 Cipher cipher = Cipher.getInstance(CIPHER);
55 cipher.init(Cipher.ENCRYPT_MODE, m_key);
56 byte[] crypted = cipher.doFinal(uncrypted.getBytes());
57 return Base64.encodeBase64String(crypted);
58 }
59
60 public static int getExpiryDate(int lifetime) {
61 return (int) (System.currentTimeMillis()/1000) + lifetime;
62 }
63
64 private static void setBytes(byte[] bytes, int pos, int value) {
65 bytes[pos] = (byte)((value & 0xff000000)>>>24);
66 bytes[pos+1] = (byte)((value & 0x00ff0000)>>>16);
67 bytes[pos+2] = (byte)((value & 0x0000ff00)>>>8);
68 bytes[pos+3] = (byte)((value & 0x000000ff));
69 }
70 }