Subversion Repositories pub

Compare Revisions

No changes between revisions

Ignore whitespace Rev 181 → Rev 182

/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/prf_dot11_test.py
0,0 → 1,54
#!/usr/bin/env python
""" crypto.keyedHash.prf_dot11_test
Tests of the IEEE 802.11 PRF functions
"""
from crypto.keyedHash.prf_dot11 import PRF
import unittest
from binascii_plus import b2a_hex, a2b_hex, b2a_p, a2b_p
 
class prf_TestVectors(unittest.TestCase):
""" PRF from IEEE 802.11 testing known values """
def testKnowValues(self):
""" Test vectors from 11-02-298r0-I-suggested-changes-to-RSN.doc
Modified to show prefix and correct length.
"""
for [key,data,digest,prf_know_value] in prfTestVectors:
# the 298r test vectors do not include the prefix :-(
prefix = 'prefix'
# remove white spaces and convert to binary string
prf_value = a2b_p(prf_know_value)
lengthInBits=8*len(prf_value)
a_prf = PRF(key,prefix,data,lengthInBits)
 
print 'key = ', b2a_p(key)
print 'prefix = ', '"'+prefix+'"'
print 'data = ', b2a_p(data)
print 'PRF = ', b2a_p(a_prf)
print 'PRF_v = ', b2a_p(prf_value)
print 'len prf= ', len(a_prf)* 8
self.assertEqual(a_prf, prf_value)
 
""" -------------- (key, data, digest, prf_value) ------------------ """
prfTestVectors =((a2b_hex('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b'),
'Hi There',
'b617318655057264e28bc0b6fb378c8ef146be00',
'bcd4c650b30b9684951829e0d75f9d54'),
('Jefe',
'what do ya want for nothing?',
'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79',
"""51f4de5b33f249adf81aeb713a3c20f4fe631446fabdfa58
244759ae58ef9009a99abf4eac2ca5fa87e692c440eb40023e
7babb206d61de7b92f41529092b8fc"""),
(20*chr(0xaa),
50*chr(0xdd), #0xdd repeated 50 times
'125d7342b9ac11cd91a39af48aa17b4f63f175d3',
"""e1ac546ec4cb636f9976487be5c86be17a0252ca5d8d8df12c
fb0473525249ce9dd8d177ead710bc9b590547239107aef7b4ab
d43d87f0a68f1cbd9e2b6f7607"""))
 
 
 
# Make this test module runnable from the command prompt
if __name__ == "__main__":
unittest.main()
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/tkip_mic_test.py
0,0 → 1,83
#!/usr/bin/env python
""" Testing of TKIP_MIC Class
"""
from crypto.keyedHash.tkip_mic import TKIP_MIC
from binascii_plus import *
from struct import pack, unpack
import unittest
 
class TKIP_MIC_Tests(unittest.TestCase):
""" Test MIC algorithm using know values """
def testAdrianExample1(self):
""" Test 1 from Adrian 2002-12-12"""
print "==== Test 1 Adrian ===="
# raw data
k0 = 0x00000000L # assume is a 'dword'
k1 = 0x00000000L
key = pack('<II', k0, k1 ) # pack two integers into string little-endian
a1 = a2b_p('161514131211')
a2 = a2b_p('262524232221')
a3 = a2b_p('363534333231') # assumed to be TA
a4 = a2b_p('464544434241')
tcid = 2
payload = a2b_p('10 11 12 13 14 15 16 17 18 19 1a 1b 1c')
 
 
# this looks like a 4 addresses example do:
sa = a2 # a4
da = a1 # a3
print "key =", b2a_p(key)
print "sa =", b2a_p(sa)
print "da =", b2a_p(da)
print "tcid =", tcid
print "payload =", b2a_p(payload)
v0 = 0x85a3fe4cL
v1 = 0x20f4105fL
micResultAdrian = pack('<II', v0, v1) # pack little-endian dwords into 8 octets
 
tkipMic = TKIP_MIC(key)
micResult = tkipMic.hash(sa, da, tcid, payload )
print "expected MIC =", b2a_p(micResultAdrian)
print "MIC Result =", b2a_p(micResult)
v0Result, v1Result = unpack('<II', micResult)
self.assertEqual( v0, v0Result ), 'failed vo'
self.assertEqual( v1, v1Result ), 'failed v1'
 
def testParagExample1(self):
""" Test 2 from Parag 2002-12-16"""
print "==== Test 2 ===="
# raw data
k0 = 0x01234567L
k1 = 0x89abcdefL
key = pack('<II', k0, k1 ) # pack two integers into string little-endian
 
da = a2b_p('aaaaaaaaaaaa')
sa = a2b_p('bbbbbbbbbbbb')
priority = 0x03
 
payload = pack('<IIIIIIIIIII',0xdeaf0005L, 0xdeaf0006L, 0xdeaf0007L, 0xdeaf0008L, 0xdeaf0009L, 0xdeaf000aL, 0xdeaf000bL, 0xdeaf000cL, 0xdeaf000dL, 0xdeaf000eL, 0x00ccdd00L)
payload = payload[:-1] # trim off last octet
print "key =", b2a_p(key)
print "sa =", b2a_p(sa)
print "da =", b2a_p(da)
print "priority =", priority
print "payload =", b2a_p(payload)
 
# The know MIC is
v0 = 0xe597b391L
v1 = 0xb8c4a7b7L
micResultParag = pack('<II', v0, v1) # pack little-endian dwords into 8 octets
 
tkipMic = TKIP_MIC(key)
tcid = priority
micResult = tkipMic.hash(sa, da, tcid, payload )
print "expected MIC =", b2a_p(micResultParag)
print "MIC Result =", b2a_p(micResult)
v0Result, v1Result = unpack('<II', micResult)
self.assertEqual( v0, v0Result ), 'failed vo'
self.assertEqual( v1, v1Result ), 'failed v1'
 
