1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
__revision__ = '0.1'
__author__ = 'lxd'
import hmac
from StringIO import StringIO
import pickle
def create_signature(key, msg):
h = hmac.new(key)
h.update(msg)
return h.hexdigest()
##########send##########
def send_buffer(signature, msg):
#模拟数据传输
return StringIO('%s\n%d\n%s' %(signature, len(msg), msg))
def send_msg(key, message):
msg = pickle.dumps(message)
signature = create_signature(key, msg)
return send_buffer(signature, msg)
##########get##########
def parse_buffer(buffer):
signature = buffer.readline().rstrip()#strip \n
msg_length = int(buffer.readline())
msg = buffer.read(msg_length)
return signature, msg
def check_signature(signature, key, msg):
new_signature = create_signature(key, msg)
if new_signature == signature:
return msg
else:
raise ValueError('signature error')
def get_msg(key, buffer):
signature, msg = parse_buffer(buffer)
message = check_signature(signature, key, msg)
return pickle.loads(message)
msg = 'some_message'
key = 'some_key'
buffer = send_msg(key, msg)
print get_msg(key, buffer)
|