1 package org
.argeo
.util
.crypto
;
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 /** Adds a secret key to the private credentials */
19 public class KeyringLoginModule
implements LoginModule
{
20 private Subject subject
;
21 private CallbackHandler callbackHandler
;
22 private SecretKey secretKey
;
24 public void initialize(Subject subject
, CallbackHandler callbackHandler
,
25 Map
<String
, ?
> sharedState
, Map
<String
, ?
> options
) {
26 this.subject
= subject
;
27 if (subject
== null) {
28 subject
= Subject
.getSubject(AccessController
.getContext());
30 this.callbackHandler
= callbackHandler
;
33 public boolean login() throws LoginException
{
34 Set
<SecretKey
> pbes
= subject
.getPrivateCredentials(SecretKey
.class);
37 PasswordCallback pc
= new PasswordCallback("Master password", false);
38 PBEKeySpecCallback pbeCb
= new PBEKeySpecCallback();
39 Callback
[] callbacks
= { pc
, pbeCb
};
41 callbackHandler
.handle(callbacks
);
42 char[] password
= pc
.getPassword();
44 SecretKeyFactory keyFac
= SecretKeyFactory
.getInstance(pbeCb
45 .getSecretKeyFactory());
47 if (pbeCb
.getKeyLength() != null)
48 keySpec
= new PBEKeySpec(password
, pbeCb
.getSalt(),
49 pbeCb
.getIterationCount(), pbeCb
.getKeyLength());
51 keySpec
= new PBEKeySpec(password
, pbeCb
.getSalt(),
52 pbeCb
.getIterationCount());
54 String secKeyEncryption
= pbeCb
.getSecretKeyEncryption();
55 if (secKeyEncryption
!= null) {
56 SecretKey tmp
= keyFac
.generateSecret(keySpec
);
57 secretKey
= new SecretKeySpec(tmp
.getEncoded(),
60 secretKey
= keyFac
.generateSecret(keySpec
);
62 } catch (Exception e
) {
63 LoginException le
= new LoginException("Cannot login keyring");
70 public boolean commit() throws LoginException
{
71 if (secretKey
!= null)
72 subject
.getPrivateCredentials().add(secretKey
);
76 public boolean abort() throws LoginException
{
80 public boolean logout() throws LoginException
{
81 Set
<PasswordBasedEncryption
> pbes
= subject
82 .getPrivateCredentials(PasswordBasedEncryption
.class);