if __name__ == '__main__':
unittest.main() # run all the tests
 
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/__init__.py
0,0 → 1,7
""" crypto.keyedHash
 
The keyedHash package.
 
Copyright © (c) 2002 by Paul A. Lambert
Read LICENSE.txt for license information.
"""
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/prf_dot11.py
0,0 → 1,38
""" prf_dot11.py
 
The PRF function is used in a number of places in 802.11i
to create psuedo random octet strings.
 
The parameter 'prefix' is a string that shall be a unique label for each
different purpose of the PRF.
"""
 
import hmac, sha # available in any Python 2.x
 
def PRF( key, prefix, data, number_of_bits):
""" Key, prefix and data are arbitrary strings .
number_of_bits must be a multiple of 8
HMAC_SHA1 generates 20 byte blocks. Enough are generated to get the
requested number of octets and the reslut is truncated to the requested size.
"""
number_of_octets, remainder = divmod(number_of_bits,8)
if remainder != 0:
raise ValueError, 'requested bits not multiple of 8'
R = ''
i = 0
while len(R) <= number_of_octets :
hmac_sha_1= hmac.new( key, prefix + chr(0x00) + data + chr(i), sha )
i = i + 1
R = R + hmac_sha_1.digest() # concatenate latest hash to result string
return R[:number_of_octets] # return R truncated to 'number_of_octets'
 
def PRF_128(key,A,B): return PRF(key,A,B,128)
def PRF_192(key,A,B): return PRF(key,A,B,192)
def PRF_256(key,A,B): return PRF(key,A,B,256)
def PRF_384(key,A,B): return PRF(key,A,B,384)
def PRF_512(key,A,B): return PRF(key,A,B,512)
def PRF_768(key,A,B): return PRF(key,A,B,768)
 
 
 
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/tkip_mic.py
0,0 → 1,40
""" crypto.keyedHash.tkip_mic
 
A reference implementation of the TKIP Message Integrety Chek (MIC)
that is defined in IEEE 802.11i
 
The MIC is based on Michael, a 64-bit MIC, with a design strength of 20 bits.
 
(c) 2002 Paul A. Lambert
"""
from crypto.keyedHash.michael import Michael
 
class TKIP_MIC(Michael):
""" The TKIP MIC Calculation for IEEE 802.11 TGi
This MIC algorithm uses the Michael Message Integrity Check (MIC)
and incorporates the DA, SA, priority and padding as
part of the MIC calculation
"""
def __init__(self, key=None, version='D3'):
""" """
self.version = version
Michael.__init__(self,key)
 
def hash(self, sa, da, priority, msduData ):
""" The TKIP MIC appends sa, da and priority to msduData
and uses the result in the Michael keyed hash
to create an 8 octet MIC value
"""
assert( 0 <= priority <= 15 ), 'Priority must be 4 bit value'
assert( (len(sa)==6) and (len(da)==6) ), 'Addresses must be 6 octets'
 
if self.version == 'D3':
micData = da + sa + chr(priority) + 3*chr(0) + msduData
elif self.version == 'D2':
micData = da + sa + msduData
else:
raise 'bad version'
 
return Michael.hash(self, micData)
 
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/michael_test.py
0,0 → 1,57
#!/usr/bin/env python
""" crypto.keyedHash.michael_test
 
Tests of the Michael Message Integrity Check Algorithm
 
Copyright © (c) 2002 by Paul A. Lambert
Read LICENSE.txt for license information.
"""
from crypto.keyedHash.michael import Michael
from binascii import *
import unittest
 
class Michael_TestVectors(unittest.TestCase):
""" Test MIC algorithm using know values """
def testIEEE_BaseKnowValues(self):
""" Test using vectors from IEEE P802.11i/D2.0 """
def runSingleTest(key,data,micResult):
print "============================="
key = a2b_hex(key)
knownMICResult = a2b_hex(micResult)
print "key: ",b2a_hex(key)
print "data: ",b2a_hex(data)
print "knownMIC: ", b2a_hex(knownMICResult)
micAlg = Michael(key)
calculatedMIC = micAlg.hash(data)
print "CalcMIC: ", b2a_hex(calculatedMIC)
self.assertEqual( calculatedMIC, knownMICResult )
 
# alternate calling sequence
micAlg = Michael()
micAlg.setKey(key)
calculatedMIC = micAlg.hash(data)
self.assertEqual( calculatedMIC, knownMICResult )
 
# yet another way to use algorithm
calculatedMIC = micAlg(data)
self.assertEqual( calculatedMIC, knownMICResult )
 
runSingleTest( "0000000000000000", "" , "82925c1ca1d130b8" )
runSingleTest( "82925c1ca1d130b8", "M" , "434721ca40639b3f" )
runSingleTest( "434721ca40639b3f", "Mi" , "e8f9becae97e5d29" )
runSingleTest( "e8f9becae97e5d29", "Mic" , "90038fc6cf13c1db" )
runSingleTest( "90038fc6cf13c1db", "Mich" , "d55e100510128986" )
runSingleTest( "d55e100510128986", "Michael" , "0a942b124ecaa546" )
 
class Michael_Check_Corners(unittest.TestCase):
def testShortKey(self):
""" Check for assertion on short key """
pass
def testLongKey(self):
""" Check for assertion on too long key """
pass
 
if __name__ == '__main__':
unittest.main() # run all the tests
 
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/michael.py
0,0 → 1,69
""" crypto.keyedHash.michael
 
A reference implementation of the Michael Message Integrety Chek (MIC)
that is defined in IEEE 802.11 Task Group 'i'
 
Michael is a 64-bit MIC, with a design strength of 20 bits.
 
Copyright © (c) 2002 by Paul A. Lambert
Read LICENSE.txt for license information.
"""
from struct import pack, unpack
from binascii_plus import *
 
class Michael:
""" The Michael keyed hash as defined in IEEE 802.11i D2.0 """
def __init__(self, key = None):
self.name = 'Michael'
self.blocksize = 1 # single octets can be hashed by padding to raw block size
self.raw_block_size = 4 # operates on 32 bits or 4 byte blocks
self.digest_size = 8 # MIC size of 64 bits or 8 bytes
self.keySize = 8 # key size is 8 octets
self.strength = 20
if key != None:
self.setKey(key)
def __del__(self):
self.setKey(8*chr(0)) # feable attempt to clear keys on exit
 
