首页

关于keycloak源码包中KeyUtils密钥工具类获取常用javax.crypto.SecretKey、java.security.PublicKey、java.security.KeyPair密钥

标签:keycloak,KeyUtils,密钥工具类,SecretKey,PublicKey,KeyPair     发布时间:2018-05-13   

一、前言

关于keycloakkeycloak-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@}
<<热门下载>>