Пример #1
0
def _cases_cipher(key_size, mult_keys, mult_state, mode='encrypt'):
    if mult_keys:
        keys = np.random.randint(0,
                                 255, (number_of_keys, key_size),
                                 dtype='uint8')
        if mult_state:
            state = np.random.randint(0,
                                      255, (number_of_keys, 16),
                                      dtype='uint8')
            expected = np.empty((number_of_keys, 16), dtype='uint8')
            for i, key in enumerate(keys):
                a = crypto_aes.AESCipher(key)
                expected[i] = np.frombuffer(getattr(a, mode)(state[i]),
                                            dtype='uint8')
        else:
            state = np.random.randint(0, 255, (16), dtype='uint8')
            expected = np.empty((number_of_keys, 16), dtype='uint8')
            for i, key in enumerate(keys):
                a = crypto_aes.AESCipher(key)
                expected[i] = np.frombuffer(getattr(a, mode)(state),
                                            dtype='uint8')
    else:
        keys = np.random.randint(0, 255, (key_size), dtype='uint8')
        a = crypto_aes.AESCipher(keys)
        if mult_state:
            state = np.random.randint(0,
                                      255, (number_of_keys, 16),
                                      dtype='uint8')
            expected = np.empty((number_of_keys, 16), dtype='uint8')
            for i, s in enumerate(state):
                expected[i] = np.frombuffer(getattr(a, mode)(s), dtype='uint8')
        else:
            state = np.random.randint(0, 255, (16), dtype='uint8')
            expected = np.frombuffer(getattr(a, mode)(state), dtype='uint8')
    return {'keys': keys, 'state': state, 'expected': expected}
Пример #2
0
def randomEnc(pt):
    #Generate the key
    key = bytes(genData());
    #Pad the string
    padStr = randPad(pt)

    ct = None

    #Choose encryption method
    if(randint(1,2) == 1):
        #Set up the cipher
        cipher = AES.AESCipher(key, AES.MODE_ECB)
        #Pad the string using pkcs7
        padStr = pkcs7(padStr)

        ct = cipher.encrypt(bytes(padStr))#"pt.decode('latin-1')")
        #What encryption method was used?
        #print("EBC")
        method = "EBC"
    else:
        cipher = CBC(AES.AESCipher(key, AES.MODE_ECB), genData())
        ct = cipher.encrypt(padStr)
        #print("CBC")
        method = "CBC"

    return (ct, method)
Пример #3
0
 def __init__(self, my_HMAC, other_HMAC, my_key, other_key):
     self.my_HMAC_key = my_HMAC
     self.other_HMAC_key = other_HMAC
     self.my_aes = AES.AESCipher(my_key)
     self.other_aes = AES.AESCipher(other_key)
     self.write_seq = 0
     self.read_seq = 0
Пример #4
0
def main():
    # Set-up a command-line argument parser
    parser = ArgumentParser(description=__doc__, epilog="""Input is read from
        stdin and output is written to stdout. Use the stream redirection
        features of your shell to pass data through this program. If a key is
        not specified, it is generated and written to stderr.""")
    parser.add_argument('-d', '--decrypt', action='store_true')
    parser.add_argument('-k', '--key', metavar='key')
    args = parser.parse_args()

    # Decode the key if it was supplied
    key = base64.b64decode(args.key) if args.key else None

    # -- DECRYPT --

    if args.decrypt:
        # Check to see if a key was supplied
        if key is None:
            sys.stderr.write('Error: Please supply a decryption key.\n')
            exit(1)

        # Read in the initialization vector
        iv = sys.stdin.read(AES.block_size)

        # Create the cipher object and process the input stream
        cipher = AES.AESCipher(key, AES.MODE_CBC, iv)
        method = cipher.decrypt

        # Stream is processed below...

    # -- ENCRYPT --

    else:
        # Create a file object that produces random data when read from
        random = Random.new()

        # Generate a key if one was not supplied
        if key is None:
            key = random.read(AES.key_size[0])
            print("")
            sys.stderr.write('AES-256 Encryption =  %s\n' % base64.b64encode(key))

        # Create the initialization vector
        iv = random.read(AES.block_size)
        print("")
        sys.stdout.write('Initialization IV  =  %s\n' %iv)

        # Create the cipher object and process the input stream
        cipher = AES.AESCipher(key, AES.MODE_CBC, iv)
        method = cipher.encrypt

        # Stream is processed below...

    # Process the input stream
    while True:
        data = sys.stdin.read(AES.block_size)
        if data == '': break # Check for EOF
        sys.stdout.write(method(data))
