1 package org
.argeo
.cms
.auth
;
3 import java
.security
.AccessController
;
7 import javax
.crypto
.SecretKey
;
8 import javax
.crypto
.SecretKeyFactory
;
9 import javax
.crypto
.spec
.PBEKeySpec
;
10 import javax
.crypto
.spec
.SecretKeySpec
;
11 import javax
.security
.auth
.Subject
;
12 import javax
.security
.auth
.callback
.Callback
;
13 import javax
.security
.auth
.callback
.CallbackHandler
;
14 import javax
.security
.auth
.callback
.PasswordCallback
;
15 import javax
.security
.auth
.login
.LoginException
;
16 import javax
.security
.auth
.spi
.LoginModule
;
18 import org
.argeo
.api
.security
.PBEKeySpecCallback
;
19 import org
.argeo
.util
.PasswordEncryption
;
21 /** Adds a secret key to the private credentials */
22 public class KeyringLoginModule
implements LoginModule
{
23 private Subject subject
;
24 private CallbackHandler callbackHandler
;
25 private SecretKey secretKey
;
27 public void initialize(Subject subject
, CallbackHandler callbackHandler
, Map
<String
, ?
> sharedState
,
28 Map
<String
, ?
> options
) {
29 this.subject
= subject
;
30 if (subject
== null) {
31 subject
= Subject
.getSubject(AccessController
.getContext());
33 this.callbackHandler
= callbackHandler
;
36 public boolean login() throws LoginException
{
37 // Set<SecretKey> pbes = subject.getPrivateCredentials(SecretKey.class);
38 // if (pbes.size() > 0)
40 PasswordCallback pc
= new PasswordCallback("Master password", false);
41 PBEKeySpecCallback pbeCb
= new PBEKeySpecCallback();
42 Callback
[] callbacks
= { pc
, pbeCb
};
44 callbackHandler
.handle(callbacks
);
45 char[] password
= pc
.getPassword();
47 SecretKeyFactory keyFac
= SecretKeyFactory
.getInstance(pbeCb
.getSecretKeyFactory());
49 if (pbeCb
.getKeyLength() != null)
50 keySpec
= new PBEKeySpec(password
, pbeCb
.getSalt(), pbeCb
.getIterationCount(), pbeCb
.getKeyLength());
52 keySpec
= new PBEKeySpec(password
, pbeCb
.getSalt(), pbeCb
.getIterationCount());
54 String secKeyEncryption
= pbeCb
.getSecretKeyEncryption();
55 if (secKeyEncryption
!= null) {
56 SecretKey tmp
= keyFac
.generateSecret(keySpec
);
57 secretKey
= new SecretKeySpec(tmp
.getEncoded(), secKeyEncryption
);
59 secretKey
= keyFac
.generateSecret(keySpec
);
61 } catch (Exception e
) {
62 LoginException le
= new LoginException("Cannot login keyring");
69 public boolean commit() throws LoginException
{
70 if (secretKey
!= null) {
71 subject
.getPrivateCredentials().removeAll(subject
.getPrivateCredentials(SecretKey
.class));
72 subject
.getPrivateCredentials().add(secretKey
);
77 public boolean abort() throws LoginException
{
81 public boolean logout() throws LoginException
{
82 Set
<PasswordEncryption
> pbes
= subject
.getPrivateCredentials(PasswordEncryption
.class);