Skip to content

Instantly share code, notes, and snippets.

@goofmint
Created February 15, 2019 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goofmint/9f4205f90a25d9c0f7896c5ea3e87e2d to your computer and use it in GitHub Desktop.
Save goofmint/9f4205f90a25d9c0f7896c5ea3e87e2d to your computer and use it in GitHub Desktop.
GolangでNCMB用の署名文字列を生成する
package main
import (
"time"
"net/url"
"strings"
"sort"
"encoding/json"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
)
func main() {
method := "GET"
fqdn := "mbaas.api.nifcloud.com"
path := "/2013-09-01/classes/TestClass"
queries := make(map[string]map[string]string)
queries["where"] = make(map[string]string)
queries["where"]["testKey"] = "testValue"
applicationKey := "6145f91061916580c742f806bab67649d10f45920246ff459404c46f00ff3e56"
clientKey := "1343d198b510a0315db1c03f3aa0e32418b7a743f8e4b47cbff670601345cf75"
signatureMethod := "HmacSHA256"
signatureVersion := "2"
timestamp := time.Date(2013, 12, 02, 02, 44, 35, 452e6, time.UTC)
signature := sign(method, fqdn, path, queries, applicationKey, clientKey, signatureMethod, signatureVersion, timestamp)
print(signature)
}
func sign(
method string, fqdn string, path string,
queries map[string]map[string]string, applicationKey string,
clientKey string, signatureMethod string, signatureVersion string, timestamp time.Time) string {
// マップを作成
arySig := make(map[string]string)
// 基本的な項目の設定
arySig["SignatureMethod"] = signatureMethod
arySig["SignatureVersion"] = signatureVersion
arySig["X-NCMB-Application-Key"] = applicationKey
arySig["X-NCMB-Timestamp"] = timestamp.Format("2006-01-02T15:04:05.000Z")
// クエリ文字列のエスケープ
if (len(queries) > 0) {
for key, params := range queries {
j, _ := json.Marshal(params)
arySig[key] = url.QueryEscape(string(j))
}
}
// ソートするために配列に入れ替え
ary := []string{}
for val := range arySig {
ary = append(ary, val)
}
sort.Strings(ary)
params := []string{}
for _, name := range ary {
params = append(params, name + "=" + arySig[name])
}
// シグネチャ用文字列の作成
signature := []string{}
signature = append(signature, method)
signature = append(signature, fqdn)
signature = append(signature, path)
signature = append(signature, strings.Join(params, "&"))
// ハッシュ値の作成
mac := hmac.New(sha256.New, []byte(clientKey))
mac.Write([]byte(strings.Join(signature, "\n")))
// 署名文字列の返却
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment