Sha256: 2eb40c74274d20dcbd40a8de509ed064d9512ff9d6f4880077bf9275df6f91b0

Contents?: true

Size: 699 Bytes

Versions: 1

Compression:

Stored size: 699 Bytes

Contents

require "ipaddr"
require "openssl"

require "ip_anonymizer/hash_ip"
require "ip_anonymizer/mask_ip"
require "ip_anonymizer/version"

module IpAnonymizer
  def self.mask_ip(ip)
    addr = IPAddr.new(ip)
    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

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

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ip_anonymizer-0.1.0 lib/ip_anonymizer.rb