如何在ruby中使用openssl生成csr和crt文件

时间:2017-11-01 18:55:36

标签: ruby amazon-web-services ssl certificate

所以我使用AWS Iot并在后端有一台服务器在rails上运行ruby。我需要为客户端生成一些证书,AWS网站上的示例仅提供了使用openssl命令行执行此操作的方法。如果可能的话,我想在ruby中使用open ssl库来避免在终端中发出可能导致问题的ruby run命令。
这些是我想用ruby复制的命令

openssl genrsa -out deviceCert.key 2048    

openssl req -new -key deviceCert.key -out deviceCert.csr    

openssl x509 -req -in deviceCert.csr -CA sampleCACertificate.pem -CAkey sampleCACertificate.key -CAcreateserial -out deviceCert.crt -days 99999 -sha256  

我找到的第一行并认为我能做到

require 'openssl'    
rsa_key = OpenSSL::PKey::RSA.new(2048)    

但是我坚持了最后两行。有任何想法吗?

2 个答案:

答案 0 :(得分:0)

以下是生成自签名证书的示例。

require 'rubygems'
require 'openssl'

key = OpenSSL::PKey::RSA.new(1024)
public_key = key.public_key

subject = "/C=BE/O=Test/OU=Test/CN=Test"

cert = OpenSSL::X509::Certificate.new
cert.subject = cert.issuer = OpenSSL::X509::Name.parse(subject)
cert.not_before = Time.now
cert.not_after = Time.now + 365 * 24 * 60 * 60
cert.public_key = public_key
cert.serial = 0x0
cert.version = 2

ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = cert
cert.extensions = [
  ef.create_extension("basicConstraints","CA:TRUE", true),
  ef.create_extension("subjectKeyIdentifier", "hash"),
  # ef.create_extension("keyUsage", "cRLSign,keyCertSign", true),
]
cert.add_extension ef.create_extension("authorityKeyIdentifier",
                                       "keyid:always,issuer:always")

cert.sign key, OpenSSL::Digest::SHA1.new

puts cert.to_pem

Source for Example

答案 1 :(得分:0)