Java 签名示例
import sun.misc.BASE64Encoder;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.net.URLEncoder;import java.util.HashMap;import java.util.Map;import java.util.Random;public class CmeSign {public static void main(String[] args) throws Exception {Long currentTime = System.currentTimeMillis() / 1000;Integer random = new Random().nextInt(java.lang.Integer.MAX_VALUE);Long expireTime = currentTime + 5 * 60; // 5分钟有效HashMap<String, String> paramMap = new HashMap<String, String>();// 必填参数paramMap.put("secretId", "Your SecretId");paramMap.put("currentTimeStamp", currentTime.toString());paramMap.put("random", random.toString());paramMap.put("expireTime", expireTime.toString());paramMap.put("platform", "Your Platform");paramMap.put("userId", "Your UserId");paramMap.put("action", "OpenProject"); // 可选值:OpenProject、Upload// 选填参数paramMap.put("openProject.projectId", "Your ProjectId"); // action=OpenProject时必填String secretKey = "Your SecretKey";String original = urlEncodeUTF8(paramMap);Mac mac = Mac.getInstance("HmacSHA1");SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());mac.init(keySpec);byte[] hash = mac.doFinal(original.getBytes("UTF-8"));byte[] signBuffer = byteMerger(hash, original.getBytes("UTF-8"));String sign = new String(new BASE64Encoder().encode(signBuffer).getBytes());sign = sign.replace(" ", "").replace("\\n", "").replace("\\r", "");System.out.println(sign);}private static byte[] byteMerger(byte[] byte1, byte[] byte2) {byte[] byte3 = new byte[byte1.length + byte2.length];System.arraycopy(byte1, 0, byte3, 0, byte1.length);System.arraycopy(byte2, 0, byte3, byte1.length, byte2.length);return byte3;}private static String urlEncodeUTF8(Map<String, String> map) throws Exception {StringBuilder sb = new StringBuilder();for (Map.Entry<String, String> entry : map.entrySet()) {if (sb.length() > 0) {sb.append("&");}sb.append(String.format("%s=%s",URLEncoder.encode(entry.getKey(), "UTF-8"),URLEncoder.encode(entry.getValue(), "UTF-8")));}return sb.toString();}}
Go 签名示例
package mainimport ("crypto/hmac""crypto/sha1""encoding/base64""fmt""math/rand""net/url""strconv""time")func main() {secretId := "Your SecretId"secretKey := "Your SecretKey"platform := "Your Platform"userId := "Your UserId"currentTime := time.Now().Unix()expireTime := currentTime + 5 * 60 // 签名有效期:5分钟rand.Seed(time.Now().Unix())random := rand.Uint32()values := url.Values{}values.Add("secretId", secretId)values.Add("currentTimeStamp", strconv.FormatInt(currentTime, 10))values.Add("expireTime", strconv.FormatInt(expireTime, 10))values.Add("random", strconv.Itoa(int(random)))values.Add("platform", platform)values.Add("action", "OpenProject") // 可选值:OpenProject、Uploadvalues.Add("openProject.projectId", "Your ProjectId") // action=OpenProject时必填values.Add("userId", userId)queryStr := values.Encode()mac := hmac.New(sha1.New, []byte(secretKey))mac.Write([]byte(queryStr))macBuffer := mac.Sum(nil)origin := string(macBuffer) + queryStrsignature := base64.StdEncoding.EncodeToString([]byte(origin))fmt.Println(signature)}
Python 签名示例
#!/usr/local/bin/python3#coding=utf-8import timeimport randomimport hmacimport hashlibimport base64from urllib.parse import urlencode# 确定签名的当前时间和失效时间currentTime = int(time.time())expireTime = currentTime + 5 * 60 # 签名有效期:5分钟# 参数argList = {"secretId" : "Your SecretId","currentTimeStamp" : currentTime,"expireTime" : expireTime,"random" : random.randint(0, 999999),"platform": "Your Platform","userId": "Your UserId","action": "OpenProject", # 可选值:OpenProject、Upload"openProject.projectId": "Your ProjectId" # 可选参数,action=OpenProject时必填}secretKey = "Your SecretKey"# 计算签名original = urlencode(argList)secretKeyHmac = hmac.new(bytes(secretKey, 'utf-8'), bytes(original, 'utf-8'), hashlib.sha1)secretKeySha = secretKeyHmac.digest()signTemp = bytes(secretKeySha) + bytes(original, 'utf-8')sign = base64.b64encode(signTemp)print("sign: ", sign)
PHP 签名示例
<?php// 确定签名的当前时间和失效时间$currentTime = time();$expireTime = $currentTime + 5 * 60; // 签名有效期:5分钟// 必填参数$arg_list = array("secretId" => "Your SecretId","currentTimeStamp" => $currentTime,"expireTime" => $expireTime,"random" => rand(),"platform" => "Your Platform","userId" => "Your UserId","action" => "OpenProject" // 可选值:OpenProject、Upload);// 选填参数$arg_list["openProject.projectId"] = "Your ProjectId";$secretKey = "Your SecretKey";// 计算签名$original = http_build_query($arg_list);$signature = base64_encode(hash_hmac('SHA1', $original, $secretKey, true).$original);echo $signature;
Node.js 签名示例
var querystring = require("querystring");var crypto = require('crypto');// 确定签名的当前时间和失效时间var currentTime = parseInt((new Date()).getTime() / 1000);var expireTime = currentTime + 5 * 60; // 签名有效期:5分钟// 必填参数var arg_list = {secretId : "Your SecretId",currentTimeStamp : currentTime,expireTime : expireTime,random : Math.round(Math.random() * Math.pow(2, 32)),platform: "Your Platform",userId: "Your UserId",action: "OpenProject" // 可选值:OpenProject、Upload};// 可选参数arg_list["openProject.projectId"] = "Your PorjectId";var secretKey = "Your SecretKey";// 计算签名var orignal = querystring.stringify(arg_list);var orignal_buffer = Buffer.from(orignal, "utf8");var hmac = crypto.createHmac("sha1", secretKey);var hmac_buffer = hmac.update(orignal_buffer).digest();var sign = Buffer.concat([hmac_buffer, orignal_buffer]).toString("base64");console.log(sign);