Пример #5
0
def handle(conn: socket.socket, addr):
    agent_hashcode = conn.recv(32)
    if binascii.hexlify(agent_hashcode) != config['agent_hashcode']:
        try:
            if agent_hashcode.decode().isprintable():
                thread_print('1')
        except:
            thread_print('got connection with wrong hash: {}'.format(
                binascii.hexlify(agent_hashcode)))
        conn.close()
        return
    thread_print('got valid agent hashcode')
    session_aes_key = generate_aes_key()
    thread_print('aes key: ' + binascii.hexlify(session_aes_key).decode())
    conn.send(session_aes_key)

    agent_hello_enc = conn.recv(32)
    agent_hello = AES.AESCipher(session_aes_key).decrypt(agent_hello_enc)
    assert agent_hello == config['agent_hello']

    agent_hashcode_xored_encrypted = conn.recv(32)
    agent_hashcode_xored = AES.AESCipher(session_aes_key).decrypt(
        agent_hashcode_xored_encrypted)
    agent_hashcode = binascii.hexlify(
        bytes(i ^ 0x55 for i in agent_hashcode_xored))
    if agent_hashcode != config['agent_hashcode']:
        thread_print(
            'got connection with wrong xored encrypted hash: {}'.format(
                agent_hashcode))
        conn.close()
        return
    thread_print('got valid agent xored encrypted hashcode')

    grabbed_data_aes = AES.new(session_aes_key, AES.MODE_CBC,
                               agent_hello_enc[:16])
    try:
        thread_print('trying to parse...')
        assert parse_grabbed(conn, grabbed_data_aes)
    except Exception as e:
        thread_print('got exception when parsing grabbed data: {}'.format(e))
        conn.close()
        return
    thread_print('got and parsed valid grabbed data')

    shellcode_iv = generate_aes_key()
    sc = prepare_shellcode(bytes([i ^ 0x88 for i in session_aes_key]),
                           shellcode_iv)
    conn.send(shellcode_iv + struct.pack("I", len(sc)))
    conn.send(sc)
    conn.close()
    return
Пример #6
0
def decrypt(key, enc):
    if (enc is None) or (len(enc) == 0):
        raise ValueError('input text cannot be null or empty set')
    enc = binascii.unhexlify(enc)
    cipher = AES.AESCipher(key[:32], AES.MODE_ECB)
    enc = cipher.decrypt(enc)
    return enc
Пример #7
0
def CBCDecrypt(cipherText, KEY, IV):
    cipher = AES.AESCipher(KEY, AES.MODE_ECB)
    dBlocks = []
    Blocks = Padding.pad(cipherText, 16)
    iBlock = Blocks[0]
    cBlock = cipher.decrypt(iBlock)
    dBlock = XOR(cBlock, IV)
    dBlocks.append(dBlock)
    for Block in Blocks[1:]:
        cBlock = cipher.decrypt(Block)
        dBlock = XOR(cBlock, iBlock)
        iBlock = Block
        dBlocks.append(dBlock)
    plainText = ""
    for Block in dBlocks:
        plainText += Block
    return plainText


# IV = "\x00" * 16
# KEY = "YELLOW SUBMARINE"
# file = open("CBCCipherText","r")
# cipherText = ""
# for line in file:
#     cipherText += line.strip("\n")
# file.close()
# # encrypted = CBCEncrypt("Hello World",KEY,IV)
# # print encrypted
# # decrypted = CBCDecrypt(encrypted,KEY,IV)
# # print decrypted
#
# cipherText = binascii.a2b_base64(cipherText)
#
# decrypt = CBCDecrypt(cipherText, KEY, IV)
# print decrypt
    def updateInfo(self, json_data="[]"):
        print '[LOG] Updating service information...'
        data = json.loads(json_data)
        if(not data['masterPassword']):
            self.listData.listInfo(data, "Wrong master password while removing a service! Try again.")
        elif self.common.checkAuth('password', data['masterPassword'], data['username']):
            # Get decrypted intermediary key
            key = self.common.decKey('password', data['masterPassword'], data['username'])
            # Open iv to encrypt data info
            path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/security/iv_data_' + str(KEY_LENGTH/2) + '_' + data['username'] + '.txt'
            iv = open(path, 'r').read()
            # Open data info file
            path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/data/info/data_enc_' + data['username'] + '_' + data['timestamp'] + '.txt'
            df = open(path, 'w')
            # Pad data info
            infoPad = self.common.pad(data['infoName'] + '\n' + data['login'] + '\n' + data['password'], len(key))

            # Create the cipher object and process the input stream
            cipher = AES.AESCipher(key, AES.MODE_CBC, iv)

            encData = (iv + cipher.encrypt(infoPad))

            df.write(encData)
            df.close()
            key = None
            
            # Replace masterPassword to password attr (listInfo requires the masterPassword as password)
            data['password'] = data['masterPassword']
            self.listData.listInfo(data, "")
        else:
            self.listData.listInfo(data, "Wrong master password while adding a new service! Try again.")
