前端调用腾讯文字翻译接口

gg22g2

起因是我在浏览器上安装了一个叫做网页翻译助手的油猴脚本,但只有百度,谷歌,有道的接口。我感觉腾讯翻译的结果也不错,就像自己加上去。

跟着官方文档一通操作,终于是把请求写出来了,但是有个问题,就是签名需要使用TC3-HMAC-SHA256算法。因为脚本不想要链接外部js的加密库,就像看一下标准api里边是否有相关功能。
虽然过程很艰难,但是最总还是找到了解决方法。

以下是计算签名部分代码

 //字符串转为字节输入
    const getUtf8Bytes = msg =>
        new Uint8Array(
            [...unescape(encodeURIComponent(msg))].map(c => c.charCodeAt(0))
        );

    /**
     *
     * */
    async function HMAC_SHA256(keyBuffer, msg) {

        const messageBuffer = getUtf8Bytes(msg);
        const cryptoKey = await crypto.subtle.importKey(
            "raw", keyBuffer, {name: "HMAC", hash: {name: "SHA-256"}},
            true, ["sign"]
        );

        let hashArray = await window.crypto.subtle.sign(
            "HMAC",
            cryptoKey,
            messageBuffer
        );
        return hashArray;
    }

    function HexEncode(hashBuffer) {
        const hashArray = Array.from(new Uint8Array(hashBuffer));                     // convert buffer to byte array
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
        return hashHex;
    }

    async function SHA256(str) {
        const msgUint8 = new TextEncoder().encode(str);                           // encode as (utf-8) Uint8Array
        const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);           // hash the message
        return hashBuffer;
    }

    /**
     * payload : json请求体
     * timeStamp 时间戳
     * dateStr 年月日
     * SecretKey 
     * 
     * */
    async function calSignature(payload, timeStamp, dateStr, SecretKey) {
        // 拼接规范请求串过程
        let HTTPRequestMethod = "POST";
        let CanonicalURI = '/';
        let CanonicalQueryString = '';
        let CanonicalHeaders = 'content-type:application/json\nhost:tmt.tencentcloudapi.com\n';
        let SignedHeaders = 'content-type;host';

        //Lowercase(HexEncode(Hash.SHA256(RequestPayload))) 根据payload 生成HashedRequestPayload。 做SHA256哈希,然后十六进制编码,最后编码串转换成小写字母
        let HashedRequestPayload = HexEncode(await SHA256(JSON.stringify(payload))).toLowerCase();

        //规范请求串
        let CanonicalRequest = HTTPRequestMethod + '\n' + CanonicalURI + '\n' + CanonicalQueryString + '\n' + CanonicalHeaders + '\n' + SignedHeaders + '\n' + HashedRequestPayload;

        // 拼接待签名字符串过程
        // Lowercase(HexEncode(Hash.SHA256(CanonicalRequest)))
        let HashedCanonicalRequest = HexEncode(await SHA256(CanonicalRequest)).toLowerCase();

        let StringToSign = 'TC3-HMAC-SHA256\n' + timeStamp + '\n' + dateStr + '/tmt/tc3_request\n' + HashedCanonicalRequest

        let SecretDate = await HMAC_SHA256(getUtf8Bytes("TC3" + SecretKey), dateStr)
        let SecretService = await HMAC_SHA256(SecretDate, 'tmt')
        let SecretSigning = await HMAC_SHA256(SecretService, "tc3_request")
        let Signature = HexEncode(await HMAC_SHA256(SecretSigning, StringToSign))
        return Signature;
    }
    
    async function test() {
        let payload = {
            "SourceText": "hello",
            "Source": "auto",
            "Target": "zh",
            "ProjectId": 0
        };
        let timeStamp = 1619350841;
        let dateStr = '2021-04-25';
        //这个SecretKey是随便写的
        let SecretKey = 'mNRRUdaaaPeidRp6Bbbb8WmqcccuzsYF';
        let result = await calSignature(payload, timeStamp, dateStr, SecretKey);
        console.log(result)
    }
阅读 825
228 声望
5 粉丝
0 条评论
你知道吗?

228 声望
5 粉丝
文章目录
宣传栏