class

OpenSSL::Cipher

Inherits Reference / Object

A class which can be used to encrypt and decrypt data using a specified cipher.

NOTE: The ciphers available to an application are determined by the linked version of the system SSL library. A comprehensive list of ciphers can be found in the OpenSSL Cipher documentation.

require "random/secure"
require "openssl"

def encrypt(data, key, iv)
  cipher = OpenSSL::Cipher.new("aes-256-cbc")
  cipher.encrypt
  cipher.key = key
  cipher.iv = iv

  io = IO::Memory.new
  io.write(cipher.update(data))
  io.write(cipher.final)
  io.rewind

  io.to_slice
end

def decrypt(data, key, iv)
  cipher = OpenSSL::Cipher.new("aes-256-cbc")
  cipher.decrypt
  cipher.key = key
  cipher.iv = iv

  io = IO::Memory.new
  io.write(cipher.update(data))
  io.write(cipher.final)
  io.rewind

  io.gets_to_end
end

key = Random::Secure.random_bytes(64) # You can also use OpenSSL::Cipher#random_key to do this same thing
iv = Random::Secure.random_bytes(32)  # You can also use OpenSSL::Cipher#random_iv to do this same thing

encrypted_data = encrypt("Encrypted", key, iv)    # => Bytes[95, 182, 21, 86, 193, 155, 149, 164, 82, 102, 171, 182, 56, 153, 223, 33]
decrypted_data = decrypt(encrypted_data, key, iv) # => "Encrypted"

Constructors

new(name)
Source

Instance methods

authenticated?
Source
block_size
Source
decrypt

Sets this cipher to decryption mode.

Source
encrypt

Sets this cipher to encryption mode.

Source
final

Outputs the decrypted or encrypted buffer.

Source
finalize
Source
iv=(iv)
Source
iv_len

How many bytes the iv should be.

Source
key=(key)
Source
key_len

How many bytes the key should be.

Source
name
Source
padding=(pad : Bool)
Source
random_iv

Sets the iv using Random::Secure.

Source
random_key

Sets the key using Random::Secure.

Source
reset

Resets the encrypt/decrypt mode.

Source
update(data)

Add the data to be encrypted or decrypted to this cipher's buffer.

Source

Nested types