阿里云的 HTTP协议加密文档感觉写的不太好,搞了很久才搞定。
顺便分享一下~
1. 为了防止重放攻击,阿里云加密加入了uuid这么个参数,因此 GO 实现的时候引入了一个uuid生成的三方库;

go get -u "github.com/satori/go.uuid"
  1. 其余的就不多说了,上代码,也比较简单。
package main 

import (
    "time"
    "strings"
    "fmt"
    "net/url"
    "github.com/satori/go.uuid"
    "crypto/hmac"
    "crypto/sha1"
    "encoding/base64"
)

const sortQueryString_fmt string = 
"AccessKeyId=%s"+
"&Action=SendSms"+
"&Format=JSON"+
"&OutId=123"+
"&PhoneNumbers=%s"+
"&RegionId=cn-hangzhou"+
"&SignName=%s"+
"&SignatureMethod=HMAC-SHA1"+
"&SignatureNonce=%s"+
"&SignatureVersion=1.0"+
"&TemplateCode=%s"+
"&TemplateParam=%s"+
"&Timestamp=%s"+
"&Version=2017-05-25"

func encode_local(encode_str string) string{
    urlencode := url.QueryEscape(encode_str)
    urlencode = strings.Replace(urlencode,"+","%%20",-1)
    urlencode = strings.Replace(urlencode,"*","%2A",-1)
    urlencode = strings.Replace(urlencode,"%%7E","~",-1)
    urlencode = strings.Replace(urlencode,"/","%%2F",-1)
    return urlencode
}

func main() {
    const token string = "xxxxx&" // 阿里云 accessSecret 注意这个地方要添加一个 &

    AccessKeyId := "xxxx" // 自己的阿里云 accessKeyID
    PhoneNumbers := "15088888888"  // 发送目标的手机号
    SignName := url.QueryEscape("阿里云短信测试专用")
    SignatureNonce,_ := uuid.NewV4()
    TemplateCode := "SMS_136035178"
    TemplateParam := url.QueryEscape("{\"code\":\"888888\"}")
    Timestamp := url.QueryEscape(time.Now().UTC().Format("2006-01-02T15:04:05Z"))

    sortQueryString := fmt.Sprintf(sortQueryString_fmt,
        AccessKeyId,
        PhoneNumbers,
        SignName,
        SignatureNonce,
        TemplateCode,
        TemplateParam,
        Timestamp,
    )

    urlencode := encode_local(sortQueryString)
    sign_str := fmt.Sprintf("GET&%%2F&%s",urlencode)

    key := []byte(token)
    mac := hmac.New(sha1.New, key)
    mac.Write([]byte(sign_str))
    signture := base64.StdEncoding.EncodeToString(mac.Sum(nil))
    signture = encode_local(signture)
    fmt.Println(signture)
    fmt.Printf("http://dysmsapi.aliyuncs.com/?Signature=%s&%s\n",signture,sortQueryString)
}

希望能够帮到后来人~

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