一、生成密钥证书jwt.jks
tips: 需jdk环境
keytool -genkeypair -alias small-tools -keyalg RSA -keypass 123456 -keystore jwt.jks -storepass 123456
keytool -list -keystore jwt.jks
二、获取jks文件的公钥
1、下载安装OpenSSL
http://slproweb.com/products/Win32OpenSSL.html
2、配置环境变量
此电脑 -> 属性 -> 高级系统设置 -> 环境变量
OPENSSL_HOME -> D:\zhengqingya\soft\soft-dev\OpenSSL-Win64\bin
%OPENSSL_HOME%
openssl version
3、获取jks文件的公钥
进入jwt.jks所在目录执行
keytool -list -rfc --keystore jwt.jks | openssl x509 -inform pem -pubkey
三、测试
public class JwtTest {
@Test
public void testCreateJwt() throws Exception {
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
new ClassPathResource("jwt.jks"),
"123456".toCharArray()
);
KeyPair keyPair = keyStoreKeyFactory.getKeyPair("small-tools", "123456".toCharArray());
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, String> map = Maps.newHashMap();
map.put("username", "zq");
map.put("password", "123456");
Jwt jwt = JwtHelper.encode(JSON.toJSONString(map), new RsaSigner(rsaPrivateKey));
String jwtEncoded = jwt.getEncoded();
System.out.println("jwtEncoded:" + jwtEncoded);
String claims = jwt.getClaims();
System.out.println("claims:" + claims);
}
@Test
public void testParseJwt() throws Exception {
String jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsInVzZXJuYW1lIjoienEifQ.KoD8HDRiaKzGQwC493tTrIO2YbCNdkMR-ENPHab31mhFYE1K2IR3knxQ-yaVEg1-lJPbVSmZV4mrsQGKq17VetZhl9onvKAIsupwbi0CI0riPknQsTf6UEMLwgTY7cLbf6cLUa5XaoqiH0wVTM-xCLnBVIXEpjM8jMZQ_5V47TGsa5rAIYePK_FUpxhhuVKcbIed-DvkGBvNwOuD7iVh__2iLSSGh2V-4LkJeJXDGloReb4srS1sdbDK2gdmUD3VljXURU2HAIG0QvZA7PCe1BWgAWBlFaa2VO1NxysWY5SvMgR7vVjgnwH6-iBkbpzwmZMdXU_Vc-mDZaxvv575YQ";
String publicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoDx/QIbsN80KBXZ+yxT+\n" +
"UcwTvqF1T92w9ZkwDdzNLQLX0XV7Th5sFRAWRgR2cCBPas7V3ZWFNvAWiUUjTrYK\n" +
"mY7wUzTHyYR9nekoaw6VceNvw109ycNjZhJGLoYkz/MMSvBfZsdtxjeWZ2xhuGw1\n" +
"Ufhz8HbQFU0UQO8Zb+OdRq36FzN5+MHX/rgMyZSBrEf2cJnoeVv0Jb4RQMtpOs4T\n" +
"g18/i5iNJICecrmWiady6pUTgidXqHHCLL76GIPPSmWir84AR0PlZqSRPj51DXnI\n" +
"zOXkbptxqhBmsIquP/FGTQemnySKxHBe9q36gcfCdPHQqX64k2D15i0HVlYyznOA\n" +
"0QIDAQAB\n" +
"-----END PUBLIC KEY-----";
Jwt token = JwtHelper.decodeAndVerify(jwt, new RsaVerifier(publicKey));
String claims = token.getClaims();
System.out.println(claims);
}
}
今日分享语句: 你既然认准一条道路何必去打听要走多久!
|