Class: SecureString

Inherits:
String
  • Object
show all
Includes:
Base64Methods, CipherMethods, DigestMethods, RSAMethods
Defined in:
lib/secure_string.rb,
lib/secure_string/rsa_methods.rb,
lib/secure_string/base64_methods.rb,
lib/secure_string/cipher_methods.rb,
lib/secure_string/digest_methods.rb

Overview

SecureString is a String subclass whose emphasis is on byte data rather than human readable strings. class gives a number of conveniences, such as easier viewing of the byte data as hex, digest methods, and encryption and decryption methods.

Defined Under Namespace

Modules: Base64Methods, CipherMethods, DigestMethods, RSAMethods

Instance Method Summary collapse

Methods included from CipherMethods

included

Methods included from RSAMethods

included

Methods included from DigestMethods

included

Methods included from Base64Methods

included

Constructor Details

#initialize(mode = :data, value) ⇒ SecureString

Creates the string from one many kinds of values:

:data

(default) The passed string value is directly used.

:hex

Initialize using a hexidecimal string.

:int

Initialize using the numeric value of the hexidecimal string.

:base64

Initialize using the given base64 encoded data.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/secure_string.rb', line 23

def initialize(mode = :data, value)
  case mode
  when :hex
    hex_string = value.to_s
    data = [hex_string].pack('H' + hex_string.length.to_s)
  when :data
    data = value.to_s
  when :int
    data = self.send(__method__, :hex, value.to_i.to_s(16))
  when :base64
    data = Base64.decode64(value.to_s)
  end
  
  self.replace(data)
end

Instance Method Details

#inspectObject

Override the default String inspect to return the hexidecimal representation of the data contained in this string.



41
42
43
# File 'lib/secure_string.rb', line 41

def inspect
  return "<#{to_hex}>"
end

#to_hexObject

Returns the hexidecimal string representation of the data.



46
47
48
# File 'lib/secure_string.rb', line 46

def to_hex
  return (self.empty? ? '' : self.unpack('H' + (self.length*2).to_s)[0])
end

#to_iObject

Returns the data converted from hexidecimal into an integer. This is usually as a BigInt.

WARNING: If the data string is empty, then this returns -1, as there is no integer representation of the absence of data.



55
56
57
# File 'lib/secure_string.rb', line 55

def to_i
  return (self.empty? ? -1 : to_hex.hex)
end