HMAC-SHA256 でIPアドレスを仮名化


In [12]:
import hmac
import hashlib
import Crypto.Cipher.AES
import socket
import struct
from array import array
import ipaddress
import numpy as np

key = "secret"
text = "192.168.0."
signature = hmac.new(key,text,hashlib.sha256).hexdigest()
print signature
text = "192.168.0."
signature = hmac.new(key,text,hashlib.sha256).hexdigest()
print signature
key = "secret2"
text = "192.168.0."
signature = hmac.new(key,text,hashlib.sha256).hexdigest()
print signature


67fc5539637305c38e3256cfa11ca196a22f3c02fba6016018a2da45d0b90765
67fc5539637305c38e3256cfa11ca196a22f3c02fba6016018a2da45d0b90765
d4877bfec686040daf976a0846afccc0deffef9cb9b7f5e4d771f49833d61853

In [34]:
ip=ipaddress.ip_address(u"255.255.255.255")

In [35]:
ip


Out[35]:
IPv4Address(u'255.255.255.255')

In [36]:
addr = int(ip)

In [37]:
addr


Out[37]:
4294967295

In [38]:
print "addr:\n",format(addr,'032b')


addr:
11111111111111111111111111111111

In [39]:
net = addr >> 8 << 8
print "addr:\n",format(net,'032b')


addr:
11111111111111111111111100000000

In [40]:
ipaddress.IPv4Address(net)


Out[40]:
IPv4Address(u'255.255.255.0')

In [66]:
host = addr & (2**8-1) 
print "addr:\n",format(host,'032b')


addr:
00000000000000000000000011111111

In [67]:
ipaddress.IPv4Address(host)


Out[67]:
IPv4Address(u'0.0.0.255')

In [68]:



Out[68]:
'1111111111111111111111111111111100000000'

In [72]:
2**8


Out[72]:
256

In [73]:
ip=ipaddress.ip_address(u"192.168.0.1")

In [74]:
addr = int(ip)

In [101]:
key = "secret"
ip=ipaddress.ip_address(u"192.168.0.0")
print ip.exploded
signature = hmac.new(key,ip.exploded,hashlib.sha256).hexdigest()
print signature


192.168.0.0
a8d0041786413438397fad8ca9ac76b953a3d69eae02c71f80260c1a504b1f7f

In [104]:
key = "secret"
ip=ipaddress.ip_address(u"192.168.1.0")
print ip.exploded
signature = hmac.new(key,ip.exploded,hashlib.sha256).hexdigest()
print signature


192.168.1.0
8c3846806237fb162152c5aa3a6f33402a887c8aaddcb429e7e7035b6c2e4ef0

In [ ]:


In [99]:



Out[99]:
u'2001:0db8:0000:0000:0000:0000:0000:0000'

In [102]:
ip=ipaddress.ip_address(u"2001:db8::0")
print ip.exploded
signature = hmac.new(key,ip.exploded,hashlib.sha256).hexdigest()
print signature


2001:0db8:0000:0000:0000:0000:0000:0000
b57bc65d1bfb665858bdf45ee0ebc984115c63734223be206e35d53781a91694

In [ ]:


In [106]:
ip=ipaddress.ip_address(u"2001:DB8:0:0:8:800:200C:0")
print ip.exploded
signature = hmac.new(key,ip.exploded,hashlib.sha256).hexdigest()
print signature


2001:0db8:0000:0000:0008:0800:200c:0000
6e7f8162892efa041d94188f4ad19a1e9968535d735133ef17cd01e60db832ac

In [107]:
ip=ipaddress.ip_address(u"2001:DB8:0:0:8:800:200C:0")
print ip.exploded
signature = hmac.new(key,ip.exploded,hashlib.sha256).hexdigest()
print signature


2001:0db8:0000:0000:0008:0800:200c:0000
6e7f8162892efa041d94188f4ad19a1e9968535d735133ef17cd01e60db832ac

In [ ]: