source: trunk/src/org/expeditee/auth/Authenticator.java@ 1201

Last change on this file since 1201 was 1201, checked in by bln4, 6 years ago
File size: 2.3 KB
Line 
1package org.expeditee.auth;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileNotFoundException;
6import java.io.FileOutputStream;
7import java.io.IOException;
8import java.io.InputStream;
9import java.security.KeyStore;
10import java.security.KeyStore.SecretKeyEntry;
11import java.security.KeyStoreException;
12import java.security.NoSuchAlgorithmException;
13import java.security.UnrecoverableEntryException;
14import java.security.cert.CertificateException;
15
16import javax.crypto.SecretKey;
17
18import org.expeditee.gui.FrameIO;
19import org.ngikm.cryptography.CryptographyConstants;
20
21public 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}
Note: See TracBrowser for help on using the repository browser.