2 * Copyright (C) 2007-2012 Argeo GmbH
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org
.argeo
.cms
.internal
.kernel
;
18 import java
.io
.ByteArrayInputStream
;
19 import java
.io
.CharArrayReader
;
20 import java
.io
.InputStream
;
21 import java
.io
.Reader
;
22 import java
.security
.Provider
;
23 import java
.security
.SecureRandom
;
25 import javax
.crypto
.Cipher
;
26 import javax
.crypto
.CipherInputStream
;
27 import javax
.crypto
.SecretKey
;
28 import javax
.crypto
.spec
.IvParameterSpec
;
29 import javax
.jcr
.Binary
;
30 import javax
.jcr
.Node
;
31 import javax
.jcr
.Property
;
32 import javax
.jcr
.RepositoryException
;
33 import javax
.jcr
.Session
;
35 import org
.apache
.commons
.io
.IOUtils
;
36 import org
.argeo
.jcr
.ArgeoJcrException
;
37 import org
.argeo
.jcr
.JcrUtils
;
38 import org
.argeo
.node
.ArgeoNames
;
39 import org
.argeo
.node
.ArgeoTypes
;
40 import org
.argeo
.node
.NodeUtils
;
41 import org
.argeo
.util
.security
.AbstractKeyring
;
42 import org
.argeo
.util
.security
.PBEKeySpecCallback
;
44 /** JCR based implementation of a keyring */
45 public class JcrKeyring
extends AbstractKeyring
implements ArgeoNames
{
47 * Stronger with 256, but causes problem with Oracle JVM, force 128 in this
50 public final static Long DEFAULT_SECRETE_KEY_LENGTH
= 256l;
51 public final static String DEFAULT_SECRETE_KEY_FACTORY
= "PBKDF2WithHmacSHA1";
52 public final static String DEFAULT_SECRETE_KEY_ENCRYPTION
= "AES";
53 public final static String DEFAULT_CIPHER_NAME
= "AES/CBC/PKCS5Padding";
55 private Integer iterationCountFactor
= 200;
56 private Long secreteKeyLength
= DEFAULT_SECRETE_KEY_LENGTH
;
57 private String secreteKeyFactoryName
= DEFAULT_SECRETE_KEY_FACTORY
;
58 private String secreteKeyEncryption
= DEFAULT_SECRETE_KEY_ENCRYPTION
;
59 private String cipherName
= DEFAULT_CIPHER_NAME
;
61 private Session session
;
64 * When setup is called the session has not yet been saved and we don't want
65 * to save it since there maybe other data which would be inconsistent. So
66 * we keep a reference to this node which will then be used (an reset to
67 * null) when handling the PBE callback. We keep one per thread in case
68 * multiple users are accessing the same instance of a keyring.
70 private ThreadLocal
<Node
> notYetSavedKeyring
= new ThreadLocal
<Node
>() {
73 protected Node
initialValue() {
79 protected Boolean
isSetup() {
81 if (notYetSavedKeyring
.get() != null)
84 Node userHome
= NodeUtils
.getUserHome(session
);
85 return userHome
.hasNode(ARGEO_KEYRING
);
86 } catch (RepositoryException e
) {
87 throw new ArgeoJcrException("Cannot check whether keyring is setup", e
);
92 protected void setup(char[] password
) {
94 InputStream in
= null;
96 Node userHome
= NodeUtils
.getUserHome(session
);
97 if (userHome
.hasNode(ARGEO_KEYRING
))
98 throw new ArgeoJcrException("Keyring already setup");
99 Node keyring
= userHome
.addNode(ARGEO_KEYRING
);
100 keyring
.addMixin(ArgeoTypes
.ARGEO_PBE_SPEC
);
102 // deterministic salt and iteration count based on username
103 String username
= session
.getUserID();
104 byte[] salt
= new byte[8];
105 byte[] usernameBytes
= username
.getBytes();
106 for (int i
= 0; i
< salt
.length
; i
++) {
107 if (i
< usernameBytes
.length
)
108 salt
[i
] = usernameBytes
[i
];
112 in
= new ByteArrayInputStream(salt
);
113 binary
= session
.getValueFactory().createBinary(in
);
114 keyring
.setProperty(ARGEO_SALT
, binary
);
116 Integer iterationCount
= username
.length() * iterationCountFactor
;
117 keyring
.setProperty(ARGEO_ITERATION_COUNT
, iterationCount
);
120 // TODO check if algo and key length are available, use DES if not
121 keyring
.setProperty(ARGEO_SECRET_KEY_FACTORY
, secreteKeyFactoryName
);
122 keyring
.setProperty(ARGEO_KEY_LENGTH
, secreteKeyLength
);
123 keyring
.setProperty(ARGEO_SECRET_KEY_ENCRYPTION
, secreteKeyEncryption
);
124 keyring
.setProperty(ARGEO_CIPHER
, cipherName
);
126 // keyring.getSession().save();
128 // encrypted password hash
129 // IOUtils.closeQuietly(in);
130 // JcrUtils.closeQuietly(binary);
131 // byte[] btPass = hash(password, salt, iterationCount);
132 // in = new ByteArrayInputStream(btPass);
133 // binary = session.getValueFactory().createBinary(in);
134 // keyring.setProperty(ARGEO_PASSWORD, binary);
136 notYetSavedKeyring
.set(keyring
);
137 } catch (Exception e
) {
138 throw new ArgeoJcrException("Cannot setup keyring", e
);
140 JcrUtils
.closeQuietly(binary
);
141 IOUtils
.closeQuietly(in
);
142 // JcrUtils.discardQuietly(session);
147 protected void handleKeySpecCallback(PBEKeySpecCallback pbeCallback
) {
149 Node userHome
= NodeUtils
.getUserHome(session
);
151 if (userHome
.hasNode(ARGEO_KEYRING
))
152 keyring
= userHome
.getNode(ARGEO_KEYRING
);
153 else if (notYetSavedKeyring
.get() != null)
154 keyring
= notYetSavedKeyring
.get();
156 throw new ArgeoJcrException("Keyring not setup");
158 pbeCallback
.set(keyring
.getProperty(ARGEO_SECRET_KEY_FACTORY
).getString(),
159 JcrUtils
.getBinaryAsBytes(keyring
.getProperty(ARGEO_SALT
)),
160 (int) keyring
.getProperty(ARGEO_ITERATION_COUNT
).getLong(),
161 (int) keyring
.getProperty(ARGEO_KEY_LENGTH
).getLong(),
162 keyring
.getProperty(ARGEO_SECRET_KEY_ENCRYPTION
).getString());
164 if (notYetSavedKeyring
.get() != null)
165 notYetSavedKeyring
.remove();
166 } catch (RepositoryException e
) {
167 throw new ArgeoJcrException("Cannot handle key spec callback", e
);
171 /** The parent node must already exist at this path. */
173 protected synchronized void encrypt(String path
, InputStream unencrypted
) {
174 // should be called first for lazy initialization
175 SecretKey secretKey
= getSecretKey();
177 Binary binary
= null;
178 InputStream in
= null;
180 Cipher cipher
= createCipher();
182 if (!session
.nodeExists(path
)) {
183 String parentPath
= JcrUtils
.parentPath(path
);
184 if (!session
.nodeExists(parentPath
))
185 throw new ArgeoJcrException("No parent node of " + path
);
186 Node parentNode
= session
.getNode(parentPath
);
187 node
= parentNode
.addNode(JcrUtils
.nodeNameFromPath(path
));
189 node
= session
.getNode(path
);
191 node
.addMixin(ArgeoTypes
.ARGEO_ENCRYPTED
);
192 SecureRandom random
= new SecureRandom();
193 byte[] iv
= new byte[16];
194 random
.nextBytes(iv
);
195 cipher
.init(Cipher
.ENCRYPT_MODE
, secretKey
, new IvParameterSpec(iv
));
196 JcrUtils
.setBinaryAsBytes(node
, ARGEO_IV
, iv
);
198 in
= new CipherInputStream(unencrypted
, cipher
);
199 binary
= session
.getValueFactory().createBinary(in
);
200 node
.setProperty(Property
.JCR_DATA
, binary
);
202 } catch (Exception e
) {
203 throw new ArgeoJcrException("Cannot encrypt", e
);
205 IOUtils
.closeQuietly(unencrypted
);
206 IOUtils
.closeQuietly(in
);
207 JcrUtils
.closeQuietly(binary
);
212 protected synchronized InputStream
decrypt(String path
) {
213 Binary binary
= null;
214 InputStream encrypted
= null;
215 Reader reader
= null;
217 if (!session
.nodeExists(path
)) {
218 char[] password
= ask();
219 reader
= new CharArrayReader(password
);
220 return new ByteArrayInputStream(IOUtils
.toByteArray(reader
));
222 // should be called first for lazy initialisation
223 SecretKey secretKey
= getSecretKey();
225 Cipher cipher
= createCipher();
227 Node node
= session
.getNode(path
);
228 if (node
.hasProperty(ARGEO_IV
)) {
229 byte[] iv
= JcrUtils
.getBinaryAsBytes(node
.getProperty(ARGEO_IV
));
230 cipher
.init(Cipher
.DECRYPT_MODE
, secretKey
, new IvParameterSpec(iv
));
232 cipher
.init(Cipher
.DECRYPT_MODE
, secretKey
);
235 binary
= node
.getProperty(Property
.JCR_DATA
).getBinary();
236 encrypted
= binary
.getStream();
237 return new CipherInputStream(encrypted
, cipher
);
239 } catch (Exception e
) {
240 throw new ArgeoJcrException("Cannot decrypt", e
);
242 IOUtils
.closeQuietly(encrypted
);
243 IOUtils
.closeQuietly(reader
);
244 JcrUtils
.closeQuietly(binary
);
248 protected Cipher
createCipher() {
250 Node userHome
= NodeUtils
.getUserHome(session
);
251 if (!userHome
.hasNode(ARGEO_KEYRING
))
252 throw new ArgeoJcrException("Keyring not setup");
253 Node keyring
= userHome
.getNode(ARGEO_KEYRING
);
254 String cipherName
= keyring
.getProperty(ARGEO_CIPHER
).getString();
255 Provider securityProvider
= getSecurityProvider();
257 if (securityProvider
== null)// TODO use BC?
258 cipher
= Cipher
.getInstance(cipherName
);
260 cipher
= Cipher
.getInstance(cipherName
, securityProvider
);
262 } catch (Exception e
) {
263 throw new ArgeoJcrException("Cannot get cipher", e
);
267 public synchronized void changePassword(char[] oldPassword
, char[] newPassword
) {
268 // TODO decrypt with old pw / encrypt with new pw all argeo:encrypted
271 public synchronized void setSession(Session session
) {
272 this.session
= session
;
275 public void setIterationCountFactor(Integer iterationCountFactor
) {
276 this.iterationCountFactor
= iterationCountFactor
;
279 public void setSecreteKeyLength(Long keyLength
) {
280 this.secreteKeyLength
= keyLength
;
283 public void setSecreteKeyFactoryName(String secreteKeyFactoryName
) {
284 this.secreteKeyFactoryName
= secreteKeyFactoryName
;
287 public void setSecreteKeyEncryption(String secreteKeyEncryption
) {
288 this.secreteKeyEncryption
= secreteKeyEncryption
;
291 public void setCipherName(String cipherName
) {
292 this.cipherName
= cipherName
;