def decryptaesecb_base64(rawfile):
    cipher = AES.AESCipher(bytes('YELLOW SUBMARINE', encoding='utf-8'),
                           AES.MODE_ECB)
    hexstrfile = base64tohex(rawfile)
    hexstrfile = binascii.unhexlify(hexstrfile)
    decryptedtext = cipher.decrypt(hexstrfile).rstrip(b'\x00').decode('utf-8')
    return decryptedtext
Пример #10
0
def decrypt(blocks, Key):

    plain_text = []
    cipher = AES.AESCipher(Key, AES.MODE_ECB)
    index = 0
    l = len(blocks) - 1
    IV = blocks[0]

    for i in range(len(blocks))[1:]:
        txt = cipher.decrypt(blocks[i])
        r = int.from_bytes(txt, sys.byteorder) ^ int.from_bytes(
            IV, sys.byteorder)
        IV = blocks[i]
        plain_text.append(r.to_bytes((r.bit_length() + 7) // 8,
                                     'big')[::-1])  ##bytes are decryptted
        #backward, this corrects it
    block_pad = plain_text[len(plain_text) - 1]

    try:

        len_pad = block_pad[
            0]  ## if pad is simply a cap pad of /x00's this will fail
        plain_text = plain_text[:len(plain_text) - 1]
        plain_text[len(plain_text) - 1] = plain_text[len(plain_text) -
                                                     1][:16 - len_pad]

    except:  #case that the cypher text length could be evenly devided by 16

        plain_text = plain_text[:len(plain_text) - 1]

    return plain_text
Пример #11
0
 def __init__(self):
   self.mode = "ECB" if randint(0,1) else "CBC"
   if self.mode == "CBC":
     args = [random_bytes(16),AES.MODE_CBC,random_bytes(16)]
   else:
     args = [random_bytes(16),AES.MODE_ECB]
   self.cipher = AES.AESCipher(*args)
Пример #12
0
def encrypt(key, ctr, message, output):
    cipher = AES.AESCipher(key[:32], AES.MODE_ECB)
    aescipher = cipher.decrypt(bytes(hex(ctr)[2:], 'utf-8'))

    c = strxor.strxor(aescipher, ba.unhexlify(message))
    #print(ba.hexlify(c))
    output.put(ba.hexlify(c))
Пример #13
0
def ecb(s, key):
    out = b''
    s = pkcs7(s)
    c = AES.AESCipher(key, AES.MODE_ECB)
    for b in [s[i:i+16] for i in range(0, len(s), 16)]:
        out += c.encrypt(b)
    return out
Пример #14
0
def upload_data():
    """
    # 1. query for AESkey
    # 2. decrypt
    # 3. parse
    # 4. insert
    :return:
    """
    needed_args = ['deviceID', 'data']
    if not check_exists(needed_args, request.form):
        return 'No device ID or input data', 400
    device_id = request.form['deviceID']
    data = request.form['data']
    enc_data = bytes.fromhex(data)
    r = redis.StrictRedis(host='localhost', port=6379, db=0)
    aes_key = r.get(device_id)
    if aes_key is None:
        return 'No passwd for you, please restart', 400
    cipher = AES.AESCipher(aes_key, AES.MODE_CBC, iv)
    dec = cipher.decrypt(enc_data)
    plain = pkcs5_unpad(dec)
    body = msg_pb2.Body()
    body.ParseFromString(plain)
    xinlv = body.xinlv
    xueyang = body.xueyang
    b = BodyInDB(xinlv, xueyang, device_id)
    db.session.add(b)
    db.session.commit()