def setKey(self,key):
""" setKey(key) ... key is binary string """
assert( len(key)== self.keySize), 'Key must be 8 octets'
self._key = unpack('<II', key) # unpack into 2 32bit integers
 
def __call__(self,data,more=None):
return self.hash(data)
 
def hash(self,data):
""" Michael keyed hash """
fullBlocks, extraOctets = divmod(len(data),4)
paddedData = data + chr(0x5a) + chr(0)*(7-extraOctets)
l, r = self._key
for i in range(fullBlocks+2):
mSub_i = unpack('<I', paddedData[i*4:i*4+4])[0] # ith block as 32 bit integer
l = l ^ mSub_i
l, r = b(l,r)
digest = pack('<II', l, r )
return digest
 
def update(self,data):
raise 'No update method supported for Michael keyed hash'
def digest(self):
raise 'No digest method supported for Michael keyed hash'
def final(self,data):
raise 'No final method supported for Michael keyed hash'
 
def b(l,r):
""" The 'b' block function for the IEEE 802.11i Michael Integrity Check """
r ^= (((l<<17) & 0xffffffffL)|((l>>15) & 0x1ffffL)) # r = r ^ (l <<< 17)
l = (l+r) & 0xffffffffL # l = (l+r) mod 2**32
r ^= ((l & 0xff00ff00L)>>8)|((l & 0x00ff00ffL)<<8) # r = r ^ XSWAP(l)
l = (l+r) & 0xffffffffL # l = (l+r) mod 2**32
r ^= (((l<<3) & 0xffffffffL) | ((l>>29)& 0x7)) # r = r ^ (l <<< 3)
l = (l+r) & 0xffffffffL # l = (l+r) mod 2**32
r ^= (((l<<30L) & 0xffffffffL)|((l>>2) & 0x3fffffff)) # r = r ^ (l >>> 2)
l = (l+r) & 0xffffffffL # l = (l+r) mod 2**32
return (l,r)
 
 
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/pbkdf2_test.py
0,0 → 1,83
#!/usr/bin/env python
""" crypto.keyedHash.pbkdf2_test
 
Unit tests for crypto.keyedHash.pbkdf2
 
Copyright © (c) 2002 by Paul A. Lambert
Read LICENSE.txt for license information.
"""
 
from crypto.keyedHash.pbkdf2 import pbkdf2, dot11PassPhraseToPSK
import unittest
from binascii_plus import a2b_p, b2a_p, b2a_hex,b2a_pter
 
class PBDKDF22_KnowAnswerTests(unittest.TestCase):
""" """
def pbkdf2KAT(self,testDescription, password, salt, iterations, keySize, ka):
""" Know Answer Tests from IEEE """
knownAnswer = a2b_p(ka) # convert ascii 2 binary
derivedKey = pbkdf2(password, salt, iterations, keySize)
print "========== %s ==========" % testDescription
print 'password = "%s"' % password
print "salt/ssid = %s" % b2a_pter(salt, frnt=' ')[15:]
print "iterations =", iterations
print "keySize =", keySize
print "derivedKey =", b2a_p(derivedKey, frnt=' ')[15:]
#print "knownAnswer =", b2a_p(knownAnswer, frnt=' ')[15:]
self.assertEqual(derivedKey, knownAnswer), "KAT Failed-> %s "% testDescription
 
 
def testKnownAnswerRFC3211_1(self):
description = "RFC3211 KAT Test 1"
password = "password"
salt = a2b_p("12 34 56 78 78 56 34 12")
iterations = 5
keySize = 8
knownAnswer = "D1 DA A7 86 15 F2 87 E6"
self.pbkdf2KAT(description, password, salt, iterations, keySize, knownAnswer)
 
def testknownAnswerTGi_1(self):
description = "pbkdf2 IEEE 802.11 TGi Test 1"
password = "password"
ssid = "IEEE"
iterations = 4096 # IEEE 802.11 TGi spcification
keySize = 32 # 32 bytes, 256 bits
knownAnswer = """f4 2c 6f c5 2d f0 eb ef 9e bb 4b 90 b3 8a 5f 90
2e 83 fe 1b 13 5a 70 e2 3a ed 76 2e 97 10 a1 2e"""
self.pbkdf2KAT(description, password, ssid, iterations, keySize, knownAnswer)
 
def testknownAnswerTGi_2(self):
description = "pbkdf2 IEEE 802.11 TGi Test 2"
password = "ThisIsAPassword"
ssid = "ThisIsASSID"
iterations = 4096 # IEEE 802.11 TGi spcification
keySize = 32 # 32 bytes, 256 bits
knownAnswer = """0d c0 d6 eb 90 55 5e d6 41 97 56 b9 a1 5e c3 e3
20 9b 63 df 70 7d d5 08 d1 45 81 f8 98 27 21 af"""
self.pbkdf2KAT(description, password, ssid, iterations, keySize, knownAnswer)
 
def testknownAnswerTGi_3(self):
description = "pbkdf2 IEEE 802.11 TGi Test 3"
password = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
ssid = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
iterations = 4096 # IEEE 802.11 TGi spcification
keySize = 32 # 32 bytes, 256 bits
knownAnswer = """be cb 93 86 6b b8 c3 83 2c b7 77 c2 f5 59 80 7c
8c 59 af cb 6e ae 73 48 85 00 13 00 a9 81 cc 62"""
self.pbkdf2KAT(description, password, ssid, iterations, keySize, knownAnswer)
 
def testDot11PassPhraseToPSK(self):
passPhrase = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
ssid = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
knownAnswer = """be cb 93 86 6b b8 c3 83 2c b7 77 c2 f5 59 80 7c
8c 59 af cb 6e ae 73 48 85 00 13 00 a9 81 cc 62"""
 
key = dot11PassPhraseToPSK( passPhrase, ssid )
 
self.assertEqual( a2b_p(knownAnswer), key )
 
