KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > entity > util > EntityCrypto


1 /*
2  * $Id: EntityCrypto.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2004-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.entity.util;
26
27 import java.security.NoSuchAlgorithmException JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Map JavaDoc;
30 import java.util.Random JavaDoc;
31
32 import javax.crypto.SecretKey;
33 import javax.transaction.Transaction JavaDoc;
34
35 import org.ofbiz.base.crypto.DesCrypt;
36 import org.ofbiz.base.crypto.HashCrypt;
37 import org.ofbiz.base.util.Debug;
38 import org.ofbiz.base.util.GeneralException;
39 import org.ofbiz.base.util.StringUtil;
40 import org.ofbiz.base.util.UtilMisc;
41 import org.ofbiz.base.util.UtilObject;
42 import org.ofbiz.entity.EntityCryptoException;
43 import org.ofbiz.entity.GenericDelegator;
44 import org.ofbiz.entity.GenericEntityException;
45 import org.ofbiz.entity.GenericValue;
46 import org.ofbiz.entity.transaction.GenericTransactionException;
47 import org.ofbiz.entity.transaction.TransactionUtil;
48
49 /**
50  *
51  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
52  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
53  * @version $Rev: 5462 $
54  * @since 3.2
55  */

56 public class EntityCrypto {
57
58     public static final String JavaDoc module = EntityCrypto.class.getName();
59
60     protected GenericDelegator delegator = null;
61     protected Map JavaDoc keyMap = null;
62
63     protected EntityCrypto() { }
64     public EntityCrypto(GenericDelegator delegator) {
65         this.delegator = delegator;
66         this.keyMap = new HashMap JavaDoc();
67
68         // check the key table and make sure there
69
// make sure there are some dummy keys
70
synchronized(EntityCrypto.class) {
71             try {
72                 long size = delegator.findCountByAnd("EntityKeyStore", null);
73                 if (size == 0) {
74                     for (int i = 0; i < 20; i++) {
75                         String JavaDoc randomName = this.getRandomString();
76                         this.getKeyFromStore(randomName);
77                     }
78                 }
79             } catch (GenericEntityException e) {
80                 Debug.logError(e, module);
81             }
82         }
83     }
84
85     /** Encrypts a String into an encrypted hex encoded byte array */
86     public String JavaDoc encrypt(String JavaDoc keyName, Object JavaDoc obj) throws EntityCryptoException {
87         try {
88             return StringUtil.toHexString(DesCrypt.encrypt(this.getKey(keyName), UtilObject.getBytes(obj)));
89         } catch (GeneralException e) {
90             throw new EntityCryptoException(e);
91         }
92     }
93
94     /** Decrypts a hex encoded byte array into a String */
95     public Object JavaDoc decrypt(String JavaDoc keyName, String JavaDoc str) throws EntityCryptoException {
96         try {
97             return UtilObject.getObject(DesCrypt.decrypt(this.getKey(keyName), StringUtil.fromHexString(str)));
98         } catch (GeneralException e) {
99             throw new EntityCryptoException(e);
100         }
101     }
102
103     protected SecretKey getKey(String JavaDoc name) throws EntityCryptoException {
104         SecretKey key = (SecretKey) keyMap.get(name);
105         if (key == null) {
106             synchronized(this) {
107                 String JavaDoc keyName = HashCrypt.getDigestHash(name);
108                 key = this.getKeyFromStore(keyName);
109                 keyMap.put(name, key);
110             }
111         }
112         return key;
113     }
114
115     protected SecretKey getKeyFromStore(String JavaDoc keyName) throws EntityCryptoException {
116         GenericValue keyValue = null;
117         try {
118             keyValue = delegator.findByPrimaryKey("EntityKeyStore", UtilMisc.toMap("keyName", keyName));
119         } catch (GenericEntityException e) {
120             throw new EntityCryptoException(e);
121         }
122         if (keyValue == null || keyValue.get("keyText") == null) {
123             SecretKey key = null;
124             try {
125                 key = DesCrypt.generateKey();
126             } catch (NoSuchAlgorithmException JavaDoc e) {
127                 throw new EntityCryptoException(e);
128             }
129             GenericValue newValue = delegator.makeValue("EntityKeyStore", null);
130             newValue.set("keyText", StringUtil.toHexString(key.getEncoded()));
131             newValue.set("keyName", keyName);
132
133             Transaction JavaDoc parentTransaction = null;
134             boolean beganTrans = false;
135             try {
136                 beganTrans = TransactionUtil.begin();
137             } catch (GenericTransactionException e) {
138                 throw new EntityCryptoException(e);
139             }
140
141             if (!beganTrans) {
142                 try {
143                     parentTransaction = TransactionUtil.suspend();
144                 } catch (GenericTransactionException e) {
145                     throw new EntityCryptoException(e);
146                 }
147
148                 // now start a new transaction
149
try {
150                     beganTrans = TransactionUtil.begin();
151                 } catch (GenericTransactionException e) {
152                     throw new EntityCryptoException(e);
153                 }
154             }
155
156             try {
157                 delegator.create(newValue);
158             } catch (GenericEntityException e) {
159                 try {
160                     TransactionUtil.rollback(beganTrans, "Error creating encrypted value", e);
161                 } catch (GenericTransactionException e1) {
162                     Debug.logError(e1, "Could not rollback transaction", module);
163                 }
164                 throw new EntityCryptoException(e);
165             } finally {
166                 try {
167                     TransactionUtil.commit(beganTrans);
168                 } catch (GenericTransactionException e) {
169                     throw new EntityCryptoException(e);
170                 }
171                 // resume the parent transaction
172
if (parentTransaction != null) {
173                     try {
174                         TransactionUtil.resume(parentTransaction);
175                     } catch (GenericTransactionException e) {
176                         throw new EntityCryptoException(e);
177                     }
178                 }
179             }
180
181
182             return key;
183         } else {
184             byte[] keyBytes = StringUtil.fromHexString(keyValue.getString("keyText"));
185             try {
186                 return DesCrypt.getDesKey(keyBytes);
187             } catch (GeneralException e) {
188                 throw new EntityCryptoException(e);
189             }
190         }
191     }
192
193     protected String JavaDoc getRandomString() {
194         Random JavaDoc rand = new Random JavaDoc();
195         byte[] randomBytes = new byte[24];
196         rand.nextBytes(randomBytes);
197         return StringUtil.toHexString(randomBytes);
198     }
199 }
200
Popular Tags