def __init__(self, key, msg=None, digestmod=None): """Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ if digestmod == None: import MD5 digestmod = MD5 self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() try: self.digest_size = digestmod.digest_size except AttributeError: self.digest_size = len(self.outer.digest()) blocksize = 64 ipad = 0x36 opad = 0x5C if len(key) > blocksize: key = digestmod.new(key).digest() key = key + chr(0) * (blocksize - len(key)) self.outer.update(strxor_c(key, opad)) self.inner.update(strxor_c(key, ipad)) if (msg): self.update(msg)
def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ if digestmod == None: import MD5 digestmod = MD5 self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() try: self.digest_size = digestmod.digest_size except AttributeError: self.digest_size = len(self.outer.digest()) blocksize = 64 ipad = 0x36 opad = 0x5C if len(key) > blocksize: key = digestmod.new(key).digest() key = key + chr(0) * (blocksize - len(key)) self.outer.update(strxor_c(key, opad)) self.inner.update(strxor_c(key, ipad)) if (msg): self.update(msg)
def __init__(self, key, msg=None, digestmod=None): if digestmod is None: import MD5 digestmod = MD5 self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() try: self.digest_size = digestmod.digest_size except AttributeError: self.digest_size = len(self.outer.digest()) try: blocksize = digestmod.block_size except AttributeError: blocksize = 64 ipad = 54 opad = 92 if len(key) > blocksize: key = digestmod.new(key).digest() key = key + bchr(0) * (blocksize - len(key)) self.outer.update(strxor_c(key, opad)) self.inner.update(strxor_c(key, ipad)) if msg: self.update(msg) return
def hmacSHA1(key, message): if len(key) > blocksize: key = sha1(key) if len(key) < blocksize: key += b'\x00' * (blocksize - len(key)) opad = strxor_c(key, 0x5c) ipad = strxor_c(key, 0x36) return sha1(opad + sha1(ipad + message))
def hmac(key, message, hash_function=hash_sha1, blocksize=64): if len(key) > blocksize: key = hash_function(key) if len(key) < blocksize: key += b'\x00' * (blocksize - len(key)) opad = strxor_c(key, 0x5c) ipad = strxor_c(key, 0x36) return hash_function(opad + hash_function(ipad + message))
def __init__(self, key): self.key = key # self.m = b'Hi There' self.hash = SHA1_29() self.bs = 64 self.output_size = 20 if len(self.key) > self.bs: self.key = self.hash.digest(self.key) if len(self.key) < self.bs: self.key = self.key + (0).to_bytes( (self.bs - len(self.key)), 'little') self.o_key_pad = strxor_c(self.key, 0x5c) self.i_key_pad = strxor_c(self.key, 0x36)
def __init__(self, key, msg=None, digestmod=None): """Create a new HMAC object. :Parameters: key : byte string secret key for the MAC object. It must be long enough to match the expected security level of the MAC. However, there is no benefit in using keys longer than the `digest_size` of the underlying hash algorithm. msg : byte string The very first chunk of the message to authenticate. It is equivalent to an early call to `update()`. Optional. :Parameter digestmod: The hash algorithm the HMAC is based on. Default is `Crypto.Hash.MD5`. :Type digestmod: A hash module or object instantiated from `Crypto.Hash` """ if digestmod is None: import MD5 digestmod = MD5 self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() try: self.digest_size = digestmod.digest_size except AttributeError: self.digest_size = len(self.outer.digest()) try: # The block size is 128 bytes for SHA384 and SHA512 and 64 bytes # for the others hash function blocksize = digestmod.block_size except AttributeError: blocksize = 64 ipad = 0x36 opad = 0x5C if len(key) > blocksize: key = digestmod.new(key).digest() key = key + bchr(0) * (blocksize - len(key)) self.outer.update(strxor_c(key, opad)) self.inner.update(strxor_c(key, ipad)) if (msg): self.update(msg)
def find_key(hh): score_list = dict() for k in range(0, 256): score_list.update({k: find_score(strxor_c(hh, k))}) key = max(score_list, key=score_list.get) return key
def maxLike(s): maximum = ((0,''),0) for x in range(0,256): tmp = (freqScore(cu.strxor_c(unhexlify(s),x)),x) if maximum[0][0] < tmp[0][0]: maximum = tmp return maximum
def answer(s): print(s) def compfunc(items): return englishness(items[1]) return max([(i, strxor_c(s, i)) for i in range(0, 256)], key=compfunc)
def find_key(hh): score_list = dict() for k in range(0, 256): score_list.update({k : find_score(strxor_c(hh,k))}) key = max(score_list, key=score_list.get) return key
def brute(cipher): score = [] for i in range(32, 128): #taking only printable characters text = strxor_c(cipher, i) score.append(has_english_words(text) + has_forbidden_digraphs(text)) temp = score.index(max(score)) return temp + 32
def bruteforce(hex_b): def score(t): return freq_score(t[1]) key_byte, plaintext = \ max([(k, strxor_c(hex_b,k)) for k in range(0,256)], key=score) key_char= chr(key_byte) return(key_byte, key_char, plaintext)
def solve(crypt_msg): max_score, decoder, secret = 0, None, None unhex_msg = stringlib.decode_hex(crypt_msg) for c in range(256): dec_msg = strxor.strxor_c(unhex_msg, c) score = stringlib.score(dec_msg) if score > max_score: max_score, decoder, secret = score, c, dec_msg return secret, max_score, decoder
def test_invalid_mac(self): from Crypto.Util.strxor import strxor_c cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96) ct, mac = cipher.encrypt_and_digest(self.data_128) invalid_mac = strxor_c(mac, 0x01) cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96) self.assertRaises(ValueError, cipher.decrypt_and_verify, ct, invalid_mac)
def test_output_overlapping_memoryview(self): """Verify result can be stored in overlapping memory""" term1 = memoryview(bytearray(unhexlify(b"ff339a83e5cd4cdf5649"))) expected_xor = unhexlify(b"be72dbc2a48c0d9e1708") result = strxor_c(term1, 65, output=term1) self.assertEqual(result, None) self.assertEqual(term1, expected_xor)
def __init__(self, key): self.__key_gen = itertools.cycle([ord(x) for x in key]).next self.__key_xor = lambda s: ''.join(chr(ord(x) ^ self.__key_gen()) for x in s) if len(key) == 1: try: from Crypto.Util.strxor import strxor_c c = ord(key) self.__key_xor = lambda s: strxor_c(s, c) except ImportError: sys.stderr.write('Load Crypto.Util.strxor Failed, Use Pure Python Instead.\n')
def test_invalid_mac(self): from Crypto.Util.strxor import strxor_c cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) ct, mac = cipher.encrypt_and_digest(self.data_128) invalid_mac = strxor_c(mac, 0x01) cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) self.assertRaises(ValueError, cipher.decrypt_and_verify, ct, invalid_mac)
def test_invalid_mac(self): from Crypto.Util.strxor import strxor_c cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) ct, mac = cipher.encrypt_and_digest(self.data_128) invalid_mac = strxor_c(mac, 0x01) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) self.assertRaises(ValueError, cipher.decrypt_and_verify, ct, invalid_mac)
def test_output_memoryview(self): term1 = unhexlify(b"ff339a83e5cd4cdf5649") original_term1 = term1[:] expected_result = unhexlify(b"be72dbc2a48c0d9e1708") output = memoryview(bytearray(len(term1))) result = strxor_c(term1, 65, output=output) self.assertEqual(result, None) self.assertEqual(output, expected_result) self.assertEqual(term1, original_term1)
def check(s): max=0 pos =0; for i in range(0,256): res = strxor_c(s, i) temp =score(res) if temp > max: max=temp pos =i # print max return pos
def runTest(self): key = binascii.a2b_hex(b(self.key)) data = binascii.a2b_hex(b(self.input)) # Strip whitespace from the expected string (which should be in lowercase-hex) expected = b("".join(self.result.split())) h = self.module.new(key, **self.params) h.update(data) out1_bin = h.digest() out1 = binascii.b2a_hex(h.digest()) out2 = h.hexdigest() # Verify that correct MAC does not raise any exception h.hexverify(out1) h.verify(out1_bin) # Verify that incorrect MAC does raise ValueError exception wrong_mac = strxor_c(out1_bin, 255) self.assertRaises(ValueError, h.verify, wrong_mac) self.assertRaises(ValueError, h.hexverify, "4556") h = self.module.new(key, data, **self.params) out3 = h.hexdigest() out4 = binascii.b2a_hex(h.digest()) # Test .copy() h2 = h.copy() h.update(b("blah blah blah")) # Corrupt the original hash object out5 = binascii.b2a_hex(h2.digest( )) # The copied hash object should return the correct result # PY3K: Check that hexdigest() returns str and digest() returns bytes if sys.version_info[0] > 2: self.assertTrue(isinstance(h.digest(), type(b("")))) self.assertTrue(isinstance(h.hexdigest(), type(""))) # PY3K: Check that .hexverify() accepts bytes or str if sys.version_info[0] > 2: h.hexverify(h.hexdigest()) h.hexverify(h.hexdigest().encode('ascii')) # PY3K: hexdigest() should return str, and digest() should return bytes self.assertEqual(expected, out1) if sys.version_info[0] == 2: self.assertEqual(expected, out2) self.assertEqual(expected, out3) else: self.assertEqual(expected.decode(), out2) self.assertEqual(expected.decode(), out3) self.assertEqual(expected, out4) self.assertEqual(expected, out5)
def check(s): check_string =s; max_val=0 pos =0; for i in range(0,256): res = strxor_c(check_string, i) temp =score(res) if temp > max_val: max_val=temp pos =i return pos,max_val,check_string
def runTest(self): key = binascii.a2b_hex(b(self.key)) data = binascii.a2b_hex(b(self.input)) # Strip whitespace from the expected string (which should be in lowercase-hex) expected = b("".join(self.result.split())) h = self.module.new(key, **self.params) h.update(data) out1_bin = h.digest() out1 = binascii.b2a_hex(h.digest()) out2 = h.hexdigest() # Verify that correct MAC does not raise any exception h.hexverify(out1) h.verify(out1_bin) # Verify that incorrect MAC does raise ValueError exception wrong_mac = strxor_c(out1_bin, 255) self.assertRaises(ValueError, h.verify, wrong_mac) self.assertRaises(ValueError, h.hexverify, "4556") h = self.module.new(key, data, **self.params) out3 = h.hexdigest() out4 = binascii.b2a_hex(h.digest()) # Test .copy() h2 = h.copy() h.update(b("blah blah blah")) # Corrupt the original hash object out5 = binascii.b2a_hex(h2.digest()) # The copied hash object should return the correct result # PY3K: Check that hexdigest() returns str and digest() returns bytes if sys.version_info[0] > 2: self.assertTrue(isinstance(h.digest(), type(b("")))) self.assertTrue(isinstance(h.hexdigest(), type(""))) # PY3K: Check that .hexverify() accepts bytes or str if sys.version_info[0] > 2: h.hexverify(h.hexdigest()) h.hexverify(h.hexdigest().encode('ascii')) # PY3K: hexdigest() should return str, and digest() should return bytes self.assertEqual(expected, out1) if sys.version_info[0] == 2: self.assertEqual(expected, out2) self.assertEqual(expected, out3) else: self.assertEqual(expected.decode(), out2) self.assertEqual(expected.decode(), out3) self.assertEqual(expected, out4) self.assertEqual(expected, out5)
def repeating_xor(key, plaintext): # computes the xor of the plaintext with a repeating key keylen = len(key) split_text = (plaintext[i::keylen] for i in range(keylen)) xor_split = tuple(strxor_c(txt, k) for txt, k in zip(split_text, key)) # have to encode the text becaue python3 is puts the characters into # unicode strings xor_text = ''.join(''.join(map(chr, t)) for t in zip(*xor_split)).encode() # if the key doesn't match the text length exactly, add in the last # characters from remainder = len(plaintext) % keylen xor_text += ''.join(chr(s[-1]) for s in xor_split[:remainder]).encode() return xor_text
def detect_key_decrypt(text): w, h = 34, 256 results = [[" " for x in range(w)] for y in range(h)] for i in range(0,256): results[i] = (strxor_c(text,i).lower()) max = 0 sentence = [] for i in range(0,h): if(score(results[i]) > max): max = score(results[i]) sentence = results[i] return sentence
def __init__(self, key, msg=None, digestmod=None): """Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ if digestmod is None: import MD5 digestmod = MD5 self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() try: self.digest_size = digestmod.digest_size except AttributeError: self.digest_size = len(self.outer.digest()) try: # The block size is 128 bytes for SHA384 and SHA512 and 64 bytes # for the others hash function blocksize = digestmod.block_size except AttributeError: blocksize = 64 ipad = 0x36 opad = 0x5C if len(key) > blocksize: key = digestmod.new(key).digest() key = key + bchr(0) * (blocksize - len(key)) self.outer.update(strxor_c(key, opad)) self.inner.update(strxor_c(key, ipad)) if msg: self.update(msg)
def runTest(self): tag = unhexlify(b"fb447350c4e868c52ac3275cf9d4327e") msg = b'' for msg_len in range(5000 + 1): key = tag + strxor_c(tag, 0xFF) nonce = tag[::-1] if msg_len > 0: msg = msg + tobytes(tag[0]) auth = Poly1305.new(key=key, nonce=nonce, cipher=AES, data=msg) tag = auth.digest() # Compare against output of original DJB's poly1305aes-20050218 self.assertEqual("CDFA436DDD629C7DC20E1128530BAED2", auth.hexdigest().upper())
def breakSingleKeyXOR(ct_raw): topCandidate = b'' topScore = 0 # ct = sys.stdin.buffer.read(4000) # ct_raw = binascii.unhexlify( ct ) for key in range(KEY_CANDIDATE_FLOOR, KEY_CANDIDATE_CEIL + 1): ptCandidate = strxor_c(ct_raw, key) currentScore = scoreCandidate(ptCandidate) if currentScore > topScore: topScore = currentScore topCandidate = ptCandidate # best candidate # print( topCandidate.decode("ISO-8859-1") ) return topCandidate
def runTest(self): result_hex = hexlify(self.result) # Verify result h = self.module.new(self.key, **self.params) h.update(self.data) self.assertEqual(self.result, h.digest()) self.assertEqual(hexlify(self.result).decode('ascii'), h.hexdigest()) # Verify that correct MAC does not raise any exception h.verify(self.result) h.hexverify(result_hex) # Verify that incorrect MAC does raise ValueError exception wrong_mac = strxor_c(self.result, 255) self.assertRaises(ValueError, h.verify, wrong_mac) self.assertRaises(ValueError, h.hexverify, "4556") # Verify again, with data passed to new() h = self.module.new(self.key, self.data, **self.params) self.assertEqual(self.result, h.digest()) self.assertEqual(hexlify(self.result).decode('ascii'), h.hexdigest()) # Test .copy() try: h = self.module.new(self.key, self.data, **self.params) h2 = h.copy() h3 = h.copy() # Verify that changing the copy does not change the original h2.update(b"bla") self.assertEqual(h3.digest(), self.result) # Verify that both can reach the same state h.update(b"bla") self.assertEqual(h.digest(), h2.digest()) except NotImplementedError: pass # PY3K: Check that hexdigest() returns str and digest() returns bytes self.assertTrue(isinstance(h.digest(), type(b""))) self.assertTrue(isinstance(h.hexdigest(), type(""))) # PY3K: Check that .hexverify() accepts bytes or str h.hexverify(h.hexdigest()) h.hexverify(h.hexdigest().encode('ascii'))
def test_degradation(self): sub_key1 = bchr(1) * 8 sub_key2 = bchr(255) * 8 # K1 == K2 self.assertRaises(ValueError, DES3.adjust_key_parity, sub_key1 * 2 + sub_key2) # K2 == K3 self.assertRaises(ValueError, DES3.adjust_key_parity, sub_key1 + sub_key2 * 2) # K1 == K2 == K3 self.assertRaises(ValueError, DES3.adjust_key_parity, sub_key1 * 3) # K1 == K2 (with different parity) self.assertRaises(ValueError, DES3.adjust_key_parity, sub_key1 + strxor_c(sub_key1, 1) + sub_key2)
def runTest(self): sub_key1 = bchr(1) * 8 sub_key2 = bchr(255) * 8 # K1 == K2 self.assertRaises(ValueError, DES3.new, sub_key1 * 2 + sub_key2, DES3.MODE_ECB) # K2 == K3 self.assertRaises(ValueError, DES3.new, sub_key1 + sub_key2 * 2, DES3.MODE_ECB) # K1 == K2 == K3 self.assertRaises(ValueError, DES3.new, sub_key1 * 3, DES3.MODE_ECB) # K2 == K3 (parity is ignored) self.assertRaises(ValueError, DES3.new, sub_key1 + sub_key2 + strxor_c(sub_key2, 0x1), DES3.MODE_ECB)
def wrong_mac_test(self): """Negative tests for MAC""" self.description = "Test for wrong MAC in %s of %s" % \ (self.mode_name, self.module.__name__) ad_ref = b("Reference AD") pt_ref = b("Reference plaintext") # Encrypt and create the reference MAC cipher = self.module.new(self.key, self.mode, self.iv) cipher.update(ad_ref) ct_ref = cipher.encrypt(pt_ref) mac_ref = cipher.digest() # Modify the MAC and verify it is NOT ACCEPTED wrong_mac = strxor_c(mac_ref, 255) decipher = self.module.new(self.key, self.mode, self.iv) decipher.update(ad_ref) self.assertRaises(ValueError, decipher.decrypt_and_verify, ct_ref, wrong_mac)
def highscore_xor(keyspace, ciphertext): # returns the key with the highest number of characters in the most_common # set, and no unprintable characters # any character in the ciphertext is excluded as null byte generating keyspace = keyspace.difference(set(ciphertext)) highscore = 0 for key in keyspace: decipher = strxor_c(ciphertext, key) # skip if there are any unprintable characters if any(c in unprintable for c in decipher): continue count = Counter(decipher.lower()) score = sum(count[k] for k in most_common) if score > highscore: highscore = score truekey = key # if no key actually works, return None try: return truekey except NameError: return None
def runTest(self): sub_key1 = bchr(1) * 8 sub_key2 = bchr(255) * 8 # K1 == K2 self.assertRaises(ValueError, DES3.new, sub_key1 * 2 + sub_key2, DES3.MODE_ECB) # K2 == K3 self.assertRaises(ValueError, DES3.new, sub_key1 + sub_key2 * 2, DES3.MODE_ECB) # K1 == K2 == K3 self.assertRaises(ValueError, DES3.new, sub_key1 *3, DES3.MODE_ECB) # K2 == K3 (parity is ignored) self.assertRaises(ValueError, DES3.new, sub_key1 + sub_key2 + strxor_c(sub_key2, 0x1), DES3.MODE_ECB)
def test3(self): self.assertEqual(strxor_c(b(""), 90), b(""))
def test_verify(self): h = self.BLAKE2.new(digest_bytes=self.max_bytes, key=b("4")) mac = h.digest() h.verify(mac) wrong_mac = strxor_c(mac, 255) self.assertRaises(ValueError, h.verify, wrong_mac)
def break_single_byte_XOR(s): 'Input byte string s. XOR each letter in s against all chars. Return max score base on char frequency.' def key(p): return score(p[1]) # 2nd element in tuple below return max([(i, strxor_c(s, i)) for i in range(0, 256)], key=key)
def check(s): check_string =s; max_val=0 pos =0; for i in range(0,256): res = strxor_c(check_string, i) temp =score(res) if temp > max_val: max_val=temp pos =i return pos,max_val,check_string f_in= open("file1-4.txt",'r') f_out = open("ans.txt",'w') final_max = 0 final_pos =0 final_string ="" for line in f_in: line= line.strip() s = line.decode('hex') pos,max_val,fin = check(s) if max_val> final_max: final_max = max_val final_pos =pos final_string = fin print final_max, final_pos , strxor_c(final_string,final_pos)
def test_failed_mac(self): pt = bchr(9) * 100 ct, mac = self._create_cipher().encrypt_and_digest(pt) cipher = self._create_cipher() self.assertRaises(ValueError, cipher.decrypt_and_verify, ct, strxor_c(mac, 1))
def breakSingleByteKey(self,s): def key(p): return p[1] return max([(i, self.scoreStr(strxor_c(s, i)), strxor_c(s,i)) for i in range(0, 256)], key=key)
def test3(self): self.assertEqual(strxor_c(b"", 90), b"")
def score(s): score = 0 for c in s: if c in freqs: score += freqs[c] # print score return score def check(s): max = 0 pos = 0 for i in range(0, 256): res = strxor_c(s, i) temp = score(res) if temp > max: max = temp pos = i print max return pos var = raw_input("Enter hex: ") input = var.decode('hex') ans = check(input) print ans print strxor_c(input, ans)
def test_verify(self): h = Poly1305.new(key=self.key, cipher=AES) mac = h.digest() h.verify(mac) wrong_mac = strxor_c(mac, 255) self.assertRaises(ValueError, h.verify, wrong_mac)
def breakSingleByteXOR(s): def key(p): return score(p[1]) return max([(i, strxor_c(s, i)) for i in range(0, 256)], key=key)
def fixed_xor(value1, char): result = strxor_c(value1, char) return result
def break_single_byte_xor(s): def key(p): return score(p[1]) # 2nd element in tuple below return max([(i, strxor_c(s, i)) for i in range(0, 256)], key=key)
for key in range(0, 100): keys.append(key) def score(answer): scr = 0 for i in answer: c = chr(i).lower() if c in freqs: scr += freqs[c] return scr with open('/Users/amandaclark/PycharmProjects/CryptoChallenge/Set 1/data') as f: for line in f: files.append(line.rstrip('\n').encode('UTF-8')) for string in files: unhex.append(binascii.unhexlify(string)) for encrypt in unhex: for key in keys: answer = strxor_c(encrypt, key) scr = score(answer) scores[scr] = encrypt foo = max(scores, key = scores.get) print(foo, scores[foo])
def test1(self): term1 = unhexlify(b("ff339a83e5cd4cdf5649")) result = unhexlify(b("be72dbc2a48c0d9e1708")) self.assertEqual(strxor_c(term1, 65), result)
def test_memoryview(self): term1 = unhexlify(b"ff339a83e5cd4cdf5649") term1_mv = memoryview(term1) result = unhexlify(b"be72dbc2a48c0d9e1708") self.assertEqual(strxor_c(term1_mv, 65), result)
def test2(self): term1 = unhexlify(b("ff339a83e5cd4cdf5649")) self.assertEqual(strxor_c(term1, 0), term1)