if __name__ == '__main__':
# Run the tests from the command line
unittest.main()
 
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/pbkdf2.py
0,0 → 1,43
""" crypto.keyedHash.pbkdf2
 
 
Password Based Key Derivation Function 2
References: RFC2898, B. Kaliski, September 2000, PKCS #5
 
This function is used for IEEE 802.11/WPA passphrase to key hashing
 
Copyright © (c) 2002 by Paul A. Lambert
Read LICENSE.txt for license information.
"""
from crypto.keyedHash.hmacHash import HMAC_SHA1
from crypto.common import xor
from math import ceil
from struct import pack
 
def pbkdf2(password, salt, iterations, keySize, PRF=HMAC_SHA1):
""" Create key of size keySize from password and salt """
if len(password)>63:
raise 'Password too long for pbkdf2'
#if len(password)<8 : raise 'Password too short for pbkdf2'
if (keySize > 10000): # spec says >4294967295L*digestSize
raise 'keySize too long for PBKDF2'
 
prf = PRF(key=password) # HMAC_SHA1
numBlocks = ceil(1.*keySize/prf.digest_size) # ceiling function
key = ''
for block in range(1,numBlocks+1):
# Calculate F(P, salt, iterations, i)
F = prf(salt+pack('>i',block)) # i is packed into 4 big-endian bytes
U = prf(salt+pack('>i',block)) # i is packed into 4 big-endian bytes
for count in range(2,iterations+1):
U = prf(U)
F = xor(F,U)
key = key + F
return key[:keySize]
 
def dot11PassPhraseToPSK(passPhrase,ssid):
""" The 802.11 TGi recommended pass-phrase-to-preshared-key mapping.
This function simply uses pbkdf2 with interations=4096 and keySize=32
"""
assert( 7<len(passPhrase)<64 ), 'Passphrase must be greater than 7 or less than 64 characters'
return pbkdf2(passPhrase, ssid, iterations=4096, keySize=32)
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/tkip_key_mixing_test.py
0,0 → 1,214
#! /usr/bin/env python
""" crypto.keyedHash.tkip_key_mixing
Tests for TKIP key mixing function
Paul Lambert
November 4, 2002
"""
import unittest
from crypto.keyedHash.tkip_key_mixing import TKIP_Mixer
from struct import pack, unpack
from binascii_plus import a2b_p, b2a_p, b2a_hex
 
class TKIP_Mixer_Know_Answer_Tests(unittest.TestCase):
""" Test TKIP Mixing using know values (aka test vectors) """
def testTKIP_Mixer_KnowValues(self):
""" Test using vectors from IEEE 802.11TGi D2.4.2 """
for testCase in TKIP_MixerTestCases:
description = testCase['testCase']
tk = a2b_p(testCase['TK'])
ta = a2b_p(testCase['TA'])
iv32 = a2b_p(testCase['IV32']) # last 4 octets of PN/IV field
iv16 = a2b_p(testCase['IV16'])
# NOTE - iv16 and iv32 are confused notation from early drafts
# may not match notation in the future
 
pnField = iv16[1]+iv16[0] + iv32[3]+iv32[2]+iv32[1]+iv32[0]
pn = unpack('<Q', pnField + 2*chr(0) )[0]
 
knownP1key = a2b_p(testCase['P1K'])
knownRC4Key = a2b_p(testCase['RC4KEY'])
 
print '==========================================================='
print 'testCase:%s'%description
print 'TK: %s'%b2a_p(tk)[9:]
print 'TA: %s'%b2a_p(ta)[9:]
print 'IV32: %s'%b2a_p(iv32)[9:]
print 'IV16: %s'%b2a_p(iv16)[9:]
keyId = 0
eh1 = chr((ord(pnField[1])|0x20)&0x7f)
eh = pnField[0]+eh1+pnField[1]+chr((keyId<<6)|0x20)+pnField[2:]
print 'EncHdr: %s (with KeyId=0)' % b2a_p(eh)[9:]
print 'PNfield: %s' % b2a_p(pnField)[9:]
print 'PNvalue: hex 0x%012X decimal %d' % (pn,pn)
#print 'TSC: [0x%04x, 0x%04x, 0x%04x]' % (unpack('<H',pnField[0:2])[0],\
# unpack('<H',pnField[2:4])[0],unpack('<H',pnField[4:6])[0])
 
mixer = TKIP_Mixer(tk,ta)
newRC4Key = mixer.newKey(pnField)
 
p1kstring = ''.join([pack('>H',i) for i in mixer.phase1Key]) # a list of int's
print 'TTAK: [0x%04x, 0x%04x, 0x%04x, 0x%04x, 0x%04x]' % (mixer.phase1Key[0], \
mixer.phase1Key[1],mixer.phase1Key[2],mixer.phase1Key[3],mixer.phase1Key[4])
print 'P1K: %s'%b2a_p(p1kstring)[9:]
#print 'knownP1K:%s'%b2a_p(knownP1key)[9:]
self.assertEqual( p1kstring, knownP1key),'Phase1 Keys dont match'
 
print 'RC4Key: %s'% b2a_p(newRC4Key)[9:]
#print 'knownRC4Key: %s'% b2a_p(knownRC4Key)[9:]
self.assertEqual( newRC4Key, knownRC4Key ),'Final Key does not match'
print '==========================================================='
 
def xtestTKIP_Mixer_Sequence(self):
""" Test TKIP Mixing using alternate calling approaches """
key = 16*chr(0)
ta = 6*chr(0)
tscOctets = 6*chr(0)
 
keyMixer = TKIP_Mixer(key)
keyMixer.setTA(ta)
newKey = keyMixer.newKey(tscOctets)
 
keyMixer = TKIP_Mixer()
keyMixer.setTA(ta)
keyMixer.setKey(key)
newKey = keyMixer.newKey(tscOctets)
 
