I generated a RSA key using keytool.
keytool -genkeypair -alias myAlias -keyalg RSA -dname ...
creates a jks.
I am using this to sign..
String sig = Jwts.builder().setClaims(claims).setIssuedAt(new
Date(now)).setExpiration(expires.getTime()).signWith(
SignatureAlgorithm.RS256, myKey).compact();
and for verifying..
Certificate cert = keystore.getCertificate(myAlias);
PublicKey publicKey = cert.getPublicKey();
Jwt jwt = Jwts.parser().setSigningKey(publicKey).require("user",
"me").require("iotDevice", "123456789").parse(signature);
verifies fine.
I created a public key for this cert..
keytool -export -alias myAlias -keystore myKeyStore.jks -file myPem.pem
openssl rsa -in myPem.pem -pubout > myApp.pub
I am loading this public key to verify again..
RSAPublicKey getPublicKeyFromString(String key) throws IOException,
GeneralSecurityException {
String publicKey = key;
publicKey = publicKey.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKey = publicKey.replace("-----END PUBLIC KEY-----", "");
publicKey = publicKey.replace("\n", "");
byte[] encoded = Base64.getDecoder().decode(publicKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new
X509EncodedKeySpec(encoded));
return pubKey;
}
PublicKey publicKey2 = getPublicKeyFromString(keyString); // keyString has myApp.pub
Jwt jwt = Jwts.parser().setSigningKey(publicKey2).require("user",
"me").require("iotDevice", "123456789").parse(signature);
// fails with message
JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
Any help is appreciated.
Thanks in advance