SpringCloud(15) JWT生成密钥证书jwt.jks
SpringCloud JWTKeytool生成密钥证书jwt.jks&获取jks文件的公钥
·
一、生成密钥证书jwt.jks
tips: 需jdk环境
# Keytool 是一个java提供的证书管理工具
# -alias:密钥的别名
# -keyalg:使用的hash算法
# -keypass:密钥的访问密码
# -keystore:密钥库文件名,jwt.jks -> 生成的证书
# -storepass:密钥库的访问密码
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
# 编辑PATH环境变量,新增
%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 {
// 1、创建秘钥工厂
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
// 秘钥位置
new ClassPathResource("jwt.jks"),
// 秘钥库密码
"123456".toCharArray()
);
// 2、基于工厂拿到私钥
KeyPair keyPair = keyStoreKeyFactory.getKeyPair("small-tools", "123456".toCharArray());
// 转化为rsa私钥
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
// 3、生成jwt
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 {
// 基于公钥去解析jwt
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);
}
}
今日分享语句:
你既然认准一条道路何必去打听要走多久!
更多推荐
已为社区贡献9条内容
所有评论(0)