From 3377dfe40abe7f614b26f5b235b0a11e991d6630 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 20 Jan 2023 14:59:07 +0300 Subject: KeystoreManager: refactoring --- src/main/java/com/juick/KeystoreManager.java | 34 ++++++++++------------------ 1 file changed, 12 insertions(+), 22 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/juick/KeystoreManager.java b/src/main/java/com/juick/KeystoreManager.java index e00d99e8..d43b9d52 100644 --- a/src/main/java/com/juick/KeystoreManager.java +++ b/src/main/java/com/juick/KeystoreManager.java @@ -33,44 +33,34 @@ import java.security.cert.CertificateException; public class KeystoreManager { private static final Logger logger = LoggerFactory.getLogger("ActivityPub"); - - private final String keystorePassword; - - private KeyStore ks; - + private PrivateKey privateKey; + private PublicKey publicKey; + private String pem; public KeystoreManager(Resource keystore, String keystorePassword) { - this.keystorePassword = keystorePassword; try (InputStream ksIs = keystore.getInputStream()) { - ks = KeyStore.getInstance("PKCS12"); + KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(ksIs, keystorePassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory .getDefaultAlgorithm()); kmf.init(ks, keystorePassword.toCharArray()); + privateKey = (PrivateKey) ks.getKey("1", keystorePassword.toCharArray()); + Certificate certificate = ks.getCertificate("1"); + var keyPair = new KeyPair(certificate.getPublicKey(), privateKey); + publicKey = keyPair.getPublic(); + pem = new String(Keys.of(getPublicKey()).encode(Key.Format.PEM)).replace("\r\n", "\n"); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException e) { logger.error("Keystore error", e); } } - - public KeyPair getKeyPair() { - java.security.Key privateKey; - try { - privateKey = ks.getKey("1", keystorePassword.toCharArray()); - Certificate certificate = ks.getCertificate("1"); - return new KeyPair(certificate.getPublicKey(), (PrivateKey) privateKey); - } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) { - e.printStackTrace(); - } - return null; - } public PrivateKey getPrivateKey() { - return getKeyPair().getPrivate(); + return privateKey; } public PublicKey getPublicKey() { - return getKeyPair().getPublic(); + return publicKey; } public String getPublicKeyPem() { - return new String(Keys.of(getPublicKey()).encode(Key.Format.PEM)).replace("\r\n", "\n"); + return pem; } public static java.security.Key publicKeyOf(Actor person) { -- cgit v1.2.3