【发布时间】:2015-05-06 21:39:18
【问题描述】:
我有 RSA 密钥格式
<RSAKeyValue>
<Modulus> ..</Modulus>
<Exponent>..</Exponent>
...
</RSAKeyValue>
我需要使用 java 连接到 REST API。 我应该使用带有模式“TokenIssuer”的 JWT 安全令牌。 Nimbus 库提供了以下示例。它会帮助我还是我需要别的东西?如果是,我应该在哪里写 RSA 密钥?
// RSA signatures require a public and private RSA key pair,
// the public key must be made known to the JWS recipient in
// order to verify the signatures
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
keyGenerator.initialize(1024);
KeyPair kp = keyGenerator.genKeyPair();
RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey)kp.getPrivate();
// Create RSA-signer with the private key
JWSSigner signer = new RSASSASigner(privateKey);
// Prepare JWT with claims set
JWTClaimsSet claimsSet = new JWTClaimsSet();
claimsSet.setSubject("alice");
claimsSet.setIssueTime(new Date());
claimsSet.setIssuer("https://c2id.com");
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
// Compute the RSA signature
signedJWT.sign(signer);
// To serialize to compact form, produces something like
// eyJhbGciOiJSUzI1NiJ9.SW4gUlNBIHdlIHRydXN0IQ.IRMQENi4nJyp4er2L
// mZq3ivwoAjqa1uUkSBKFIX7ATndFF5ivnt-m8uApHO4kfIFOrW7w2Ezmlg3Qd
// maXlS9DhN0nUk_hGI3amEjkKd0BWYCB8vfUbUv0XGjQip78AI4z1PrFRNidm7
// -jPDm5Iq0SZnjKjCNS5Q15fokXZc8u0A
String s = signedJWT.serialize();
// To parse the JWS and verify it, e.g. on client-side
signedJWT = SignedJWT.parse(s);
JWSVerifier verifier = new RSASSAVerifier(publicKey);
assertTrue(signedJWT.verify(verifier));
// Retrieve the JWT claims
assertEquals("alice", signedJWT.getJWTClaimsSet().getSubject());
【问题讨论】: