Go 如何执行CloudKit服务器到服务器身份验证

Go 如何执行CloudKit服务器到服务器身份验证,go,cloudkit-web-services,Go,Cloudkit Web Services,我在跟踪 执行 我们的想法是让这个简单的请求生效,然后再提出更复杂的请求,比如上传资产 下面的代码从请求返回错误 import ( "bytes" "crypto/ecdsa" "crypto/rand" "crypto/sha256" "crypto/x509" "encoding/base64" "enc

我在跟踪

执行

我们的想法是让这个简单的请求生效,然后再提出更复杂的请求,比如上传资产

下面的代码从请求返回错误


import (
    "bytes"
    "crypto/ecdsa"
    "crypto/rand"
    "crypto/sha256"
    "crypto/x509"
    "encoding/base64"
    "encoding/pem"
    "fmt"
    "math/big"
    "net/http"
    "time"
    //...
)

func main() {

    fmt.Printf("\nprivate key:\n")

    const privPEM = `-----BEGIN EC PRIVATE KEY-----
MyProvateKey
-----END EC PRIVATE KEY-----`

    // https://golang.org/pkg/crypto/x509/#example_ParsePKIXPublicKey
    privBlock, _ := pem.Decode([]byte(privPEM))
    if privBlock == nil {
        panic("failed to parse PEM block containing the public key")
    }

    requestPathStr := "/database/1/iCloud.<MyContainer>/development/public/users/discover"

    var requestPath []byte
    requestPath = []byte(requestPathStr)
    fmt.Printf("requestPath: %s\n", requestPath)

    requestBody := ""
    var jsonStr = []byte(requestBody)
    //
    h := sha256.New()
    h.Write([]byte(requestBody))
    b := h.Sum(nil)
    hashedBody := base64.StdEncoding.EncodeToString(b)
    //

    f := "2006-01-02T15:04:05Z"
    requestDate := time.Now().UTC().Format(f)
    fmt.Println(requestDate)

    rawPayload := []byte(requestDate + ":" + hashedBody + ":" + requestPathStr)

    r, s, err := pkSign(rawPayload, privBlock)
    if err != nil {
        fmt.Printf("signing hash error: %s\n", err)
    }
    fmt.Printf("r: %v\n", r)
    fmt.Printf("s: %v\n", s)

    fmt.Printf("\npublic key:\n")

    const pubPEM = `-----BEGIN PUBLIC KEY-----
MyPublicKey
-----END PUBLIC KEY-----`
    pubBlock, _ := pem.Decode([]byte(pubPEM))
    if pubBlock == nil {
        panic("failed to parse PEM block containing the public key")
    }
    // ECDSA signature
    ECDSAsignature := r.Bytes()
    ECDSAsignature = append(ECDSAsignature, s.Bytes()...)

    fmt.Printf("ECDSAsignature : %x\n", ECDSAsignature)

    verify := pkVerify(rawPayload, pubBlock, r, s)
    fmt.Printf("signature verification result: %t\n", verify)

    // GET [path]/database/[version]/[container]/[environment]/public/users/discover

    url := "https://api.apple-cloudkit.com/" + requestPathStr
    fmt.Printf("\nurl:%v\n", url)
    fmt.Printf("\njsonStr:%s\n", jsonStr)
    fmt.Printf("\nrequestDate:%s\n", requestDate)

    client := &http.Client{}

    // GET [path]/database/[version]/[container]/[environment]/public/users/discover

    req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonStr))
    var authKeyID = "MyKeyID"

    req.Header.Add("content-type", "text/plain")
    req.Header.Add("X-Apple-CloudKit-Request-KeyID", authKeyID)
    req.Header.Add("X-Apple-CloudKit-Request-ISO8601Date", requestDate)

    ECDSAsignatureBase64 := base64.StdEncoding.EncodeToString(ECDSAsignature)

    req.Header.Add("X-Apple-CloudKit-Request-SignatureV1", ECDSAsignatureBase64)
    resp, _ := client.Do(req)
    fmt.Printf("\nresp:%v\n", resp)

    resp, err = client.Do(req)
    if err != nil {
        fmt.Printf("\nerr:%v\n", err.Error())

    } else {
        resp.Body.Close()
        fmt.Printf("\nresp.Body:%v\n", resp.Body)

    }
    fmt.Printf("\nresp:%v\n", resp)

}

