带有密钥的{JWT for Android

时间:2016-06-27 23:49:07

标签: android jwt

我必须使用SHA-256算法和密钥(例如“blablablamysecretkey”)获得JWT。

尽管检查了SO,但是我还不知道如何执行此操作。

如果我使用这个库https://github.com/jwtk/jjwt(最常用的一个),这就是代码示例:

Key key = MacProvider.generateKey();
String s = Jwts.builder().setSubject("stringtoencode").signWith(SignatureAlgorithm.HS512, key).compact();

由于我必须使用SHA-256算法,我想我应该使用:

Key key = MacProvider.generateKey();
String s = Jwts.builder().setSubject("stringtoencode").signWith(SignatureAlgorithm.HS256, key).compact();

我的问题是这个样本(以及我顺便看到的所有样本)都使用Key key = MacProvider.generateKey();,如果我没有错,这会产生一个通用密钥。事实上,这就是文档所说的:

// We need a signing key, so we'll create one just for this example. Usually
// the key would be read from your application configuration instead.

所以我的问题是如何将我的密钥(字符串)转换为Key类?

1 个答案:

答案 0 :(得分:1)

MacProvider.generateKey()生成一个随机密钥,比使用密码更安全。密钥需要随机选择。如果您想知道如何生成hmac密钥,请阅读此帖子https://security.stackexchange.com/questions/95972/what-are-requirements-for-hmac-secret-key

  

//我们需要一个签名密钥,因此我们只为此示例创建一个。平时   //将从您的应用程序配置中读取密钥。

您突出显示的文本意味着您必须在服务器中保留密钥,以便在客户端发送令牌时验证JWT签名。 HMAC密钥是对称的,密钥用于签名和验证

如果您想使用密码Key使用

生成String
byte hmacKey[] = passphrase.getBytes(StandardCharsets.UTF8);
Key key = new SecretKeySpec(hmacKey,signatureAlgorithm.getJcaName());