Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sample.logic;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKey;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.security.KeyStore;
- import java.security.KeyStoreException;
- import java.security.NoSuchAlgorithmException;
- import java.security.UnrecoverableKeyException;
- import java.security.cert.CertificateException;
- class KeyLoader {
- private static final String KEYSTORE_TYPE = "JCEKS";
- private static final String KEYSTORE_NAME = "KeyStore";
- private static final String SECRET_KEY_NAME = "secretKeyAlias";
- private static final String KEYSTORE_PWD = "password";
- static SecretKey getKey(String algorithm) throws SecretKeyException{
- SecretKey key = loadKey();
- if (key == null){
- try {
- key = KeyGenerator.getInstance(algorithm).generateKey();
- } catch (NoSuchAlgorithmException e) {
- throw new SecretKeyException();
- }
- try {
- storeKey(key);
- } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
- throw new SecretKeyException();
- }
- }
- return key;
- }
- private static void storeKey(SecretKey secretKey) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
- KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
- ks.load(null, KEYSTORE_PWD.toCharArray());
- KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray());
- KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(secretKey);
- ks.setEntry(SECRET_KEY_NAME, skEntry, protParam);
- try (FileOutputStream fos = new FileOutputStream(KEYSTORE_NAME)) {
- ks.store(fos, KEYSTORE_PWD.toCharArray());
- } catch (Exception asd) {
- System.out.println(asd.getMessage());
- }
- }
- private static SecretKey loadKey() {
- KeyStore ks = null;
- try {
- ks = KeyStore.getInstance(KEYSTORE_TYPE);
- ks.load(new FileInputStream(KEYSTORE_NAME), KEYSTORE_PWD.toCharArray());
- }
- catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
- System.out.println(e.getMessage());
- return null;
- }
- try {
- return (SecretKey) ks.getKey(SECRET_KEY_NAME, KEYSTORE_PWD.toCharArray());
- } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
- System.out.println(e.getMessage());
- return null;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement