Golang令牌验证错误

时间:2014-10-02 11:18:04

标签: go oauth-2.0 rsa google-oauth jwt

我需要验证google id_token,其中一步是检查令牌签名。

首先,我从https://www.googleapis.com/oauth2/v2/certs获取证书并从证书中提取模数(n)和指数(e)部分并生成公钥,然后我拆开令牌(标题,有效负载和摘要)之后,我将已解码的header.payload与Google pKey +摘要一起发送到rsa函数rsa.VerifyPKCS1v15

我遇到了这个验证错误:crypto/rsa: verification error

这里是代码(我评论了部分代码失败了// validation here fails):

func ValidateIDToken(auth_token string) (err error){    
    res, err := http.Get("https://www.googleapis.com/oauth2/v2/certs")
    if err != nil {
        log.Fatal(err)
        return err
    }

    certs, err := ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        log.Fatal(err)
        return err
    }

    //get modulus and exponent from the cert
    var goCertificate interface{}

    err = json.Unmarshal(certs, &goCertificate)    
    k := goCertificate.(map[string]interface{})["keys"]
    j := k.([]interface{})
    x := j[1]
    h := x.(map[string]interface{})["n"]
    g := x.(map[string]interface{})["e"]
    e64 := base64.StdEncoding
    //build the google pub key
    nStr := h.(string)
    decN, err := base64.StdEncoding.DecodeString(nStr)
    if err != nil {
        log.Println(err)
        return
    }

    n := big.NewInt(0)
    n.SetBytes(decN)
    eStr := g.(string)
    decE, err := base64.StdEncoding.DecodeString(eStr)
    if err != nil {
        log.Println(err)
        return
    }

    var eBytes []byte
    if len(decE) < 8 {
        eBytes = make([]byte, 8-len(decE), 8)
        eBytes = append(eBytes, decE...)
    } else {
        eBytes = decE
    }

    eReader := bytes.NewReader(eBytes)
    var e uint64
    err = binary.Read(eReader, binary.BigEndian, &e)
    if err != nil {
        log.Println(err)
        return
    }

    pKey := rsa.PublicKey{N: n, E: int(e)}
    w := strings.SplitAfter(auth_token, ".")    
    for i, val := range w {
        w[i] = strings.Trim(val, ".")
    }
    y := w[0:2]

    //Join just the first two parts, the header and the payload without the signature
    o := strings.Join(y, ".")   
    headerOauth := DecodeB64(nil,[]byte(w[0]),e64)
    inblockOauth := DecodeB64(nil,[]byte(w[1]),e64)
    toHash := string(headerOauth) + "}." + string(inblockOauth)
    digestOauth := DecodeB64(nil, []byte(w[2]),e64)

    hasherOauth := sha256.New()
    hasherOauth.Write([]byte(toHash))

    // validation here fails
    err = rsa.VerifyPKCS1v15(&pKey,crypto.SHA256,hasherOauth.Sum(nil),digestOauth)

    if err != nil {
        log.Printf("Error verifying key %s",err.Error())
        return err
    }
    return err
}

更新1: 这是包含头和有效负载的哈希var:

{"alg":"RS256","kid":"d91c503452d0f8849200a321ffbf7dea76f9371d"}.{"iss":"accounts.google.com","sub":"104869993929250743503","azp":"client_email_till_@.apps.googleusercontent.com","email":"test@test.hr","at_hash":"KAm1M0g-ssMkdjds7jkbVQ","email_verified":true,"aud":client_email_till_@.apps.googleusercontent.com","hd":"test.hr","iat":1412246551,"exp":1412250451}

更新2: 感谢@Florent Morselli的回复,我再次尝试了它失败了,我这次B64解码只有第三部分(签名)但是错误仍然存​​在,有人可以测试它们 auth_token,只需将ID令牌放在代码中的auth_token变量中,如果有效,请告诉我,谢谢。

package main
import(
    "strings"
    "encoding/binary"
    "errors"
    "fmt"
    "log"
    "encoding/base64"
    "io/ioutil"
    "crypto"    
    "crypto/sha256"
    "crypto/rsa"
    "bytes"
    "encoding/json"
    "net/http"
    "math/big"  

)

func main() {
    auth_token := ""
    w := strings.SplitAfter(auth_token, ".")    
    for i, val := range w {
        w[i] = strings.Trim(val, ".")
    }
    headerOauth, err := base64.URLEncoding.DecodeString(w[0])

    res, err := http.Get("https://www.googleapis.com/oauth2/v2/certs")
    if err != nil {
        fmt.Println(err)
    }

    certs, err := ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        fmt.Println(err)
    }

    //extract kid from token header
    var header interface{}

    err = json.Unmarshal([]byte(string(headerOauth)+"}"), &header)

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

    var goCertificate interface{}

    err = json.Unmarshal(certs, &goCertificate)    

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

    ///*mod & exp part
    j := k.([]interface{})
    x := j[0]

    if j[0].(map[string]interface{})["kid"] == token_kid {
        x = j[0]
    }else{
        if j[1].(map[string]interface{})["kid"] == token_kid {
            x = j[1]
        }else{
            errors.New("Token is not valid, kid from token and certificate don't match")

        }
    }
    h := x.(map[string]interface{})["n"]
    g := x.(map[string]interface{})["e"]

    //build the google pub key
    nStr := h.(string)
    decN, err := base64.URLEncoding.DecodeString(nStr)
    if err != nil {
        fmt.Println(err)
        return
    }

    n := big.NewInt(0)
    n.SetBytes(decN)
    eStr := g.(string)
    decE, err := base64.URLEncoding.DecodeString(eStr)
    if err != nil {
        fmt.Println(err)
        return
    }

    var eBytes []byte
    if len(decE) < 8 {
        eBytes = make([]byte, 8-len(decE), 8)
        eBytes = append(eBytes, decE...)
    } else {
        eBytes = decE
    }

    eReader := bytes.NewReader(eBytes)
    var e uint64
    err = binary.Read(eReader, binary.BigEndian, &e)
    if err != nil {
        log.Println(err)
        return
    }

    pKey := rsa.PublicKey{N: n, E: int(e)}
        //inblockOauth := base64.URLEncoding.DecodeString(w[1])
    toHash := w[0] + "." + w[1]
    digestOauth, err := base64.URLEncoding.DecodeString(w[2])

    hasherOauth := sha256.New()
    hasherOauth.Write([]byte(toHash))

    // verification here fails
    err = rsa.VerifyPKCS1v15(&pKey,crypto.SHA256,hasherOauth.Sum(nil),digestOauth)

    if err != nil {
        fmt.Printf("Error verifying key %s",err.Error())

    }

}

4 个答案:

答案 0 :(得分:5)

正如聊天中所解释的那样,问题是Base64解码器无法解码标头和签名(如果它们丢失了)#34; =&#34;。

您只需使用以下代码添加它们:

    if m := len(h_) % 4; m != 0 {
        h_ += strings.Repeat("=", 4-m)
    }

以下是完整的代码:

package main
import(
    "strings"
    "encoding/binary"
    "errors"
    "fmt"
    "log"
    "encoding/base64"
    "io/ioutil"
    "crypto"    
    "crypto/sha256"
    "crypto/rsa"
    "bytes"
    "encoding/json"
    "net/http"
    "math/big"  

)

func main() {
    auth_token := ""
    w := strings.Split(auth_token, ".")    
    h_, s_ := w[0], w[2]

    if m := len(h_) % 4; m != 0 {
        h_ += strings.Repeat("=", 4-m)
    }
    if m := len(s_) % 4; m != 0 {
        s_ += strings.Repeat("=", 4-m)
    }

    headerOauth, err := base64.URLEncoding.DecodeString(h_)

    res, err := http.Get("https://www.googleapis.com/oauth2/v2/certs")
    if err != nil {
        fmt.Println(err)
    }

    certs, err := ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        fmt.Println(err)
    }

    //extract kid from token header
    var header interface{}

    err = json.Unmarshal([]byte(string(headerOauth)), &header)

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

    var goCertificate interface{}

    err = json.Unmarshal(certs, &goCertificate)    

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

    ///*mod & exp part
    j := k.([]interface{})
    x := j[0]

    if j[0].(map[string]interface{})["kid"] == token_kid {
        x = j[0]
    }else{
        if j[1].(map[string]interface{})["kid"] == token_kid {
            x = j[1]
        }else{
            errors.New("Token is not valid, kid from token and certificate don't match")

        }
    }
    h := x.(map[string]interface{})["n"]
    g := x.(map[string]interface{})["e"]

    //build the google pub key
    nStr := h.(string)
    decN, err := base64.URLEncoding.DecodeString(nStr)
    if err != nil {
        fmt.Println(err)
        return
    }

    n := big.NewInt(0)
    n.SetBytes(decN)
    eStr := g.(string)
    decE, err := base64.URLEncoding.DecodeString(eStr)
    if err != nil {
        fmt.Println(err)
        return
    }

    var eBytes []byte
    if len(decE) < 8 {
        eBytes = make([]byte, 8-len(decE), 8)
        eBytes = append(eBytes, decE...)
    } else {
        eBytes = decE
    }

    eReader := bytes.NewReader(eBytes)
    var e uint64
    err = binary.Read(eReader, binary.BigEndian, &e)
    if err != nil {
        log.Println(err)
        return
    }

    pKey := rsa.PublicKey{N: n, E: int(e)}
        //inblockOauth := base64.URLEncoding.DecodeString(w[1])
    toHash := w[0] + "." + w[1]
    digestOauth, err := base64.URLEncoding.DecodeString(s_)

    hasherOauth := sha256.New()
    hasherOauth.Write([]byte(toHash))

    // verification of the signature
    err = rsa.VerifyPKCS1v15(&pKey,crypto.SHA256,hasherOauth.Sum(nil),digestOauth)


    if err != nil {
        fmt.Printf("Error verifying key %s",err.Error())
    }
    fmt.Printf("OK!")
}

答案 1 :(得分:2)

不要使用StdEncoding,它不符合规范要求的URL安全。

改为使用 URLEncoding 。有关更多信息,请参阅https://gobyexample.com/base64-encoding

Base64 Url Safe与Base64相同,但不包含'/'和'+'(替换为'_'和' - '),并删除尾随'='。

答案 2 :(得分:2)

I send the **decoded** header.payload together with the Google pKey + digest to the rsa function rsa.VerifyPKCS1v15.

这部分你错了。您必须向RSA函数rsa.VerifyPKCS1v15发送编码 header.payload

换句话说:您检查了{"alg":"RS256","kid":"d91c503452d0f8849200a321ffbf7dea76f9371d"}.{"iss":"accounts.google.com","sub":"104869993929250743503","azp":"client_email_till_@.apps.googleusercontent.com","email":"test@test.hr","at_hash":"KAm1M0g-ssMkdjds7jkbVQ","email_verified":true,"aud":client_email_till_@.apps.googleusercontent.com","hd":"test.hr","iat":1412246551,"exp":1412250451} 的签名错误

您必须检查eyJhbGciOiJSUzI1NiIsImtpZCI6ImQ5MWM1MDM0NTJkMGY4ODQ5MjAwYTMyMWZmYmY3ZGVhNzZmOTM3MWQifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTA0ODY5OTkzOTI5MjUwNzQzNTAzIiwiYXpwIjoiY2xpZW50X2VtYWlsX3RpbGxfQC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImVtYWlsIjoidGVzdEB0ZXN0LmhyIiwiYXRfaGFzaCI6IktBbTFNMGctc3NNa2RqZHM3amtiVlEiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXVkIjpjbGllbnRfZW1haWxfdGlsbF9ALmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaGQiOiJ0ZXN0LmhyIiwiaWF0IjoxNDEyMjQ2NTUxLCJleHAiOjE0MTIyNTA0NTF9的签名。

答案 3 :(得分:1)

要检查的输入应该是$ base64_header。$ base64_claim_set。 来自Google's documentation

  

JSON Web签名(JWS)是指导它的规范   为JWT生成签名的机制。的输入   signature是以下内容的字节数组:
  {Base64url encoded header}.{Base64url encoded claim set}

我认为你可能刚刚对证书索引进行了硬编码以进行演示。在您的真实代码中,您应该根据&#34; kid&#34;选择正确的证书。标题中的字段。