Ruby 生成自签名证书

发布于 2024-08-23 10:30:53 字数 1984 浏览 6 评论 0原文

我正在尝试用 ruby​​ 生成自签名证书,但遇到了麻烦。这就是我现在所拥有的:

require 'openssl'

if ARGV.length != 3 then
    puts "USAGE: #{__FILE__} <type[der|pem]> <private-out> <public-out>"
    exit
end

type = ARGV[0].downcase
privateKeyFile = ARGV[1]
publicKeyFile = ARGV[2]

values = [{ 'C' => 'US'},
          {'ST' => 'SomeState'},
          { 'L' => 'SomeCity'},
          { 'O' => 'Organization'},
          {'OU' => 'Organizational Unit'},
          {'CN' => "somesite.com"}]

name = values.collect{ |l| l.collect { |k, v| "/#{k}=#{v}" }.join }.join

key = OpenSSL::PKey::RSA.generate(1024)
pub = key.public_key
ca = OpenSSL::X509::Name.parse(name)
cert = OpenSSL::X509::Certificate.new
cert.version = 2 
cert.serial = 1 
cert.subject = ca
cert.issuer = ca
cert.public_key = pub 
cert.not_before = Time.now
cert.not_before = Time.now + (360 * 24 * 3600)

File.open(privateKeyFile + "." + type, "w") {|f| f.write key.send("to_#{type}") }
File.open(publicKeyFile + "." + type, "w") {|f| f.write cert.send("to_#{type}") }

当我尝试在 apache 中使用生成的私钥和证书时,我收到此错误:

[Thu Mar 04 10:58:44 2010] [error] Init: Unable to read server certificate from file /etc/ssl/certs/gnarly.pem
[Thu Mar 04 10:58:44 2010] [error] SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Thu Mar 04 10:58:44 2010] [error] SSL Library Error: 218595386 error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error

这就是我的证书所说的:

-----BEGIN CERTIFICATE-----
<lots of stuff>
-----END CERTIFICATE-----

它称自己为证书而不是 CSR,这是大多数我在网上找到的关于 apache2 错误的内容(我可能混淆了 CSR 和 CERT)。我的猜测是我没有生成正确类型的证书。也许我必须更改序列或版本属性。另外,据我所知,我不会在任何地方进行任何自签名。我知道你可以这样做:

require "openssl"
key = OpenSSL::PKey::RSA.generate(1024)
signature = key.sign(OpenSSL::Digest::SHA1.new, "data to sign")

提醒:我的目标是生成一个自签名证书,以防我的长问题失去焦点。

编辑:我想真正的问题是如何用密钥签署证书

I'm trying to generate a self-signed certificate in ruby, but am running into trouble. This is what I currently have right now:

require 'openssl'

if ARGV.length != 3 then
    puts "USAGE: #{__FILE__} <type[der|pem]> <private-out> <public-out>"
    exit
end

type = ARGV[0].downcase
privateKeyFile = ARGV[1]
publicKeyFile = ARGV[2]

values = [{ 'C' => 'US'},
          {'ST' => 'SomeState'},
          { 'L' => 'SomeCity'},
          { 'O' => 'Organization'},
          {'OU' => 'Organizational Unit'},
          {'CN' => "somesite.com"}]

name = values.collect{ |l| l.collect { |k, v| "/#{k}=#{v}" }.join }.join

key = OpenSSL::PKey::RSA.generate(1024)
pub = key.public_key
ca = OpenSSL::X509::Name.parse(name)
cert = OpenSSL::X509::Certificate.new
cert.version = 2 
cert.serial = 1 
cert.subject = ca
cert.issuer = ca
cert.public_key = pub 
cert.not_before = Time.now
cert.not_before = Time.now + (360 * 24 * 3600)

File.open(privateKeyFile + "." + type, "w") {|f| f.write key.send("to_#{type}") }
File.open(publicKeyFile + "." + type, "w") {|f| f.write cert.send("to_#{type}") }

When I try to use the generated private key and certificate in apache, I get this error:

[Thu Mar 04 10:58:44 2010] [error] Init: Unable to read server certificate from file /etc/ssl/certs/gnarly.pem
[Thu Mar 04 10:58:44 2010] [error] SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Thu Mar 04 10:58:44 2010] [error] SSL Library Error: 218595386 error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error

This is what my certificate says:

-----BEGIN CERTIFICATE-----
<lots of stuff>
-----END CERTIFICATE-----

