HART SHA1和DART Base 64编码 [英] Hmac sha1 and base 64 encoding in dart
问题描述
我正在尝试生成oauth_signature以使用Fatsecret API,但出现无效的签名错误。
I am trying to produce oauth_signature to use Fatsecret API, but getting an invalid signature error.
要创建oauth_signature值,文档中会显示:
To create oauth_signature value the Documentation says:
使用[RFC2104]定义的HMAC-SHA1签名算法对请求进行签名,其中text是Signature Base String,key是Consumer的连接值机密和访问机密由'&'字符分隔(即使访问机密为空,因为某些方法不需要访问令牌也显示&)。
计算的摘要八位字节串,第一个base64 [RFC2045]-编码,然后使用[RFC3986]百分比编码(%xx)机制进行转义的是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).
The calculated digest octet string, first base64-encoded per [RFC2045], then escaped using the [RFC3986] percent-encoding (%xx) mechanism is the oauth_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);
}
当我进行API调用时,它会返回
When I make API call, it returns
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='}}
请大家帮帮我...
推荐答案
如果我像下面那样修改代码,那么我就不会得到任何无效的签名
错误。
If i modify the code like below then i am not getting any Invalid signature
error.
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));
}
这篇关于HART SHA1和DART Base 64编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!