赞
踩
RSA算法是一种非对称加密算法,其安全性基于大整数分解的困难性。在RSA算法中,有以下几个关键参数:
总结来说,RSA算法通过公钥加密、私钥解密的方式实现信息的安全传输,公钥用于加密数据,私钥用于解密数据;反过来,私钥可以用来生成签名,而公钥可以用来验证签名的有效性。
因此,可以说RS256是RSA算法的一种特定应用,用于数字签名,并且结合了SHA-256哈希算法。RSA算法还可以用于加密数据等其他用途,而RS256主要用于数字签名。
// RSA公钥的模数
String modulus = "yOCNCy8x280...";
// RSA公钥的指数
String exponent = "AQAB";
// keycloak拿到的公钥
String publicKeyString = "MIIBIjANBg...B";
String KcJwtToken = "eyJh...";
@Test public void verifySign() throws Exception { String[] jwtParts = KcJwtToken.split("\\."); String header = jwtParts[0]; String payload = jwtParts[1]; // 解码Base64格式的模数和指数 byte[] decodedModulus = Base64.getUrlDecoder().decode(modulus);// getMimeDecoder()会忽略非Base64字符(如换行符、空格等) byte[] decodedExponent = Base64.getUrlDecoder().decode(exponent); // 构建RSA公钥对象 RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(new BigInteger(1, decodedModulus), new BigInteger(1, decodedExponent)); // 验征RSA签名 PublicKey publicKey = KeyFactory.getInstance("rsa").generatePublic(publicSpec); boolean result = RSAUtils.verify(header + "." + payload, publicKey, jwtParts[2]); System.out.print("验签结果:" + result); }
// 根据认证平台颁发的公钥字符串来验证签名
@Test
public void verifyJwtToken() throws Exception {
String[] jwtParts = KcJwtToken.split("\\.");
String header = jwtParts[0];
String payload = jwtParts[1];
String sign = jwtParts[2];
PublicKey publicKey = RSAUtils.getPublicKey(publicKeyString);
boolean result = RSAUtils.verify(header + "." + payload, publicKey, sign);
System.out.print("验签结果:" + result);
}
需要注意的是,以上jwt的token签名使用rs256(SHA256withRSA)算法生成的签名,所以本例子都是采用这种签名算法实现的,例外,也有h256,h512等哈希算法。
public static final String RS256 = "SHA256withRSA"; public static final String RS384 = "SHA384withRSA"; public static final String RS512 = "SHA512withRSA"; public static final String HS256 = "HMACSHA256"; public static final String HS384 = "HMACSHA384"; public static final String HS512 = "HMACSHA512"; public static final String ES256 = "SHA256withECDSA"; public static final String ES384 = "SHA384withECDSA"; public static final String ES512 = "SHA512withECDSA"; public static final String PS256 = "SHA256withRSAandMGF1"; public static final String PS384 = "SHA384withRSAandMGF1"; public static final String PS512 = "SHA512withRSAandMGF1"; public static final String AES = "AES"; public static final String SHA256 = "SHA-256"; public static final String SHA384 = "SHA-384"; public static final String SHA512 = "SHA-512";
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。