签名认证(推荐)

最后更新时间:2020-12-31 17:43:48

    概述

    本文主要为您介绍移动推送 TPNS 签名认证方法。

    采用 HMAC-SHA256 算法,根据 SecretKey 生产签名信息。通过校验签名进行鉴权,安全性更好,推荐使用。

    参数说明

    参数 说明
    AccessId 移动推送 TPNS 后台分配的应用 ID,请前往 【移动推送 TPNS 控制台】>【配置管理】>【基础配置】 获取
    SecretKey 移动推送 TPNS 后台分配的 SecretKey,与 AccessId 对应,请前往 【移动推送 TPNS 控制台】>【配置管理】>【基础配置】 获取
    Sign 接口签名方式
    timeStamp 请求时间戳

    签名生成方式

    1. 通过请求时间戳 + accessId + 请求 body 进行字符拼接,得到原始的待签名字符串:
      待签名字符串 = ${timeStamp} + ${accessId} + ${请求body}
    2. 通过 secretKey 作为密钥,对原始待签名字符串进行签名,生成得到签名:
      sign = Base64(HMAC_SHA256(待签名字符串, secretKey))

    HTTP 协议拼装方式

    HTTP 协议 header 中 除了通用头部协议外,需要携带当前请求时间戳、 AccessId、 以及签名 Sign 信息,具体参数如下:

    Header 中参数 Key 含义 是否必须
    Sign 请求签名
    AccessId 应用 ID
    TimeStamp 请求时间戳

    具体 HTTP 请求报文如下:

    POST /v3/push/app HTTP/1.1
    Host: api.tpns.tencent.com
    Content-Type: application/json
    AccessId: 1500001048
    TimeStamp: 1565314789
    Sign: Y2QyMDc3NDY4MmJmNzhiZmRiNDNlMTdkMWQ1ZDU2YjNlNWI3ODlhMTY3MGZjMTUyN2VmNTRjNjVkMmQ3Yjc2ZA==
    {"audience_type": "account","platform": "android","message": {"title": "test title","content": "test content","android": { "action": {"action_type": 3,"intent": "xgscheme://com.xg.push/notify_detail?param1=xg"}}},"message_type": "notify","account_list": ["5822f0eee44c3625ef0000bb"] }

    签名生成示例

    1. 生成待拼接签名字符串如下:
      待加密字符串=15653147891500001048{"audience_type": "account","platform": "android","message": {"title": "test title","content": "test content","android": { "action": {"action_type": 3,"intent": "xgscheme://com.xg.push/notify_detail?param1=xg"}}},"message_type": "notify","account_list": ["5822f0eee44c3625ef0000bb"] }
    2. 根据密钥通过 HMAC-SHA256 算法,生成十六进制 hash,其中示例对应 secretKey =1452fcebae9f3115ba794fb0fff2fd73
      hashcode= hmac-sha256(待签名字符串, secretKey)
      得到 hashcode="cd20774682bf78bfdb43e17d1d5d56b3e5b789a1670fc1527ef54c65d2d7b76d"
    3. 对 hashcode 进行 base64 编码,得到签名串如下:
      得到 Sign=Base64(hashcode)
      Sign="Y2QyMDc3NDY4MmJmNzhiZmRiNDNlMTdkMWQ1ZDU2YjNlNWI3ODlhMTY3MGZjMTUyN2VmNTRjNjVkMmQ3Yjc2ZA=="

    各语言签名代码示例

    ::: Python2 python #!/usr/bin/env python import hmac import base64 from hashlib import sha256

    s = '15653147891500001048{"audience_type": "account","platform": "android","message": {"title": "test title","content": "test content","android": { "action": {"action_type": 3,"intent": "xgscheme://com.xg.push/notify_detail?param1=xg"}}},"message_type": "notify","account_list": ["5822f0eee44c3625ef0000bb"] }'
    key = '1452fcebae9f3115ba794fb0fff2fd73'
    hashcode = hmac.new(key, s, digestmod=sha256).hexdigest()
    print base64.b64encode(hashcode)
    :::
    ::: Python3 python
    import hmac
    import base64
    from hashlib import sha256

    s = '15653147891500001048{"audience_type": "account","platform": "android","message": {"title": "test title","content": "test content","android": { "action": {"action_type": 3,"intent": "xgscheme://com.xg.push/notify_detail?param1=xg"}}},"message_type": "notify","account_list": ["5822f0eee44c3625ef0000bb"] }'
    key = '1452fcebae9f3115ba794fb0fff2fd73'
    hashcode = hmac.new(bytes(key, "utf-8"), bytes(s, "utf-8"),
    digestmod=sha256).hexdigest()
    print(base64.b64encode(bytes(hashcode, "utf-8")))
    :::
    ::: Java java
    package com.tencent.xg;

    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;
    import org.apache.commons.codec.binary.Hex;

    public class SignTest {
    public static void main(String[] args) {
    try {
    String stringToSign = "15653147891500001048{"audience_type": "account","platform": "android","message": {"title": "test title","content": "test content","android": { "action": {"action_type": 3,"intent": "xgscheme://com.xg.push/notify_detail?param1=xg"}}},"message_type": "notify","account_list": ["5822f0eee44c3625ef0000bb"] }";
    String appSecret = "1452fcebae9f3115ba794fb0fff2fd73";

            Mac mac;
            mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signatureBytes = mac.doFinal(stringToSign.getBytes("UTF-8"));
    
            String hexStr = Hex.encodeHexString(signatureBytes);
            String signature = Base64.encodeBase64String(hexStr.getBytes());
    
            System.out.println(signature);
        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    }
    :::
    ::: Golang go
    import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
    "testing"
    )

    func TestSign(t *testing.T) {
    requestBody := "15653147891500001048{"audience_type": "account","platform": "android","message": {"title": "test title","content": "test content","android": { "action": {"action_type": 3,"intent": "xgscheme://com.xg.push/notify_detail?param1=xg"}}},"message_type": "notify","account_list": ["5822f0eee44c3625ef0000bb"] }"
    secretKey := "1452fcebae9f3115ba794fb0fff2fd73"

    h := hmac.New(sha256.New, []byte(secretKey))
    h.Write([]byte(requestBody))
    sha := hex.EncodeToString(h.Sum(nil))
    sign := base64.StdEncoding.EncodeToString([]byte(sha))
    println(sign)
    }
    :::
    ::: C# c#
    using System;
    using System.Security.Cryptography;
    using System.Text;

    namespace tpns_server_sdk_cs
    {
    class GenSign {

        // Main Method 
        // static public void Main(String[] args)
        // {
        //     string reqBody =
        //         "{\"audience_type\": \"account\",\"platform\": \"android\",\"message\": {\"title\": \"test title\",\"content\": \"test content\",\"android\": { \"action\": {\"action_type\": 3,\"intent\": \"xgscheme://com.xg.push/notify_detail?param1=xg\"}}},\"message_type\": \"notify\",\"account_list\": [\"5822f0eee44c3625ef0000bb\"] }";
        //     string genSign = GenSign.genSign("1565314789", "1500001048", "reqBody", "1452fcebae9f3115ba794fb0fff2fd73");
        //     Console.WriteLine(genSign);
        // } 
        public static string HmacSHA256(string key, string data)
        {
            string hash;
            ASCIIEncoding encoder = new ASCIIEncoding();
            Byte[] code = encoder.GetBytes(key);
            using (HMACSHA256 hmac = new HMACSHA256(code))
            {
                Byte[] hmBytes = hmac.ComputeHash(encoder.GetBytes(data));
                hash = ToHexString(hmBytes);
            }
            return hash;
        }
    
        public static string ToHexString(byte[] array)
        {
            StringBuilder hex = new StringBuilder(array.Length * 2);
            foreach (byte b in array)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            return hex.ToString();
        }
    
        public static string genSign(string timeStampStr, string accessId, string requestBody, string keySecret)
        {
            string data = timeStampStr + accessId + requestBody;
            string hash = HmacSHA256(keySecret, data);
            string sign = Base64Encode(hash);
            Console.WriteLine("timeStampStr: "  + timeStampStr + " accessId:" + accessId + " requestBody" + requestBody + " keySecret:" + keySecret);
            return sign;
        }
    
        public static string Base64Encode(string plainText) {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }
    }

    }
    :::
    ::: PHP php

    <?php
    $accessId = "1500001048";
    $secretKey = "1452fcebae9f3115ba794fb0fff2fd73";
    $timeStamp = "1565314789";
    $requestBody = "{\"audience_type\": \"account\",\"platform\": \"android\",\"message\": {\"title\": \"test title\",\"content\": \"test content\",\"android\": { \"action\": {\"action_type\": 3,\"intent\": \"xgscheme://com.xg.push/notify_detail?param1=xg\"}}},\"message_type\": \"notify\",\"account_list\": [\"5822f0eee44c3625ef0000bb\"] }";
    $hashData = "{$timeStamp}{$accessId}{$requestBody}";
    echo "reqBody: " . $hashData . "\n";
    //获取 sha256 and hex 结果
    $hashRes = hash_hmac("sha256", $hashData, $secretKey, false);
    //进行 base64
    $sign = base64_encode($hashRes);
    echo $sign . "\n";
    ?>

    :::

    Was this page helpful?

    本页内容是否解决了您的问题?

    • 完全没帮助
    • 文档较差
    • 文档一般
    • 文档不错
    • 文档很好
    反馈
    帮助