github.com/NaverCloudPlatform/ncloud-sdk-go-v2@v1.6.13/hmac/hmac.go (about) 1 package hmac 2 3 import ( 4 "crypto" 5 "crypto/hmac" 6 "encoding/base64" 7 "fmt" 8 "net/url" 9 ) 10 11 func NewSigner(secretKey string, hashFunc crypto.Hash) *HMACSigner { 12 return &HMACSigner{ 13 secretKey: secretKey, 14 hashFunc: hashFunc, 15 } 16 } 17 18 type signer interface { 19 Sign(method string, url string, accessKey string, apiKey string, timestamp string) (string, error) 20 HashFunc() crypto.Hash 21 Debug(enabled bool) 22 } 23 24 type HMACSigner struct { 25 secretKey string 26 hashFunc crypto.Hash 27 debug bool 28 } 29 30 func (s *HMACSigner) Debug(enabled bool) { 31 s.debug = enabled 32 } 33 34 func (s *HMACSigner) Sign(method string, reqUrl string, accessKey string, timestamp string) (string, error) { 35 const space = " " 36 const newLine = "\n" 37 38 u, err := url.Parse(reqUrl) 39 if err != nil { 40 return "", err 41 } 42 43 if s.debug { 44 fmt.Println("reqUrl: ", reqUrl) 45 fmt.Println("accessKey: ", accessKey) 46 } 47 48 h := hmac.New(s.HashFunc().New, []byte(s.secretKey)) 49 h.Write([]byte(method)) 50 h.Write([]byte(space)) 51 h.Write([]byte(u.RequestURI())) 52 h.Write([]byte(newLine)) 53 h.Write([]byte(timestamp)) 54 h.Write([]byte(newLine)) 55 h.Write([]byte(accessKey)) 56 rawSignature := h.Sum(nil) 57 58 base64signature := base64.StdEncoding.EncodeToString(rawSignature) 59 if s.debug { 60 fmt.Println("Base64 signature:", base64signature) 61 } 62 return base64signature, nil 63 } 64 65 func (s *HMACSigner) HashFunc() crypto.Hash { 66 return s.hashFunc 67 }