Class: IPCrypt::Engine
- Inherits:
-
Object
- Object
- IPCrypt::Engine
- Defined in:
- lib/ipcrypt/engine.rb
Constant Summary collapse
- IPv4 =
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
Instance Attribute Summary collapse
-
#default_key ⇒ Object
readonly
Returns the value of attribute default_key.
-
#ips ⇒ Object
Returns the value of attribute ips.
Instance Method Summary collapse
- #decrypt(key) ⇒ Object
- #encrypt(key = @default_key) ⇒ Object
-
#initialize(*ips) ⇒ Engine
constructor
A new instance of Engine.
Constructor Details
#initialize(*ips) ⇒ Engine
Returns a new instance of Engine.
8 9 10 11 12 13 14 |
# File 'lib/ipcrypt/engine.rb', line 8 def initialize(*ips) @default_key = SecureRandom.random_bytes(16) @ips = ips.flatten.map do |ip| raise InvalidIPv4Error.new(ip) unless IPv4.match? ip ip end end |
Instance Attribute Details
#default_key ⇒ Object (readonly)
Returns the value of attribute default_key.
5 6 7 |
# File 'lib/ipcrypt/engine.rb', line 5 def default_key @default_key end |
#ips ⇒ Object
Returns the value of attribute ips.
5 6 7 |
# File 'lib/ipcrypt/engine.rb', line 5 def ips @ips end |
Instance Method Details
#decrypt(key) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/ipcrypt/engine.rb', line 45 def decrypt(key) raise InvalidKeyTypeError.new(key, key.class) unless key.is_a? String bytes = key.bytesize raise InvalidKeyBytesError.new(key, bytes) unless bytes == 16 decrypted = @ips.map do |ip| k = key.chars.map {|c| c.unpack('<C').first } state = ip.split(?.).map &:to_i state = xor4 state, k[12...16] state = permute_bwd state state = xor4 state, k[8...12] state = permute_bwd state state = xor4 state, k[4...8] state = permute_bwd state state = xor4 state, k[0...4] state * ?. end decrypted.size == 1 ? decrypted.first : decrypted end |
#encrypt(key = @default_key) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/ipcrypt/engine.rb', line 21 def encrypt(key = @default_key) raise InvalidKeyTypeError.new(key, key.class) unless key.is_a? String bytes = key.bytesize raise InvalidKeyBytesError.new(key, bytes) unless bytes == 16 encrypted = @ips.map do |ip| k = key.chars.map {|c| c.unpack('<C').first } state = ip.split(?.).map &:to_i state = xor4 state, k[0...4] state = permute_fwd state state = xor4 state, k[4...8] state = permute_fwd state state = xor4 state, k[8...12] state = permute_fwd state state = xor4 state, k[12...16] state * ?. end encrypted.size == 1 ? encrypted.first : encrypted end |