Class: ExtID::Type
- Inherits:
-
Object
- Object
- ExtID::Type
- Defined in:
- lib/extid.rb
Instance Method Summary collapse
- #decode(s) ⇒ Object
- #encode(n) ⇒ Object
-
#initialize(prefix, key) ⇒ Type
constructor
A new instance of Type.
Constructor Details
#initialize(prefix, key) ⇒ Type
Returns a new instance of Type.
11 12 13 14 15 16 |
# File 'lib/extid.rb', line 11 def initialize(prefix, key) raise ArgumentError, "key must be exactly 16 bytes" unless key.bytesize == 16 @prefix = prefix + "_" @key = key end |
Instance Method Details
#decode(s) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/extid.rb', line 35 def decode(s) raise ArgumentError, "invalid prefix" unless s.start_with?(@prefix) hex_ciphertext = s[@prefix.size..] ciphertext = [hex_ciphertext].pack("H*") cipher = OpenSSL::Cipher.new('AES-128-ECB') cipher.decrypt cipher.key = @key cipher.padding = 0 plaintext = cipher.update(ciphertext) + cipher.final plaintext[0, 8].unpack("q>").first end |
#encode(n) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/extid.rb', line 18 def encode(n) raise ArgumentError, "n is too small" unless n >= MinInt64 raise ArgumentError, "n is too big" unless n <= MaxInt64 binary_number = [n].pack("q>") raise ArgumentError, "n could not be encoded into 64-bit binary" unless binary_number.bytesize == 8 plaintext = binary_number + "\x0\x0\x0\x0\x0\x0\x0\x0" cipher = OpenSSL::Cipher.new('AES-128-ECB') cipher.encrypt cipher.key = @key cipher.padding = 0 ciphertext = cipher.update(plaintext) + cipher.final @prefix + ciphertext.unpack("H*").first end |