登录
首页 >  Golang >  Go问答

将 JSON 公钥/私钥对转换为 rsa.PrivateKey 和 rsa.PublicKey

来源:Golang技术栈

时间:2023-04-19 15:12:51 409浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《将 JSON 公钥/私钥对转换为 rsa.PrivateKey 和 rsa.PublicKey》,聊聊golang,我们一起来看看吧!

问题内容

正如标题所说,我有一个基于https://mkjwk.org/生成的 JSON 文件,现在我想使用生成的值来签署 JWT。我将为多个“客户”执行此操作,每个“客户”都有自己的签名。然后将根据一组包含不同“客户端”的公钥的 JWKS 来验证这些。

但是,我很难理解如何使用生成的 JSON 值。

我知道我可以直接使用crypto/rsa模块生成一个 priv/pub 密钥。我还看到了将 ppk 作为 X509 格式的输入给出的示例,尽管我尽量避免它(我想我只是很挑剔,因为我更喜欢能够读取文件的内容而不是看到随机字符..)

从我所做的多个示例和大量搜索中,我还没有看到执行获取 json 文件和生成 rsa.privateKey 的过程。我也在使用jwt- goandjwx模块来处理其余的用例,但是这个正在逃避我..

那么,我错过了什么?我怎样才能从像下面这样的 JSON 转到一个rsa.PrivateKey

{
    "p": "vQXloZI9y5..._PPE6m05J-VqhIF6-FQjvwc",
    "kty": "RSA",
    "q": "u1OqnCCLyEZDMoSfK...SfcIGNSd90PEcPs",
    "d": "eoAj0Z0PkK3A0pc5t...9Q8iqGntoxMVARBtQ",
    "e": "AQAB",
    "use": "sig",
    "kid": "r9cuFC3...HiAc7VhSME",
    "qi": "upOjfCF_na...H4a7Bs2pWGoS6w5mcqXU",
    "dp": "HKGzCclEEP...GdofDVR5Yas",
    "alg": "RS256",
    "dq": "PDyRNhc5G7OMVChVTm61kn2ShRFTe...BLytOxGBm5ntJv4V0HRBU",
    "n": "ilEVn6tSuh7-tZBV8qXmlvzWDE5jTS...sNH8-wPf6gKCuZzEyyS2AyZE8S4NzqoFkaepVpdoOPtb3Q"
}

谢谢

正确答案

jwx具有解析 JWK 的功能:

func ParseString(s string)

你可以像这样使用它来解析 JWK,并使用密钥对 JWT 进行签名和验证(更多细节请关注代码注释):

package main

import(
  "log"
  "github.com/lestrrat-go/jwx/jwk"
  "github.com/lestrrat-go/jwx/jws"
  "github.com/lestrrat-go/jwx/jwa"
)