keyMixer = TKIP_Mixer(transmitterAddress=ta)
keyMixer.setKey(key)
newKey = keyMixer.newKey(tscOctets)
 
 
def xtestGunarExample1(self):
""" Test example from Gunnar 2003-01-27 """
tk1 = a2b_p( "A9 90 6D C8 3E 78 92 3F 86 04 E9 9E F6 CD BA BB" )
ta = a2b_p( "50 30 F1 84 44 08" )
iv32 = a2b_p( "B5039776" ) # [transmitted as B5 03 97 76]
iv16 = a2b_p( "E70C" )
p1k = a2b_p( "26D5 F1E1 2A59 2021 0E8E" )
rc4Key = a2b_p( "E7 67 0C 68 15 E0 2E 3F 1C 15 92 92 D4 E2 78 82" )
mixer = TKIP_Mixer(tk1,ta)
newRC4Key = mixer.newKey(iv16+iv32)
print "=== Gunnar Example ==="
print "rc4Key = ", b2a_p( rc4Key )
print "newRC4Key = ", b2a_p( newRC4Key )
print "knownp1K = ", b2a_p( p1k )
print "calcp1K = %04X %04X %04x %04x %04x" % (mixer.phase1Key[0],mixer.phase1Key[1],mixer.phase1Key[2],mixer.phase1Key[3],mixer.phase1Key[4])
self.assertEqual(rc4Key,newRC4Key)
 
def xtestTKIP_Mixer_TV_values(self):
""" Test using vectors from IEEE 802.11TGi D2.4.2 """
for testCase in TKIP_TestVector:
description = testCase['testCase']
tk = a2b_p(testCase['TK'])
ta = a2b_p(testCase['TA'])
pn = testCase['PN']
pnField = pack('<Q', pn)[:6]
 
print '==========================================================='
print 'testCase:%s'%description
print 'TK: %s'%b2a_p(tk)[9:]
print 'TA: %s'%b2a_p(ta)[9:]
keyId = 0
eh1 = chr((ord(pnField[1])|0x20)&0x7f)
eh = pnField[0]+eh1+pnField[1]+chr((keyId<<6)|0x20)+pnField[2:]
print 'EncHdr: %s (with KeyId=0)' % b2a_p(eh)[9:]
print 'PNfield: %s' % b2a_p(pnField)[9:]
print 'PNvalue: 0x%06X' % pn
print 'TSC?: [0x%04x, 0x%04x, 0x%04x]' % (unpack('<H',pnField[0:2])[0],\
unpack('<H',pnField[2:4])[0],unpack('<H',pnField[4:6])[0])
 
mixer = TKIP_Mixer(tk,ta)
newRC4Key = mixer.newKey(pnField)
p1kstring = ''.join([pack('>H',i) for i in mixer.phase1Key]) # a list of int's
print 'TTAK: [0x%04x, 0x%04x, 0x%04x, 0x%04x, 0x%04x]' % (mixer.phase1Key[0], \
mixer.phase1Key[1],mixer.phase1Key[2],mixer.phase1Key[3],mixer.phase1Key[4])
print 'P1K: %s'%b2a_p(p1kstring)[9:]
 
print 'RC4Key: %s' % b2a_p( newRC4Key )[9:]
print 'kRC4Key: %s' % b2a_p( a2b_p(testCase['RC4KEY']))[9:]
self.assertEqual(newRC4Key, a2b_p(testCase['RC4KEY']))
print '==========================================================='
 
""" TKIP_Mixer Know Answer Tests from IEEE TGi """
TKIP_MixerTestCases = [
{'testCase': "IEEE TGi TKIP_Mixer Test vector #1",
'TK' : "00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F",
'TA' : "10 22 33 44 55 66",
'IV32' : "00000000",
'IV16' : "0000",
'P1K' : "3DD2 016E 76F4 8697 B2E8",
'RC4KEY': "00 20 00 33 EA 8D 2F 60 CA 6D 13 74 23 4A 66 0B"},
 
{'testCase': "IEEE TGi TKIP_Mixer Test vector #2",
'TK' : "00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F",
'TA' : "10 22 33 44 55 66",
'IV32' : "00000000", #[transmitted as 00 00 00 00]
'IV16' : "0001",
'P1K' : "3DD2 016E 76F4 8697 B2E8",
'RC4KEY': "00 20 01 90 FF DC 31 43 89 A9 D9 D0 74 FD 20 AA"},
 
{'testCase':"IEEE TGi TKIP_Mixer Test vector #3",
'TK' : "63 89 3B 25 08 40 B8 AE 0B D0 FA 7E 61 D2 78 3E",
'TA' : "64 F2 EA ED DC 25",
'IV32' : "20DCFD43",
'IV16' : "FFFF",
'P1K' : "7C67 49D7 9724 B5E9 B4F1",
'RC4KEY': "FF 7F FF 93 81 0F C6 E5 8F 5D D3 26 25 15 44 CE"},
 
{'testCase': "IEEE TGi TKIP_Mixer Test vector #4",
'TK' : "63 89 3B 25 08 40 B8 AE 0B D0 FA 7E 61 D2 78 3E",
'TA' : "64 F2 EA ED DC 25",
'IV32' : "20DCFD44",
'IV16' : "0000",
'P1K' : "5A5D 73A8 A859 2EC1 DC8B",
'RC4KEY': "00 20 00 49 8C A4 71 FC FB FA A1 6E 36 10 F0 05"},
 
{'testCase': "IEEE TGi TKIP_Mixer Test vector #5",
'TK' : "98 3A 16 EF 4F AC B3 51 AA 9E CC 27 1D 73 09 E2",
'TA' : "50 9C 4B 17 27 D9",
'IV32' : "F0A410FC",
'IV16' : "058C",
'P1K' : "F2DF EBB1 88D3 5923 A07C",
'RC4KEY': "05 25 8C F4 D8 51 52 F4 D9 AF 1A 64 F1 D0 70 21"},
 
{'testCase': "IEEE TGi TKIP_Mixer Test vector #6",
'TK' : "98 3A 16 EF 4F AC B3 51 AA 9E CC 27 1D 73 09 E2",
'TA' : "50 9C 4B 17 27 D9",
'IV32' : "F0A410FC",
'IV16' : "058D",
'P1K' : "F2DF EBB1 88D3 5923 A07C ",
'RC4KEY': "05 25 8D 09 F8 15 43 B7 6A 59 6F C2 C6 73 8B 30"},
 
{'testCase': "IEEE TGi TKIP_Mixer Test vector #7",
'TK' : "C8 AD C1 6A 8B 4D DA 3B 4D D5 B6 54 38 35 9B 05",
'TA' : "94 5E 24 4E 4D 6E",
'IV32' : "8B1573B7",
'IV16' : "30F8",
'P1K' : "EFF1 3F38 A364 60A9 76F3",
'RC4KEY': "30 30 F8 65 0D A0 73 EA 61 4E A8 F4 74 EE 03 19"},
 
{'testCase': "IEEE TGi TKIP_Mixer Test vector #8",
'TK' : "C8 AD C1 6A 8B 4D DA 3B 4D D5 B6 54 38 35 9B 05",
'TA' : "94 5E 24 4E 4D 6E",
'IV32' : "8B1573B7",
'IV16' : "30F9",
'P1K' : "EFF1 3F38 A364 60A9 76F3",
'RC4KEY': "30 30 F9 31 55 CE 29 34 37 CC 76 71 27 16 AB 8F"}
]
 
