Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nakagami
Created September 24, 2018 22:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakagami/93c1a88de4aa34eaa25c7d2f96c12ae4 to your computer and use it in GitHub Desktop.
Save nakagami/93c1a88de4aa34eaa25c7d2f96c12ae4 to your computer and use it in GitHub Desktop.
PostgreSQL SCRAM-SHA-256 authentication
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