packagemyoidc.server.infrastructure;importcom.google.common.base.Charsets;importcom.google.common.io.CharStreams;import com.nimbusds.jose.*;import com.nimbusds.jose.crypto.*;importcom.nimbusds.jose.jwk.Curve;importcom.nimbusds.jose.jwk.JWK;importcom.nimbusds.jose.jwk.JWKSet;importcom.nimbusds.jwt.EncryptedJWT;importcom.nimbusds.jwt.JWTClaimsSet;importcom.nimbusds.jwt.SignedJWT;importnet.minidev.json.JSONObject;importorg.apache.commons.lang3.RandomStringUtils;importorg.junit.Ignore;importorg.junit.Test;importorg.springframework.core.io.ClassPathResource;importorg.springframework.core.io.Resource;importjavax.crypto.KeyGenerator;importjavax.crypto.SecretKey;importjava.io.InputStreamReader;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.PrivateKey;importjava.security.interfaces.ECPrivateKey;importjava.security.interfaces.ECPublicKey;importjava.security.interfaces.RSAPublicKey;importjava.util.Date;importjava.util.List;import static org.junit.Assert.*;/*** 2016/12/25
*
* Testing
*http://connect2id.com/products/nimbus-jose-jwt*
*@authorShengzhao Li*/
public classNimbusJoseJwtTest {/***@throwsException e
*@since1.1.0*/@Test
@Ignorepublic void testJWKSet() throwsException {
Resource resource= new ClassPathResource("classpath*:keystore.jwks");//read in the file
String s = CharStreams.toString(newInputStreamReader(resource.getInputStream(), Charsets.UTF_8));
JWKSet jwkSet=JWKSet.parse(s);
assertNotNull(jwkSet);//System.out.println(jwkSet);
List keys =jwkSet.getKeys();for(JWK key : keys) {//System.out.println(key);//System.out.println(key.getAlgorithm());//System.out.println(key.getKeyStore());//System.out.println(key.getKeyUse());//System.out.println(key.getKeyType());//System.out.println(key.getParsedX509CertChain());
System.out.println(key.getKeyID());
System.out.println(key.isPrivate());//JWK jwk = key.toPublicJWK();//System.out.println(jwk);//JSONObject jsonObject = key.toJSONObject();//System.out.println(jsonObject);//PublicJsonWebKey rsk = RsaJsonWebKey.Factory.newPublicJwk(key.toString());//PrivateKey privateKey = rsk.getPrivateKey();//PublicKey publicKey = rsk.getPublicKey();//System.out.println(publicKey + "\n" + privateKey);//RSAKey rsaKey= new RSAKey();//rsaKey.
}
}/*** JWS
* 使用HMAC SHA-256 进行加密 与 解密
* 基于相同的 secret (对称算法)
*
* 算法 Secret长度
* HS256 32
* HS384 64
* HS512 64
*
*@throwsException*/@Testpublic void jwsMAC() throwsException {
String sharedSecret= RandomStringUtils.random(64, true, true);
JWSSigner jwsSigner= newMACSigner(sharedSecret);//加密//JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);//JWSHeader header = new JWSHeader(JWSAlgorithm.HS384);
JWSHeader header = newJWSHeader(JWSAlgorithm.HS512);final String payloadText = "I am MyOIDC";
Payload payload= newPayload(payloadText);
JWSObject jwsObject= newJWSObject(header, payload);
jwsObject.sign(jwsSigner);//获取 idToken
<