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87asp1wdb6lD9snvLZix1UGK7VQg6
wUFYNlMqJh1m7ITVvzhjdnx7EzCKkBXSxEom4mwbvSNvzqOKAWsDE0gvHQ9aCSby
NFBQQMoW94LqrG/kuIQtjwVdZA==
-----END NEW CERTIFICATE REQUEST-----

How to decode it to plaintext like

Certificate information

  • Common name: www.somedomain.com
  • Organization:someorg.com
  • Organizational unit:someunit.com
  • City/locality:bj
  • State/province:bj
  • Country:CN

问题评论:

    
Luckily, Ruby comes with an OpenSSL module which wraps the OpenSSL library.
    
RubyOpenSSL can generate CSR, but there is no decoding method there.
– Igor Polyakov
7 hours ago
    
What about OpenSSL::X509::Request.new(your_request_data)?
    
Thank you very much! This solved my problem. P.S. OpenSSL::X509::Request.new(File.open("/my/file.csr").read)
– Igor Polyakov
6 hours ago
    
That will leave you with an open file handle, use File.read('/my/file.csr') instead.

答案:

答案1:

  def parse_csr(file_path)
    csr = OpenSSL::X509::Request.new(File.read(file_path))
    # puts csr.subject.to_a
    # => [["C", "RU", 19], ["ST", "State", 12], ["L", "City", 12], ["O", "CompanyName", 12], ["OU", "Unit", 12], ["CN", "App 1.0", 12], ["emailAddress", "user@company.com", 22]]
    csr.subject.to_a.inject({}) do |r, s|
      r.merge!(s[0] => s[1])
    end
  end

Output:

=> {"C"=>"RU", "ST"=>"State", "L"=>"City", "O"=>"Company Name", "OU"=>"Unit", "CN"=>"App v1.0", "emailAddress"=>"user@company.com"}

答案评论:

    
Slightly shorter: subject.to_a.each(&:pop).to_h

原文地址:

https://stackoverflow.com/questions/47748640/how-to-decode-csr-using-ruby

添加评论