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
.jcr
.security
;
18 import java
.io
.ByteArrayInputStream
;
19 import java
.io
.CharArrayReader
;
20 import java
.io
.InputStream
;
21 import java
.io
.Reader
;
22 import java
.security
.SecureRandom
;
24 import javax
.crypto
.Cipher
;
25 import javax
.crypto
.CipherInputStream
;
26 import javax
.crypto
.SecretKey
;
27 import javax
.crypto
.spec
.IvParameterSpec
;
28 import javax
.jcr
.Binary
;
29 import javax
.jcr
.Node
;
30 import javax
.jcr
.Property
;
31 import javax
.jcr
.RepositoryException
;
32 import javax
.jcr
.Session
;
34 import org
.apache
.commons
.io
.IOUtils
;
35 import org
.argeo
.jcr
.ArgeoJcrException
;
36 import org
.argeo
.jcr
.ArgeoNames
;
37 import org
.argeo
.jcr
.ArgeoTypes
;
38 import org
.argeo
.jcr
.JcrUtils
;
39 import org
.argeo
.jcr
.UserJcrUtils
;
40 import org
.argeo
.util
.security
.AbstractKeyring
;
41 import org
.argeo
.util
.security
.PBEKeySpecCallback
;
43 /** JCR based implementation of a keyring */
44 public class JcrKeyring
extends AbstractKeyring
implements ArgeoNames
{
46 * Stronger with 256, but causes problem with Oracle JVM, force 128 in this
49 public final static Long DEFAULT_SECRETE_KEY_LENGTH
= 256l;
50 public final static String DEFAULT_SECRETE_KEY_FACTORY
= "PBKDF2WithHmacSHA1";
51 public final static String DEFAULT_SECRETE_KEY_ENCRYPTION
= "AES";
52 public final static String DEFAULT_CIPHER_NAME
= "AES/CBC/PKCS5Padding";
54 private Integer iterationCountFactor
= 200;
55 private Long secreteKeyLength
= DEFAULT_SECRETE_KEY_LENGTH
;
56 private String secreteKeyFactoryName
= DEFAULT_SECRETE_KEY_FACTORY
;
57 private String secreteKeyEncryption
= DEFAULT_SECRETE_KEY_ENCRYPTION
;
58 private String cipherName
= DEFAULT_CIPHER_NAME
;
60 private Session session
;
63 * When setup is called the session has not yet been saved and we don't want
64 * to save it since there maybe other data which would be inconsistent. So
65 * we keep a reference to this node which will then be used (an reset to
66 * null) when handling the PBE callback. We keep one per thread in case
67 * multiple users are accessing the same instance of a keyring.
69 private ThreadLocal
<Node
> notYetSavedKeyring
= new ThreadLocal
<Node
>() {
72 protected Node
initialValue() {
78 protected Boolean
isSetup() {
80 if (notYetSavedKeyring
.get() != null)
83 Node userHome
= UserJcrUtils
.getUserHome(session
);
84 return userHome
.hasNode(ARGEO_KEYRING
);
85 } catch (RepositoryException e
) {
86 throw new ArgeoJcrException("Cannot check whether keyring is setup", e
);
91 protected void setup(char[] password
) {
93 InputStream in
= null;
95 Node userHome
= UserJcrUtils
.getUserHome(session
);
96 if (userHome
.hasNode(ARGEO_KEYRING
))
97 throw new ArgeoJcrException("Keyring already setup");
98 Node keyring
= userHome
.addNode(ARGEO_KEYRING
);
99 keyring
.addMixin(ArgeoTypes
.ARGEO_PBE_SPEC
);
101 // deterministic salt and iteration count based on username
102 String username
= session
.getUserID();
103 byte[] salt
= new byte[8];
104 byte[] usernameBytes
= username
.getBytes();
105 for (int i
= 0; i
< salt
.length
; i
++) {
106 if (i
< usernameBytes
.length
)
107 salt
[i
] = usernameBytes
[i
];
111 in
= new ByteArrayInputStream(salt
);
112 binary
= session
.getValueFactory().createBinary(in
);
113 keyring
.setProperty(ARGEO_SALT
, binary
);
115 Integer iterationCount
= username
.length() * iterationCountFactor
;
116 keyring
.setProperty(ARGEO_ITERATION_COUNT
, iterationCount
);
119 // TODO check if algo and key length are available, use DES if not
120 keyring
.setProperty(ARGEO_SECRET_KEY_FACTORY
, secreteKeyFactoryName
);
121 keyring
.setProperty(ARGEO_KEY_LENGTH
, secreteKeyLength
);
122 keyring
.setProperty(ARGEO_SECRET_KEY_ENCRYPTION
,
123 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
= UserJcrUtils
.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
)
159 .getString(), JcrUtils
.getBinaryAsBytes(keyring
160 .getProperty(ARGEO_SALT
)),
161 (int) keyring
.getProperty(ARGEO_ITERATION_COUNT
).getLong(),
162 (int) keyring
.getProperty(ARGEO_KEY_LENGTH
).getLong(),
163 keyring
.getProperty(ARGEO_SECRET_KEY_ENCRYPTION
)
166 if (notYetSavedKeyring
.get() != null)
167 notYetSavedKeyring
.remove();
168 } catch (RepositoryException e
) {
169 throw new ArgeoJcrException("Cannot handle key spec callback", e
);
173 /** The parent node must already exist at this path. */
175 protected synchronized void encrypt(String path
, InputStream unencrypted
) {
176 // should be called first for lazy initialization
177 SecretKey secretKey
= getSecretKey();
179 Binary binary
= null;
180 InputStream in
= null;
182 Cipher cipher
= createCipher();
184 if (!session
.nodeExists(path
)) {
185 String parentPath
= JcrUtils
.parentPath(path
);
186 if (!session
.nodeExists(parentPath
))
187 throw new ArgeoJcrException("No parent node of " + path
);
188 Node parentNode
= session
.getNode(parentPath
);
189 node
= parentNode
.addNode(JcrUtils
.nodeNameFromPath(path
));
191 node
= session
.getNode(path
);
193 node
.addMixin(ArgeoTypes
.ARGEO_ENCRYPTED
);
194 SecureRandom random
= new SecureRandom();
195 byte[] iv
= new byte[16];
196 random
.nextBytes(iv
);
197 cipher
.init(Cipher
.ENCRYPT_MODE
, secretKey
, new IvParameterSpec(iv
));
198 JcrUtils
.setBinaryAsBytes(node
, ARGEO_IV
, iv
);
200 in
= new CipherInputStream(unencrypted
, cipher
);
201 binary
= session
.getValueFactory().createBinary(in
);
202 node
.setProperty(Property
.JCR_DATA
, binary
);
204 } catch (Exception e
) {
205 throw new ArgeoJcrException("Cannot encrypt", e
);
207 IOUtils
.closeQuietly(unencrypted
);
208 IOUtils
.closeQuietly(in
);
209 JcrUtils
.closeQuietly(binary
);
214 protected synchronized InputStream
decrypt(String path
) {
215 Binary binary
= null;
216 InputStream encrypted
= null;
217 Reader reader
= null;
219 if (!session
.nodeExists(path
)) {
220 char[] password
= ask();
221 reader
= new CharArrayReader(password
);
222 return new ByteArrayInputStream(IOUtils
.toByteArray(reader
));
224 // should be called first for lazy initialisation
225 SecretKey secretKey
= getSecretKey();
227 Cipher cipher
= createCipher();
229 Node node
= session
.getNode(path
);
230 if (node
.hasProperty(ARGEO_IV
)) {
231 byte[] iv
= JcrUtils
.getBinaryAsBytes(node
232 .getProperty(ARGEO_IV
));
233 cipher
.init(Cipher
.DECRYPT_MODE
, secretKey
,
234 new IvParameterSpec(iv
));
236 cipher
.init(Cipher
.DECRYPT_MODE
, secretKey
);
239 binary
= node
.getProperty(Property
.JCR_DATA
).getBinary();
240 encrypted
= binary
.getStream();
241 return new CipherInputStream(encrypted
, cipher
);
243 } catch (Exception e
) {
244 throw new ArgeoJcrException("Cannot decrypt", e
);
246 IOUtils
.closeQuietly(encrypted
);
247 IOUtils
.closeQuietly(reader
);
248 JcrUtils
.closeQuietly(binary
);
252 protected Cipher
createCipher() {
254 Node userHome
= UserJcrUtils
.getUserHome(session
);
255 if (!userHome
.hasNode(ARGEO_KEYRING
))
256 throw new ArgeoJcrException("Keyring not setup");
257 Node keyring
= userHome
.getNode(ARGEO_KEYRING
);
258 Cipher cipher
= Cipher
.getInstance(keyring
259 .getProperty(ARGEO_CIPHER
).getString(),
260 getSecurityProvider());
262 } catch (Exception e
) {
263 throw new ArgeoJcrException("Cannot get cipher", e
);
267 public synchronized void changePassword(char[] oldPassword
,
268 char[] newPassword
) {
269 // TODO decrypt with old pw / encrypt with new pw all argeo:encrypted
272 public synchronized void setSession(Session session
) {
273 this.session
= session
;
276 public void setIterationCountFactor(Integer iterationCountFactor
) {
277 this.iterationCountFactor
= iterationCountFactor
;
280 public void setSecreteKeyLength(Long keyLength
) {
281 this.secreteKeyLength
= keyLength
;
284 public void setSecreteKeyFactoryName(String secreteKeyFactoryName
) {
285 this.secreteKeyFactoryName
= secreteKeyFactoryName
;
288 public void setSecreteKeyEncryption(String secreteKeyEncryption
) {
289 this.secreteKeyEncryption
= secreteKeyEncryption
;
292 public void setCipherName(String cipherName
) {
293 this.cipherName
= cipherName
;