Esempio n. 1
0
def add_student(name, password, email):
    """creates unique id for each student, and adds student to the
       student table"""

    conn = sqlite3.connect(DBNAME)
    c = conn.cursor()

    #get length
    c.execute('SELECT name FROM {}'.format(STUDENTTNAME))

    ctnum = len(c.fetchall())

    #encrypt/encode text
    cipher = AES.new(SECRET)
    encoded = encodeAES(cipher, password)

    internstring = "" #string will contain 0 for each entry in internship table
    for r in view_internship_t():
        internstring += '0'

    c.execute("INSERT INTO {} values {}".format(STUDENTTNAME, STUDENTPARAMS),
              (name, encoded, ctnum, email, internstring))

    conn.commit()
    conn.close()

    return ctnum
    def runTest(self):
        key = b'0' * 16
        h = SHA256.new()

        for length in range(160):
            nonce = '{0:04d}'.format(length).encode('utf-8')
            data = bchr(length) * length
            cipher = AES.new(key, AES.MODE_GCM, nonce=nonce, **self._extra_params)
            ct, tag = cipher.encrypt_and_digest(data)
            h.update(ct)
            h.update(tag)

        self.assertEqual(h.hexdigest(), "7b7eb1ffbe67a2e53a912067c0ec8e62ebc7ce4d83490ea7426941349811bdf4")
 def test_invalid_mixing_encrypt_decrypt(self):
     # Once per method, with or without assoc. data
     for method1_name, method2_name in (("encrypt", "decrypt"),
                                        ("decrypt", "encrypt")):
         for assoc_data_present in (True, False):
             cipher = AES.new(self.key_128,
                              AES.MODE_OCB,
                              nonce=self.nonce_96)
             if assoc_data_present:
                 cipher.update(self.data_128)
             getattr(cipher, method1_name)(self.data_128)
             self.assertRaises(TypeError, getattr(cipher, method2_name),
                               self.data_128)
    def test_aes_256_cfb128(self):
        plaintext =     '6bc1bee22e409f96e93d7e117393172a' +\
                        'ae2d8a571e03ac9c9eb76fac45af8e51' +\
                        '30c81c46a35ce411e5fbc1191a0a52ef' +\
                        'f69f2445df4f9b17ad2b417be66c3710'

        ciphertext =    'dc7e84bfda79164b7ecd8486985d3860' +\
                        '39ffed143b28b1c832113c6331e5407b' +\
                        'df10132415e54b92a13ed0a8267ae2f9' +\
                        '75a385741ab9cef82031623d55b1e471'
        key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
        iv = '000102030405060708090a0b0c0d0e0f'

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Esempio n. 5
0
def decrypt_oracle(text, key):
    # # 秘钥
    # key = '123456'
    # # 密文
    # text = 'qR/TQk4INsWeXdMSbCDDdA=='
    # 初始化加密器
    aes = AES.new(add_to_16(key), AES.MODE_ECB)
    #优先逆向解密base64成bytes
    base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
    #执行解密密并转码返回str
    decrypted_text = str(aes.decrypt(base64_decrypted),
                         encoding='utf-8').replace('\0', '')
    return decrypted_text.rstrip("\r\n")
