腾讯云接口调用签名鉴权

介绍

调用腾讯云接口需要很多公共参数,这些参数需要自己实现,有两种方法,一个是集成腾讯的SDK,直接引用jar包中的方法,一种是自己实现;
目前采用自己实现的方式,因为腾讯的SDK是一个工具包,东西太多了,并不适合继承到项目中,可能你需要的只是其中的一个class。
参数

方法一:集成SDK

集成后直接调用。

<dependency>
     <groupId>com.tencentcloudapi</groupId>
     <artifactId>tencentcloud-sdk-java</artifactId>
     <version>3.0.8</version><!-- 注:这里只是示例版本号,请到 https://mvnrepository.com/artifact/com.tencentcloudapi/tencentcloud-sdk-java 获取最新版本号 -->
</dependency>
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import com.tencentcloudapi.asr.v20190614.AsrClient;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionRequest;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionResponse;

public class SentenceRecognition
{
    public static void main(String [] args) throws IOException {
         // 采用语音URL方式调用
        try{
              //重要:<Your SecretId>、<Your SecretKey>需要替换成用户自己的账号信息
              //请参考接口说明中的使用步骤1进行获取。 
            Credential cred = new Credential("Your SecretId", "Your SecretKey");

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("asr.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);            

            AsrClient client = new AsrClient(cred, "ap-shanghai", clientProfile);

            String params = "{\"ProjectId\":0,\"SubServiceType\":2,\"EngSerViceType\":\"16k\",\"SourceType\":0,\"Url\":\"https://ruskin-1256085166.cos.ap-guangzhou.myqcloud.com/test.wav\",\"VoiceFormat\":\"wav\",\"UsrAudioKey\":\"session-123\"}";
            SentenceRecognitionRequest req = SentenceRecognitionRequest.fromJsonString(params, SentenceRecognitionRequest.class);

            SentenceRecognitionResponse resp = client.SentenceRecognition(req);

            System.out.println(SentenceRecognitionRequest.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
                System.out.println(e.toString());
        }
    }

}

方法二:自己开发

自己开发其实只需要几个核心的方法转换。

public class TencentCloudVoiceUtil {
    private final static String CHARSET = "UTF-8";

    public static String sign(String s, String key, String method) throws Exception {
        Mac mac = Mac.getInstance(method);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(CHARSET), mac.getAlgorithm());
        mac.init(secretKeySpec);
        byte[] hash = mac.doFinal(s.getBytes(CHARSET));
        return DatatypeConverter.printBase64Binary(hash);
    }

    public static String getStringToSign(TreeMap<String, Object> params) {
        StringBuilder s2s = new StringBuilder("GETasr.tencentcloudapi.com/?");
        // 签名时要求对参数进行字典排序,此处用TreeMap保证顺序
        for (String k : params.keySet()) {
            s2s.append(k).append("=").append(params.get(k).toString()).append("&");
        }
        return s2s.toString().substring(0, s2s.length() - 1);
    }

    public static String getUrl(TreeMap<String, Object> params) throws UnsupportedEncodingException {
        StringBuilder url = new StringBuilder("https://asr.tencentcloudapi.com/?");
        // 实际请求的url中对参数顺序没有要求
        for (String k : params.keySet()) {
            // 需要对请求串进行urlencode,由于key都是英文字母,故此处仅对其value进行urlencode
            url.append(k).append("=").append(URLEncoder.encode(params.get(k).toString(), CHARSET)).append("&");
        }
        return url.toString().substring(0, url.length() - 1);
    }

    public static void main(String[] args) throws Exception {
        TreeMap<String, Object> params = new TreeMap<String, Object>(); // TreeMap可以自动排序
        // 公共参数
        params.put("Nonce", new Random().nextInt(Integer.MAX_VALUE));
        params.put("Timestamp", System.currentTimeMillis() / 1000);
        params.put("SecretId", "SecretId");
        params.put("Action", "SentenceRecognition");
        params.put("Version", "2019-06-14");
        params.put("Region", "ap-shanghai");
        // 业务参数
        params.put("ProjectId", 0);
        params.put("SubServiceType", 2);
        params.put("EngSerViceType", "16k");
        params.put("SourceType", 0);
        params.put("VoiceFormat", "wav");
        params.put("UsrAudioKey", "www111");
        params.put("Url", "https://ruskin-1256085166.cos.ap-guangzhou.myqcloud.com/test.wav");
        // 公共参数
        params.put("Signature", sign(getStringToSign(params), "Key", "HmacSHA1"));
        System.out.println(getUrl(params));
        String s = HttpUtil.get(getUrl(params));
        System.out.println(s);

    }
}

附:加密规则

加密规则这里腾讯的都是差不多的,很多大厂也都是这么用的。这里参考腾讯支付加密介绍
地址
签名生成的通用步骤如下:
第一步,设所有发送或者接收到的数据为集合M,将集合M内非空参数值的参数按照参数名ASCII码从小到大排序(字典序),使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串stringA。
特别注意以下重要规则:

  1. ◆ 参数名ASCII码从小到大排序(字典序);
  2. ◆ 如果参数的值为空不参与签名;
  3. ◆ 参数名区分大小写;
  4. ◆ 验证调用返回或微信主动通知签名时,传送的sign参数不参与签名,将生成的签名与该sign值作校验。
  5. ◆ 微信接口可能增加字段,验证签名时必须支持增加的扩展字段

第二步,在stringA最后拼接上key得到stringSignTemp字符串,并对stringSignTemp进行MD5运算,再将得到的字符串所有字符转换为大写,得到sign值signValue。
◆ key设置路径:微信商户平台(pay.weixin.qq.com)–>账户设置–>API安全–>密钥设置

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个使用 PHP 调用腾讯云对象存储 API 接口生成签名的示例代码: ```php $secretId = "你的 SecretId"; $secretKey = "你的 SecretKey"; $bucket = "你的存储桶名称"; $expired = time() + 3600; function getAuthorization($secretId, $secretKey, $bucket, $expired, $fileid = null) { $now = time(); $rdm = rand(); $plainText = "a=" . $secretId . "&b=" . $bucket . "&k=" . $secretKey . "&e=" . $expired . "&t=" . $now . "&r=" . $rdm . "&f="; if ($fileid !== null) { $plainText = "a=" . $secretId . "&b=" . $bucket . "&k=" . $secretKey . "&e=" . $expired . "&t=" . $now . "&r=" . $rdm . "&f=" . $fileid; } $bin = hash_hmac("SHA1", $plainText, $secretKey, true); $bin = $bin . $plainText; $sign = base64_encode($bin); return $sign; } $sign = getAuthorization($secretId, $secretKey, $bucket, $expired); echo $sign; ``` 在这个示例代码中,我们定义了一个 `getAuthorization()` 函数,它接收四个参数:SecretId、SecretKey、存储桶名称和过期时间。如果要访问特定的文件,还可以传递第五个参数,即文件 ID。 函数中,我们首先生成了一个随机数 `rdm` 和当前时间戳 `now`。然后,我们根据 API 接口要求的格式拼接了一个明文字符串 `plainText`,其中包含了 SecretId、存储桶名称、SecretKey、过期时间、随机数和文件 ID(如果有的话)。接着,我们使用 `hash_hmac()` 函数计算了 HMAC-SHA1 值,并将其与明文字符串拼接在一起,最后使用 `base64_encode()` 函数将其编码为 Base64 格式,得到了签名。最后,我们在示例代码的最后输出了签名。 使用示例: ```php $objectKey = "example.jpg"; $sign = getAuthorization($secretId, $secretKey, $bucket, $expired, $objectKey); echo $sign; ``` 这个示例代码将会输出一个字符串,即生成的签名,它可以用于调用腾讯云对象存储 API 接口

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值