Class: Keycard::DigestKey

Inherits:
Object
  • Object
show all
Defined in:
lib/keycard/digest_key.rb

Overview

A typical digest or api key, ready to be encrypted.

Defined Under Namespace

Classes: HiddenKeyError

Constant Summary collapse

HIDDEN_KEY =
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".freeze

Instance Method Summary collapse

Constructor Details

#initialize(digest = nil, key: nil) ⇒ DigestKey

To simply mint a new key, call #new without any parameters. For wrapping existing, deserialized keys, pass the digest to the constructor.

Parameters:

  • digest (String) (defaults to: nil)

    The value of the hashed key

  • key (String) (defaults to: nil)

    Use this if you’d like to specify the unhashed key. If a digest is also provided, this parameter is ignored.



16
17
18
19
20
21
22
# File 'lib/keycard/digest_key.rb', line 16

def initialize(digest = nil, key: nil)
  if digest
    @digest = digest
  else
    @key = key || SecureRandom.uuid
  end
end

Instance Method Details

#digestString

The result of hashing the key

Returns:

  • (String)


45
46
47
# File 'lib/keycard/digest_key.rb', line 45

def digest
  @digest ||= Digest::SHA256.hexdigest(@key)
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


49
50
51
52
53
54
55
# File 'lib/keycard/digest_key.rb', line 49

def eql?(other)
  digest == if other.is_a?(self.class)
              other.digest
            else
              other.to_s
            end
end

#to_sString

A string representation of this key. For hidden keys, this returns an obfuscated value.

Returns:

  • (String)


27
28
29
# File 'lib/keycard/digest_key.rb', line 27

def to_s
  @key || HIDDEN_KEY
end

#valueString

The unhashed value of the key.

Returns:

  • (String)

Raises:

  • (HiddenKeyError)

    This exception is raised if the unhashed key is not available.



35
36
37
38
39
40
41
# File 'lib/keycard/digest_key.rb', line 35

def value
  if @key
    @key
  else
    raise HiddenKeyError, "Cannot display hashed/hidden keys"
  end
end