예제 #1
0
파일: drsuapi.py 프로젝트: skelsec/impacket
def removeDESLayer(cryptedHash, rid):
        Key1,Key2 = deriveKey(rid)

        Crypt1 = DES.new(Key1, DES.MODE_ECB)
        Crypt2 = DES.new(Key2, DES.MODE_ECB)

        decryptedHash = Crypt1.decrypt(cryptedHash[:8]) + Crypt2.decrypt(cryptedHash[8:])

        return decryptedHash
예제 #2
0
    def decryptData(self, decryptKey, privParameters, encryptedData):
        if DES is None:
            raise error.StatusInformation(
                errorIndication=errind.decryptionError)

        snmpEngineBoots, snmpEngineTime, salt = privParameters

        # 8.3.2.1
        if len(salt) != 8:
            raise error.StatusInformation(
                errorIndication=errind.decryptionError)

        # 8.3.2.2 no-op

        # 8.3.2.3
        desKey, iv = self.__getDecryptionKey(decryptKey, salt)

        # 8.3.2.4 -> 8.1.1.3
        if len(encryptedData) % 8 != 0:
            raise error.StatusInformation(
                errorIndication=errind.decryptionError)

        desObj = DES.new(desKey, DES.MODE_CBC, iv)

        # 8.3.2.6
        return desObj.decrypt(encryptedData.asOctets())
예제 #3
0
def decrypt_response(des_key, des_iv, aes_key, aes_iv, content):
    """
    AES解密
     key,iv使用同一个
    模式cbc
    去填充pkcs7
    :param content:
    :return:
    """
    aes = AES.new(aes_key, AES.MODE_CBC, aes_iv)
    des = DES.new(des_key, DES.MODE_CBC, des_iv)
    # base64解码
    encrypt_bytes = base64.b64decode(content)
    # 解密
    decrypt_bytes = aes.decrypt(encrypt_bytes)
    decrypt_bytes = base64.b64decode(decrypt_bytes)
    decrypt_bytes = des.decrypt(decrypt_bytes)

    # base64解码
    decrypt_bytes = base64.b64decode(decrypt_bytes)
    # 重新编码
    result = str(decrypt_bytes, encoding="utf8")
    # 去除填充内容
    # result = pkcs7unpadding(result)
    return result
    def runTest(self):
        # Encrypt/Decrypt data and test output parameter

        cipher = DES.new(b'4'*8, DES.MODE_ECB)

        pt = b'5' * 8
        ct = cipher.encrypt(pt)

        output = bytearray(8)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)

        output = memoryview(bytearray(8))
        cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        
        cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)

        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*8)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*8)

        shorter_output = bytearray(7)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
 def retrievePassword(cor_site, key):
     """
     retrieve password from db according to username, and decrypt it with key
     """
     des = DES()
     des.setKey(key)
     with _mysql.connect(Constant.HOST, Constant.USER, Constant.PASSWORD,
                         Constant.DB) as db:
         cur = db.cursor()
         cur.query("SELECT * FROM passtable WHERE corsite = %s" % cor_site)
         for match in cur.fetchall():
             print("Username: "******"Password: "******"#################################################################"
             )
