1 | package org.expeditee.auth;
|
---|
2 |
|
---|
3 | import java.io.File;
|
---|
4 | import java.io.FileInputStream;
|
---|
5 | import java.io.FileNotFoundException;
|
---|
6 | import java.io.FileOutputStream;
|
---|
7 | import java.io.IOException;
|
---|
8 | import java.io.InputStream;
|
---|
9 | import java.security.KeyStore;
|
---|
10 | import java.security.KeyStore.SecretKeyEntry;
|
---|
11 | import java.security.KeyStoreException;
|
---|
12 | import java.security.NoSuchAlgorithmException;
|
---|
13 | import java.security.UnrecoverableEntryException;
|
---|
14 | import java.security.cert.CertificateException;
|
---|
15 |
|
---|
16 | import javax.crypto.SecretKey;
|
---|
17 |
|
---|
18 | import org.expeditee.gui.FrameIO;
|
---|
19 | import org.ngikm.cryptography.CryptographyConstants;
|
---|
20 |
|
---|
21 | public final class Authenticator implements CryptographyConstants {
|
---|
22 | final KeyStore keyStore = KeyStore.getInstance(KeystoreType);
|
---|
23 | private static final String keystoreFileName = FrameIO.PARENT_FOLDER + "keystore.ks" + File.separator;
|
---|
24 |
|
---|
25 | public Authenticator() throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException {
|
---|
26 | final File keyStoreFile = new File(keystoreFileName);
|
---|
27 | if (!keyStoreFile.exists()) {
|
---|
28 | keyStore.load(null, "ExpediteeAuthPassword".toCharArray());
|
---|
29 | } else {
|
---|
30 | try (final InputStream in = new FileInputStream(keystoreFileName)) {
|
---|
31 | keyStore.load(in, "ExpediteeAuthPassword".toCharArray());
|
---|
32 | }
|
---|
33 | }
|
---|
34 | }
|
---|
35 |
|
---|
36 | public final SecretKey getSecretKey(final String label, final String password) throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException {
|
---|
37 | final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(password.toCharArray());
|
---|
38 | final KeyStore.SecretKeyEntry entry = (SecretKeyEntry) keyStore.getEntry(label, entryPassword);
|
---|
39 | if (entry == null) { return null; }
|
---|
40 | else { return entry.getSecretKey(); }
|
---|
41 | }
|
---|
42 |
|
---|
43 | public final void putKey(final String label, final String password, final SecretKey key) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
|
---|
44 | final KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(key);
|
---|
45 | final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(password.toCharArray());
|
---|
46 | keyStore.setEntry(label, entry, entryPassword);
|
---|
47 | keyStore.store(new FileOutputStream(keystoreFileName), "ExpediteeAuthPassword".toCharArray());
|
---|
48 | }
|
---|
49 | }
|
---|