我想知道如何在 ruby 中生成 hmac-sha1 哈希,就像在 iOS 中生成一样。到目前为止,来自 iOS 的哈希值与通过 Ruby 生成的哈希值不匹配。 这是为了对通过 iOS 应用程序和 Web 应用程序提供用户名和密码的用户进行身份验证。
到目前为止我已经:
iOS 代码
+ (NSString *)hmacsha1:(NSString *)text key:(NSString *)secret {
NSData *secretData = [secret dataUsingEncoding:NSUTF8StringEncoding];
NSData *clearTextData = [text dataUsingEncoding:NSUTF8StringEncoding];
unsigned char result[20];
CCHmac(kCCHmacAlgSHA1, [secretData bytes], [secretData length], [clearTextData bytes], [clearTextData length], result);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", result[i]];
return output;
}
Ruby 代码
def self.signature(base_string, consumer_secret=HOST_KEY)
require "base64"
digest = OpenSSL::Digest.new('sha1')
hmac = OpenSSL::HMAC.digest(digest, consumer_secret, base_string)
hmac = Base64.encode64(hmac)
xx_log("SIGNATURE", hmac)
return hmac
end
在 Ruby 中调用函数
string_for_hash = params[:username].to_s.downcase + ' ' + params[:password].to_s
params[:hash] = ApiKey.signature(string_for_hash)
提前致谢。
最佳答案
解决方案
结果应该与通用 hmac sha1 转换匹配。无需翻译iOS代码。
def hmac_sha1(data, secret=HOST_KEY)
require 'base64'
require 'cgi'
require 'openssl'
hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha1'), secret.encode("ASCII"), data.encode("ASCII"))
return hmac
end
关于ios - 如何将 iOS 函数转换为 Ruby。生成 hmac-sha1 哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22520004/