IP Anonymizer
:earth_americas: IP address anonymizer for Ruby
Works with IPv4 and IPv6, and includes middleware for Rails
Getting Started
Add these lines to your application’s Gemfile:
gem 'ip_anonymizer'
There are two strategies for anonymizing IPs.
Masking
This is the approach Google Analytics uses for IP anonymization:
- For IPv4, the last octet is set to 0
- For IPv6, the last 80 bits are set to zeros
IpAnonymizer.mask_ip("8.8.4.4")
# => "8.8.4.0"
IpAnonymizer.mask_ip("2001:4860:4860:0:0:0:0:8844")
# => "2001:4860:4860::"
An advantange of this approach is geocoding will still work, only with slightly less accuracy.
Hashing
Transform IP addresses with a keyed hash function (PBKDF2-HMAC-SHA256).
IpAnonymizer.hash_ip("8.8.4.4", key: "secret")
# => "6.128.151.207"
IpAnonymizer.hash_ip("2001:4860:4860:0:0:0:0:8844", key: "secret")
# => "f6e4:a4fe:32dc:2f39:3e47:84cc:e85e:865c"
Be sure to keep the key secret, or else a rainbow table can be constructed.
Rails
Automatically anonymize request.remote_ip
in Rails.
For masking, add to config/application.rb
:
config.middleware.insert_after ActionDispatch::RemoteIp, IpAnonymizer::MaskIp
For hashing, use:
config.middleware.insert_after ActionDispatch::RemoteIp, IpAnonymizer::HashIp, key: "secret"
History
View the changelog
Contributing
Everyone is encouraged to help improve this project. Here are a few ways you can help:
- Report bugs
- Fix bugs and submit pull requests
- Write, clarify, or fix documentation
- Suggest or add new features
To get started with development and testing:
git clone https://github.com/ankane/ip_anonymizer.git
cd ip_anonymizer
bundle install
rake test