【问题标题】:How can I safely read a PKCS12 and pass it to an object in ruby?如何安全地读取 PKCS12 并将其传递给 ruby​​ 中的对象?
【发布时间】:2013-11-28 00:34:20
【问题描述】:

我目前正在使用 google api 客户端 gem 与 google api 进行通信。它使用 PKCS12 对这些服务进行身份验证,并使用 OpenSSL::PKCS12.new

http://www.ruby-doc.org/stdlib-2.0/libdoc/openssl/rdoc/OpenSSL/PKCS12.html

但是,当我使用 File.read 读取文件并尝试传递字符串时,我得到 String 有一个空字节错误。我怎样才能避免这种情况并确保它仍然为 PKCS12 类进行 DER 编码?

【问题讨论】:

  • @JamesMcMahon,你能发布失败的代码吗?

标签: ruby ssl encoding openssl pkcs#12


【解决方案1】:
require 'openssl'

p12 = OpenSSL::PKCS12.new(File.read('/path/to/p12'), "pass_phrase")
key = p12.key
certificate = p12.certificate

【讨论】:

    【解决方案2】:

    我在发布关于这个问题的赏金后不久就发现了这一点。 这个问题In ruby, how do I get the subject, issuer etc. after creating an OpenSSL PKCS12 object 在提出这个解决方案时很有用。

    OpenSSL::PKCS12::new 将抛出异常,如果字符串不是有效的 DER 编码字符串或密码不正确。

    这是我为我的模型编写的验证器,

    def valid_pkcs12_file
      begin
        test = OpenSSL::PKCS12::new(pkcs12_file.read, password)
      rescue Exception => e
        Rails.logger.warn "pkcs12 error #{e.message}"
        errors.add(:pkcs12_file, 'invalid pkcs12 file or password')
      ensure
        pkcs12_file.rewind
      end
    end 
    

    如果有人有更优雅的方法,我愿意接受建议。

    【讨论】:

      【解决方案3】:

      使用Google::APIClient::KeyUtils.load_from_pkcs12 而不是OpenSSL::PKCS12.new。它将返回一个OpenSSL::PKey::RSA 实例。

      如果文件无效或密码错误,load_from_pkcs12 将引发 ArgumentError: Invalid keyfile or passphrase

      来自README

      key = Google::APIClient::KeyUtils.load_from_pkcs12('client.p12', 'notasecret')
      # and so on
      

      (使用 ruby​​-2.1.0 测试)

      【讨论】:

      • 您将如何使用该方法检查文件的有效性?
      • @JamesMcMahon 我已经更新了我的答案。希望有帮助吗?
      • 谢谢,但我想我会使用我建议的答案来避免导入另一个 gem。
      • 我使用了 Google-Gem,因为原始问题提到了这一点。当然,如果您不使用 Google-API-Client gem,那么使用它是没有意义的......
      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      相关资源
      最近更新 更多