func pkSign(hash []byte, block *pem.Block) (r, s *big.Int, err error) {
    zero := big.NewInt(0)
    private_key, err := x509.ParseECPrivateKey(block.Bytes)
    if err != nil {
        return zero, zero, err
    }

    // Sign signs a hash (which should be the result of hashing a larger message)
    // using the private key, priv.
    // If the hash is longer than the bit-length of the private key's curve order,
    // the hash will be truncated to that length.
    // It returns the signature as a pair of integers.
    // The security of the private key depends on the entropy of rand.

    r, s, err = ecdsa.Sign(rand.Reader, private_key, hash)
    if err != nil {
        return zero, zero, err
    }
    return r, s, nil
}

func pkVerify(hash []byte, block *pem.Block, r *big.Int, s *big.Int) (result bool) {
    public_key, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return false
    }

    switch public_key := public_key.(type) {
    case *ecdsa.PublicKey:
        return ecdsa.Verify(public_key, hash, r, s)
    default:
        return false
    }
}


进口(
“字节”
“加密/ecdsa”
“加密/兰德”
“加密/sha256”
“加密/x509”
“编码/base64”
“编码/pem”
“fmt”
“数学/大”
“net/http”
“时间”
//...
)
func main(){
fmt.Printf(“\n专用密钥:\n”)
const privPEM=`BEGIN EC私钥-----
MyProvateKey
-----结束EC私钥-----`
// https://golang.org/pkg/crypto/x509/#example_ParsePKIXPublicKey
privBlock,:=pem.Decode([]字节(privPEM))
如果privBlock==nil{
panic(“未能解析包含公钥的PEM块”)
}
requestPathStr:=“/database/1/iCloud./development/public/users/discover”
var requestPath[]字节
requestPath=[]字节(requestPathStr)
fmt.Printf(“请求路径:%s\n”,请求路径)
请求主体:=“”
var jsonStr=[]字节(请求体)
//
h:=sha256.New()
h、 写入([]字节(请求正文))
b:=h.和(零)
hashedBody:=base64.StdEncoding.EncodeToString(b)
//
f:=“2006-01-02T15:04:05Z”
requestDate:=时间.Now().UTC().Format(f)
格式打印项次(请求日期)
rawPayload:=[]字节(requestDate+“:”+hashedBody+“:”+requestPathStr)
r、 s,err:=pkSign(rawPayload,privBlock)
如果错误!=零{
fmt.Printf(“签名哈希错误:%s\n”,错误)
}
fmt.Printf(“r:%v\n”,r)
fmt.Printf(“s:%v\n”,s)
fmt.Printf(“\n公钥:\n”)
const pubPEM=`----开始公钥-----
我的公钥
-----结束公钥-----`
pubBlock,:=pem.Decode([]字节(pubPEM))
如果pubBlock==nil{
panic(“未能解析包含公钥的PEM块”)
}
//ECDSA签名
ECDSAsignature:=r.Bytes()
ECDSAsignature=append(ECDSAsignature,s.Bytes()…)
fmt.Printf(“ECDSAsignature:%x\n”,ECDSAsignature)
验证:=pkVerify(rawPayload,pubBlock,r,s)
fmt.Printf(“签名验证结果:%t\n”,验证)
//获取[path]/database/[version]/[container]/[environment]/public/users/discover
url:=”https://api.apple-cloudkit.com/“+requestPathStr
fmt.Printf(“\nurl:%v\n”,url)
fmt.Printf(“\njsonStr:%s\n”,jsonStr)
fmt.Printf(“\n请求日期:%s\n”,请求日期)
客户端:=&http.client{}
//获取[path]/database/[version]/[container]/[environment]/public/users/discover
req,err:=http.NewRequest(“GET”,url,bytes.NewBuffer(jsonStr))
var authKeyID=“MyKeyID”
请求标题添加(“内容类型”、“文本/普通”)
请求头添加(“X-Apple-CloudKit-Request-KeyID”,authKeyID)
请求标题添加(“X-Apple-CloudKit-Request-ISO8601Date”,请求日期)
ECDSAsignatureBase64:=base64.StdEncoding.EncodeToString(ECDSAsignature)
请求标题添加(“X-Apple-CloudKit-Request-SignatureV1”,ECDSAsignatureBase64)
resp,u:=client.Do(请求)
fmt.Printf(“\nRep:%v\n”,resp)
resp,err=client.Do(请求)
如果错误!=零{
fmt.Printf(“\n错误:%v\n”,err.Error())
}否则{
各自主体关闭()
格式打印文件(“\n打印正文:%v\n”,分别为正文)
}
fmt.Printf(“\nRep:%v\n”,resp)
}
func pkSign(散列[]字节,块*pem.block)(r,s*big.Int,err error){
零:=big.NewInt(0)
私钥,err:=x509.ParseECPrivateKey(block.Bytes)
如果错误!=零{
返回零,零,错误
}
//Sign对散列进行签名(这应该是对较大消息进行散列的结果)
//使用私钥priv。
//如果散列长度大于私钥曲线顺序的位长度,
//哈希将被截断为该长度。
//它以一对整数的形式返回签名。
//私钥的安全性取决于rand的熵。
r、 s,err=ecdsa.Sign(rand.Reader,私钥,散列)
如果错误!=零{
返回零,零,错误
}
返回r,s,零
}
func pkVerify(hash[]字节,block*pem.block,r*big.Int,s*big.Int)(结果bool){
公钥,错误:=x509.ParsePKIXPublicKey(block.Bytes)
如果错误!=零{
返回错误
}
开关公共密钥:=公共密钥。(类型){
案例*ecdsa.PublicKey:
返回ecdsa.Verify(公钥、散列、r、s)
违约:
返回错误
}
}
我得到的错误如下:

响应:&{503服务不可用503 HTTP/1.1 1映射[Access Control Expose Header:[X-Apple-Request-UUID Via]连接:[keep alive]内容长度:[0]内容类型:[text/plain]日期:[2019年6月24日星期一07:47:52 GMT]在:[30]服务器之后重试:[AppleHttpServer/70a91026]通过:[icloudedge:mi01p00ic-ZTEU021104010401:7401:19RC207:Miami]X-Apple-Cache:[false]X-Apple-Request-Uuid:[ddeb0fa3-ea16-40e9-a15b-c2e68cb5fe78]{}0[]假假映射[]0xc00015c000 0xc0000ce2c0}

响应体:{}


如果有人需要,这里有一个有效的解决方案

package main

import (
    "bytes"
    "crypto/ecdsa"
    "crypto/rand"
    "crypto/sha256"
    "crypto/x509"
    "encoding/asn1"
    "encoding/base64"
    "encoding/pem"
    "fmt"
    "io/ioutil"
    "math/big"
    "net/http"
    "time"
)

const projectID = "<your ID>"

//
const authKeyID = "your ID"
const path = "https://api.apple-cloudkit.com"
const version = "1"
const container = "your container"
const environment = "development"
const database = "public"

const privPEM = `-----BEGIN EC PRIVATE KEY-----
your privste key
-----END EC PRIVATE KEY-----`

const pubPEM = `-----BEGIN PUBLIC KEY-----
your public key
-----END PUBLIC KEY-----`

type ecdsaSignature struct {
    R, S *big.Int
}

func main() {
    t0 := time.Now().UTC()
    t1 := time.Now().UTC()

    // fmt.Printf("\nprivate key:\n")
    // https://golang.org/pkg/crypto/x509/#example_ParsePKIXPublicKey
    privBlock, _ := pem.Decode([]byte(privPEM))
    if privBlock == nil {
        panic("failed to parse PEM block containing the public key")
    }

    private_key, err := x509.ParseECPrivateKey(privBlock.Bytes)
    if err != nil {
        panic("failed to parse PEM block containing the public key")
    }

    pubBlock, _ := pem.Decode([]byte(pubPEM))
    if pubBlock == nil {
        panic("failed to parse PEM block containing the public key")
    }

    var public_key *ecdsa.PublicKey
    public_k, err := x509.ParsePKIXPublicKey(pubBlock.Bytes)
    if err != nil {
        panic("failed to parse PEM block containing the public key")
    }
    switch public_k1 := public_k.(type) {
    case *ecdsa.PublicKey:
        public_key = public_k1
    default:
        //return false
    }
    //////////
    // Config
    //////////
    requestPath := "/database/" +
        version + "/" +
        container + "/" +
        environment + "/" +
        database + "/" +
        "records/query"

    requestBody := `{"query": {"recordType": "<your record type"}}`

    f := "2006-01-02T15:04:05Z"
    requestDate := time.Now().UTC().Format(f)

    h := sha256.New()
    h.Write([]byte(requestBody))
    b := h.Sum(nil)
    hashedBody := base64.StdEncoding.EncodeToString(b)

    rawPayload := requestDate + ":" + hashedBody + ":" + requestPath

    signedSignature, err := SignMessage(private_key, []byte(rawPayload))
    if err != nil {
        fmt.Printf("SignMessage  error: %s\n", err.Error())
    }

    verify := VerifyMessage(public_key, []byte(rawPayload), signedSignature)
    fmt.Printf("signature verification result: %t\n", verify)

    requestSignature := base64.StdEncoding.EncodeToString(signedSignature)
    url := path + requestPath

    req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(requestBody)))

    req.Header.Add("content-type", "text/plain")
    req.Header.Add("X-Apple-CloudKit-Request-KeyID", authKeyID)

    req.Header.Add("X-Apple-CloudKit-Request-ISO8601Date", requestDate)

    req.Header.Add("X-Apple-CloudKit-Request-SignatureV1", requestSignature)

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Printf("\nresp.err:%v\n", err.Error())

    }

    defer resp.Body.Close()
    rbody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("\nioutil.ReadAll.err:%v\n", err.Error())

    }
    fmt.Printf("\nrbody:%s\n", rbody)

    curl := "curl -X POST -H \"content-type: text/plain\"" + " " +
        "-H X-Apple-CloudKit-Request-KeyID:" + authKeyID + " " +
        "-H X-Apple-CloudKit-Request-ISO8601Date:" + requestDate + " " +
        "-H X-Apple-CloudKit-Request-SignatureV1:" + base64.StdEncoding.EncodeToString(signedSignature) + " " +
        " -d " + "'" + requestBody + "'" + " " +
        url

    fmt.Printf("\n%s\n", curl)

}

func SignMessage(priv *ecdsa.PrivateKey, message []byte) ([]byte, error) {
    hashed := sha256.Sum256(message)
    r, s, err := ecdsa.Sign(rand.Reader, priv, hashed[:])
    if err != nil {
        return nil, err
    }

    return asn1.Marshal(ecdsaSignature{r, s})
}

func VerifyMessage(pub *ecdsa.PublicKey, message []byte, signature []byte) bool {
    var rs ecdsaSignature

    if _, err := asn1.Unmarshal(signature, &rs); err != nil {
        return false
    }

    hashed := sha256.Sum256(message)
    return ecdsa.Verify(pub, hashed[:], rs.R, rs.S)
}
主程序包
进口(
“字节”
“加密/ecdsa”
“加密/兰德”
“加密/sha256”
“加密/x509”
“编码/asn1”
“编码/base64”
“编码/pem”
“fmt”
“io/ioutil”
“数学/大”
“net/http”
“时间”
)
const projectd=“”
//
const authKeyID=“您的ID”
常量路径=”https://api.apple-cloudkit.com"
const version=“1”
const container=“您的容器”
const environment=“开发”
const database=“public”
const privPEM=`BEGIN EC私钥-----
你的私钥
-----结束EC私钥-----`
const pubPEM=`----开始公钥-----
您的公钥
-----结束公钥-----`
类型ecdsaSignature结构{
R、 S*big.Int
}
func main(){
t0:=time.Now().UTC()
t1:=time.Now().UTC()
//fmt.Printf(“\n专用密钥:\n”)
// https://golang.org/pkg/crypto/x509/#example_ParsePKIXPublicKey
privBlock,:=pem.Decode([]字节(privPEM))
如果privBlock==nil{
panic(“未能解析包含公钥的PEM块”)
}
私有的