Esempio n. 6
0
 def setup_crypto(self, sn):
     """
     Performs decryption of packets received. Stores decrypted packets in a Queue for use.
     """
     if is_old_model(sn):
         self.old_model = True
     # print self.old_model
     k = ['\0'] * 16
     k[0] = sn[-1]
     k[1] = '\0'
     k[2] = sn[-2]
     if self.is_research:
         k[3] = 'H'
         k[4] = sn[-1]
         k[5] = '\0'
         k[6] = sn[-2]
         k[7] = 'T'
         k[8] = sn[-3]
         k[9] = '\x10'
         k[10] = sn[-4]
         k[11] = 'B'
     else:
         k[3] = 'T'
         k[4] = sn[-3]
         k[5] = '\x10'
         k[6] = sn[-4]
         k[7] = 'B'
         k[8] = sn[-1]
         k[9] = '\0'
         k[10] = sn[-2]
         k[11] = 'H'
     k[12] = sn[-3]
     k[13] = '\0'
     k[14] = sn[-4]
     k[15] = 'P'
     key = ''.join(k)
     iv = Random.new().read(AES.block_size)
     cipher = AES.new(key, AES.MODE_ECB, iv)
     # for i in k:
     #     print "0x%.02x " % (ord(i))
     while self.running:
         while not tasks.empty():
             task = tasks.get()
             try:
                 data = cipher.decrypt(task[:16]) + cipher.decrypt(task[16:])
                 self.packets.put_nowait(EmotivPacket(data, self.sensors, self.old_model))
                 self.packets_processed += 1
             except:
                 pass
             gevent.sleep(0)
         gevent.sleep(0)
    def test3(self):

        for keylen, taglen, result in self.tv3:

            key = bchr(0) * (keylen // 8 - 1) + bchr(taglen)
            C = b("")

            for i in range(128):
                S = bchr(0) * i

                N = long_to_bytes(3 * i + 1, 12)
                cipher = AES.new(key,
                                 AES.MODE_OCB,
                                 nonce=N,
                                 mac_len=taglen // 8)
                cipher.update(S)
                C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest()

                N = long_to_bytes(3 * i + 2, 12)
                cipher = AES.new(key,
                                 AES.MODE_OCB,
                                 nonce=N,
                                 mac_len=taglen // 8)
                C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest()

                N = long_to_bytes(3 * i + 3, 12)
                cipher = AES.new(key,
                                 AES.MODE_OCB,
                                 nonce=N,
                                 mac_len=taglen // 8)
                cipher.update(S)
                C += cipher.encrypt() + cipher.digest()

            N = long_to_bytes(385, 12)
            cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8)
            cipher.update(C)
            result2 = cipher.encrypt() + cipher.digest()
            self.assertEqual(unhexlify(b(result)), result2)
    def test_initial_value_bytes_parameter(self):
        # Same result as when passing an integer
        cipher1 = AES.new(self.key_128,
                          AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=b("\x00") * 6 + b("\xFF\xFF"))
        cipher2 = AES.new(self.key_128,
                          AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=0xFFFF)
        pt = get_tag_random("plaintext", 65536)
        self.assertEqual(cipher1.encrypt(pt), cipher2.encrypt(pt))

        # Fail if the iv is too large
        self.assertRaises(ValueError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          initial_value=b("5") * 17)
        self.assertRaises(ValueError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=b("5") * 9)

        # Fail if the iv is too short
        self.assertRaises(ValueError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          initial_value=b("5") * 15)
        self.assertRaises(ValueError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=b("5") * 7)
Esempio n. 9
0
def decrypt(enc_message):
	'''This function returns the decrypted version of the passed message'''
	#Now Decryption of message
	iv = enc_message[:AES.block_size]
	cipher = AES.new(key,AES.MODE_CBC,iv)
	dec_ret = unpad(cipher.decrypt(enc_message[AES.block_size:])) #Decrypt the message by removing the IV which is of the size AES.block_size
																  #and then unpad it
	dec_message = dec_ret[1]
	pad_flag = dec_ret[0]
	nhash = hmac.new(key,dec_message[:-32],hashlib.sha256).digest()
	if nhash != dec_message[-32:]:
		#print("Verification Failed")
		return False,pad_flag,dec_message
	return True,pad_flag,dec_message
    def test_segment_size_128(self):
        for bits in range(8, 129, 8):
            cipher = AES.new(self.key_128,
                             AES.MODE_CFB,
                             self.iv_128,
                             segment_size=bits)

        for bits in 0, 7, 9, 127, 129:
            self.assertRaises(ValueError,
                              AES.new,
                              self.key_128,
                              AES.MODE_CFB,
                              self.iv_128,
                              segment_size=bits)
Esempio n. 11
0
 def encrypt(self, text):
     cryptor = AES.new(self.key, self.mode, b'0000000000000000')
     length = 16
     count = len(text)
     if count < length:
         add = (length - count)
         text = text + ('\0' * add)
     elif count > length:
         add = (length - (count % length))
         text = text + ('\0' * add)
     self.ciphertext = cryptor.encrypt(text)
     # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
     # 所以这里统一把加密后的字符串转化为16进制字符串
     return b2a_hex(self.ciphertext)
Esempio n. 12
0
    def test_encrypt(self, tv):
        self._id = "Wycheproof Encrypt EAX Test #" + str(tv.id)

        try:
            cipher = AES.new(tv.key, AES.MODE_EAX, tv.iv, mac_len=tv.tag_size)
        except ValueError as e:
            assert len(tv.iv) == 0 and "Nonce cannot be empty" in str(e)
            return

        cipher.update(tv.aad)
        ct, tag = cipher.encrypt_and_digest(tv.msg)
        if tv.valid:
            self.assertEqual(ct, tv.ct)
            self.assertEqual(tag, tv.tag)
            self.warn(tv)
Esempio n. 13
0
    def encrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        # 这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用
        length = 16
        count = len(text)

        if (count % length != 0):
            add = length - (count % length)
        else:
            add = 0
            text = text + ('\0' * add)
            self.ciphertext = cryptor.encrypt(text)
            # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
            # 所以这里统一把加密后的字符串转化为16进制字符串
            return b2a_hex(self.ciphertext)
    def _do_mct_aes_test(self, file_name, segment_size):
        test_vectors = load_tests(
            ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"), file_name,
            "AES CFB%d Montecarlo" % segment_size, {"count": lambda x: int(x)})
        assert (test_vectors)
        assert (segment_size in (8, 128))

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                direction = tv
                continue

            self.description = tv.desc
            cipher = AES.new(tv.key,
                             AES.MODE_CFB,
                             tv.iv,
                             segment_size=segment_size)

            def get_input(input_text, output_seq, j):
                # CFB128
                if segment_size == 128:
                    if j >= 2:
                        return output_seq[-2]
                    return [input_text, tv.iv][j]
                # CFB8
                if j == 0:
                    return input_text
                elif j <= 16:
                    return tv.iv[j - 1:j]
                return output_seq[j - 17]

            if direction == '[ENCRYPT]':
                cts = []
                for j in range(1000):
                    plaintext = get_input(tv.plaintext, cts, j)
                    cts.append(cipher.encrypt(plaintext))
                self.assertEqual(cts[-1], tv.ciphertext)
            elif direction == '[DECRYPT]':
                pts = []
                for j in range(1000):
                    ciphertext = get_input(tv.ciphertext, pts, j)
                    pts.append(cipher.decrypt(ciphertext))
                self.assertEqual(pts[-1], tv.plaintext)
            else:
                assert False
Esempio n. 15
0
def student_login(email, password):
    #check company's login information
    conn = sqlite3.connect(DBNAME)
    c = conn.cursor()
    cipher = AES.new(SECRET)

    c.execute('SELECT password FROM {} WHERE email = ?'.format(STUDENTTNAME),(email,))
    data = c.fetchone()
    if data is None:
        return False
    else:
        encoded = encodeAES(cipher, password)
        if data[0] == encoded:
            return True
        else:
            return False
Esempio n. 16
0
    def encrypt_message(self, plaintext, public_key):
        if not public_key.startswith("-----BEGIN RSA PUBLIC KEY-----"):
            public_key = "-----BEGIN RSA PUBLIC KEY-----\n" + public_key + "\n-----END RSA PUBLIC KEY-----"
        recipient_key = RSA.importKey(public_key)
        session_key = get_random_bytes(16)

        # Encrypt the session key with the public RSA key
        cipher_rsa = PKCS1_OAEP.new(recipient_key)
        enc_session_key = cipher_rsa.encrypt(session_key)

        # Encrypt the data with the AES session key
        cipher_aes = AES.new(session_key, AES.MODE_EAX)
        ciphertext, tag = cipher_aes.encrypt_and_digest(
            plaintext.encode("UTF-8"))
        encrypted_message = b"".join(
            [x for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext)])
        return encrypted_message
 def test_valid_multiple_encrypt_or_decrypt(self):
     for method_name in "encrypt", "decrypt":
         for auth_data in (None, b("333"), self.data_128,
                           self.data_128 + b("3")):
             if auth_data is None:
                 assoc_len = None
             else:
                 assoc_len = len(auth_data)
             cipher = AES.new(self.key_128, AES.MODE_GCM,
                              nonce=self.nonce_96)
             if auth_data is not None:
                 cipher.update(auth_data)
             method = getattr(cipher, method_name)
             method(self.data_128)
             method(self.data_128)
             method(self.data_128)
             method(self.data_128)
    def test_encrypt(self, tv):
        self._id = "Wycheproof Encrypt GCM Test #" + str(tv.id)

        try:
            cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
                    **self._extra_params)
        except ValueError as e:
            if len(tv.iv) == 0 and "Nonce cannot be empty" in str(e):
                return
            raise e

        cipher.update(tv.aad)
        ct, tag = cipher.encrypt_and_digest(tv.msg)
        if tv.valid:
            self.assertEqual(ct, tv.ct)
            self.assertEqual(tag, tv.tag)
            self.warn(tv)
Esempio n. 19
0
    def aes_bytes(self, bytes_data: bytes) -> str:
        chunk = []
        for data in zip(bytes_data):
            chunk.append(bytes(data))

        data_joined = b''.join(chunk)
        cipher = AES.new(self._iv)

        _cr = False
        while _cr is False:
            if len(data_joined) % 16 == 0:
                _cr = True
            else:
                _cr = False
                data_joined += b'\00'
        data_encrypted = cipher.encrypt(data_joined)
        return data_encrypted
Esempio n. 20
0
 def decrypt_and_verify(hsel, iv, ciphertext, h):
     #verify
     hashfunc = None
     if hsel == 'S512':
         hashfunc = SHA512.new()
     else:
         hashfunc = SHA256.new()
     hashfunc.update(ciphertext)
     h2 = hashfunc.digest()
     if h != h2:  # todo: switch to timing-safe comparison
         print("Checksum failed")
         raise Exception("Hash Comparison Failed - Wrong Checksum\n")
     else:
         print("Checksum ok")
     #decrypt
     cipher = AES.new(shared_key, AES.MODE_CBC, iv)
     plaintext = cipher.decrypt(ciphertext).decode()
     return plaintext
Esempio n. 21
0
    def test_decrypt(self, tv):
        self._id = "Wycheproof Decrypt EAX Test #" + str(tv.id)

        try:
            cipher = AES.new(tv.key, AES.MODE_EAX, tv.iv, mac_len=tv.tag_size)
        except ValueError as e:
            assert len(tv.iv) == 0 and "Nonce cannot be empty" in str(e)
            return

        cipher.update(tv.aad)
        try:
            pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
        except ValueError:
            assert not tv.valid
        else:
            assert tv.valid
            self.assertEqual(pt, tv.msg)
            self.warn(tv)
Esempio n. 22
0
def encrypt(data):
    """
    将明文数据进行加密
    :param data: 需要被加密的内容
    :return:加密后的数据
    """
    key = b'qwertyuioplkjhgfdsazxcvbnm'
    bytes_data = bytearray(data, encoding='utf-8')
    l1 = len(bytes_data)
    l2 = l1 % 16  # 获取需要补充在bytes_data后面的数据,并用不足的数据进行填充
    if l2 == 0:
        l3 = 16
    else:
        l3 = 16 - l2
    for i in range(l3):
        bytes_data.append(l3)  # 填充数据
    cipher = AES.new(key, AES.MODE_CBC, key)  # 实例化一个加密对象
    encrypt_data = cipher.encrypt(bytes_data)  # 被加密的数据必须是16的倍数
    return encrypt_data
Esempio n. 23
0
 def test_valid_multiple_encrypt_or_decrypt(self):
     # Only possible if msg_len is declared in advance
     for method_name in "encrypt", "decrypt":
         for auth_data in (None, b("333"), self.data_128,
                           self.data_128 + b("3")):
             if auth_data is None:
                 assoc_len = None
             else:
                 assoc_len = len(auth_data)
             cipher = AES.new(self.key_128, AES.MODE_CCM,
                              nonce=self.nonce_96,
                              msg_len=64,
                              assoc_len=assoc_len)
             if auth_data is not None:
                 cipher.update(auth_data)
             method = getattr(cipher, method_name)
             method(self.data_128)
             method(self.data_128)
             method(self.data_128)
             method(self.data_128)
Esempio n. 24
0
 def encrypt(self, text, appid):
     """对明文进行加密
     @param text: 需要加密的明文
     @return: 加密得到的字符串
     """
     # 16位随机字符串添加到明文开头
     text = self.get_random_str() + struct.pack("I", socket.htonl(
         len(text))) + text + appid
     # 使用自定义的填充方式对明文进行补位填充
     pkcs7 = PKCS7Encoder()
     text = pkcs7.encode(text)
     # 加密
     cryptor = AES.new(self.key, self.mode, self.key[:16])
     try:
         ciphertext = cryptor.encrypt(text)
         # 使用BASE64对加密后的字符串进行编码
         return ierror.WXBizMsgCrypt_OK, base64.b64encode(ciphertext)
     except Exception as e:
         #print e
         return ierror.WXBizMsgCrypt_EncryptAES_Error, None
 def encrypt(self, text):
     text = text.encode('utf-8')
     cryptor = AES.new(self.key, self.mode, b'0000000000000000')
     # 这里密钥key 长度必须为16(AES-128),
     # 24(AES-192),或者32 (AES-256)Bytes 长度
     # 目前AES-128 足够目前使用
     length = 16
     count = len(text)
     if count < length:
         add = (length - count)
         # \0 backspace
         # text = text + ('\0' * add)
         text = text + ('\0' * add).encode('utf-8')
     elif count > length:
         add = (length - (count % length))
         # text = text + ('\0' * add)
         text = text + ('\0' * add).encode('utf-8')
     self.ciphertext = cryptor.encrypt(text)
     # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
     # 所以这里统一把加密后的字符串转化为16进制字符串
     return b2a_hex(self.ciphertext)
    def test_2(self):
        key = unhexlify("843ffcf5d2b72694d19ed01d01249412")
        iv  = unhexlify("dbcca32ebf9b804617c3aa9e")
        aad = unhexlify("00000000000000000000000000000000" +
                        "101112131415161718191a1b1c1d1e1f")
        pt  = unhexlify("000102030405060708090a0b0c0d0e0f" +
                        "101112131415161718191a1b1c1d1e1f" +
                        "202122232425262728292a2b2c2d2e2f" +
                        "303132333435363738393a3b3c3d3e3f" +
                        "404142434445464748494a4b4c4d4e4f")
        ct  = unhexlify("6268c6fa2a80b2d137467f092f657ac0" +
                        "4d89be2beaa623d61b5a868c8f03ff95" +
                        "d3dcee23ad2f1ab3a6c80eaf4b140eb0" +
                        "5de3457f0fbc111a6b43d0763aa422a3" +
                        "013cf1dc37fe417d1fbfc449b75d4cc5")
        digest = unhexlify("3b629ccfbc1119b7319e1dce2cd6fd6d")

        cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
        ct2, digest2 = cipher.encrypt_and_digest(pt)

        self.assertEqual(ct, ct2)
        self.assertEqual(digest, digest2)
Esempio n. 27
0
def add_company(name, password, email):
    """Creates unique id for each company, and adds company to the
       company table"""

    conn = sqlite3.connect(DBNAME)
    c = conn.cursor()

    #get length
    c.execute('SELECT name FROM {}'.format(COMPANYTNAME))

    ctnum = len(c.fetchall())

    #encrypt/encode text
    cipher = AES.new(SECRET)
    encoded = encodeAES(cipher, password)

    c.execute("INSERT INTO {} values {}".format(COMPANYTNAME, COMPANYPARAMS),
              (name, encoded, ctnum, 1, email))

    conn.commit()
    conn.close()

    return ctnum
Esempio n. 28
0
    def _do_kat_aes_test(self, file_name):
        test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                                  file_name,
                                  "AES KAT",
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if isinstance(tv, str):
                direction = tv
                continue

            self.description = tv.desc

            cipher = AES.new(tv.key, self.aes_mode, tv.iv)
            if direction == "[ENCRYPT]":
                self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
            elif direction == "[DECRYPT]":
                self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
            else:
                assert False
Esempio n. 29
0
 def decrypt(self,text):
     cryptor = AES.new(self.key,self.mode,self.values)
     plain_text  = cryptor.decrypt(a2b_hex(text))
     return plain_text.rstrip('\0')
Esempio n. 30
0
assert (hamming(q, z) == 37)
assert (hamming(bytes(q, 'utf-8'), bytes(z, 'utf-8')) == 37)

f = open('6.txt', 'r')
x = f.read()
base = b64decode(x)
bb = hexlify(base)
key = b''
for b in block(bb, findLowestHammingLength(base)):
    sort = sortBySuitability(trials(unhexlify(b)))
    key += sort[-1]['key']
lyrics = b"I'm back and I'm ringin' the bell \nA rockin' on the mike while the fly girls yell \nIn ecstasy in the back of me \nWell that's my DJ Deshay cuttin' all them Z's \nHittin' hard and the girlies goin' crazy \nVanilla's on the mike, man I'm not lazy. \n\nI'm lettin' my drug kick in \nIt controls my mouth and I begin \nTo just let it flow, let my concepts go \nMy posse's to the side yellin', Go Vanilla Go! \n\nSmooth 'cause that's the way I will be \nAnd if you don't give a damn, then \nWhy you starin' at me \nSo get off 'cause I control the stage \nThere's no dissin' allowed \nI'm in my own phase \nThe girlies sa y they love me and that is ok \nAnd I can dance better than any kid n' play \n\nStage 2 -- Yea the one ya' wanna listen to \nIt's off my head so let the beat play through \nSo I can funk it up and make it sound good \n1-2-3 Yo -- Knock on some wood \nFor good luck, I like my rhymes atrocious \nSupercalafragilisticexpialidocious \nI'm an effect and that you can bet \nI can take a fly girl and make her wet. \n\nI'm like Samson -- Samson to Delilah \nThere's no denyin', You can try to hang \nBut you'll keep tryin' to get my style \nOver and over, practice makes perfect \nBut not if you're a loafer. \n\nYou'll get nowhere, no place, no time, no girls \nSoon -- Oh my God, homebody, you probably eat \nSpaghetti with a spoon! Come on and say it! \n\nVIP. Vanilla Ice yep, yep, I'm comin' hard like a rhino \nIntoxicating so you stagger like a wino \nSo punks stop trying and girl stop cryin' \nVanilla Ice is sellin' and you people are buyin' \n'Cause why the freaks are jockin' like Crazy Glue \nMovin' and groovin' trying to sing along \nAll through the ghetto groovin' this here song \nNow you're amazed by the VIP posse. \n\nSteppin' so hard like a German Nazi \nStartled by the bases hittin' ground \nThere's no trippin' on mine, I'm just gettin' down \nSparkamatic, I'm hangin' tight like a fanatic \nYou trapped me once and I thought that \nYou might have it \nSo step down and lend me your ear \n'89 in my time! You, '90 is my year. \n\nYou're weakenin' fast, YO! and I can tell it \nYour body's gettin' hot, so, so I can smell it \nSo don't be mad and don't be sad \n'Cause the lyrics belong to ICE, You can call me Dad \nYou're pitchin' a fit, so step back and endure \nLet the witch doctor, Ice, do the dance to cure \nSo come up close and don't be square \nYou wanna battle me -- Anytime, anywhere \n\nYou thought that I was weak, Boy, you're dead wrong \nSo come on, everybody and sing this song \n\nSay -- Play that funky music Say, go white boy, go white boy go \nplay that funky music Go white boy, go white boy, go \nLay down and boogie and play that funky music till you die. \n\nPlay that funky music Come on, Come on, let me hear \nPlay that funky music white boy you say it, say it \nPlay that funky music A little louder now \nPlay that funky music, white boy Come on, Come on, Come on \nPlay that funky music \n"
assert (xor(base, key) == lyrics)

#Exercise 7
seven = open('7.txt', 'r')
ff = seven.read()
ff = b64decode(ff)
obj2 = AES.new('YELLOW SUBMARINE', AES.MODE_ECB)
lyrics = b"I'm back and I'm ringin' the bell \nA rockin' on the mike while the fly girls yell \nIn ecstasy in the back of me \nWell that's my DJ Deshay cuttin' all them Z's \nHittin' hard and the girlies goin' crazy \nVanilla's on the mike, man I'm not lazy. \n\nI'm lettin' my drug kick in \nIt controls my mouth and I begin \nTo just let it flow, let my concepts go \nMy posse's to the side yellin', Go Vanilla Go! \n\nSmooth 'cause that's the way I will be \nAnd if you don't give a damn, then \nWhy you starin' at me \nSo get off 'cause I control the stage \nThere's no dissin' allowed \nI'm in my own phase \nThe girlies sa y they love me and that is ok \nAnd I can dance better than any kid n' play \n\nStage 2 -- Yea the one ya' wanna listen to \nIt's off my head so let the beat play through \nSo I can funk it up and make it sound good \n1-2-3 Yo -- Knock on some wood \nFor good luck, I like my rhymes atrocious \nSupercalafragilisticexpialidocious \nI'm an effect and that you can bet \nI can take a fly girl and make her wet. \n\nI'm like Samson -- Samson to Delilah \nThere's no denyin', You can try to hang \nBut you'll keep tryin' to get my style \nOver and over, practice makes perfect \nBut not if you're a loafer. \n\nYou'll get nowhere, no place, no time, no girls \nSoon -- Oh my God, homebody, you probably eat \nSpaghetti with a spoon! Come on and say it! \n\nVIP. Vanilla Ice yep, yep, I'm comin' hard like a rhino \nIntoxicating so you stagger like a wino \nSo punks stop trying and girl stop cryin' \nVanilla Ice is sellin' and you people are buyin' \n'Cause why the freaks are jockin' like Crazy Glue \nMovin' and groovin' trying to sing along \nAll through the ghetto groovin' this here song \nNow you're amazed by the VIP posse. \n\nSteppin' so hard like a German Nazi \nStartled by the bases hittin' ground \nThere's no trippin' on mine, I'm just gettin' down \nSparkamatic, I'm hangin' tight like a fanatic \nYou trapped me once and I thought that \nYou might have it \nSo step down and lend me your ear \n'89 in my time! You, '90 is my year. \n\nYou're weakenin' fast, YO! and I can tell it \nYour body's gettin' hot, so, so I can smell it \nSo don't be mad and don't be sad \n'Cause the lyrics belong to ICE, You can call me Dad \nYou're pitchin' a fit, so step back and endure \nLet the witch doctor, Ice, do the dance to cure \nSo come up close and don't be square \nYou wanna battle me -- Anytime, anywhere \n\nYou thought that I was weak, Boy, you're dead wrong \nSo come on, everybody and sing this song \n\nSay -- Play that funky music Say, go white boy, go white boy go \nplay that funky music Go white boy, go white boy, go \nLay down and boogie and play that funky music till you die. \n\nPlay that funky music Come on, Come on, let me hear \nPlay that funky music white boy you say it, say it \nPlay that funky music A little louder now \nPlay that funky music, white boy Come on, Come on, Come on \nPlay that funky music \n\x04\x04\x04\x04"
assert (obj2.decrypt(ff) == lyrics)

#Exercise 8
#08649af70dc06f4fd5d2d69c744cd283
eight = open('8.txt', 'r')
ff = eight.read()

x = [a for a in ff.split('\n') if detectECB(a)]
ecbLine = 'd880619740a8a19b7840a8a31c810a3d08649af70dc06f4fd5d2d69c744cd283e2dd052f6b641dbf9d11b0348542bb5708649af70dc06f4fd5d2d69c744cd2839475c9dfdbc1d46597949d9c7e82bf5a08649af70dc06f4fd5d2d69c744cd28397a93eab8d6aecd566489154789a6b0308649af70dc06f4fd5d2d69c744cd283d403180c98c8f6db1f2a3f9c4040deb0ab51b29933f2c123c58386b06fba186a'
assert (x[0] == ecbLine)
 def decrypt(self, text):
     cryptor = AES.new(self.key, self.mode, b'0000000000000000')
     plain_text = cryptor.decrypt(a2b_hex(text))
     # return plain_text.rstrip('\0')
     return bytes.decode(plain_text).rstrip('\0')
Esempio n. 32
0
 def encrypt(self, text, key, key_size=256):
     text = self.padding(text)
     iv = Random.new().read(AES.block_size)
     cipher = AES.new(key, AES.MODE_CBC, iv)
     return iv + cipher.encrypt(text)
Esempio n. 33
0
def decode(pem_data, passphrase=None):
    """Decode a PEM block into binary.

    Args:
      pem_data (string):
        The PEM block.
      passphrase (byte string):
        If given and the PEM block is encrypted,
        the key will be derived from the passphrase.

    Returns:
      A tuple with the binary data, the marker string, and a boolean to
      indicate if decryption was performed.

    Raises:
      ValueError: if decoding fails, if the PEM file is encrypted and no passphrase has
                  been provided or if the passphrase is incorrect.
    """

    # Verify Pre-Encapsulation Boundary
    r = re.compile("\s*-----BEGIN (.*)-----\s+")
    m = r.match(pem_data)
    if not m:
        raise ValueError("Not a valid PEM pre boundary")
    marker = m.group(1)

    # Verify Post-Encapsulation Boundary
    r = re.compile("-----END (.*)-----\s*$")
    m = r.search(pem_data)
    if not m or m.group(1) != marker:
        raise ValueError("Not a valid PEM post boundary")

    # Removes spaces and slit on lines
    lines = pem_data.replace(" ", '').split()

    # Decrypts, if necessary
    if lines[1].startswith('Proc-Type:4,ENCRYPTED'):
        if not passphrase:
            raise ValueError("PEM is encrypted, but no passphrase available")
        DEK = lines[2].split(':')
        if len(DEK) != 2 or DEK[0] != 'DEK-Info':
            raise ValueError("PEM encryption format not supported.")
        algo, salt = DEK[1].split(',')
        salt = unhexlify(tobytes(salt))
        if algo == "DES-CBC":
            # This is EVP_BytesToKey in OpenSSL
            key = PBKDF1(passphrase, salt, 8, 1, MD5)
            objdec = DES.new(key, DES.MODE_CBC, salt)
        elif algo == "DES-EDE3-CBC":
            # Note that EVP_BytesToKey is note exactly the same as PBKDF1
            key = PBKDF1(passphrase, salt, 16, 1, MD5)
            key += PBKDF1(key + passphrase, salt, 8, 1, MD5)
            objdec = DES3.new(key, DES3.MODE_CBC, salt)
        elif algo == "AES-128-CBC":
            key = PBKDF1(passphrase, salt[:8], 16, 1, MD5)
            objdec = AES.new(key, AES.MODE_CBC, salt)
        else:
            raise ValueError("Unsupport PEM encryption algorithm (%s)." % algo)
        lines = lines[2:]
    else:
        objdec = None

    # Decode body
    data = a2b_base64(b(''.join(lines[1:-1])))
    enc_flag = False
    if objdec:
        data = unpad(objdec.decrypt(data), objdec.block_size)
        enc_flag = True

    return (data, marker, enc_flag)
Esempio n. 34
0
match_message = ""
messages = []
NEW_MESSAGE = False

while 1:
    inputready, outputready, exceptrdy = select.select([0, client], [], [],
                                                       0.5)

    for i in inputready:
        if NEW_MESSAGE:
            NEW_MESSAGE = False
            messages = []

        data, address = client.recvfrom(1024)
        port = address[1]
        cipher = AES.new(keys[int(cid)][port_mapper[port]], AES.MODE_EAX, IV)
        plaintext = cipher.decrypt(data)
        data = plaintext[:-plaintext[-1]]
        print(messages)
        messages.append(data.decode())

    if not (inputready or outputready or exceptrdy):
        if STAGE == 'PRE':
            match_message = "PREP10".encode()
            if BYZANTINE == 'n':
                length = 16 - (len(match_message) % 16)
                match_message += bytes([length]) * length
                for i in neighbors:
                    cipher = AES.new(keys[int(cid)][i[0]], AES.MODE_EAX, IV)
                    ciphertext = cipher.encrypt(match_message)
                    client.sendto(ciphertext, (SERVER, i[2]))
Esempio n. 35
0
#Function to unpad messages
def unpad(s):
    '''This function returns the unpadded version of given parameter string s according to PKCS7 standard
		which is used with AES ciphers'''
    return s[:-ord(
        s[len(s) - 1:]
    )]  #This implies remove the last padding character as many times as it's value from given string to get the
    #unpadded string


message = "Attack at the night in the woods"
data = message.encode('UTF-8')  #Encoding the message is must
#Now the hash of the message
hash = hmac.new(key, data, hashlib.sha256).digest()
raw = data + hash
#Now encryption
cipher = AES.new(key, AES.MODE_CBC, iv)
enc_message = iv + cipher.encrypt(pad(raw))

#Now Decryption of message
cipher = AES.new(key, AES.MODE_CBC, iv)
dec_message = cipher.decrypt(
    enc_message[AES.block_size:]
)  #Decrypt the message by removing the IV which is of the size AES.block_size
print(
    unpad(dec_message)[:-32].decode('UTF-8')
)  #The output of decrypt function is unpadded aauming it is correct.The program demonstrating
#the verification can be seen in aes-hmac-verify.py file.Then SHA256 hash is removed and
#decoded using UTF-8
Esempio n. 36
0
 def encrypt(self,text):
     if len(text)%16!=0:
         text=text+str((16-len(text)%16)*'0')
     cryptor = AES.new(self.key,self.mode,self.values)
     self.ciphertext = cryptor.encrypt(text)
     return b2a_hex(self.ciphertext)