Elixir中的JWS令牌生成

时间:2019-03-15 14:34:54

标签: encryption jwt elixir

我正在尝试使用Elixir创建JWS令牌。 我所拥有的:

  • RSA私钥
  • Base 64编码的sha256证书指纹
  • 令牌头
  • 令牌主体

我需要什么:

  • 令牌签名

JWS标头看起来像这样

{ 
  "x5t#S256": {{ cert thumbprint }},
  "alg":"RS256"
}

要获取标头令牌,只需将其转换为base64即可。与令牌主体相同,我只是将有效负载转换为base64。

问题在于获取令牌签名。据我了解,应该这样做:

token signature = base64(rsa-sha256(token header + "." + token body))

Q1:我的逻辑在这里正确吗?

Q2:如何在Elixir上进行rsa-sha256加密?还是和:crypto.hash(sha256, ...)一样?

2 个答案:

答案 0 :(得分:1)

我没有在Elixir中使用JWS,但是我决定尝试一下作为练习。您可以使用RSA这样生成JWS签名:

rsa_private_key = JOSE.JWK.from_pem_file("rsa-2048.pem")
header = %{"alg" => "RS256"}
payload = %{"example" => "foo"}

JOSE.JWT.sign(rsa_private_key, header, payload)

输出:

{%{alg: :jose_jws_alg_rsa_pkcs1_v1_5},
 %{
   "payload" => "eyJleGFtcGxlIjoiZm9vIn0",
   "protected" => "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9",
   "signature" => "T2llXS2pGN-jev10Xd5EZQmaEih_dn9DIn5FJJg8ocEwIpNLupEWiNLz-5mP21z9JGpyYPFaRuq77AtKL67nP7KMDTpKKYJonOxQdL31sHU4vTKBRf-2XcVbDLGkST5dUMUWHOS106Sw_0x7DSiuFBUzkkYQ_lZKES8idVUp88Kx4uWU65Yoti0_Pu7aVLRGWDu0EiMjzuTPTBkMoib21VEVBqrJ4jiKXFudEFiNNSaV_GOH9yNZqyxwl4RhCYYT9U-Mda8Dc7xPjQk0LaJhwlaV91OhxJQHP2fGR8XkznHFlRRHTEsesYgl9OKZuSzVXoffydLc1VotphKUnG1WZQ"
 }}

如果您希望使用简写形式:

JOSE.JWT.sign(rsa_private_key, header, payload) |> JOSE.JWS.compact

产生:

{%{alg: :jose_jws_alg_rsa_pkcs1_v1_5},
"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleGFtcGxlIjoiZm9vIn0.T2llXS2pGN-jev10Xd5EZQmaEih_dn9DIn5FJJg8ocEwIpNLupEWiNLz-5mP21z9JGpyYPFaRuq77AtKL67nP7KMDTpKKYJonOxQdL31sHU4vTKBRf-2XcVbDLGkST5dUMUWHOS106Sw_0x7DSiuFBUzkkYQ_lZKES8idVUp88Kx4uWU65Yoti0_Pu7aVLRGWDu0EiMjzuTPTBkMoib21VEVBqrJ4jiKXFudEFiNNSaV_GOH9yNZqyxwl4RhCYYT9U-Mda8Dc7xPjQk0LaJhwlaV91OhxJQHP2fGR8XkznHFlRRHTEsesYgl9OKZuSzVXoffydLc1VotphKUnG1WZQ"}

如果要验证,则为公用密钥:

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAtRPXSP1W+5sgVLeRFYrrF6L7+gaEkPOWV2FDtPL/vRQH77bicJYb
oVytE/8JyHj8kH24hxwCy2LFl5fZLaIrqYBy1B1t8LtxTRVhi3JIc76IGZ3dfxrz
Dnv94Vu9BRxE7y37f7w8ulDVlGpmJhfCIMj8SYJrFWgHlQB2u7c/B43RE6uphRfD
nr4FkJ3ChUFKhuVZHm27r5/CllHNhMejA/WawtlWKdU33In1Xp2O+GxjLKoYuGGQ
U9MdrismDtn6bVcq5K97bByxelJel2rUG4sbtQk01gVtfun63rSzOP9EkNJOoRll
YDm3HQlDUY7+D9AMG3XlQuR7tlDXQtGIJQIDAQAB
-----END RSA PUBLIC KEY-----

答案 1 :(得分:0)

JWT Auth with an Elixir on Phoenix上查看此示例

使用:bcrypt_elixir:guardian