dongshen9686 2014-10-07 13:33
浏览 86

使用Go以PEM格式从Google“ oauth2 / v1 / certs”证书中提取公钥

I fetched the Google cert from:

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

but I don't know how to parse the cert in Go and extract the public key and make it aplicable for use in rsa.VerifyPKCS1v15() to verify id token (openID connect) signature. If someone could advise me I would appreciate it. Here is the code what I already have:

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)
  • 写回答

1条回答 默认 最新

  • duanmiaosi0150 2014-10-07 14:10
    关注

    I might be way off here (not familiar with x509/rsa) but ParseCertificates returns all the keys:

    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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题