View Javadoc

1   package fr.in2p3.jsaga.adaptor.security;
2   
3   import org.apache.commons.codec.binary.Base64;
4   import org.ogf.saga.error.BadParameterException;
5   
6   import javax.crypto.Cipher;
7   
8   /* ***************************************************
9   * *** Centre de Calcul de l'IN2P3 - Lyon (France) ***
10  * ***             http://cc.in2p3.fr/             ***
11  * ***************************************************
12  * File:   PasswordDecrypterSingleton
13  * Author: Sylvain Reynaud (sreynaud@in2p3.fr)
14  * Date:   21 sept. 2007
15  * ***************************************************
16  * Description:                                      */
17  /**
18   *
19   */
20  public class PasswordDecrypterSingleton extends PasswordAbstract {
21      private static final int EXPIRY_DATE_POSITION = 12;
22  
23      /**
24       * @param keyalias the alias of the secret key
25       */
26      public PasswordDecrypterSingleton(String keyalias) throws Exception {
27          super();
28  
29          // load key from keystore
30          m_key = m_keystore.getKey(keyalias, m_keypass);
31          if (m_key == null) {
32              throw new BadParameterException("Key not found in keystore: "+keyalias);
33          }
34      }
35  
36      public int getExpiryDate() {
37          return getValue(m_key.getEncoded(), EXPIRY_DATE_POSITION);
38      }
39  
40      public String decrypt(String cryptedBase64) throws Exception {
41          byte[] crypted = Base64.decodeBase64(cryptedBase64);
42          Cipher cipher = Cipher.getInstance(CIPHER);
43          cipher.init(Cipher.DECRYPT_MODE, m_key);
44          byte[] decrypted = cipher.doFinal(crypted);
45          return new String(decrypted);
46      }
47  
48      private static int getValue(byte[] bytes, int pos) {
49          return ((bytes[pos] & 0xFF) << 24)
50                  | ((bytes[pos+1] & 0xFF) << 16)
51                  | ((bytes[pos+2] & 0xFF) << 8)
52                  | (bytes[pos+3] & 0xFF);
53      }
54  }