Пример #15
0
def cbc_mac(s, key, l):
    s = pkcs7(s)
    c = AES.AESCipher(key, AES.MODE_ECB)
    for b in [s[i:i + 16] for i in range(0, len(s), 16)]:
        print hex(xor(b, l))
        l = c.encrypt(xor(b, l))
    return l
Пример #16
0
def ecb_decrypt(s, key):
    out = b''
    c = AES.AESCipher(key, AES.MODE_ECB)
    for b in [s[i:i + 16] for i in range(0, len(s), 16)]:
        out += c.decrypt(b)
    print('Raw:', out)
    return out[:-out[-1]]
Пример #17
0
    def setup_cipher(self):
        # https://github.com/ethereum/cpp-ethereum/blob/develop/libp2p/RLPxFrameIO.cpp#L34
        assert self.responder_nonce
        assert self.initiator_nonce
        assert self.auth_init
        assert self.auth_ack
        assert self.remote_ephemeral_pubkey
        if not self.ecc.is_valid_key(self.remote_ephemeral_pubkey):
            raise InvalidKeyError('invalid remote ephemeral pubkey')

        # derive base secrets from ephemeral key agreement
        # ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk)
        ecdhe_shared_secret = self.ephemeral_ecc.get_ecdh_key(
            self.remote_ephemeral_pubkey)

        # shared-secret = sha3(ecdhe-shared-secret || sha3(nonce || initiator-nonce))
        shared_secret = sha3(ecdhe_shared_secret +
                             sha3(self.responder_nonce + self.initiator_nonce))

        self.ecdhe_shared_secret = ecdhe_shared_secret  # FIXME DEBUG
        self.shared_secret = shared_secret  # FIXME DEBUG

        # token = sha3(shared-secret)
        self.token = sha3(shared_secret)
        self.token_by_pubkey[self.remote_pubkey] = self.token

        # aes-secret = sha3(ecdhe-shared-secret || shared-secret)
        self.aes_secret = sha3(ecdhe_shared_secret + shared_secret)

        # mac-secret = sha3(ecdhe-shared-secret || aes-secret)
        self.mac_secret = sha3(ecdhe_shared_secret + self.aes_secret)

        # setup sha3 instances for the MACs
        # egress-mac = sha3.update(mac-secret ^ recipient-nonce || auth-sent-init)
        mac1 = sha3_256(
            sxor(self.mac_secret, self.responder_nonce) + self.auth_init)
        # ingress-mac = sha3.update(mac-secret ^ initiator-nonce || auth-recvd-ack)
        mac2 = sha3_256(
            sxor(self.mac_secret, self.initiator_nonce) + self.auth_ack)

        if self.is_initiator:
            self.egress_mac, self.ingress_mac = mac1, mac2
        else:
            self.egress_mac, self.ingress_mac = mac2, mac1

        ciphername = 'aes-256-ctr'
        iv = "\x00" * 16
        assert len(iv) == 16
        self.aes_enc = pyelliptic.Cipher(self.aes_secret,
                                         iv,
                                         1,
                                         ciphername=ciphername)
        self.aes_dec = pyelliptic.Cipher(self.aes_secret,
                                         iv,
                                         0,
                                         ciphername=ciphername)
        self.mac_enc = AES.AESCipher(self.mac_secret, AES.MODE_ECB).encrypt

        self.is_ready = True
Пример #18
0
def reveal_yoself(ciphertext):
    if not ciphertext:
        return None
    key =  passphrase + (b" " * (32 - len(passphrase))) # turn a 16byte password into a 32 byte one by padding with SPACES (i thought we were using pbkdf2 here? oh well...)!
    pbkdf2_key = hashlib.pbkdf2_hmac("sha1", key, b"\x01\x02\x03\x04\x05\x06\x07\x08", 1024, dklen=32)
    ctr = Crypto.Util.Counter.new(128, initial_value=int(codecs.encode(base64.b64decode(ciphertext)[:16], 'hex'), 16))
    cipher = AES.AESCipher(pbkdf2_key, AES.MODE_CTR, counter=ctr)
    return cipher.decrypt(base64.b64decode(ciphertext)[16:])