TKIP_TestVector = [
{'testCase': "-------------TKIP Test Vector 1",
'TK' : "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f",
'TA' : "10 22 33 44 55 66",
'PN' : 0x000000000000,
'RC4KEY': "00 20 00 33 EA 8D 2F 60 CA 6D 13 74 23 4A 66 0B"},
{'testCase': "-------------IEEE TGi TKIP_Mixer Test vector #6 Mod to PN",
'TK' : "98 3A 16 EF 4F AC B3 51 AA 9E CC 27 1D 73 09 E2",
'TA' : "50 9C 4B 17 27 D9",
'PN' : 0xF0A410FC058D, # [transmitted as: 8D 25 05 DefKeyID FC 10 A4 F0]
'RC4KEY': "05 25 8D 09 F8 15 43 B7 6A 59 6F C2 C6 73 8B 30"}]
 
# Make this test module runnable from the command prompt
if __name__ == "__main__":
unittest.main()
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/tkip_key_mixing.py
0,0 → 1,135
""" crypto.keyedHash.tkip_key_mixing.py
TKIP Temporal Key Mixing Function reference implementation
 
2002-11-04
 
"""
from struct import pack, unpack
from binascii_plus import *
 
def S(word):
""" TKIP S-Box non-linear substitution of a 16 bit word """
return (tkipSbox[0][word & 0x00FF] ^ tkipSbox[1][(word>>8) & 0x00FF])
 
""" tkipSbox consists of two 256 word arrays
The tkip Sbox is formed from the AES/Rijndael Sbox
"""
 
from crypto.cipher.rijndael import Sbox
tkipSbox = [range(256),range(256)] # arbitrary initialization
for i in range(256):
k = Sbox[i] # the rijndael S box (imported)
if k & 0x80 : # calculate k*2 polynomial math
k2 = (k<<1)^0x11b # reduce by rijndael modulas
else:
k2 = k<<1
k3 = k ^ k2
tkipSbox[0][i] = (k2<<8)^k3
tkipSbox[1][i] = (k3<<8)^k2 # second array is just byte swap of first array
 
def rotR1(v16):
""" circular right rotate on 16 bits """
return ((((v16) >> 1) & 0x7FFF) ^ (((v16) & 1) << 15))
 
class TKIP_Mixer:
""" The TKIP_Mixer class generates dynamic keys for TKIP based on the
TK (temporal key), TA and PN
"""
def __init__(self, tk1=None, transmitterAddress=None, pnBytes=6*chr(0)):
""" The TKIP Mixer is initialized with tk1 and TA
tk1 is a temporal key (16 octet string)
transmitterAddress is a 6 octet MAC address
pn is the packet number, here as an integer < (1<<8*6)
"""
self.tk = None
self.ta = None
self.setPnBytes(pnBytes) # sets self.pnBytes and validates input
self.upper4SequenceOctets = self.pnBytes[-4:]
if tk1 != None :
self.setKey(tk1)
if transmitterAddress != None :
self.setTA(transmitterAddress)
 
def setKey(self, key):
""" Set the temporal key (tk1) for key mixing """
if len(key)!= 16: raise 'Wrong key size'
# for readability of subroutines, make tk a list of 1 octet ints
self.tk = [ord(byte) for byte in key]
if self.ta != None : # reset phase1 value
self.phase1Key = phase1KeyMixing( self.tk, self.ta, self.pn)
 
def setTA(self, taBytes):
""" Set the transmitter address """
if len(taBytes) != 6: raise 'Bad size for transmitterAddress'
self.ta = [ord(byte) for byte in taBytes]
if self.tk != None : # reset phase1 value
self.phase1Key = phase1KeyMixing( self.tk, self.ta, self.pn )
 
def setPnBytes(self, pnBytes):
""" Set the pnBytes from the packet number (int) """
assert( len(pnBytes)==6 ), 'pnBytes must be 6 octets'
self.pnBytes = pnBytes
self.pn = [ord(byte) for byte in pnBytes] # int list for readability
 
def newKey(self, pnBytes):
""" return a new 'mixed' key (16 octets) based on
the pn in 6 octets, also know as TSC
"""
assert(self.ta != None), 'No TA'
assert(self.tk != None), 'No TK'
self.setPnBytes(pnBytes)
if self.pnBytes[-4:] != self.upper4SequenceOctets: # check if upper bits change
# calculate phase1 key only when upper bytes change
self.upper4SequenceOctets = pnBytes[-4:]
self.phase1Key = phase1KeyMixing( self.tk, self.ta, self.pn )
return phase2KeyMixing( self.tk, self.phase1Key, self.pn )
 