It calls itself a certificate instead of a CSR, which is what most of the things I've found online say about that apache2 error (that I might have gotten the CSR and CERT mixed up). My guess is that I'm not generating the right type of certificate. Maybe I have to change the serial or version attributes. Also, I'm not doing any self-signing anywhere, not that I know of anyways. I know you can do something like this though:

require "openssl"
key = OpenSSL::PKey::RSA.generate(1024)
signature = key.sign(OpenSSL::Digest::SHA1.new, "data to sign")

Reminder: My goal is to generate a self-signed certificate, in case my long-ish question lost focus on the way.

EDIT: I guess the real question is how to sign a certificate with a key

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

权谋诡计 2024-08-30 10:30:54

我使用直接从 nickyp 的要点,我在 Google 搜索中找到的。您需要的唯一依赖项是 openssl gem (gem install openssl)

require 'openssl'

class SelfSignedCertificate
  def initialize
    @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
  end

  def self_signed_pem
    @cert.to_pem
  end

  def private_key
    @key
  end
end

用法:

my_cert = SelfSignedCertificate.new
puts "Private Key:\n#{my_cert.private_key}"
puts "Self-signed PEM:\n#{my_cert.self_signed_pem}"

输出:

Private Key:
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDTtjPd3X9KX9BZpXKS82tM74Bs/hXsSLgnkitrc+oR4oF5PVko
N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QUAA4GNADCBiQKBgQDTtjPd3X9KX9BZpXKS82tM74Bs/hXsSLgnkitr
c+oR4oF5PVkoNZL3j51gkX3jJRSG9tNPQC5NVR+5h7tXPxU5TAQZl6MUiV+YWuRn
g98GeCjP3ePpmeSStsKEMUiZI8YLVWrdbIjS+Q+lZnYMffeEOAoMSaei9hR4rOX0
i+9hdwIDAQABo4GXMIGUMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNNbdqck
QT/B5hdQqimtW1Wnf+fmMGIGA1UdIwRbMFmAFNNbdqckQT/B5hdQqimtW1Wnf+fm
oT6kPDA6MQswCQYDVQQGEwJCRTENMAsGA1UECgwEVGVzdDENMAsGA1UECwwEVGVz
dDENMAsGA1UEAwwEVGVzdIIBADANBgkqhkiG9w0BAQUFAAOBgQB80KzzhkXCgJ0s
1zXJXuocNDU5v0Z42ditNX9jS8pXuhHwcQbx7PVfOieO3GHC5YzzgMHGR3i2U2CQ
rz9hP937ERxCfqpxhfMAD3Q+3rHsdGdNIauzzFb6XoXsM7koRnM27I6qvO3bamcz
AVGH5eLic9IjZTQbZizFzNoR+H2N/g==
-----END CERTIFICATE-----

I created a helper class for this from code I lifted directly from nickyp's gist that I found on a Google search. The only dependency you need is the openssl gem (gem install openssl)

require 'openssl'

class SelfSignedCertificate
  def initialize
    @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
  end

  def self_signed_pem
    @cert.to_pem
  end

  def private_key
    @key
  end
end

Usage:

my_cert = SelfSignedCertificate.new
puts "Private Key:\n#{my_cert.private_key}"
puts "Self-signed PEM:\n#{my_cert.self_signed_pem}"

Output:

