truecaller / backend-sdk-validation

5 stars 16 forks source link

Golang Support #7

Open kushalbikriapp opened 4 years ago

kushalbikriapp commented 4 years ago

Can we see the golang implementation for this?

kushalhalder commented 4 years ago
func FetchPublicKey() (publicKey *TPublicKeyResponse, err error) {
    req := httplib.Get(beego.AppConfig.String("TRUECALLER_PUBLIC_KEY_URL"))
    req.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
    req.Debug(true)

    str, err := req.String()
    if err != nil {
        l.Printf("Error: %v", err)
        return nil, err
    }
    l.Println(str)
    pr := TPublicKeyResponse{}
    _ = json.Unmarshal([]byte(str), &pr)
    return &pr, nil
}

func VerifyPayload(s *SDKResponse) bool {
    publicKeyString, err := FetchPublicKey()
    if err != nil {
        l.Printf("Error: %v", err)
        return false
    }
    publicKeyInterface, err := x509.ParsePKIXPublicKey([]byte(publicKeyString.Key))
    publicKey, isRSAPublicKey := publicKeyInterface.(*rsa.PublicKey)
    if !isRSAPublicKey {
        l.Printf("isRSAPublicKey: %v", isRSAPublicKey)
        return false
    }
    hashed := sha256.Sum256([]byte(s.Payload))
    sDec, esDec := base64.StdEncoding.DecodeString(s.Signature)
    if esDec != nil {
        l.Printf("Signature Decode Error: %v", esDec)
        return false
    }
    e := rsa.VerifyPKCS1v15(publicKey, crypto.SHA512, hashed[:], sDec)
    if e != nil {
        l.Printf("Verify: %v", e)
        return false
    }

    return true
}

This is what I have, but it fails at publicKey, isRSAPublicKey := publicKeyInterface.(*rsa.PublicKey)

kushalhalder commented 4 years ago

The error at publicKeyInterface, err := x509.ParsePKIXPublicKey([]byte(publicKeyString.Key)) is PublicKey Parse error: asn1: syntax error: sequence truncated