【问题标题】:Extract public key from Google "oauth2/v1/certs" cert in PEM format using Go使用 Go 从 PEM 格式的 Google“oauth2/v1/certs”证书中提取公钥
【发布时间】:2014-12-01 22:55:51
【问题描述】:

我从以下位置获取 Google 证书:

https://www.googleapis.com/oauth2/v1/certs

但我不知道如何在 Go 中解析证书并提取公钥并使其适用于 rsa.VerifyPKCS1v15() 以验证 id 令牌(openID 连接)签名。如果有人可以建议我,我将不胜感激。这是我已经拥有的代码:

res, err := http.Get("https://www.googleapis.com/oauth2/v1/certs")
if err != nil {
    log.Fatal(err)
    return 
}

certs, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
    log.Fatal(err)
    return 
}
//extract kid from token header
var header interface{}
log.Printf("Oauth header: %v", headerOauth)
err = json.Unmarshal([]byte(headerOauth), &header)

token_kid := header.(map[string]interface{})["kid"]
//get modulus and exponent from the cert

var goCertificate interface{}

err = json.Unmarshal(certs, &goCertificate)    

k := goCertificate.(map[string]interface{})[token_kid.(string)]

google_cert := k.(string)
block_pub, _ := pem.Decode([]byte(google_cert))
certInterface, err := x509.ParseCertificates(block_pub.Bytes)
log.Printf("certInterface: %v", *certInterface.PublicKey)
//I know the line below is wrong but thats how I usualy parse public keys
pubkeyInterface, err := x509.ParsePKIXPublicKey(certInterface.Bytes)
pKey, ok := pubkeyInterface.(*rsa.PublicKey)

【问题讨论】:

    标签: go rsa google-oauth urlfetch openid-connect


    【解决方案1】:

    我可能离这里很远(不熟悉 x509/rsa)但ParseCertificates 返回所有键:

    func main() {
        res, err := http.Get("https://www.googleapis.com/oauth2/v1/certs")
        if err != nil {
            log.Fatal(err)
            return
        }
    
        var header = map[string]string{
            "kid": "ef9007a67db85f13ed67462abe2df63145c09aaf",
        }
    
        token_kid := header["kid"]
    
        defer res.Body.Close()
        var certs map[string]string
        dec := json.NewDecoder(res.Body)
        dec.Decode(&certs)
        // add error checking
        google_cert := certs[token_kid]
        block_pub, _ := pem.Decode([]byte(google_cert))
        certInterface, err := x509.ParseCertificates(block_pub.Bytes)
        log.Printf("certInterface: %#v", certInterface)
        pkey := certInterface[0].PublicKey.(*rsa.PublicKey)
        log.Printf("pkey: %v", pkey)
    }
    

    【讨论】:

    • 谢谢,但是当我使用我的 id 令牌运行脚本时,它返回以下错误:certInterface: []*x509.Certificate{(*x509.Certificate)(0xc210165480)} 验证密钥加密时出错/rsa: 验证错误#
    • @kingSlayer 这应该是一个不同的问题,不过我对加密/rsa 还不够熟悉。
    猜你喜欢
    • 2016-06-02
    • 2015-05-16
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2020-03-06
    • 2013-06-13
    • 1970-01-01
    相关资源
    最近更新 更多