Created
September 24, 2018 22:01
-
-
Save nakagami/93c1a88de4aa34eaa25c7d2f96c12ae4 to your computer and use it in GitHub Desktop.
PostgreSQL SCRAM-SHA-256 authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
import hmac | |
import base64 | |
import binascii | |
password = 'foobar' | |
client_nonce = '9IZ2O01zb9IgiIZ1WJ/zgpJB' | |
server = { | |
'r': '9IZ2O01zb9IgiIZ1WJ/zgpJBjx/oIRLs02gGSHcw1KEty3eY', | |
's': 'fs3IXBy7U7+IvVjZ', | |
'i': '4096', | |
} | |
salted_pass = hashlib.pbkdf2_hmac( | |
'sha256', | |
password.encode('utf-8'), | |
base64.standard_b64decode(server['s']), | |
int(server['i']), | |
) | |
print(binascii.b2a_hex(salted_pass)) | |
client_key = hmac.HMAC( | |
salted_pass, b"Client Key", hashlib.sha256 | |
).digest() | |
print(binascii.b2a_hex(client_key)) | |
print(binascii.b2a_hex(hashlib.sha256(client_key).digest())) | |
client_first_message_bare = "n=,r=" + client_nonce | |
print(client_first_message_bare) | |
server_first_message = "r=%s,s=%s,i=%s" % (server['r'], server['s'], server['i']) | |
client_final_message_without_proof = "c=biws,r=" + server['r'] | |
print(client_final_message_without_proof) | |
auth_msg = ','.join([ | |
client_first_message_bare, | |
server_first_message, | |
client_final_message_without_proof | |
]) | |
print('auth_msg') | |
print(auth_msg) | |
client_sig = hmac.HMAC( | |
hashlib.sha256(client_key).digest(), | |
auth_msg.encode('utf-8'), | |
hashlib.sha256 | |
).digest() | |
print('client_key') | |
print(binascii.b2a_hex(client_key)) | |
print('client_sig') | |
print(binascii.b2a_hex(client_sig)) | |
print('bare proof') | |
print(binascii.b2a_hex(b"".join([bytes([x ^ y]) for x, y in zip(client_key, client_sig)]))) | |
proof = base64.standard_b64encode( | |
b"".join([bytes([x ^ y]) for x, y in zip(client_key, client_sig)]) | |
) | |
print('proof') | |
print(binascii.b2a_hex(proof)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment