class Marten::Core::Signer

Overview

Provides the ability to easily sign string values to prevent tampering.

The Marten::Core::Signer class makes it easy to build signed value, and to verify that they have not been tampered:

signer = Marten::Core::Signer.new
signed_value = signer.sign("hello world") # => "aGVsb..."
signer.unsign(signed_value)               # => "hello world"

Marten::Core::Signer objects create HMAC signatures using the SHA256 hash algorithm by default. They also use Marten's configured secret key by default. Both the algorithm and the key used to generate signatures can be defined at initialization time using the algorithm and the key arguments:

signer = Marten::Core::Signer.new(key: "insecure_key", algorithm: OpenSSL::Algorithm::SHA1)

Defined in:

marten/core/signer.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(key : String | Nil = nil, algorithm : OpenSSL::Algorithm = OpenSSL::Algorithm::SHA256) #

[View source]

Instance Method Detail

def sign(value : String, expires : Time | Nil = nil) : String #

Generates a signed value for the passed value.

The value is signed by using the key used when initializing the signer instance. A Base64-encoded version of the original data is embedded in the generated signature:

signer = Marten::Core::Signer.new
signer.sign("hello world") # => "aGVsb..."

It is also possible to define an expiry time for the generated signature by using the expires argument:

signer = Marten::Core::Signer.new
signer.sign("hello world", expires: Time.local + Time::Span.new(hours: 20)) # => "eyJfb..."

[View source]
def unsign(value : String) : Nil | String #

Verifies the signature of the passed value and returns the original value if it is valid, or nil otherwise.

This method verifies that the signed value has not been tampered and returns the original value if the signature is valid, and if it is not expired:

signer = Marten::Core::Signer.new
signed_value = signer.sign("hello world") # => "aGVsb..."
signer.unsign(signed_value)               # => "hello world"

If the passed value is invalid, or if the associated signature is invalid, a nil value is returned:

signer = Marten::Core::Signer.new
signer.unsign("bad_value") # => nil

[View source]
def unsign!(value : String) : String #

Verifies the signature of the passed value and returns the original value if it is valid, or raise an error.

This method verifies that the signed value has not been tampered and returns the original value if the signature is valid, and if it is not expired:

signer = Marten::Core::Signer.new
signed_value = signer.sign("hello world") # => "aGVsb..."
signer.unsign!(signed_value)              # => "hello world"

If the passed value is invalid, or if the associated signature is invalid, a Marten::Core::Signer::InvalidSignatureError exception is raised:

signer = Marten::Core::Signer.new
signer.unsign!("bad_value") # => Marten::Core::Signer::InvalidSignatureError

[View source]