module Crypt

Overview

Crypto utilities.

See also in complement:

Defined in:

bcrypt.cr
crypt.cr
crypter.cr
key-deriv.cr
random.cr
signer.cr

Constant Summary

VERSION = "0.1.2"

Class Method Summary

Class Method Detail

def self.check_min_bytesize(min_bytesize : Int, value, name : String = "Value") #

Check the desired minimal value bytesize. Raises a BytesizeError if the value bytesize is lesser than min_bytesize.

value must implements value.bytesize (String and Slice / Bytes implements bytesize).

name argument is used to contextualize error message.

def self.create_bcrypt_password(secret : String, cost : Int32 = Crypto::Bcrypt::DEFAULT_COST) : Crypto::Bcrypt::Password #

Create a Bcrypt password (Crypto::Bcrypt::Password). https://crystal-lang.org/api/Crypto/Bcrypt/Password.html

Generate, read and verify Crypto::Bcrypt hashes:

require "crypt"
require "crypt/bcrypt"

password = Crypt.create_bcrypt_password("super secret", cost: 10)
# => $2a$10$rI4xRiuAN2fyiKwynO6PPuorfuoM4L2PVv6hlnVJEmNLjqcibAfHq

password.verify("wrong secret") # => false
password.verify("super secret") # => true

def self.key_deriv(password, salt, iter = 65536, algo : OpenSSL::Algorithm = OpenSSL::Algorithm::SHA1, key_size = 64) #

Key derivation PKCS5/PBKDF2 (Password-Based Key Derivation Function 2).

  • https://crystal-lang.org/api/OpenSSL/HMAC.html
  • https://en.wikipedia.org/wiki/PBKDF2

def self.key_deriv(password, salt, iter = 65536, algo : Symbol = :sha1, key_size = 64) #

See .key_deriv.

Argument algo takes a Symbol instead of OpenSSL::Algorithm (Enum).

:md4, :md5, :ripemd160, :sha1, :sha224, :sha256, :sha384, :sha512

def self.load_bcrypt_password(hash : String) : Crypto::Bcrypt::Password #

Loads a Bcrypt password hash.

require "crypt"
require "crypt/bcrypt"

password = Crypt.load_bcrypt_password(
  "$2a$10$X6rw/jDiLBuzHV./JjBNXe8/Po4wTL0fhdDNdAdjcKN/Fup8tGCya"
)
password.version # => "2a"
password.salt    # => "X6rw/jDiLBuzHV./JjBNXe"
password.digest  # => "8/Po4wTL0fhdDNdAdjcKN/Fup8tGCya"

def self.random_bytes(n : Int = 16) : Bytes #

Generates a slice filled with n random bytes.

  • https://crystal-lang.org/api/Random.html#random_bytes(n:Int=16):Bytes-instance-method

See also:


def self.random_bytes_string(n : Int = 16) : String #

Generates a string whose size is n bytes. Be careful the string generated contains more characters than n, but size is n bytes.

str = Crypt.random_bytes_string(4) # => "\u001DF\xD4\u000E"
str.bytesize                       # => 4
str.to_slice                       # => Bytes[195, 219, 187, 142]

See also:


def self.random_string(n : Int = 16) : String #

Generates a string filled with n random characters. The string generated is URL and filename safe alphabet (RFC 4648). The alphabet uses '-' instead of '+' and '_' instead of '/'.

See also: