基于python3的SCRAM基础过程的描述,协议中定义的数据结构和类型此处并没有完整实现
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 |
import hashlib import os import hmac import sys def xor(str1, str2): return b''.join((a^b).to_bytes(1, sys.byteorder) for a,b in zip(str1,str2)) #define the password, salt and iteration number password = b'Aa123456' salt = os.urandom(16) i = 10000 #client first mesg client_first_message_bare = os.urandom(32) #server first mesg, contain client_nonce and its own nonce server_first_message = os.urandom(32) #generate client proof SaltedPassword = hashlib.pbkdf2_hmac('sha256', password, salt, i) ClientKey = hmac.new(SaltedPassword, b'Client Key', 'sha256').digest() StoredKey = hashlib.sha256(ClientKey).digest() AuthMessage = client_first_message_bare + server_first_message ClientSignature = hmac.new(StoredKey, AuthMessage, 'sha256').digest() ClientProof = xor(ClientKey, ClientSignature) #client send the ClientProof and ClientSignature to the server #server verify the client s_ClientKey = xor(ClientSignature, ClientProof) if hmac.compare_digest(ClientKey, s_ClientKey): print('verify client success') #generate server signature ServerKey = hmac.new(SaltedPassword, b'Server Key', 'sha256').digest() ServerSignature = hmac.new(ServerKey, AuthMessage, 'sha256').digest() #client verify the server #compare the ServerSignature received from server and the one computed at client side c_ServerKey = hmac.new(SaltedPassword, b'Server Key', 'sha256').digest() c_ServerSignature = hmac.new(c_ServerKey, AuthMessage, 'sha256').digest() if hmac.compare_digest(ServerSignature, c_ServerSignature): print('verify server success') |
官方地址: https://tools.ietf.org/html/rfc5802