从JKS导出公钥并从Java读取

时间:2017-08-11 05:07:07

标签: java openssl rsa jks

我已经生成了JKS格式的RSA 256公钥/私钥。

keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 10950

此文件在Keycloak中配置,后者将使用私钥对访问令牌(JWT)进行签名。

从我的基于Java的应用程序,我想用公钥验证访问令牌的签名。可能存在一种更简单的机制,但我在尝试各种方法后感到困惑。

从JKS文件导出公钥证书

keytool -export -alias selfsigned -keystore keystore.jks -rfc -file publickey.cert

从Java app中读取证书文件:

// Use file stream to load from file system or class.getResourceAsStream to load from classpath             
InputStream readStream = this.getClass().getClassLoader().getResourceAsStream("publickey.cert");

CertificateFactory f = CertificateFactory.getInstance("X.509");

//Certificate certificate = f.generateCertificate(readStream);
X509Certificate certificate = (X509Certificate)f.generateCertificate(readStream);

publicKey = certificate.getPublicKey();

readStream.close();

使用公钥和jjwt验证签名

Jwts.parser().setSigningKey(publicKey).parseClaimsJws(accessToken).getBody();

上面的代码抛出了这个异常:

io.jsonwebtoken.SignatureException: Unable to verify RSA signature using configured PublicKey. Signature length not correct: got 256 but was expecting 1369

我做得对吗?

1 个答案:

答案 0 :(得分:0)

它应该可以工作,我尝试生成相同的密钥/证书并验证它(我使用了Bouncy Castle)

{{1}}

打印:RSA