[英]Hmac sha1 and base 64 encoding in dart
I am trying to produce oauth_signature to use Fatsecret API, but getting an invalid signature error.我正在尝试生成 oauth_signature 以使用 Fatsecret API,但收到无效签名错误。
To create oauth_signature value the Documentation says:要创建 oauth_signature 值,文档说:
Use the HMAC-SHA1 signature algorithm as defined by the [RFC2104] to sign the request where text is the Signature Base String and key is the concatenated values of the Consumer Secret and Access Secret separated by a '&' character (show '&' even if Access Secret is empty as some methods do not require an Access Token).
使用 [RFC2104] 定义的 HMAC-SHA1 签名算法对请求进行签名,其中 text 是签名基本字符串,key 是由“&”字符分隔的 Consumer Secret 和 Access Secret 的串联值(显示 '&'即使访问密钥为空,因为某些方法不需要访问令牌)。
The calculated digest octet string, first base64-encoded per [RFC2045], then escaped using the [RFC3986] percent-encoding (%xx) mechanism is the oauth_signature.计算的摘要八位字节字符串,首先根据 [RFC2045] 进行 base64 编码,然后使用 [RFC3986] 百分比编码 (%xx) 机制进行转义,即 oauth_signature。
Following code is used to generate the signature以下代码用于生成签名
String _generateSignature(String method, String url, Map<String, String> params) {
// sort the parameters
var sortedParams = SplayTreeMap.from(params);
// Concatenate the sortedParams with '&'
String concatenatedParams = sortedParams.keys.map((key) {
return '$key=${sortedParams[key]}';
}).join('&');
// encode the sorted and concatenated params string
var encodedParams = Uri.encodeComponent(concatenatedParams);
var encodedUrl = Uri.encodeComponent(url);
String baseString = '$method&$encodedUrl&$encodedParams';
print(baseString);
String signingKey = '${Uri.encodeComponent(SHARED_SECRET)}&';
var hmac = Hmac(sha1, signingKey.codeUnits);
return base64Encode(hmac.convert(baseString.codeUnits).bytes);
}
When I make API call, it returns当我进行 API 调用时,它返回
11-12 09:52:45.924 15525-15612/com.example.delete I/flutter: {error: {code: 8, message: Invalid signature: oauth_signature 'y81+JIzX/P+xNqOCYLgbrMtDV2I='}}
Please help me, guys...I am stuck at this for weeks!请帮帮我,伙计们......我被困在这几个星期!
If i modify the code like below then i am not getting any Invalid signature
error.如果我修改如下代码,则不会收到任何
Invalid signature
错误。
String _generateSignature(String method, String url, Map<String, dynamic> params) {
// Sort the parameters
var sortedParams = SplayTreeMap.from(params);
// Concatenate the sortedParams with '&'
String concatenatedParams = sortedParams.keys.map((key) {
return '$key=${sortedParams[key]}';
}).join('&');
// encode the sorted and concatenated params string
var encodedParams = Uri.encodeComponent(concatenatedParams);
var encodedUrl = Uri.encodeComponent(url);
String baseString = '$method&$encodedUrl&$encodedParams';
String signingKey = '${Uri.encodeComponent(SHARED_SECRET)}&';
var hmac = Hmac(sha1, signingKey.codeUnits);
return Uri.encodeComponent(base64Encode(hmac.convert(baseString.codeUnits).bytes));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.