Private Key:
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDTtjPd3X9KX9BZpXKS82tM74Bs/hXsSLgnkitrc+oR4oF5PVko
NZL3j51gkX3jJRSG9tNPQC5NVR+5h7tXPxU5TAQZl6MUiV+YWuRng98GeCjP3ePp
meSStsKEMUiZI8YLVWrdbIjS+Q+lZnYMffeEOAoMSaei9hR4rOX0i+9hdwIDAQAB
AoGBALdAc/6sFd0zuC2Qhu7p4kvS11AAUsuWWkhuPkUhLU9TxwxBbOXgEZlVZzzK
UrQFSZJVHazweeOYNgCqmx82zE+cB4YzRLqkCPUD9t1bZcgk31tV39MSrC9CDKCB
inUTMKflPbHL0B+Lq24S8KfuW9bOPofhspjlV7cZCX5adFiBAkEA7KOMkiQMyq9X
ZVeRzJU0LmVdjrb7UBD5NebV+KaN8O7q+W4FG0nihcNj7xt2fZnvKM4FMfRwDP3G
HRUfR0alQQJBAOUIjKXYyoUsk+tLASoYLX+uPocjd7YSB9UPK2lFxqHOzekAlynF
u1JWEDPOjZNtNHmsQKOp5AWTUnm33JxfQLcCQByY5zQCB0m3RuiIXKZMobG5rkTA
+D4EzxkkfFdASYcEWIEsOpHBrA5ePoV23Crxn2VfAGG5GJF5WafKFa2XbAECQFL/
5Ch+BfZ5DynnxoZAuMxakuJaYhmjMx9tHehKlw8waMKVqjJDK/1MnxaHNhtFKg0l
9U7aVH4Iw4zEqrgodMUCQQCWZEUepSGoRVs1YDtag4FKSTMGXcnI/jllJmxHQhf4
uiy/8Hb+FW49w3KO1zeq7WdXw7W7Q1uO94npYX5p535d
-----END RSA PRIVATE KEY-----
Signed PEM:
-----BEGIN CERTIFICATE-----
MIICgjCCAeugAwIBAgIBADANBgkqhkiG9w0BAQUFADA6MQswCQYDVQQGEwJCRTEN
MAsGA1UECgwEVGVzdDENMAsGA1UECwwEVGVzdDENMAsGA1UEAwwEVGVzdDAeFw0x
NDA4MjEwMTI1MTZaFw0xNTA4MjEwMTI1MTZaMDoxCzAJBgNVBAYTAkJFMQ0wCwYD
VQQKDARUZXN0MQ0wCwYDVQQLDARUZXN0MQ0wCwYDVQQDDARUZXN0MIGfMA0GCSqG
SIb3DQEBAQUAA4GNADCBiQKBgQDTtjPd3X9KX9BZpXKS82tM74Bs/hXsSLgnkitr
c+oR4oF5PVkoNZL3j51gkX3jJRSG9tNPQC5NVR+5h7tXPxU5TAQZl6MUiV+YWuRn
g98GeCjP3ePpmeSStsKEMUiZI8YLVWrdbIjS+Q+lZnYMffeEOAoMSaei9hR4rOX0
i+9hdwIDAQABo4GXMIGUMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNNbdqck
QT/B5hdQqimtW1Wnf+fmMGIGA1UdIwRbMFmAFNNbdqckQT/B5hdQqimtW1Wnf+fm
oT6kPDA6MQswCQYDVQQGEwJCRTENMAsGA1UECgwEVGVzdDENMAsGA1UECwwEVGVz
dDENMAsGA1UEAwwEVGVzdIIBADANBgkqhkiG9w0BAQUFAAOBgQB80KzzhkXCgJ0s
1zXJXuocNDU5v0Z42ditNX9jS8pXuhHwcQbx7PVfOieO3GHC5YzzgMHGR3i2U2CQ
rz9hP937ERxCfqpxhfMAD3Q+3rHsdGdNIauzzFb6XoXsM7koRnM27I6qvO3bamcz
AVGH5eLic9IjZTQbZizFzNoR+H2N/g==
-----END CERTIFICATE-----
血之狂魔 2024-08-30 10:30:54

webrick/ssl中有一个create_self_signed_cert方法,很容易理解,也很有用。

There is a create_self_signed_cert method in webrick/ssl, which is easy to understand and useful.

窗影残 2024-08-30 10:30:54

此后,我找到了几个非常好的使用 OpenSSL 的示例来源:

http://snippets.dzone。 com/posts/show/6309

http://projects.reducinglabs.com/projects/puppet/repository/revisions/master/entry/lib/puppet/sslcertificates.rb

http://projects.reducinglabs.com/projects/puppet/repository/revisions/master/条目/lib/puppet/sslcertificates/ca.rb

http://projects.reducinglabs.com/projects/puppet/repository/revisions/master/entry/lib/puppet/sslcertificates/certificate.rb

我还没找到目前还没有任何好的文档,尽管我认为写下示例中的内容不会花费太长时间。

我还弄清楚了如何从木偶源代码中执行我想要的操作。希望这可以帮助那些因 ruby​​ 中缺少 OpenSSL 文档而感到沮丧的人。

I've since found several very good sources for examples using OpenSSL:

http://snippets.dzone.com/posts/show/6309

http://projects.reductivelabs.com/projects/puppet/repository/revisions/master/entry/lib/puppet/sslcertificates.rb

http://projects.reductivelabs.com/projects/puppet/repository/revisions/master/entry/lib/puppet/sslcertificates/ca.rb

http://projects.reductivelabs.com/projects/puppet/repository/revisions/master/entry/lib/puppet/sslcertificates/certificate.rb

I still haven't found any good documentation for this yet, although I don't think it would take too long to write down what's in the examples.

I've also figured out how to do what I wanted from the puppet source code. Hope this helps someone else who's frustrated at the lack of documentation of OpenSSL in ruby.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文