Пример #19
0
 def decryptECB(self, cipher):
     enc = bytes(self.hextoBytes(cipher))
     file = open("Key_AES", 'r')
     k = file.read()
     key = hashlib.sha256(k.encode()).digest()
     cipher = AES.AESCipher(key[:32], AES.MODE_ECB)
     enc = unpad(cipher.decrypt(enc))
     return enc.decode('utf-8')
Пример #20
0
def decrypt(input):
    if (input is None) or (len(input) == 0):
        print "Input text cannot be null or empty"

    encrypted = input.decode("hex")
    cipher = AES.AESCipher(encKey, AES.MODE_ECB)
    plainText = unpad(cipher.decrypt(encrypted))
    return plainText
Пример #21
0
def ECB_Encrypt(Message, Key, Addition, Rand):
    plain = Rand + Addition + Message
    Blocks = Padding.pad(plain, 16)
    plainText = ""
    for Block in Blocks:
        plainText += Block
    cipher = AES.AESCipher(Key, AES.MODE_ECB)
    return cipher.encrypt(plainText)
Пример #22
0
def encrypt(key, raw):
    # Takes in a string of text and encrypts it.
    # padding put on before sent for encryption
    raw = __pad(raw)
    cipher = AES.AESCipher(key[:32], AES.MODE_ECB)
    ciphertext = cipher.encrypt(raw)
    # changes the ciphertext into hex then decodes it into utf-8
    return binascii.hexlify(bytearray(ciphertext))
def encECB(Message, Key):
    Blocks = Padding.pad(Message, 16)
    plainText = ""
    for Block in Blocks:
        plainText += Block
    cipher = AES.AESCipher(Key, AES.MODE_ECB)
    cipherText = cipher.encrypt(plainText)
    return cipherText
Пример #24
0
 def decrypter(x):
     cipher = AES.AESCipher(key[:32], AES.MODE_ECB)
     dest_size = len(x)
     x = _pad_data(
         x, block_size=block_size)  # Yes, this is a hack -- read above.
     x = cipher.decrypt(x)
     x = _unpad_data(x, dest_size=dest_size, block_size=block_size)
     return x
Пример #25
0
def cbc(s, key, l=urandom(16)):
    out = l
    s = pkcs7(s)
    c = AES.AESCipher(key, AES.MODE_ECB)
    for b in [s[i:i + 16] for i in range(0, len(s), 16)]:
        l = c.encrypt(xor(b, l))
        out += l
    return out
Пример #26
0
def encrypt(input):
    if (input is None) or (len(input) == 0):
        print "Input text cannot be null or empty"

    toEncrypt = prepend + input + secret
    toEncrypt = pad(toEncrypt)
    cipher = AES.AESCipher(encKey, AES.MODE_ECB)
    cipherText = cipher.encrypt(toEncrypt)
    return cipherText.encode("hex")
Пример #27
0
 def encrypt(self, msg):
     """encrypts a message"""
     iv = self.random_bytes(AES.block_size)
     ctr = Counter.new(AES.block_size * 8, initial_value=self.bin2long(iv))
     cipher = AES.AESCipher(self._cipherkey, AES.MODE_CTR, counter=ctr)
     cipher_text = cipher.encrypt(msg)
     intermediate = iv + cipher_text
     signature = self.sign(intermediate)
     return signature + intermediate
def encCBC(Message, Key):
    Blocks = Padding.pad(Message, 16)
    IV = os.urandom(16)
    plainText = ""
    for Block in Blocks:
        plainText += Block
    cipher = AES.AESCipher(Key, AES.MODE_CBC, IV)
    cipherText = cipher.encrypt(plainText)
    return cipherText
Пример #29
0
def ctr(s, key, nonce=b''):
    if not nonce:
        nonce = s[:8]
        s = s[8:]
    l = b''
    c = AES.AESCipher(key, AES.MODE_ECB)
    for cnt in range(0, ceil(len(s) / 16)):
        l += c.encrypt(nonce + struct.pack('<Q', cnt))
    return nonce + xor(s, l)
Пример #30
0
def seek(cipherText, KEY, COUNTER, offset, newPlain):
    cipherBlock = cipherText[offset * 16:offset * 16 + 16]
    newCipher = ""
    count = COUNTER
    cipher = AES.AESCipher(Key, AES.MODE_ECB)
    xor = cipher.encrypt(count)
    for i, j in zip(xor, newPlain):
        newCipher += chr(ord(i) ^ ord(j))
    return newCipher