Skip to content

class OpenSSL::Cipher
inherits Reference

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

require "random/secure"

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

def encrypt(data)
  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)
  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

Class methods

.new(name)

View source

Methods

#authenticated?

View source

#block_size

View source

#decrypt

Sets this cipher to decryption mode.

View source

#encrypt

Sets this cipher to encryption mode.

View source

#final

Outputs the decrypted or encrypted buffer.

View source

#finalize

View source

#iv=(iv)

View source

#iv_len

How many bytes the iv should be.

View source

#key=(key)

View source

#key_len

How many bytes the key should be.

View source

#name

View source

#padding=(pad : Bool)

View source

#random_iv

Sets the iv using Random::Secure.

View source

#random_key

Sets the key using Random::Secure.

View source

#reset

Resets the encrypt/decrypt mode.

View source

#update(data)

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

View source