Module: IpAnonymizer

Defined in:
lib/ip_anonymizer.rb,
lib/ip_anonymizer/hash_ip.rb,
lib/ip_anonymizer/mask_ip.rb,
lib/ip_anonymizer/version.rb

Defined Under Namespace

Classes: HashIp, MaskIp

Constant Summary collapse

VERSION =
"0.3.0"

Class Method Summary collapse

Class Method Details

.hash_ip(ip, key:, iterations: 1) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/ip_anonymizer.rb', line 22

def self.hash_ip(ip, key:, iterations: 1)
  addr = IPAddr.new(ip.to_s)
  key_len = addr.ipv4? ? 4 : 16
  family = addr.ipv4? ? Socket::AF_INET : Socket::AF_INET6

  keyed_hash = OpenSSL::KDF.pbkdf2_hmac(addr.to_s, salt: key, iterations: iterations, length: key_len, hash: "sha256")
  IPAddr.new(keyed_hash.bytes.inject { |a, b| (a << 8) + b }, family).to_s
end

.mask_ip(ip) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/ip_anonymizer.rb', line 11

def self.mask_ip(ip)
  addr = IPAddr.new(ip.to_s)
  if addr.ipv4?
    # set last octet to 0
    addr.mask(24).to_s
  else
    # set last 80 bits to zeros
    addr.mask(48).to_s
  end
end