2017-08-24 68 views
0

我想用JSON Web签名(JWS)做一个项目,并且我想发送用于签名的证书的公钥,以便一旦收到消息就可以验证消息用这个公钥。我正在使用Ninbus JOS JWT库。我可以签署JSON对象,我可以看到公钥,但我无法正确验证它。 这是代码:JSON Web签名(Ninbus-JOSE-JWT)

// 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是:“孙RSA公共密钥,2048位”,但是当我从JWK(_rsaPublicKey2)得到它,我得到“孙RSA公共密钥,3696位”我不知道为什么。

谢谢!

回答

1

在接受方,您是否在信任密钥之前验证X.509证书颁发者,主体和链?在收件人确信它可以信任JWS中包含的证书之前,不得尝试签名验证。

另一个注意事项:请勿在JWS标头中包含公共JWK。这应该只用于ECDH中的短暂公钥(用于JWE的另一个alg)。在JWS头中传递证书链就足够了,但是在使用公钥之前,您必须验证它/找出证书是否可信。

图书馆不会验证/发现证书是否可以为您信任!

如果第二次签名验证失败,那么用于签名JWS的密钥和X.509证书附带的密钥可能不一样(正如不同的报告长度所暗示的那样 - 2048位与3696位)。

+0

谢谢,我认为问题在于从RSAKey到RSAPublicKey的转换。从RSAKey到RSAPublicKey(带有_rsakey.toRSAPublicKey()),我得到了不同的模数和指数。 – jandres

+0

JWK _jwk = jwsObject.getHeader()。getJWK(); 'RSAKey _rsakey =(RSAKey)_jwk;' //// - >模数和指数ok 'RSAPublicKey _rsaPublicKey2 = _rsakey.toRSAPublicKey();' /// - > – jandres

+0

我认为我的问题可以概括:一旦我有了JWSObject对象,并且我可以访问它的头文件和x509CertChain(它是一个com.nimbusds.jose.util.Base64对象列表),那么怎么能我得到了X509CertChain的公钥?我可以看到它的调试,但我无法正确验证签名。 – jandres