一、前言
关于keycloak的keycloak-common源码包org.keycloak.common.util.KeyUtils密钥工具类, 获取javax.crypto.SecretKey密钥、生成java.security.KeyPair密钥对、根据私钥java.security.PrivateKey获取extractPublicKey公钥java.security.PublicKey等。
二、源码说明
package org.keycloak.common.util;@b@@b@import javax.crypto.SecretKey;@b@import javax.crypto.spec.SecretKeySpec;@b@import java.security.Key;@b@import java.security.KeyFactory;@b@import java.security.KeyPair;@b@import java.security.KeyPairGenerator;@b@import java.security.MessageDigest;@b@import java.security.NoSuchAlgorithmException;@b@import java.security.PrivateKey;@b@import java.security.PublicKey;@b@import java.security.interfaces.RSAPrivateCrtKey;@b@import java.security.spec.RSAPublicKeySpec;@b@@b@ @b@public class KeyUtils {@b@@b@ private static final String DEFAULT_MESSAGE_DIGEST = "SHA-256";@b@@b@ private KeyUtils() {@b@ }@b@@b@ public static SecretKey loadSecretKey(byte[] secret, String javaAlgorithmName) {@b@ return new SecretKeySpec(secret, javaAlgorithmName);@b@ }@b@@b@ public static KeyPair generateRsaKeyPair(int keysize) {@b@ try {@b@ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");@b@ generator.initialize(keysize);@b@ KeyPair keyPair = generator.generateKeyPair();@b@ return keyPair;@b@ } catch (Exception e) {@b@ throw new RuntimeException(e);@b@ }@b@ }@b@@b@ public static PublicKey extractPublicKey(PrivateKey key) {@b@ if (key == null) {@b@ return null;@b@ }@b@@b@ try {@b@ RSAPrivateCrtKey rsaPrivateCrtKey = (RSAPrivateCrtKey) key;@b@ RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateCrtKey.getModulus(), rsaPrivateCrtKey.getPublicExponent());@b@ KeyFactory keyFactory = KeyFactory.getInstance("RSA");@b@ return keyFactory.generatePublic(publicKeySpec);@b@ } catch (Exception e) {@b@ throw new RuntimeException(e);@b@ }@b@ }@b@@b@ public static String createKeyId(Key key) {@b@ try {@b@ return Base64Url.encode(MessageDigest.getInstance(DEFAULT_MESSAGE_DIGEST).digest(key.getEncoded()));@b@ } catch (NoSuchAlgorithmException e) {@b@ throw new RuntimeException(e);@b@ }@b@ }@b@@b@@b@}