예제 #6
0
    def _do_tdes_test(self, file_name):
        test_vectors = load_tests(("Cryptodome", "SelfTest", "Cipher", "test_vectors", "TDES"),
                                  file_name,
                                  "TDES CBC 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, basestring):
                direction = tv
                continue

            self.description = tv.desc
            if hasattr(tv, "keys"):
                cipher = DES.new(tv.keys, self.des_mode, tv.iv)
            else:
                if tv.key1 != tv.key3:
                    key = tv.key1 + tv.key2 + tv.key3  # Option 3
                else:
                    key = tv.key1 + tv.key2            # Option 2
                cipher = DES3.new(key, self.des3_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
예제 #7
0
def encryption(data):
    crypt = DES.new(b'12345678', DES.MODE_ECB)
    content = json.dumps(data, separators=(',', ':'))
    content = Padding.pad(content.encode('utf8'), 8, 'pkcs7')
    content = crypt.encrypt(content)
    content = base64.b64encode(content)
    return content
def main():
    s = clientSetup()

    # Gets Public Key from Bob
    # public_key = s.recv(4096).decode()
    public_key = RSA.import_key(open("public.pem").read())
    # Generates Session Key
    session_key = get_random_bytes(8)

    # Sends Encrypted Session Key to Bob
    cipher_rsa = PKCS1_OAEP.new(public_key)
    enc_session_key = cipher_rsa.encrypt(session_key)

    s.send(enc_session_key)
    confirmation = s.recv(4096).decode()
    print(confirmation)

    # Reads NoWar.dat file
    message = readFile("NoWar.dat").encode()

    # Using DES to transmit message to Bob
    cipher = DES.new(session_key, DES.MODE_EAX)
    cipherText = cipher.encrypt(message)

    s.send(cipher.nonce)
    confirmation = s.recv(4096).decode()
    print(confirmation)

    s.send(cipherText)
    confirmation = s.recv(4096).decode()
    print(confirmation)

    # Closing Socket
    s.close()
    def __call__(self, block0: bytes, block1: bytes) -> bytes:
        assert len(block0) == DES.block_size
        # assert len(block1) == DES.block_size

        cipher = DES.new(key, DES.MODE_CBC, block0)

        return cipher.decrypt(block1)
예제 #10
0
def simple_test():
    """关于加密以及解密模块的简单使用"""
    # 导入DES模块
    from Cryptodome.Cipher import DES
    import binascii

    # 这是密钥
    key = b'abcdefgh'
    # 需要去生成一个DES对象
    des = DES.new(key, DES.MODE_ECB)
    # 需要加密的数据
    text = 'python spider!'
    # 将需要加密的数据进行位数补全 差的位置都补上 "="
    text = text + (8 - (len(text) % 8)) * '='

    # 加密的过程
    encrypto_text = des.encrypt(text.encode())
    encrypto_text = binascii.b2a_hex(encrypto_text)
    print(encrypto_text)

    # 逆向解密的过程
    ret = binascii.a2b_hex(encrypto_text)
    print(ret)
    decrypto_text = des.decrypt(ret)
    print(decrypto_text)
예제 #11
0
    def _do_tdes_test(self, file_name):

        test_vectors = load_test_vectors(("Cipher", "TDES"), file_name,
                                         "TDES CBC KAT",
                                         {"count": lambda x: int(x)})
        if test_vectors is None:
            return

        direction = None
        for tv in test_vectors:

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

            self.description = tv.desc
            if hasattr(tv, "keys"):
                cipher = DES.new(tv.keys, self.des_mode, tv.iv)
            else:
                if tv.key1 != tv.key3:
                    key = tv.key1 + tv.key2 + tv.key3  # Option 3
                else:
                    key = tv.key1 + tv.key2  # Option 2
                cipher = DES3.new(key, self.des3_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
예제 #12
0
    def _do_tdes_test(self, file_name, segment_size):
        test_vectors = load_tests(("Cryptodome", "SelfTest", "Cipher", "test_vectors", "TDES"),
                                  file_name,
                                  "AES CFB%d KAT" % segment_size,
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)

        direction = None
        for tv in test_vectors:

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

            self.description = tv.desc
            if hasattr(tv, "keys"):
                cipher = DES.new(tv.keys, DES.MODE_CFB, tv.iv,
                                 segment_size=segment_size)
            else:
                if tv.key1 != tv.key3:
                    key = tv.key1 + tv.key2 + tv.key3  # Option 3
                else:
                    key = tv.key1 + tv.key2            # Option 2
                cipher = DES3.new(key, DES3.MODE_CFB, tv.iv,
                                  segment_size=segment_size)
            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
예제 #13
0
def Encryption(key, text):
    key = key.encode()
    des = DES.new(key, DES.MODE_ECB)

    padded_text = pad(text)
    encrypted_text = des.encrypt(padded_text.encode())
    return b64encode(encrypted_text).decode('utf-8')
예제 #14
0
파일: test_CFB.py 프로젝트: Kronos3/pyexec
    def _do_tdes_test(self, file_name, segment_size):
        test_vectors = load_tests(("Cryptodome", "SelfTest", "Cipher", "test_vectors", "TDES"),
                                  file_name,
                                  "AES CFB%d KAT" % segment_size,
                                  { "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
            if hasattr(tv, "keys"):
                cipher = DES.new(tv.keys, DES.MODE_CFB, tv.iv,
                                 segment_size=segment_size)
            else:
                if tv.key1 != tv.key3:
                    key = tv.key1 + tv.key2 + tv.key3  # Option 3
                else:
                    key = tv.key1 + tv.key2            # Option 2
                cipher = DES3.new(key, DES3.MODE_CFB, tv.iv,
                                  segment_size=segment_size)
            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
예제 #15
0
    def runTest(self):
        # Encrypt/Decrypt data and test output parameter

        cipher = DES.new(b'4'*8, DES.MODE_ECB)

        pt = b'5' * 8
        ct = cipher.encrypt(pt)

        output = bytearray(8)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)

        import sys
        if sys.version[:3] != '2.6':
            output = memoryview(bytearray(8))
            cipher.encrypt(pt, output=output)
            self.assertEqual(ct, output)
        
            cipher.decrypt(ct, output=output)
            self.assertEqual(pt, output)

        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*8)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*8)

        shorter_output = bytearray(7)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
예제 #16
0
def SamEncryptNTLMHash(encryptedHash, key):
    # [MS-SAMR] Section 2.2.11.1.1
    Block1 = encryptedHash[:8]
    Block2 = encryptedHash[8:]

    Key1 = key[:7]
    Key1 = transformKey(Key1)
    Key2 = key[7:14]
    Key2 = transformKey(Key2)

    Crypt1 = DES.new(Key1, DES.MODE_ECB)
    Crypt2 = DES.new(Key2, DES.MODE_ECB)

    plain1 = Crypt1.encrypt(Block1)
    plain2 = Crypt2.encrypt(Block2)

    return plain1 + plain2
예제 #17
0
def SamEncryptNTLMHash(encryptedHash, key):
    # [MS-SAMR] Section 2.2.11.1.1
    Block1 = encryptedHash[:8]
    Block2 = encryptedHash[8:]

    Key1 = key[:7]
    Key1 = transformKey(Key1)
    Key2 = key[7:14]
    Key2 = transformKey(Key2)

    Crypt1 = DES.new(Key1, DES.MODE_ECB)
    Crypt2 = DES.new(Key2, DES.MODE_ECB)

    plain1 = Crypt1.encrypt(Block1)
    plain2 = Crypt2.encrypt(Block2)

    return plain1 + plain2
예제 #18
0
def decrypt_des(encrypted, password):
    if len(password) != 8:
        raise Exception
    else:
        cipher = DES.new(bytes(password, "utf-8"), DES.MODE_ECB)
        bytes_tuple = encrypted[2:-1].replace("\\\\", "\\").encode()
        decrypted = cipher.decrypt(codecs.escape_decode(bytes_tuple, "hex")[0])
        return bytes.decode(decrypted)
예제 #19
0
def _cryptodome_cipher(key, iv):
    """Build a Pycryptodome DES Cipher object.

    :param bytes key: Encryption key
    :param bytes iv: Initialization vector
    :returns: DES Cipher instance
    """
    return DES.new(key, DES.MODE_CBC, iv)
예제 #20
0
def des_encrypt_ecb(data, key):
    try:
        data = pad(data)
        des = DES.new(key.encode('utf-8'), DES.MODE_ECB)
        encrypted_data = des.encrypt(data)
        return encrypted_data
    except Exception as e:
        error_log(e)
        return False
예제 #21
0
def des_encrypt_cbc(data, key, vi):
    try:
        data = pad(data)
        des = DES.new(key.encode('utf-8'), DES.MODE_CBC, vi.encode('utf-8'))
        encrypted_data = des.encrypt(data)
        return encrypted_data
    except Exception as e:
        error_log(e)
        return False
예제 #22
0
def des_decrypt_cbc(data, key, vi):
    try:
        des = DES.new(key.encode('utf-8'), DES.MODE_CBC, vi.encode('utf-8'))
        plain_data = des.decrypt(data)
        plain_data = un_pad(plain_data)
        return plain_data
    except Exception as e:
        error_log(e)
        return False
예제 #23
0
파일: ntlm.py 프로젝트: szaydel/pike
def KXKEY(NegFlg, SessionBaseKey, LmChallengeResponse, ServerChallenge,
          ResponseKeyLM):
    if NegFlg & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
        hm = HMAC.new(SessionBaseKey,
                      ServerChallenge + LmChallengeResponse[:8], MD5)
        KeyExchangeKey = hm.digest()
    else:
        LMOWF = ResponseKeyLM
        if NegFlg & NTLMSSP_NEGOTIATE_LMKEY:
            data = LmChallengeResponse[:8]
            KeyExchangeKey = DES(LMOWF[:7], data) + DES(
                LMOWF[8] + "\xbd" * 6, data)
        else:
            if NegFlg & NTLMSSP_REQUEST_NON_NT_SESSION_KEY:
                KeyExchangeKey = LMOWF[:8] + "\0" * 8
            else:
                KeyExchangeKey = SessionBaseKey
    return KeyExchangeKey
예제 #24
0
파일: tool.py 프로젝트: kingking888/code
def des_encrypt(data):
    key = 'kwBq8snI'.encode()
    data = data.encode()
    if len(data) % 8 != 0:
        pad = 8 - len(data) % 8
        data += bytes([pad]*pad)
    decryptor = DES.new(key, mode=DES.MODE_CBC, iv=key)
    encrypt_data = decryptor.encrypt(data)
    return base64.b64encode(encrypt_data)
예제 #25
0
파일: client.py 프로젝트: amcgavin/eleven7
    def des_encrypt_string(cls, device_id):
        key = "co.vmob.sdk.android.encrypt.key".encode()[:8]
        encryption_prefix = "co.vmob.android.sdk."
        cipher = DES.new(key, DES.MODE_ECB)
        encrypted_message = cipher.encrypt(
            pad(f"{encryption_prefix}{device_id}".encode("utf-8"),
                block_size=DES.block_size))

        return base64.b64encode(encrypted_message).replace(b"/",
                                                           b"_").decode() + "_"
예제 #26
0
def encrypt_des(message, key):
    if len(key) != 8:
        raise Exception
    else:
        while len(message) % 8 != 0:
            message += ' '
        cipher = DES.new(bytes(key, 'utf-8'), DES.MODE_ECB)
        encrypted = cipher.encrypt(bytes(message, 'utf-8'))

        return f"{encrypted}"
예제 #27
0
    def __call__(self, block0: bytes, block1: bytes) -> bytes:
        assert len(block0) == DES.block_size
        assert len(block1) == DES.block_size

        cipher = DES.new(key, DES.MODE_CBC, block0)
        decrypt = cipher.decrypt(block1)
        result = all(map(lambda x: decrypt[-1] == x, decrypt[-decrypt[-1]:]))

        print(hexlify(decrypt), result)
        return result
예제 #28
0
def run_DES():
    key = Random.get_random_bytes(8)
    nonce = Random.get_random_bytes(16)

    print("=================")
    print("Encrypting with DES")
    print("Key: ", to_hex(key))
    print("Nonce: ", to_hex(nonce))

    cipher = DES.new(key, DES.MODE_EAX, nonce)

    ciphertext = cipher.encrypt(data)

    #print("Cleartext: ", to_hex(data))
    #print("Ciphertext: ", to_hex(ciphertext))

    file_out = open("des.bin", "wb")
    [file_out.write(x) for x in (cipher.nonce, ciphertext)]
    file_out.close()

    file_in = open("des.bin", "rb")
    decrypt_nonce, decrypt_ciphertext = [file_in.read(x) for x in (16, -1)]
    file_in.close()

    print("=================")
    print("Decrypting with DES")
    print("Key: ", to_hex(key))
    print("Nonce: ", to_hex(decrypt_nonce))
    #print("Ciphertext: ", to_hex(decrypt_ciphertext))

    decipher = DES.new(key, DES.MODE_EAX, decrypt_nonce)
    cleartext = decipher.decrypt(decrypt_ciphertext)

    #print("Cleartext: ", to_hex(cleartext))
    print("=================")

    if cleartext == data:
        print("Decryption successful\n")
    else:
        print("Decryption failed\n")

    return
예제 #29
0
 def get_channel_links(self, pk_id):
     _channel = self.api_request("get_channel_link_with_token_latest", pk_id)["channel"][0]
     links = []
     for stream in _channel.keys():
         if "stream" in stream or "chrome_cast" in stream:
             _crypt_link = _channel[stream]
             if _crypt_link:
                 d = DES.new(b"98221122", DES.MODE_ECB)
                 link = unpad(d.decrypt(b64decode(_crypt_link)), 8).decode("utf-8")
                 if not link == "dummytext" and link not in links:
                     links.append(link)
     return [self.stream_url(l) for l in links]
예제 #30
0
    def __decryptHash(self, rid, cryptedHash, constant, newStyle=False):
        # Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key
        # plus hashedBootKey stuff
        Key1, Key2 = self.__cryptoCommon.deriveKey(rid)

        Crypt1 = DES.new(Key1, DES.MODE_ECB)
        Crypt2 = DES.new(Key2, DES.MODE_ECB)

        if newStyle is False:
            rc4Key = self.MD5(self.__hashedBootKey[:0x10] + pack("<L", rid) +
                              constant)
            rc4 = ARC4.new(rc4Key)
            key = rc4.encrypt(cryptedHash['Hash'])
        else:
            key = self.__cryptoCommon.decryptAES(self.__hashedBootKey[:0x10],
                                                 cryptedHash['Hash'],
                                                 cryptedHash['Salt'])[:16]

        decryptedHash = Crypt1.decrypt(key[:8]) + Crypt2.decrypt(key[8:])

        return decryptedHash
예제 #31
0
 def decipher(self, ciphered_input: bytes, iv) -> str:
     """
     Deciphers the input bytes using the IV vector and the DES algorithm. returns a legible string.
     :param ciphered_input: ciphered input in bytes
     :param iv: input vector
     :return: deciphered text
     """
     decipher_des = DES.new(self.__key, DES.MODE_CBC, iv)
     deciphered_text = unpad(decipher_des.decrypt(ciphered_input),
                             self.__BLOCK_SIZE_DES).decode(
                                 "utf-8", "ignore")
     return deciphered_text
예제 #32
0
    def execute(self):
        key = bytes(self.key, encoding="utf-8")
        key = self.pad(key, 8)

        des = DES.new(key, DES.MODE_ECB)

        text = bytes(self.text, encoding="utf-8")

        padded_text = self.pad(text, 8)

        encrypted_text = des.encrypt(padded_text)

        return encrypted_text
예제 #33
0
파일: wss.py 프로젝트: wubinbai/ubuntu
 def get_cipherheader(epochtime, token, data):
     # cipherMethod: DES/CBC/PKCS7Padding
     json_dumps = json.dumps(data, ensure_ascii=False)
     md5_hash_code = hashlib.md5((json_dumps + token).encode()).hexdigest()
     base58_hash_code = base58.b58encode(md5_hash_code)
     key_iv = (
         # 时间戳逆序取5位并作为时间戳字串索引再次取值,最后拼接"000"
         "".join([epochtime[int(i)]
                  for i in epochtime[::-1][:5]]) + "000").encode()
     cipher = DES.new(key_iv, DES.MODE_CBC, key_iv)
     cipherText = cipher.encrypt(
         Padding.pad(base58_hash_code, DES.block_size, style="pkcs7"))
     return base64.b64encode(cipherText)
예제 #34
0
    def decrypt(self, file_path, password):
        private_key = self.get_private_key(password)
        if private_key is None:
            return {'status': False, 'msg': "Cannot get private key"}
        with open(file_path, 'rb') as fi:
            try:
                msg = json.loads(fi.read())
            except ValueError:
                return {'status': False, 'msg': "File structure is damaged"}
            for key, value in msg.iteritems():
                msg[key] = b64decode(value)
            secret_key = PKCS1_OAEP.new(private_key).decrypt(msg['secret_key'])
            try:
                # init cipher
                if msg['alg'] == ALG_OPTIONS[0]:
                    cipher = AES.new(secret_key, AES.MODE_EAX, msg['nonce'])
                elif msg['alg'] == ALG_OPTIONS[1]:
                    cipher = AES.new(secret_key, AES.MODE_OCB, msg['nonce'])
                elif msg['alg'] == ALG_OPTIONS[2]:
                    cipher = AES.new(secret_key, AES.MODE_CFB, msg['iv'])
                elif msg['alg'] == ALG_OPTIONS[3]:
                    cipher = AES.new(secret_key, AES.MODE_CTR, msg['nonce'])
                elif msg['alg'] == ALG_OPTIONS[4]:
                    cipher = DES.new(secret_key, DES.MODE_OFB, iv=msg['iv'])
                elif msg['alg'] == ALG_OPTIONS[5]:
                    cipher = ARC2.new(secret_key, ARC2.MODE_CFB)
                elif msg['alg'] == ALG_OPTIONS[6]:
                    cipher = ARC4.new(secret_key)
                elif msg['alg'] == ALG_OPTIONS[7]:
                    cipher = ChaCha20.new(key=secret_key, nonce=msg['nonce'])
                elif msg['alg'] == ALG_OPTIONS[8]:
                    cipher = Salsa20.new(key=secret_key, nonce=msg['nonce'])
                else:
                    return {'status': False, 'msg': "Cannot define the algorithm used to encrypt this file"}

                # decrypt and verify
                if msg['alg'] in ALG_OPTIONS[1:3]:
                    decrypted_msg = cipher.decrypt_and_verify(msg['cipher_text'], msg['tag'])
                elif msg['alg'] in ALG_OPTIONS[3:]:
                    decrypted_msg = cipher.decrypt(msg['cipher_text'])
                    SHA256.new(decrypted_msg).hexdigest(), msg['tag']
                    if SHA256.new(decrypted_msg).hexdigest() != msg['tag']:
                        raise ValueError
                else:
                    return {'status': False, 'msg': "Cannot define the algorithm used to encrypt this file"}
            except ValueError, KeyError:
                return {'status': False, 'msg': "Decrypt failed, you are not the owner of this file"}
            dir_path, file_name = os.path.split(file_path)
            with open(dir_path + '/' + msg['file_name'], 'wb') as fo:
                fo.write(decrypted_msg)
            return {'status': True, 'msg': "Successfully decrypted file %s" % file_path}
def pycryptodomexExamples():
    from Cryptodome.Cipher import DES, DES3, ARC2, ARC4, Blowfish, AES
    from Cryptodome.Random import get_random_bytes

    key = b'-8B key-'
    DES.new(key,
            DES.MODE_OFB)  # Noncompliant {{Use a strong cipher algorithm.}}
    # ^^^^^^^

    key = DES3.adjust_key_parity(get_random_bytes(24))
    cipher = DES3.new(
        key, DES3.MODE_CFB)  # Noncompliant {{Use a strong cipher algorithm.}}
    #        ^^^^^^^^

    key = b'Sixteen byte key'
    cipher = ARC2.new(
        key, ARC2.MODE_CFB)  # Noncompliant {{Use a strong cipher algorithm.}}
    #        ^^^^^^^^

    key = b'Very long and confidential key'
    cipher = ARC4.new(key)  # Noncompliant {{Use a strong cipher algorithm.}}
    #        ^^^^^^^^

    key = b'An arbitrarily long key'
    cipher = Blowfish.new(
        key,
        Blowfish.MODE_CBC)  # Noncompliant {{Use a strong cipher algorithm.}}
    #        ^^^^^^^^^^^^

    key = b'Sixteen byte key'
    cipher = AES.new(key, AES.MODE_CCM)  # Compliant

    cipher = UnknownFlyingValue.new(
        key, UnknownMode.CBC)  # Compliant, doesn't matter

    # Force the engine to generate an ambiguous symbol, for code coverage only.
    ambiguous = "" if 42 * 42 < 1700 else (lambda x: x * x)
    cipher = ambiguous.new(key, Unknown.Mode)
예제 #36
0
    def runTest(self):
        from binascii import b2a_hex

        X = []
        X[0:] = [b'\x94\x74\xB8\xE8\xC7\x3B\xCA\x7D']

        for i in range(16):
            c = DES.new(X[i],DES.MODE_ECB)
            if not (i&1): # (num&1) returns 1 for odd numbers
                X[i+1:] = [c.encrypt(X[i])] # even
            else:
                X[i+1:] = [c.decrypt(X[i])] # odd

        self.assertEqual(b2a_hex(X[16]),
            b2a_hex(b'\x1B\x1A\x2D\xDB\x4C\x64\x24\x38'))
예제 #37
0
def decryptSecret(key, value):
    # [MS-LSAD] Section 5.1.2
    plainText = b''
    key0 = key
    for i in range(0, len(value), 8):
        cipherText = value[:8]
        tmpStrKey = key0[:7]
        tmpKey = transformKey(tmpStrKey)
        Crypt1 = DES.new(tmpKey, DES.MODE_ECB)
        plainText += Crypt1.decrypt(cipherText)
        key0 = key0[7:]
        value = value[8:]
        # AdvanceKey
        if len(key0) < 7:
            key0 = key[len(key0):]

    secret = LSA_SECRET_XP(plainText)
    return (secret['Secret'])
예제 #38
0
def encryptSecret(key, value):
    # [MS-LSAD] Section 5.1.2
    cipherText = b''
    key0 = key
    value0 = pack('<LL', len(value), 1) + value
    for i in range(0, len(value0), 8):
        if len(value0) < 8:
            value0 = value0 + b'\x00'*(8-len(value0))
        plainText = value0[:8]
        tmpStrKey = key0[:7]
        print(type(tmpStrKey))
        print(tmpStrKey)
        tmpKey = transformKey(tmpStrKey)
        Crypt1 = DES.new(tmpKey, DES.MODE_ECB)
        cipherText += Crypt1.encrypt(plainText)
        key0 = key0[7:]
        value0 = value0[8:]
        # AdvanceKey
        if len(key0) < 7:
            key0 = key[len(key0):]

    return cipherText
예제 #39
0
 def basic_decrypt(cls, key, ciphertext):
     assert len(ciphertext) % 8 == 0
     des = DES.new(key.contents, DES.MODE_CBC, b'\0' * 8)
     return des.decrypt(bytes(ciphertext))
예제 #40
0
 def basic_encrypt(cls, key, plaintext):
     assert len(plaintext) % 8 == 0
     des = DES.new(key.contents, DES.MODE_CBC, b'\0' * 8)
     return des.encrypt(bytes(plaintext))
예제 #41
0
    def mit_des_string_to_key(cls,string,salt):
    
        def fixparity(deskey):
            temp = b''
            for i in range(len(deskey)):
                t = (bin(indexbytes(deskey,i))[2:]).rjust(8,'0')
                if t[:7].count('1') %2 == 0:
                    temp+= b(chr(int(t[:7]+'1',2)))
                else:
                    temp+= b(chr(int(t[:7]+'0',2)))
            return temp
    
        def addparity(l1):
            temp = list()
            for byte in l1:
                if (bin(byte).count('1') % 2) == 0:
                    byte = (byte << 1)|0b00000001
                else:
                    byte = (byte << 1)&0b11111110
                temp.append(byte)
            return temp
        
        def XOR(l1,l2):
            temp = list()
            for b1,b2 in zip(l1,l2):
                temp.append((b1^b2)&0b01111111)
            
            return temp
        
        odd = True
        s = string + salt
        tempstring = [0,0,0,0,0,0,0,0]
        s = s + b'\x00'*( 8- (len(s)%8)) #pad(s); /* with nulls to 8 byte boundary */

        for block in [s[i:i+8] for i in range(0, len(s), 8)]:
            temp56 = list()
            #removeMSBits
            for byte in block:
                if PY3:
                    temp56.append(byte&0b01111111)
                else:
                    temp56.append(ord(byte)&0b01111111)
            
            #reverse
            if odd is False:
                bintemp = b''
                for byte in temp56:
                    bintemp += b(bin(byte)[2:].rjust(7,'0'))
                bintemp = bintemp[::-1]
                
                temp56 = list()
                for bits7 in [bintemp[i:i+7] for i in range(0, len(bintemp), 7)]:
                    temp56.append(int(bits7,2))

            odd = not odd
                
            tempstring = XOR(tempstring,temp56)
        
        tempkey = ''.join(chr(byte) for byte in addparity(tempstring))
        if _is_weak_des_key(tempkey):
            tempkey[7] = chr(ord(tempkey[7]) ^ 0xF0)

        cipher = DES.new(b(tempkey), DES.MODE_CBC, b(tempkey))
        chekcsumkey = cipher.encrypt(s)[-8:]
        chekcsumkey = fixparity(chekcsumkey)
        if _is_weak_des_key(chekcsumkey):
            chekcsumkey[7] = chr(ord(chekcsumkey[7]) ^ 0xF0)
        
        return Key(cls.enctype, chekcsumkey)
예제 #42
0
#解密加密来源https://gold.xitu.io/entry/575fae92df0eea0062c5a1dc
#原始文章http://www.blog.pythonlibrary.org/2016/05/18/python-3-an-intro-to-encryption/
#字符串转换http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
#http://lixingcong.github.io/2016/03/06/convert-data-in-python/
from Cryptodome.Cipher import DES
key = 'abcdefgh'
print(key.encode('utf-8'))
keyEN = key.encode('utf-8')
def pad(text):
    while len(text) % 8 != 0:
        text += ' '
    return text

des = DES.new(keyEN, DES.MODE_ECB)
text = 'Python rocks!'
padded_text = pad(text)
textEN = bytes(padded_text, 'utf-8')
encrypted_text = des.encrypt(textEN)
print(encrypted_text)
# print(encrypted_text.encode('utf-8'))
print(str(bytes(encrypted_text))[2:-1])
okokss = '>\xfc\x1f\x16x\x87\xb2\x93\x0e\xfcH\x02\xd59VQ'
print(bytes(map(ord,okokss)))
PPPPDD=bytes(map(ord,okokss))
DDD = des.decrypt(PPPPDD)
print(DDD.decode('utf-8'))
예제 #43
0
def __DES_block(key, msg):
    cipher = DES.new(__expand_DES_key(key),DES.MODE_ECB)
    return cipher.encrypt(msg)
예제 #44
0
파일: ciphers.py 프로젝트: chair6/bandit
bs = pycrypto_blowfish.block_size
cipher = pycrypto_blowfish.new(key, pycrypto_blowfish.MODE_CBC, iv)
msg = iv + cipher.encrypt(plaintext + padding)
bs = pycryptodomex_blowfish.block_size
cipher = pycryptodomex_blowfish.new(key, pycryptodomex_blowfish.MODE_CBC, iv)
msg = iv + cipher.encrypt(plaintext + padding)

key = b'-8B key-'
plaintext = b'We are no longer the knights who say ni!'
nonce = Random.new().read(pycrypto_des.block_size/2)
ctr = Counter.new(pycrypto_des.block_size*8/2, prefix=nonce)
cipher = pycrypto_des.new(key, pycrypto_des.MODE_CTR, counter=ctr)
msg = nonce + cipher.encrypt(plaintext)
nonce = Random.new().read(pycryptodomex_des.block_size/2)
ctr = Counter.new(pycryptodomex_des.block_size*8/2, prefix=nonce)
cipher = pycryptodomex_des.new(key, pycryptodomex_des.MODE_CTR, counter=ctr)
msg = nonce + cipher.encrypt(plaintext)

key = b'Super secret key'
plaintext = b'Encrypt me'
cipher = pycrypto_xor.new(key)
msg = cipher.encrypt(plaintext)
cipher = pycryptodomex_xor.new(key)
msg = cipher.encrypt(plaintext)

cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend())
encryptor = cipher.encryptor()
ct = encryptor.update(b"a secret message")

cipher = Cipher(algorithms.Blowfish(key), mode=None, backend=default_backend())
encryptor = cipher.encryptor()
예제 #45
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(r"\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(r"-----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(''.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)