def phase1KeyMixing(tk,ta,pn):
""" Create a p1k (5 integers) from TK, TA and upper 4 octets of sequence number pn"""
p1k = [0,0,0,0,0] # array of 5 integers (each 2 octets)
p1k[0] = pn[3]*256 + pn[2]
p1k[1] = pn[5]*256 + pn[4]
p1k[2] = ta[1]*256 + ta[0] # 2 octets of MAC as an integer (little-endian)
p1k[3] = ta[3]*256 + ta[2] # 2 octets of MAC as an integer (little-endian)
p1k[4] = ta[5]*256 + ta[4] # 2 octets of MAC as an integer (little-endian)
for i in range(8):
j = 2*(i&1)
p1k[0] = ( p1k[0] + S( p1k[4]^(tk[j+ 1]*256 + tk[j+ 0]))) & 0xFFFF
p1k[1] = ( p1k[1] + S( p1k[0]^(tk[j+ 5]*256 + tk[j+ 4]))) & 0xFFFF
p1k[2] = ( p1k[2] + S( p1k[1]^(tk[j+ 9]*256 + tk[j+ 8]))) & 0xFFFF
p1k[3] = ( p1k[3] + S( p1k[2]^(tk[j+13]*256 + tk[j+12]))) & 0xFFFF
p1k[4] = ( p1k[4] + S( p1k[3]^(tk[j+ 1]*256 + tk[j])) + i ) & 0xFFFF
return p1k
 
def phase2KeyMixing(tk,p1k,pn):
""" Create a 16 octet key from the phase1Key (p1k)
and 2 octets of sequence counter """
ppk = [i for i in p1k]
ppk.append( p1k[4] + pn[1]*256 + pn[0] ) # append value for ppk[5]
# Bijective non-linear mixing of the 96 bits of ppk
ppk[0] = (ppk[0] + S(ppk[5] ^ (tk[1]*256 + tk[0]) )) & 0xFFFF
ppk[1] = (ppk[1] + S(ppk[0] ^ (tk[3]*256 + tk[2]) )) & 0xFFFF
ppk[2] = (ppk[2] + S(ppk[1] ^ (tk[5]*256 + tk[4]) )) & 0xFFFF
ppk[3] = (ppk[3] + S(ppk[2] ^ (tk[7]*256 + tk[6]) )) & 0xFFFF
ppk[4] = (ppk[4] + S(ppk[3] ^ (tk[9]*256 + tk[8]) )) & 0xFFFF
ppk[5] = (ppk[5] + S(ppk[4] ^ (tk[11]*256+ tk[10]) )) & 0xFFFF
# Final sweep
ppk[0] = (ppk[0] + rotR1(ppk[5] ^ (tk[13]*256+tk[12]))) & 0xFFFF
ppk[1] = (ppk[1] + rotR1(ppk[0] ^ (tk[15]*256+tk[14]))) & 0xFFFF
ppk[2] = (ppk[2] + rotR1(ppk[1])) & 0xFFFF
ppk[3] = (ppk[3] + rotR1(ppk[2])) & 0xFFFF
ppk[4] = (ppk[4] + rotR1(ppk[3])) & 0xFFFF
ppk[5] = (ppk[5] + rotR1(ppk[4])) & 0xFFFF
 
rc4Key = range(16)
rc4Key[0] = pn[0]
rc4Key[1] = (pn[0] | 0x20) & 0x7F
rc4Key[2] = pn[1]
rc4Key[3] = 0xFF &((ppk[5]^(tk[1]*256+tk[0]))>>1)
for i in range(6):
rc4Key[4+2*i] = ppk[i] & 0xff
rc4Key[5+2*i] = (ppk[i]>>8) & 0xff
wepSeed = ''.join([chr(i) for i in rc4Key]) # convert to string
return wepSeed
 
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/hmacHash_test.py
0,0 → 1,121
#!/usr/bin/env python
""" hmacHash_test.py
Unit tests for hmacHash.py
 
So far only runs test vectors from RFC2104
References
[IETF] RFC 2104 "HMAC: Keyed-Hashing for Message Authentication"
[IETF] RFC 2202
"""
 
import unittest
from crypto.keyedHash.hmacHash import HMAC, HMAC_SHA1
from crypto.hash.sha1Hash import SHA1
from crypto.hash.md5Hash import MD5
from binascii import a2b_hex, b2a_hex
 
class HMAC_Simple_TestCases(unittest.TestCase):
""" HMAC constructed ny hand """
def testSHA1_NullKey(self):
""" HMAC_SHA1 testNullKey """
ki = ''.join([chr(0x36) for i in range(64)])
ko = ''.join([chr(0x5C) for i in range(64)])
h = SHA1()
keyedHashAlg = HMAC(SHA1,key='')
assert ( keyedHashAlg('') == h(ko+h(ki)) ), 'Null key, Null data test'
assert ( keyedHashAlg('a') == h(ko+h(ki+'a')) ), 'Null key, a data test'
assert ( keyedHashAlg('ab') == h(ko+h(ki+'ab')) ), 'Null key, ab data test'
assert ( keyedHashAlg(50*'a') == h(ko+h(ki+50*'a')) ), 'Null key, 50*a data test'
# try hmac in two steps of 25 chrs
manual_hmac = h(ko+h(ki+50*'a'))
keyedHashAlg.update(25*'a')
keyedHashAlg.update(25*'a')
hm = keyedHashAlg.digest()
assert (hm == manual_hmac), 'HMAC as update, update and digest'
 
def testMD5_NullKey(self):
""" HMAC_MD5 testNullKey """
ki = ''.join([chr(0x36) for i in range(64)])
ko = ''.join([chr(0x5C) for i in range(64)])
h = MD5()
keyedHashAlg = HMAC(MD5,key='')
assert ( keyedHashAlg('') == h(ko+h(ki)) ), 'Null key, Null data test'
assert ( keyedHashAlg('a') == h(ko+h(ki+'a')) ), 'Null key, a data test'
assert ( keyedHashAlg('ab') == h(ko+h(ki+'ab')) ), 'Null key, ab data test'
assert ( keyedHashAlg(50*'a') == h(ko+h(ki+50*'a')) ), 'Null key, 50*a data test'
 
def testSHA1_oneByteKey(self):
""" HMAC_SHA1 oneByteKey of 0xFF"""
ki = ''.join([chr(0x36) for i in range(64)])
ko = ''.join([chr(0x5C) for i in range(64)])
ki = chr(ord(ki[0])^0xFF)+ ki[1:]
ko = chr(ord(ko[0])^0xFF)+ ko[1:]
h = SHA1()
keyedHashAlg = HMAC(SHA1,chr(0xff))
assert ( keyedHashAlg('') == h(ko+h(ki)) ), 'one byte key, Null data test'
assert ( keyedHashAlg('a') == h(ko+h(ki+'a')) ), 'one byte key, a data test'
assert ( keyedHashAlg('ab') == h(ko+h(ki+'ab')) ), 'one byte key, ab data test'
assert ( keyedHashAlg(50*'a') == h(ko+h(ki+50*'a')) ), 'one byte key, 50*a data test'
 
