コード例 #1
0
ファイル: HMAC.py プロジェクト: AeonSaber/first_app
    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)
コード例 #2
0
    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)
コード例 #3
0
    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
コード例 #4
0
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))
コード例 #5
0
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))
コード例 #6
0
ファイル: hmac.py プロジェクト: Tubbz-alt/cryptopals
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))
コード例 #7
0
 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)
コード例 #8
0
    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)
コード例 #9
0
ファイル: HMAC.py プロジェクト: nessvm/eVoting
    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)
コード例 #10
0
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
コード例 #11
0
ファイル: Matasano_lib.py プロジェクト: dpfeif/vagrant
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
コード例 #12
0
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)
コード例 #13
0
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
コード例 #14
0
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
コード例 #15
0
ファイル: c3.py プロジェクト: sagi/cryptopals
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)
コード例 #16
0
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
コード例 #17
0
ファイル: test_GCM.py プロジェクト: JaredLLewis/DBFinal
    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)
コード例 #18
0
ファイル: test_strxor.py プロジェクト: hjw705/PillAlarm
    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)
コード例 #19
0
ファイル: index.py プロジェクト: rtrice/openshift-diy-131231
 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')
コード例 #20
0
ファイル: test_SIV.py プロジェクト: snowman-st/edu-back
    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)
コード例 #21
0
ファイル: index.py プロジェクト: qingyuan0o0/goproxy-1
 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')
コード例 #22
0
    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)
コード例 #23
0
ファイル: test_strxor.py プロジェクト: hjw705/PillAlarm
    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)
コード例 #24
0
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
コード例 #25
0
    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)
コード例 #26
0
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
コード例 #27
0
ファイル: common.py プロジェクト: alanjds/pycryptodome
    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)
コード例 #28
0
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
コード例 #29
0
ファイル: single_byte_XOR.py プロジェクト: yarenska/kraker
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
コード例 #30
0
ファイル: HMAC.py プロジェクト: chinaares/centreon-discovery
    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)
コード例 #31
0
    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())
コード例 #32
0
    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())
コード例 #33
0
ファイル: s04aux.py プロジェクト: boneitis/cryptopals
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
コード例 #34
0
    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'))
コード例 #35
0
ファイル: common.py プロジェクト: Legrandin/pycryptodome
    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'))
コード例 #36
0
    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)
コード例 #37
0
ファイル: test_DES3.py プロジェクト: shubhanus/taiga
    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)
コード例 #38
0
    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)
コード例 #39
0
    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)
コード例 #40
0
ファイル: common.py プロジェクト: NormanDenayer/pycryptodome
    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)
コード例 #41
0
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
コード例 #42
0
ファイル: test_DES3.py プロジェクト: shubhanus/taiga
    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)
コード例 #43
0
ファイル: test_strxor.py プロジェクト: Gnof/pycryptodome
 def test3(self):
     self.assertEqual(strxor_c(b(""), 90), b(""))
コード例 #44
0
 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)
コード例 #45
0
ファイル: cf.py プロジェクト: benstannard/cryptopals
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)
コード例 #46
0
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)
コード例 #47
0
ファイル: test_OCB.py プロジェクト: hannesvn/pycryptodome
 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))
コード例 #48
0
 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)
コード例 #49
0
ファイル: test_strxor.py プロジェクト: snowman-st/edu-back
 def test3(self):
     self.assertEqual(strxor_c(b"", 90), b"")
コード例 #50
0

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)
コード例 #51
0
 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)
コード例 #52
0
ファイル: challenge3.py プロジェクト: Allen-smith/ctf-tools
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)
コード例 #53
0
def fixed_xor(value1, char):
    result = strxor_c(value1, char)

    return result
コード例 #54
0
ファイル: challenge03.py プロジェクト: benstannard/cryptopals
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)
コード例 #55
0
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])



コード例 #56
0
ファイル: test_strxor.py プロジェクト: Gnof/pycryptodome
 def test1(self):
     term1 = unhexlify(b("ff339a83e5cd4cdf5649"))
     result = unhexlify(b("be72dbc2a48c0d9e1708"))
     self.assertEqual(strxor_c(term1, 65), result)
コード例 #57
0
ファイル: test_strxor.py プロジェクト: snowman-st/edu-back
    def test_memoryview(self):
        term1 = unhexlify(b"ff339a83e5cd4cdf5649")
        term1_mv = memoryview(term1)
        result = unhexlify(b"be72dbc2a48c0d9e1708")

        self.assertEqual(strxor_c(term1_mv, 65), result)
コード例 #58
0
ファイル: test_strxor.py プロジェクト: Gnof/pycryptodome
 def test2(self):
     term1 = unhexlify(b("ff339a83e5cd4cdf5649"))
     self.assertEqual(strxor_c(term1, 0), term1)