]> git.argeo.org Git - lgpl/argeo-commons.git/blob - KeyringLoginModule.java
a53295cb8411c9c01f784d3bacad11bb59aabf40
[lgpl/argeo-commons.git] / KeyringLoginModule.java
1 package org.argeo.util.crypto;
2
3 import java.security.AccessController;
4 import java.util.Map;
5 import java.util.Set;
6
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;
17
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;
23
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());
29 }
30 this.callbackHandler = callbackHandler;
31 }
32
33 public boolean login() throws LoginException {
34 Set<SecretKey> pbes = subject.getPrivateCredentials(SecretKey.class);
35 if (pbes.size() > 0)
36 return true;
37 PasswordCallback pc = new PasswordCallback("Master password", false);
38 PBEKeySpecCallback pbeCb = new PBEKeySpecCallback();
39 Callback[] callbacks = { pc, pbeCb };
40 try {
41 callbackHandler.handle(callbacks);
42 char[] password = pc.getPassword();
43
44 SecretKeyFactory keyFac = SecretKeyFactory.getInstance(pbeCb
45 .getSecretKeyFactory());
46 PBEKeySpec keySpec;
47 if (pbeCb.getKeyLength() != null)
48 keySpec = new PBEKeySpec(password, pbeCb.getSalt(),
49 pbeCb.getIterationCount(), pbeCb.getKeyLength());
50 else
51 keySpec = new PBEKeySpec(password, pbeCb.getSalt(),
52 pbeCb.getIterationCount());
53
54 String secKeyEncryption = pbeCb.getSecretKeyEncryption();
55 if (secKeyEncryption != null) {
56 SecretKey tmp = keyFac.generateSecret(keySpec);
57 secretKey = new SecretKeySpec(tmp.getEncoded(),
58 secKeyEncryption);
59 } else {
60 secretKey = keyFac.generateSecret(keySpec);
61 }
62 } catch (Exception e) {
63 LoginException le = new LoginException("Cannot login keyring");
64 le.initCause(e);
65 throw le;
66 }
67 return true;
68 }
69
70 public boolean commit() throws LoginException {
71 if (secretKey != null)
72 subject.getPrivateCredentials().add(secretKey);
73 return true;
74 }
75
76 public boolean abort() throws LoginException {
77 return true;
78 }
79
80 public boolean logout() throws LoginException {
81 Set<PasswordBasedEncryption> pbes = subject
82 .getPrivateCredentials(PasswordBasedEncryption.class);
83 pbes.clear();
84 return true;
85 }
86
87 }