func main() {

  // Here's an example of a JWK, containing a public and private RSA Keypair
  var keysJWK = `{
    "keys": [
        {
            "p": "59pSssPVWNBMd1dFBhkSx0P6uo3b3WC2MOitj7UI-9VS9gKPbPsqtDJSPdbRjK7JWXarFt_h4aPf9NPFLieu1k22jp3ProCH87geazJ8tNtV_SpaUtWQFZ-dvgGrIM-3MLf_fG7Tq5sV5R0vA9wg_INkYJ2uX5EdmVyHhxvh0eM",
            "kty": "RSA",
            "q": "jeofLDkteXfWcpif3JmX3xv8S6jWX2Axrwe9tLkWzlgxYDWvXExxD0sc4XfbVbSrqTkAdW48DYL_wcziFLYHxOYv2stqWvElF9CqdKJJrQAc7Z_qKXpWckDYZBJAO9W2WGXTBfdJfw_KQPHHTbY90ngdxMXuiwYbfbFY4H_XDM0",
            "d": "Qrx8U40tLhsy4tdnKuEmjlGF-VkB6F_DawLXwuZ2a5ZS7cwFUDRHNz9Jbl9MxvNcNMSMGaAN8lxTSDlpfT0jDqKF6lel88rUtCnN6h1FNdkD5TjkbWs-dfhftDFc1Sy8RdWPZ8LiTo0TbZaf3rPvdLw_S9FE-itnKV_1il572rT-1PvlyrPctnREQCKL5wArD4eYHwRjfVm-KvlIvo9rLj4NYzATBAAwh6PsEnSganEf1ErOvFH8qhrVqsy2kevLsFbCA0hIfoDNhL7hxlaMSJTJie3V2Ie0Kb7j_L2LsQXka3kshO1T6re-d-nGgaRp7b0buUtwS6aTax0H2cZuOQ",
            "e": "AQAB",
            "use": "sig",
            "kid": "223",
            "qi": "moGHNM3TFLeSQeM6V4izMcK6wwapSwo67r7DXk7vK_2FaSUQtijwQCHFx3nrhbQAVdwFt7pSYlmlFPlaAXixrBBNtNULnR7z6-WrRuWgqoL9LN8xARB42l94HmiOL0pp8ORyw2W338k3LHuzUy1NKZrL6a8zPIkva_Z5hFULhQE",
            "dp": "TcUm3j3gL3VXYOSOC5iXeu2ria4R5PUOx-MUbNLd25NXy5taPsUVMvJ6MbIAAj-S3IZ4pyib3RMaCUaLqoq3E71nkfkPc8o7UB4fXffGaufztQLi30wxk39B6z0mCNCD8zyU30lRiQtxUbPzVEkfa3QrVFkv53CGzC2EbGaG3d8",
            "alg": "RS256",
            "dq": "L1emNJOShw4iXTJrSiV3E7f7T6YwdbraeECF2c9RO18Sgb0HFixuHyL4rILWid3u0lIww_wVTpCgD5_w3-Xl65q65iur_FCsBijXZHdrSqpZ_C-350RnqE_XoHKyOQPPg-fcIQZg32F-IHJIAbXFI_xsOeOp83kDHMhYFPSw4hU",
            "n": "gIdJV4qWKyt3wkS66yBG5Ii9ew-eofuPU49TjlRIU5Iu5jX2mRMoHdcI7V78iKYSQHKYxz17cqzQyERxKnEiDgy_gwouStRgvPdm3H4rq__7p0t15SunsG2T1rEVf0sZEDnQ5qRkm7iqs6ZG1NqqIUtnOTd1Pd1MhbEqeENFtaPHvN37eZL82WmsQlJviFH4I9iZQVR_QT4GREQlRro8IjJTaloUyeDQTOQ-4ll1-4-g_ug2tZ-s9xleLzl5L9ZKSVJFhtMLn8WGaVldagarwa7kMLfuiVe8B5Lr7poQa4NCAR54ECPWoOHrABdPZKrkkxjVypTXUzL5cPzmzFC2xw"
        }
    ]
  }`

  // Parse the JWK to a set of keys
  setOfKeys, err := jwk.ParseString(keysJWK )
  if err != nil {
    log.Printf("failed to parse JWK: %s", err)
    return
  }
  
  // extract the private key from the set, index 0 because w only have one key
  rsaPrivatekey, success := setOfKeys.Get(0)
  if !success {
        log.Printf("could not find key at given index")
        return
  }
  
  // sign a token with the private key
  token, err := jws.Sign([]byte(`{"userId":1}`), jwa.RS256, rsaPrivatekey)
  if err != nil {
    log.Printf("failed to created JWS message: %s", err)
    return
  }

  // show the signed token
  log.Printf("Token! -> %s", token)

  // get a public key from a private key
  rsaPublicKey, err := jwk.PublicKeyOf(rsaPrivatekey)
  if err != nil {
    log.Printf("failed created public key from private key: %s", err)
    return
  }

  // verify the token that we created above with the public key
  payload, err := jws.Verify(token, jwa.RS256, rsaPublicKey)
  if err != nil {
    log.Printf("failed to verify message: %s", err)
    return
  }
  
  // show the payload of the verified token
  log.Printf("signature verified! Payload -> %s", payload)
 
}

在Go Playground上试试

理论要掌握,实操不能落!以上关于《将 JSON 公钥/私钥对转换为 rsa.PrivateKey 和 rsa.PublicKey》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>