Upload certificate generation algorithm

  1. Constructing an upload policy
PutPolicy = {scope: 'my-bucket', returnBody: '{"key": putPolicy = {scope: 'my-bucket', returnBody: '{"key": $(key)}' };Copy the code
  1. Serialize the upload policy to JSON
putPolicy = JSON.stringify(putPolicy);
Copy the code
  1. The URL – safe Base64 encoding is performed on the JSON-encoded upload policy to obtain the character string to be signed

Url-safe Base64 encoding: The first step is to encode the content as a string in Base64 format. The second step is to check the resulting string by replacing the plus sign (+) in the string with the hyphen – and the slash/with the underscore _.

EncodedPutPolicy = urlSafe_base64_encode (putPolicy) // Qiniu/js-SDK provides urlSafeBase64Encode method // import qiniu from "qiniu-js/dist/qiniu.min.js"; // qiniu.urlSafeBase64Encod(putPolicy);Copy the code
  1. Use the access key (AK/SK) to calculate the HMAC-SHA1 signature on the string generated in the previous step
Sign = hmac_sha1(encodedPutPolicy, "<SecretKey>") // function hmacSha1(encodedFlags, secretKey) { // return CryptoES.HmacSHA1(encodedFlags, secretKey).toString(CryptoES.enc.Base64); // } // hmacSha1(encodedPutPolicy, "<SecretKey>");Copy the code
  1. Base64 urL-safe encoding for signatures
EncodedSign = urlsafe_base64_encode(sign) encodedSign = urlsafe_base64_encode(sign) And will slash/with an underscore _ / / function base64ToUrlSafe (v) {/ / return v.r eplace (/ / / / g, '_'). The replace (/ \ + / g, '-'); // } // base64ToUrlSafe(sign);Copy the code
  1. Concatenate the access key (Ak/SK), encodedSign, and encodedPutPolicy with the English symbol:
uploadToken = AccessKey + ':' + encodedSign + ':' + encodedPutPolicy
Copy the code

It is mentioned in the document that the third and fifth steps both involve THE Base64 encoding of URL security. The basic process of this encoding mode is divided into two steps as mentioned above, but the source code shows that the third step uses one and two steps, but the fifth step only uses the second step:

PutPolicy.prototype.uploadToken = function (mac) {
    mac = mac || new digest.Mac();
    var flags = this.getFlags();
    // urlsafeBase64Encode
    var encodedFlags = util.urlsafeBase64Encode(JSON.stringify(flags));
    var encoded = util.hmacSha1(encodedFlags, mac.secretKey);
    // base64ToUrlSafe
    var encodedSign = util.base64ToUrlSafe(encoded);
    var uploadToken = mac.accessKey + ':' + encodedSign + ':' + encodedFlags;
    return uploadToken;
};
Copy the code
exports.base64ToUrlSafe = function (v) {
    return v.replace(/\//g, '_').replace(/\+/g, '-');
};

// UrlSafe Base64 Decode
exports.urlsafeBase64Encode = function (jsonFlags) {
    var encoded = Buffer.from(jsonFlags).toString('base64');
    return exports.base64ToUrlSafe(encoded);
};
Copy the code