module OpenSSL
OpenSSL providesSSL, TLS and general purpose cryptography. It wraps theOpenSSL library.
Examples¶↑
All examples assume you have loadedOpenSSL with:
require'openssl'
These examples build atop each other. For example the key created in the next is used in throughout these examples.
Keys¶↑
Creating a Key¶↑
This example creates a 2048 bit RSA keypair and writes it to the current directory.
key =OpenSSL::PKey::RSA.new2048File.write'private_key.pem',key.private_to_pemFile.write'public_key.pem',key.public_to_pem
Exporting a Key¶↑
Keys saved to disk without encryption are not secure as anyone who gets ahold of the key may use it unless it is encrypted. In order to securely export a key you may export it with a password.
cipher =OpenSSL::Cipher.new'aes-256-cbc'password ='my secure password goes here'key_secure =key.private_to_pemcipher,passwordFile.write'private.secure.pem',key_secure
OpenSSL::Cipher.ciphers returns a list of available ciphers.
Loading a Key¶↑
A key can also be loaded from a file.
key2 =OpenSSL::PKey.readFile.read'private_key.pem'key2.public?# => truekey2.private?# => true
or
key3 =OpenSSL::PKey.readFile.read'public_key.pem'key3.public?# => truekey3.private?# => false
Loading an Encrypted Key¶↑
OpenSSL will prompt you for your password when loading an encrypted key. If you will not be able to type in the password you may provide it when loading the key:
key4_pem =File.read'private.secure.pem'password ='my secure password goes here'key4 =OpenSSL::PKey.readkey4_pem,password
RSA Encryption¶↑
RSA provides encryption and decryption using the public and private keys. You can use a variety of padding methods depending upon the intended use of encrypted data.
Encryption & Decryption¶↑
Asymmetric public/private key encryption is slow and victim to attack in cases where it is used without padding or directly to encrypt larger chunks of data. Typical use cases for RSA encryption involve “wrapping” a symmetric key with the public key of the recipient who would “unwrap” that symmetric key again using their private key. The following illustrates a simplified example of such a key transport scheme. It shouldn’t be used in practice, though, standardized protocols should always be preferred.
wrapped_key =key.public_encryptkey
A symmetric key encrypted with the public key can only be decrypted with the corresponding private key of the recipient.
original_key =key.private_decryptwrapped_key
By default PKCS#1 padding will be used, but it is also possible to use other forms of padding, seePKey::RSA for further details.
Signatures¶↑
Using “private_encrypt” to encrypt some data with the private key is equivalent to applying a digital signature to the data. A verifying party may validate the signature by comparing the result of decrypting the signature with “public_decrypt” to the original data. However,OpenSSL::PKey already has methods “sign” and “verify” that handle digital signatures in a standardized way - “private_encrypt” and “public_decrypt” shouldn’t be used in practice.
To sign a document, a cryptographically secure hash of the document is computed first, which is then signed using the private key.
signature =key.sign'SHA256',document
To validate the signature, again a hash of the document is computed and the signature is decrypted using the public key. The result is then compared to the hash just computed, if they are equal the signature was valid.
ifkey.verify'SHA256',signature,documentputs'Valid'elseputs'Invalid'end
PBKDF2 Password-based Encryption¶↑
If supported by the underlyingOpenSSL version used, Password-based Encryption should use the features ofPKCS5. If not supported or if required by legacy applications, the older, less secure methods specified in RFC 2898 are also supported (see below).
PKCS5 supports PBKDF2 as it was specified in PKCS#5v2.0. It still uses a password, a salt, and additionally a number of iterations that will slow the key derivation process down. The slower this is, the more work it requires being able to brute-force the resulting key.
Encryption¶↑
The strategy is to first instantiate aCipher for encryption, and then to generate a random IV plus a key derived from the password using PBKDF2. PKCS #5 v2.0 recommends at least 8 bytes for the salt, the number of iterations largely depends on the hardware being used.
cipher = OpenSSL::Cipher.new 'aes-256-cbc'cipher.encryptiv = cipher.random_ivpwd = 'some hopefully not to easily guessable password'salt = OpenSSL::Random.random_bytes 16iter = 20000key_len = cipher.key_lendigest = OpenSSL::Digest.new('SHA256')key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)cipher.key = keyNow encrypt the data:encrypted = cipher.update documentencrypted << cipher.finalDecryption¶↑
Use the same steps as before to derive the symmetric AES key, this time setting theCipher up for decryption.
cipher = OpenSSL::Cipher.new 'aes-256-cbc'cipher.decryptcipher.iv = iv # the one generated with #random_ivpwd = 'some hopefully not to easily guessable password'salt = ... # the one generated aboveiter = 20000key_len = cipher.key_lendigest = OpenSSL::Digest.new('SHA256')key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)cipher.key = keyNow decrypt the data:decrypted = cipher.update encrypteddecrypted << cipher.finalX509 Certificates¶↑
Creating a Certificate¶↑
This example creates a self-signed certificate using an RSA key and a SHA1 signature.
key =OpenSSL::PKey::RSA.new2048name =OpenSSL::X509::Name.parse'/CN=nobody/DC=example'cert =OpenSSL::X509::Certificate.newcert.version =2cert.serial =0cert.not_before =Time.nowcert.not_after =Time.now+3600cert.public_key =key.public_keycert.subject =name
Certificate Extensions¶↑
You can add extensions to the certificate with OpenSSL::SSL::ExtensionFactory to indicate the purpose of the certificate.
extension_factory =OpenSSL::X509::ExtensionFactory.newnil,certcert.add_extension \extension_factory.create_extension('basicConstraints','CA:FALSE',true)cert.add_extension \extension_factory.create_extension('keyUsage','keyEncipherment,dataEncipherment,digitalSignature')cert.add_extension \extension_factory.create_extension('subjectKeyIdentifier','hash')
The list of supported extensions (and in some cases their possible values) can be derived from the “objects.h” file in theOpenSSL source code.
Signing a Certificate¶↑
To sign a certificate set the issuer and useOpenSSL::X509::Certificate#sign with a digest algorithm. This creates a self-signed cert because we’re using the same name and key to sign the certificate as was used to create the certificate.
cert.issuer =namecert.signkey,OpenSSL::Digest.new('SHA1')open'certificate.pem','w'do|io|io.writecert.to_pemend
Loading a Certificate¶↑
Like a key, a cert can also be loaded from a file.
cert2 =OpenSSL::X509::Certificate.newFile.read'certificate.pem'
Verifying a Certificate¶↑
Certificate#verify will return true when a certificate was signed with the given public key.
raise'certificate can not be verified'unlesscert2.verifykey
Certificate Authority¶↑
A certificate authority (CA) is a trusted third party that allows you to verify the ownership of unknown certificates. The CA issues key signatures that indicate it trusts the user of that key. A user encountering the key can verify the signature by using the CA’s public key.
CA Key¶↑
CA keys are valuable, so we encrypt and save it to disk and make sure it is not readable by other users.
ca_key =OpenSSL::PKey::RSA.new2048password ='my secure password goes here'cipher ='aes-256-cbc'open'ca_key.pem','w',0400do|io|io.writeca_key.private_to_pem(cipher,password)end
CA Certificate¶↑
A CA certificate is created the same way we created a certificate above, but with different extensions.
ca_name =OpenSSL::X509::Name.parse'/CN=ca/DC=example'ca_cert =OpenSSL::X509::Certificate.newca_cert.serial =0ca_cert.version =2ca_cert.not_before =Time.nowca_cert.not_after =Time.now+86400ca_cert.public_key =ca_key.public_keyca_cert.subject =ca_nameca_cert.issuer =ca_nameextension_factory =OpenSSL::X509::ExtensionFactory.newextension_factory.subject_certificate =ca_certextension_factory.issuer_certificate =ca_certca_cert.add_extension \extension_factory.create_extension('subjectKeyIdentifier','hash')
This extension indicates the CA’s key may be used as a CA.
ca_cert.add_extension \extension_factory.create_extension('basicConstraints','CA:TRUE',true)
This extension indicates the CA’s key may be used to verify signatures on both certificates and certificate revocations.
ca_cert.add_extension \extension_factory.create_extension('keyUsage','cRLSign,keyCertSign',true)
Root CA certificates are self-signed.
ca_cert.signca_key,OpenSSL::Digest.new('SHA1')
The CA certificate is saved to disk so it may be distributed to all the users of the keys this CA will sign.
open'ca_cert.pem','w'do|io|io.writeca_cert.to_pemend
Certificate Signing Request¶↑
The CA signs keys through a Certificate Signing Request (CSR). The CSR contains the information necessary to identify the key.
csr =OpenSSL::X509::Request.newcsr.version =0csr.subject =namecsr.public_key =key.public_keycsr.signkey,OpenSSL::Digest.new('SHA1')
A CSR is saved to disk and sent to the CA for signing.
open'csr.pem','w'do|io|io.writecsr.to_pemend
Creating a Certificate from a CSR¶↑
Upon receiving a CSR the CA will verify it before signing it. A minimal verification would be to check the CSR’s signature.
csr =OpenSSL::X509::Request.newFile.read'csr.pem'raise'CSR can not be verified'unlesscsr.verifycsr.public_key
After verification a certificate is created, marked for various usages, signed with the CA key and returned to the requester.
csr_cert =OpenSSL::X509::Certificate.newcsr_cert.serial =0csr_cert.version =2csr_cert.not_before =Time.nowcsr_cert.not_after =Time.now+600csr_cert.subject =csr.subjectcsr_cert.public_key =csr.public_keycsr_cert.issuer =ca_cert.subjectextension_factory =OpenSSL::X509::ExtensionFactory.newextension_factory.subject_certificate =csr_certextension_factory.issuer_certificate =ca_certcsr_cert.add_extension \extension_factory.create_extension('basicConstraints','CA:FALSE')csr_cert.add_extension \extension_factory.create_extension('keyUsage','keyEncipherment,dataEncipherment,digitalSignature')csr_cert.add_extension \extension_factory.create_extension('subjectKeyIdentifier','hash')csr_cert.signca_key,OpenSSL::Digest.new('SHA1')open'csr_cert.pem','w'do|io|io.writecsr_cert.to_pemend
SSL and TLS Connections¶↑
Using our created key and certificate we can create anSSL or TLS connection. An SSLContext is used to set up anSSL session.
context =OpenSSL::SSL::SSLContext.new
SSL Server¶↑
AnSSL server requires the certificate and private key to communicate securely with its clients:
context.cert =certcontext.key =key
Then create an SSLServer with a TCP server socket and the context. Use the SSLServer like an ordinary TCP server.
require'socket'tcp_server =TCPServer.new5000ssl_server =OpenSSL::SSL::SSLServer.newtcp_server,contextloopdossl_connection =ssl_server.acceptdata =ssl_connection.getsresponse ="I got #{data.dump}"putsresponsessl_connection.puts"I got #{data.dump}"ssl_connection.closeend
SSL client¶↑
AnSSL client is created with a TCP socket and the context. SSLSocket#connect must be called to initiate theSSL handshake and start encryption. A key and certificate are not required for the client socket.
Note that SSLSocket#close doesn’t close the underlying socket by default. Set SSLSocket#sync_close to true if you want.
require'socket'tcp_socket =TCPSocket.new'localhost',5000ssl_client =OpenSSL::SSL::SSLSocket.newtcp_socket,contextssl_client.sync_close =truessl_client.connectssl_client.puts"hello server!"putsssl_client.getsssl_client.close# shutdown the TLS connection and close tcp_socket
Peer Verification¶↑
An unverifiedSSL connection does not provide much security. For enhanced security the client or server can verify the certificate of its peer.
The client can be modified to verify the server’s certificate against the certificate authority’s certificate:
context.ca_file ='ca_cert.pem'context.verify_mode =OpenSSL::SSL::VERIFY_PEERrequire'socket'tcp_socket =TCPSocket.new'localhost',5000ssl_client =OpenSSL::SSL::SSLSocket.newtcp_socket,contextssl_client.connectssl_client.puts"hello server!"putsssl_client.gets
If the server certificate is invalid orcontext.ca_file is not set when verifying peers anOpenSSL::SSL::SSLError will be raised.
Constants
- LIBRESSL_VERSION_NUMBER
Version number of LibreSSL the ruby
OpenSSLextension was built with (base 16). The format is0xMNNFF00f (major minor fix 00 status). This constant is only defined in LibreSSL cases.See also the man page
LIBRESSL_VERSION_NUMBER(3).- OPENSSL_FIPS
Boolean indicating whether
OpenSSLis FIPS-capable or not- OPENSSL_LIBRARY_VERSION
- OPENSSL_VERSION
- OPENSSL_VERSION_NUMBER
Version number of
OpenSSLthe rubyOpenSSLextension was built with (base 16). The formats are below.OpenSSL30xMNN00PP0 (major minor 00 patch 0)OpenSSLbefore 30xMNNFFPPS (major minor fix patch status)- LibreSSL
0x20000000 (fixed value)
See also the man page
OPENSSL_VERSION_NUMBER(3).- VERSION
Public Class Methods
Source
# File ext/openssl/lib/openssl/digest.rb, line 63defDigest(name)OpenSSL::Digest.const_get(name)end
Returns aDigest subclass byname
require'openssl'OpenSSL::Digest("MD5")# => OpenSSL::Digest::MD5Digest("Foo")# => NameError: wrong constant name Foo
Source
static VALUEossl_debug_set(VALUE self, VALUE val){ dOSSL = RTEST(val) ? Qtrue : Qfalse; return val;}Turns on or off debug mode. With debug mode, all errors added to theOpenSSL error queue will be printed to stderr.
Source
static VALUEossl_get_errors(VALUE _){ VALUE ary; long e; ary = rb_ary_new(); while ((e = ERR_get_error()) != 0){ rb_ary_push(ary, rb_str_new2(ERR_error_string(e, NULL))); } return ary;}See any remaining errors held in queue.
Any errors you see here are probably due to a bug in Ruby’sOpenSSL implementation.
Source
static VALUEossl_fips_mode_get(VALUE self){#if OSSL_OPENSSL_PREREQ(3, 0, 0) VALUE enabled; enabled = EVP_default_properties_is_fips_enabled(NULL) ? Qtrue : Qfalse; return enabled;#elif defined(OPENSSL_FIPS) || defined(OPENSSL_IS_AWSLC) VALUE enabled; enabled = FIPS_mode() ? Qtrue : Qfalse; return enabled;#else return Qfalse;#endif}Source
static VALUEossl_fips_mode_set(VALUE self, VALUE enabled){#if OSSL_OPENSSL_PREREQ(3, 0, 0) if (RTEST(enabled)) { if (!EVP_default_properties_enable_fips(NULL, 1)) { ossl_raise(eOSSLError, "Turning on FIPS mode failed"); } } else { if (!EVP_default_properties_enable_fips(NULL, 0)) { ossl_raise(eOSSLError, "Turning off FIPS mode failed"); } } return enabled;#elif defined(OPENSSL_FIPS) || defined(OPENSSL_IS_AWSLC) if (RTEST(enabled)) { int mode = FIPS_mode(); if(!mode && !FIPS_mode_set(1)) /* turning on twice leads to an error */ ossl_raise(eOSSLError, "Turning on FIPS mode failed"); } else { if(!FIPS_mode_set(0)) /* turning off twice is OK */ ossl_raise(eOSSLError, "Turning off FIPS mode failed"); } return enabled;#else if (RTEST(enabled)) ossl_raise(eOSSLError, "This version of OpenSSL does not support FIPS mode"); return enabled;#endif}Turns FIPS mode on or off. Turning on FIPS mode will obviously only have an effect for FIPS-capable installations of theOpenSSL library. Trying to do so otherwise will result in an error.
Examples¶↑
OpenSSL.fips_mode =true# turn FIPS mode onOpenSSL.fips_mode =false# and off again
Source
static VALUEossl_crypto_fixed_length_secure_compare(VALUE dummy, VALUE str1, VALUE str2){ const unsigned char *p1 = (const unsigned char *)StringValuePtr(str1); const unsigned char *p2 = (const unsigned char *)StringValuePtr(str2); long len1 = RSTRING_LEN(str1); long len2 = RSTRING_LEN(str2); if (len1 != len2) { ossl_raise(rb_eArgError, "inputs must be of equal length"); } switch (CRYPTO_memcmp(p1, p2, len1)) { case 0: return Qtrue; default: return Qfalse; }}Constant time memory comparison for fixed length strings, such as results ofHMAC calculations.
Returnstrue if the strings are identical,false if they are of the same length but not identical. If the length is different,ArgumentError is raised.
Source
# File ext/openssl/lib/openssl.rb, line 33defself.secure_compare(a,b)hashed_a =OpenSSL::Digest.digest('SHA256',a)hashed_b =OpenSSL::Digest.digest('SHA256',b)OpenSSL.fixed_length_secure_compare(hashed_a,hashed_b)&&a==bend
Constant time memory comparison. Inputs are hashed using SHA-256 to mask the length of the secret. Returnstrue if the strings are identical,false otherwise.
Private Instance Methods
Source
# File ext/openssl/lib/openssl/digest.rb, line 63defDigest(name)OpenSSL::Digest.const_get(name)end
Returns aDigest subclass byname
require'openssl'OpenSSL::Digest("MD5")# => OpenSSL::Digest::MD5Digest("Foo")# => NameError: wrong constant name Foo