Skip to content

Instantly share code, notes, and snippets.

@knight42
Last active August 29, 2015 14:26
Show Gist options
  • Save knight42/3b4a6a751e8bdf2a20c4 to your computer and use it in GitHub Desktop.
Save knight42/3b4a6a751e8bdf2a20c4 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3 -O
# -*- coding: utf-8 -*-
import hashlib
import binascii
from passlib.utils import des
def GenerateNTResponse(AuthChal, PeerChal, UserName, Password):
'''
IN 16-octet AuthenticatorChallenge,
IN 16-octet PeerChallenge,
IN 0-to-256-char UserName,
IN 0-to-256-unicode-char Password,
OUT 24-octet Response
'''
if isinstance(AuthChal, str):
AuthChal = bytes.fromhex(AuthChal)
if isinstance(PeerChal, str):
PeerChal = bytes.fromhex(PeerChal)
ChalHash = ChallengeHash(PeerChal, AuthChal, UserName)
NTHash = NtPasswordHash(Password)
return ChallengeResponse(ChalHash, NTHash)
def ChallengeHash(PeerChal, AuthChal, UserName):
'''
IN 16-octet PeerChallenge,
IN 16-octet AuthenticatorChallenge,
IN 0-to-256-char UserName,
OUT 8-octet Challenge
'''
sha1 = hashlib.sha1()
sha1.update(PeerChal)
sha1.update(AuthChal)
if isinstance(UserName, str):
UserName = UserName.encode('utf-8')
sha1.update(UserName)
return sha1.digest()[:8]
def NtPasswordHash(Password):
'''
IN 0-to-256-unicode-char Password,
OUT 16-octet PasswordHash
'''
PwdBin = Password.encode('utf-16')[2:]
md4 = hashlib.new('md4')
md4.update(PwdBin)
return md4.digest()
def ChallengeResponse(ChalHash, PwdHash):
'''
IN 8-octet Challenge,
IN 16-octet PasswordHash,
OUT 24-octet Response
'''
ZPasswordHash = b''.join((PwdHash, b'\x00'*5))
Response = b''
key = des.expand_des_key(ZPasswordHash[:7])
Response += des.des_encrypt_block(key, ChalHash)
key = des.expand_des_key(ZPasswordHash[7:14])
Response += des.des_encrypt_block(key, ChalHash)
key = des.expand_des_key(ZPasswordHash[14:])
Response += des.des_encrypt_block(key, ChalHash)
return Response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment