一、前言
关于keycloak的keycloak-common源码包org.keycloak.common.util.KeystoreUtil密钥库工具类,获取java.security.KeyStore密钥库、获取java.security.KeyPair密钥对等方法。
二、源码说明
package org.keycloak.common.util;@b@@b@import org.keycloak.common.constants.GenericConstants; @b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.InputStream;@b@import java.security.KeyPair;@b@import java.security.KeyStore;@b@import java.security.PrivateKey;@b@import java.security.PublicKey;@b@ @b@public class KeystoreUtil {@b@ @b@ static{@b@ BouncyIntegration.init();@b@ }@b@@b@ public enum KeystoreFormat {@b@ JKS,@b@ PKCS12@b@ }@b@@b@ public static KeyStore loadKeyStore(String filename, String password) throws Exception {@b@ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());@b@ InputStream trustStream = null;@b@ if (filename.startsWith(GenericConstants.PROTOCOL_CLASSPATH)) {@b@ String resourcePath = filename.replace(GenericConstants.PROTOCOL_CLASSPATH, "");@b@ if (Thread.currentThread().getContextClassLoader() != null) {@b@ trustStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);@b@ }@b@ if (trustStream == null) {@b@ trustStream = KeystoreUtil.class.getResourceAsStream(resourcePath);@b@ }@b@ if (trustStream == null) {@b@ throw new RuntimeException("Unable to find key store in classpath");@b@ }@b@ } else {@b@ trustStream = new FileInputStream(new File(filename));@b@ }@b@ trustStore.load(trustStream, password.toCharArray());@b@ trustStream.close();@b@ return trustStore;@b@ }@b@@b@ public static KeyPair loadKeyPairFromKeystore(String keystoreFile, String storePassword, String keyPassword, String keyAlias, KeystoreFormat format) {@b@ InputStream stream = FindFile.findFile(keystoreFile);@b@@b@ try {@b@ KeyStore keyStore = null;@b@ if (format == KeystoreFormat.JKS) {@b@ keyStore = KeyStore.getInstance(format.toString());@b@ } else {@b@ keyStore = KeyStore.getInstance(format.toString(), "BC");@b@ }@b@@b@ keyStore.load(stream, storePassword.toCharArray());@b@ PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword.toCharArray());@b@ if (privateKey == null) {@b@ throw new RuntimeException("Couldn't load key with alias '" + keyAlias + "' from keystore");@b@ }@b@ PublicKey publicKey = keyStore.getCertificate(keyAlias).getPublicKey();@b@ return new KeyPair(publicKey, privateKey);@b@ } catch (Exception e) {@b@ throw new RuntimeException("Failed to load private key: " + e.getMessage(), e);@b@ }@b@ }@b@}