class HMAC_RFC2104_TestCases(unittest.TestCase):
""" HMAC tests from RFC2104 """
 
def testRFC2104_1(self):
""" RFC2104 test 1 and various calling methods """
key = chr(0x0b)*20
keyedHashAlg = HMAC(SHA1,key)
data = "Hi There"
digest = a2b_hex('b617318655057264e28bc0b6fb378c8ef146be00')
cd=keyedHashAlg(data)
assert( cd == digest ), 'RFC2104 test 1 failed'
 
hmac_sha1 = HMAC_SHA1(key)
cd = hmac_sha1.hash(data)
assert( cd == digest ), 'RFC2104 test 1 failed, HMAC_SHA1 called'
 
cd = hmac_sha1.hash(data[:3],more=1)
cd = hmac_sha1.hash(data[3:])
assert( cd == digest ), 'RFC2104 test 1 failed, HMAC_SHA1 called twice'
 
hmac_sha1.update(data[:3])
hmac_sha1.update(data[3:])
cd = hmac_sha1.digest()
print b2a_hex(cd)
assert( cd == digest ), 'RFC2104 test 1 failed, HMAC_SHA1 called with update'
 
hmac_sha1.reset(data)
cd1 = hmac_sha1.hash(data)
cd2 = hmac_sha1.hash(data)
print b2a_hex(cd1)
print b2a_hex(cd2)
assert( cd1 == cd2 ), 'hash method should default to reseting state'
 
 
def testRFC2104_2(self):
""" RFC2104 test 2 """
keyedHashAlg = HMAC(SHA1)
key = 'Jefe'
keyedHashAlg.setKey(key)
data = 'what do ya want for nothing?'
digest = a2b_hex('effcdf6ae5eb2fa2d27416d5f184df9c259a7c79')
cd = keyedHashAlg(data)
assert( cd == digest ), 'RFC2104 test 2 failed'
 
def testRFC2104_3(self):
""" RFC2104 test 3 """
key = a2b_hex('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
keyedHashAlg = HMAC_SHA1(key)
data = 50*chr(0xdd)
digest = a2b_hex('125d7342b9ac11cd91a39af48aa17b4f63f175d3')
cd = keyedHashAlg(data)
assert( cd == digest ), 'RFC2104 test 3 failed'
 
 
 
 
if __name__ == '__main__':
# Run the tests from the command line
unittest.main()
 
 
 
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/hmacHash.py
0,0 → 1,83
""" hmacHash.py
 
Implemention of Request for Comments: 2104
HMAC: Keyed-Hashing for Message Authentication
 
HMAC is a mechanism for message authentication
using cryptographic hash functions. HMAC can be used with any
iterative cryptographic hash function, e.g., MD5, SHA-1, in
combination with a secret shared key. The cryptographic strength of
HMAC depends on the properties of the underlying hash function.
 
This implementation of HMAC uses a generic cryptographic 'hashFunction'
(self.H). Hash functions must conform to the crypto.hash method
conventions and are not directly compatible with the Python sha1 or md5 algorithms.
 
[IETF] RFC 2104 "HMAC: Keyed-Hashing for Message Authentication"
>>>key = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>>keyedHashAlg = HMAC(SHA1, key)
>>>result = keyedHashAlg(data)
"""
from crypto.hash.hash import Hash
 
class HMAC(Hash):
""" To compute HMAC over the data `text' we perform
H(K XOR opad, H(K XOR ipad, text))
"""
def __init__(self, hashFunction, key = None):
""" initialize HMAC with hashfunction and optionally the key """
# should check for right type of function
self.H = hashFunction() # a new instance for inner hash
self.H_outer = hashFunction() # separate outer context to allow intermediate digests
self.B = self.H.raw_block_size # in bytes, note - hash block size typically 1
# and raw_block_size much larger
# e.g. raw_block_size is 64 bytes for SHA1 and MD5
self.name = 'HMAC_'+self.H.name
self.blocksize = 1 # single octets can be hashed by padding to raw block size
self.raw_block_size = self.H.raw_block_size
self.digest_size = self.H.digest_size
if key != None:
self.setKey(key)
else:
self.keyed = None
 
def setKey(self,key):
""" setKey(key) ... key is binary string """
if len(key) > self.B: # if key is too long then hash it
key = self.H(key) # humm... this is odd, hash can be smaller than B
else: # should raise error on short key, but breaks tests :-(
key =key + (self.B-len(key)) * chr(0)
self.k_xor_ipad = ''.join([chr(ord(bchar)^0x36) for bchar in key])
self.k_xor_opad = ''.join([chr(ord(bchar)^0x5C) for bchar in key])
self.keyed = 1
self.reset()
 
def reset(self):
self.H.reset()
if self.keyed == None :
raise 'no key defined'
self.H.update(self.k_xor_ipad) # start inner hash with key xored with ipad
# outer hash always called as one full pass (no updates)
def update(self,data):
if self.keyed == None :
raise 'no key defined'
self.H.update(data)
def digest(self):
if self.keyed == None :
raise 'no key defined'
return self.H_outer(self.k_xor_opad+self.H.digest())
 
from crypto.hash.sha1Hash import SHA1
class HMAC_SHA1(HMAC):
""" Predefined HMAC built on SHA1 """
def __init__(self, key = None):
""" optionally initialize with key """
HMAC.__init__(self,SHA1,key)
 
from crypto.hash.md5Hash import MD5
class HMAC_MD5(HMAC):
""" Predefined HMAC built on SHA1 """
def __init__(self, key = None):
""" optionally initialize with key """
HMAC.__init__(self,MD5,key)
/relevation/ext/cryptopy-1.2.5.orig/crypto/keyedHash/.
Property changes:
Added: bugtraq:number
+true
\ No newline at end of property