View Javadoc

1   /**
2      This file is part of GoldenGate Project (named also GoldenGate or GG).
3   
4      Copyright 2009, Frederic Bregier, and individual contributors by the @author
5      tags. See the COPYRIGHT.txt in the distribution for a full listing of
6      individual contributors.
7   
8      All GoldenGate Project is free software: you can redistribute it and/or 
9      modify it under the terms of the GNU General Public License as published 
10     by the Free Software Foundation, either version 3 of the License, or
11     (at your option) any later version.
12  
13     GoldenGate is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17  
18     You should have received a copy of the GNU General Public License
19     along with GoldenGate .  If not, see <http://www.gnu.org/licenses/>.
20   */
21  package goldengate.common.crypto;
22  
23  import goldengate.common.exception.CryptoException;
24  
25  import java.io.File;
26  import java.io.FileInputStream;
27  import java.io.FileNotFoundException;
28  import java.io.IOException;
29  import java.security.NoSuchAlgorithmException;
30  import java.util.Enumeration;
31  import java.util.LinkedList;
32  import java.util.List;
33  import java.util.concurrent.ConcurrentHashMap;
34  import java.util.concurrent.atomic.AtomicBoolean;
35  
36  /**
37   * This class implements a simple Key Manager from name
38   *
39   * @author frederic bregier
40   *
41   */
42  public abstract class KeyManager {
43      ConcurrentHashMap<String, KeyObject> keysConcurrentHashMap =
44          new ConcurrentHashMap<String, KeyObject>();
45      volatile AtomicBoolean isInitialized = new AtomicBoolean(false);
46  
47      public abstract KeyObject createKeyObject();
48      /**
49       * Init the Manager from a list of filename Key, the key name is the basename minus the extension
50       * @param keys
51       * @param extension
52       * @return the list of wrong keys
53       */
54      public List<String> initFromList(List<String> keys, String extension) {
55          LinkedList<String> wrong = new LinkedList<String>();
56          for (String filename: keys) {
57              File file = new File(filename);
58              if (file.canRead()) {
59                  String basename = file.getName();
60                  int lastpos = basename.lastIndexOf(extension);
61                  if (lastpos <= 0) {
62                      wrong.add(filename);
63                      continue;
64                  }
65                  String firstname = basename.substring(0, lastpos-1);
66                  int len = (int)file.length();
67                  byte []key = new byte[len];
68                  FileInputStream inputStream = null;
69                  try {
70                      inputStream = new FileInputStream(file);
71                  } catch (FileNotFoundException e) {
72                      // should not be
73                      wrong.add(filename);
74                      continue;
75                  }
76                  int read = 0;
77                  int offset = 0;
78                  while (read > 0) {
79                      try {
80                          read = inputStream.read(key, offset, len);
81                      } catch (IOException e) {
82                          wrong.add(filename);
83                          read = -2;
84                          break;
85                      }
86                      offset += read;
87                      if (offset < len) {
88                          len -= read;
89                      } else {
90                          break;
91                      }
92                  }
93                  if (read < -1) {
94                      // wrong
95                      continue;
96                  }
97                  KeyObject keyObject = createKeyObject();
98                  keyObject.setSecretKey(key);
99                  this.setKey(firstname, keyObject);
100             } else {
101                 wrong.add(filename);
102             }
103         }
104         this.isInitialized.set(true);
105         return wrong;
106     }
107 
108     public void saveToFiles(String extension) throws CryptoException, IOException {
109         Enumeration<String> names = keysConcurrentHashMap.keys();
110         while (names.hasMoreElements()) {
111             String name = names.nextElement();
112             KeyObject key = keysConcurrentHashMap.get(name);
113             key.saveSecretKey(new File(name+"."+extension));
114         }
115     }
116     /**
117      * Add or set a new key associated to the given name
118      *
119      * @param name
120      * @param keyObject
121      */
122     public void setKey(String name, KeyObject keyObject) {
123         this.keysConcurrentHashMap.put(name, keyObject);
124     }
125 
126     /**
127      * @param name
128      * @return the key associated to the given name
129      */
130     public KeyObject getKey(String name) {
131         return this.keysConcurrentHashMap.get(name);
132     }
133     /**
134      * One method to get the crypted String from the given string and key
135      * @param keyName
136      * @param toBeCrypted
137      * @return the crypted String
138      * @throws Exception
139      */
140     public String crypt(String keyName, String toBeCrypted) throws Exception {
141         KeyObject keyObject = this.getKey(keyName);
142         if (keyName == null) {
143             throw new NoSuchAlgorithmException("Key does not exist: "+keyName);
144         }
145         return keyObject.cryptToHex(toBeCrypted);
146     }
147     /**
148      * One method to get the uncrypted String from the given crypted string and key
149      * @param keyName
150      * @param toBeDecrypted
151      * @return the uncrypted String
152      * @throws Exception
153      */
154     public String decrypt(String keyName, String toBeDecrypted) throws Exception {
155         KeyObject keyObject = this.getKey(keyName);
156         if (keyName == null) {
157             throw new NoSuchAlgorithmException("Key does not exist: "+keyName);
158         }
159         return keyObject.decryptHexInString(toBeDecrypted);
160     }
161 
162 }