ios - 如何将 iOS 函数转换为 Ruby。生成 hmac-sha1 哈希值?

标签 ios ruby-on-rails ruby xcode

我想知道如何在 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/

相关文章:

java - API 和 Web 服务有什么区别?

ruby - Redis流水线执行顺序

ruby-on-rails - 将应用程序 Controller 方法传递给邮件程序

ruby - 无法使用 Sketchup Ruby API 获取 Sketchup 模型的位置范围

ios - 无法识别的选择器/连接 View Controller

ios - UITextView 中包含新行的排除路径不正确

ios - iPad map 上的神秘绿色叠加层

ios - 在 iphone 应用程序中调用 exit(0)

sql - 按任意时间间隔计算行数的最佳方法

javascript - 在 Javascript 重定向中包含 HTTP 方法?