我想做一个使用JSON Web Signature (JWS)的项目,我想发送用于签名的证书的公钥,这样一旦使用此公钥接收到消息,就可以验证消息。我使用的是Ninbus JOS JWT库。我可以对JSON对象进行签名,并且可以看到公钥,但是我无法正确地验证它。代码如下:
// Create RSA-signer with the private key
JWSSigner signer = new RSASSASigner(_signatureKey_); // PrivateKey
com.nimbusds.jose.util.Base64 b64 = new com.nimbusds.jose.util.Base64(_x509certificate.toString()); // X509Certificate
ArrayList<com.nimbusds.jose.util.Base64> certificados = new ArrayList<com.nimbusds.jose.util.Base64>();
certificados.add(b64);
RSAPublicKey _rsaPublicKey = (RSAPublicKey)_x509certificate.getPublicKey(); // Get the public key of the X509Certificate
RSAKey jwk = new com.nimbusds.jose.jwk.RSAKey.Builder( new Base64URL( _rsaPublicKey.getModulus().toString()), new Base64URL( _rsaPublicKey.getPublicExponent().toString()))
.x509CertChain(certificados)
.build();
JWSHeader _jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).
x509CertChain(certificados).
jwk(jwk).
build();
// Prepare JWS object with simple string as payload
JWSObject jwsObject = new JWSObject(_jwsHeader, new Payload(_jsonObject));
// Compute the RSA signature
jwsObject.sign(signer);
// Validation OK : This validation works
JWSVerifier verifier = new RSASSAVerifier(_rsaPublicKey);
boolean signatureValid = jwsObject.verify(verifier); // ---> True, OK
// Now I want to validate the JWSObject getting the public key from the same JWSObject. This validation Fails
JWK _jwk = jwsObject.getHeader().getJWK();
RSAKey _rsakey = (RSAKey)_jwk;
RSAPublicKey _rsaPublicKey2 = _rsakey.toRSAPublicKey();
JWSVerifier verifier2 = new RSASSAVerifier(_rsakey.toRSAPublicKey());
boolean verificado2 = jwsObject.verify(verifier2); // False!
// Another option, this fails too
RSAKey __rsaKey2 = new com.nimbusds.jose.jwk.RSAKey.Builder( _rsakey.toRSAPublicKey() ).x509CertChain(_jwk.getX509CertChain()).build();
JWSVerifier verifier3 = new RSASSAVerifier(__rsaKey2);
boolean verificado3 = jwsObject.verify(verifier3); // False!_rsaPublicKey是:"Sun RSA public key,2048bits“,但是当我从JWK (_rsaPublicKey2)得到它时,我得到了"Sun RSA public key,3696bits”,我不知道为什么。
谢谢!
发布于 2017-08-24 16:15:19
在接收方,您是否在信任密钥之前验证X.509证书颁发者、主题和链?在接收方确定它可以信任JWS中包含的证书之前,不能尝试签名验证。
另一个注意事项:不要在JWS标头中包含公共JWK。这应该仅用于ECDH中的临时公钥(用于JWE的不同alg )。在JWS头中传递证书链就足够了,但是在使用证书的公钥之前,您必须验证它/查明证书是否可信。
库不会验证/找出证书是否可以信任!
如果第二次签名验证失败,那么用于签署JWS的密钥可能与X.509证书附带的密钥不同(根据不同的报告长度- 2048位与3696位)。
https://stackoverflow.com/questions/45855053
复制相似问题