关于BAE云存储的签名算法(Nodejs相关问题)
关于BAE云存储的签名算法(Nodejs相关问题)
最近使用BAE的时候需要往云存储上传文件,这需要提供签名串。
官方文档给出的PHP签名算法如下:
Signture = urlencode(base64_encode(hash_hmac('sha1', Content, SecretKey,true)))
Node.js下我尝试这样实现:
hash = require('crypto').createHmac('sha1', SecrectKey).update(content).digest('hex')
Signture = (new Buffer(hash)).toString('base64')
可是计算的结果跟BAE控制台给出的结果完全不同,请问该怎么写?
关于BAE云存储的签名算法(Node.js相关问题)
最近我在使用BAE时需要向云存储上传文件,这需要提供一个签名串。官方文档给出了一个PHP版本的签名算法,但我尝试将其转换为Node.js版本时遇到了一些问题。
官方文档给出的PHP签名算法
Signture = urlencode(base64_encode(hash_hmac('sha1', Content, SecretKey, true)))
Node.js实现
在Node.js中,我们可以使用crypto
模块来实现类似的签名算法。以下是具体的实现步骤:
- 使用
crypto.createHmac
创建一个HMAC对象。 - 使用
update
方法更新数据。 - 使用
digest
方法生成签名,并将其编码为Base64格式。 - 对结果进行URL编码。
下面是完整的Node.js代码示例:
const crypto = require('crypto');
function generateSignature(content, secretKey) {
// 创建HMAC对象
const hmac = crypto.createHmac('sha1', secretKey);
// 更新数据
hmac.update(content);
// 生成签名并转为Base64格式
const signature = hmac.digest('base64');
// 对结果进行URL编码
return encodeURIComponent(signature);
}
// 示例
const content = 'exampleContent';
const secretKey = 'yourSecretKey';
const signature = generateSignature(content, secretKey);
console.log(signature); // 输出签名串
解释
crypto.createHmac('sha1', secretKey)
:创建一个基于SHA1的HMAC对象,并使用提供的密钥。hmac.update(content)
:将待签名的数据添加到HMAC对象中。hmac.digest('base64')
:生成签名并将其编码为Base64格式。encodeURIComponent(signature)
:对Base64编码后的签名进行URL编码,以符合BAE的要求。
通过上述代码,你应该能够得到与BAE控制台一致的签名串。如果仍然有差异,请确保content
和secretKey
的值与BAE预期的一致。
对了,谢谢。另外发现一个有趣的现象,谁能讲讲下面3种方式的差异吗?
hmac = require('crypto').createHmac('sha1', SecrectKey).update(content)
//test 1
hash = hmac.digest(‘hex’)
Signture = (new Buffer(hash)).toString(‘base64’)
//test 2
hash = hmac.digest(‘binary’)
Signture = (hash).toString(‘base64’)
//test 3
hash = hmac.digest()// output as buffer
Signture = (hash).toString(‘base64’)
在Node.js中实现与BAE云存储所需的签名算法时,需要确保每个步骤都严格遵循BAE提供的算法。你的尝试中有一些细节上的差异,特别是关于hash_hmac
函数的输出格式以及Base64编码后的处理。
示例代码
const crypto = require('crypto');
function generateSignature(content, secretKey) {
// 使用SHA1和HMAC创建哈希值,并指定二进制输出true
const hash = crypto.createHmac('sha1', secretKey).update(content).digest(true);
// 将哈希值进行Base64编码
const base64EncodedHash = Buffer.from(hash).toString('base64');
// 对Base64编码后的字符串进行URL编码
const signature = encodeURIComponent(base64EncodedHash);
return signature;
}
// 示例调用
const content = 'your_content_here';
const secretKey = 'your_secret_key_here';
const signature = generateSignature(content, secretKey);
console.log(signature);
解释
-
创建HMAC哈希:
crypto.createHmac('sha1', secretKey)
创建一个基于SHA-1的HMAC对象。.update(content)
更新哈希上下文以包含输入内容。.digest(true)
计算哈希值并返回一个Buffer对象。这里的关键是传递true
参数来指示返回二进制格式而不是十六进制格式。
-
Base64编码:
- 使用
Buffer.from(hash).toString('base64')
将二进制数据转换为Base64编码的字符串。
- 使用
-
URL编码:
- 使用
encodeURIComponent
对Base64编码后的字符串进行URL编码。
- 使用
通过这种方式,可以确保生成的签名与BAE云存储所期望的格式一致。