コード例 #1
0
def main(serverAddr, serverPort):
    server_socket = library.CreateServerSocket(serverAddr, serverPort)
    clientThreads = []

    # Handle commands indefinitely (^C to exit)
    while True:
        # Wait until a client connects, then get a socket for the  client.
        client_socket, addr = library.ConnectClientToServer(server_socket)

        # Read the request.
        request = library.ReadRequest(client_socket)
        command, filepath = library.ParseRequest(request)

        if command == 'GET' and filepath is not None:
            newClientThread = ClientThread(client_socket, filepath)
            newClientThread.start()
            clientThreads.append(newClientThread)

        else:
            client_socket.send(aes.encrypt(b't'))
            client_socket.send(aes.encrypt(b'Invalid request!\n'))
            client_socket.close()

    for t in clientThreads:
        t.join()

    server_socket.close()
コード例 #2
0
def test_encrypt():
    ''' perform AES encryption using 128-bit hex_key on 128-bit plaintext 
        hex_plaintext, where both key and plaintext values are expressed
    in hexadecimal string notation. '''
    p = "00112233445566778899aabbccddeeff"
    k = "000102030405060708090a0b0c0d0e0f"
    c = "69c4e0d86a7b0430d8cdb78070b4c55a"
    actual = AES.encrypt(k, p)
    assert actual == c

    p = "6bc1bee22e409f96e93d7e117393172a"
    k = "2b7e151628aed2a6abf7158809cf4f3c"
    c = "3ad77bb40d7a3660a89ecaf32466ef97"
    actual = AES.encrypt(k, p)
    assert actual == c

    p = "ae2d8a571e03ac9c9eb76fac45af8e51"
    k = "2b7e151628aed2a6abf7158809cf4f3c"
    c = "f5d3d58503b9699de785895a96fdbaaf"
    actual = AES.encrypt(k, p)
    assert actual == c

    p = "30c81c46a35ce411e5fbc1191a0a52ef"
    k = "2b7e151628aed2a6abf7158809cf4f3c"
    c = "43b1cd7f598ece23881b00e3ed030688"
    actual = AES.encrypt(k, p)
    assert actual == c

    p = "f69f2445df4f9b17ad2b417be66c3710"
    k = "2b7e151628aed2a6abf7158809cf4f3c"
    c = "7b0c785e27e8ad3f8223207104725dd4"
    actual = AES.encrypt(k, p)
    assert actual == c
コード例 #3
0
def test_encrypt():
    ''' perform AES encryption using 128-bit hex_key on 128-bit plaintext 
        hex_plaintext, where both key and plaintext values are expressed
    in hexadecimal string notation. '''
    p = "00112233445566778899aabbccddeeff"
    k = "000102030405060708090a0b0c0d0e0f"
    c = "69c4e0d86a7b0430d8cdb78070b4c55a"
    actual = AES.encrypt(k, p)
    assert actual == c

    p = "6bc1bee22e409f96e93d7e117393172a"
    k = "2b7e151628aed2a6abf7158809cf4f3c"
    c = "3ad77bb40d7a3660a89ecaf32466ef97"
    actual = AES.encrypt(k, p)
    assert actual == c

    p = "ae2d8a571e03ac9c9eb76fac45af8e51"
    k = "2b7e151628aed2a6abf7158809cf4f3c"
    c = "f5d3d58503b9699de785895a96fdbaaf"
    actual = AES.encrypt(k, p)
    assert actual == c
    
    p = "30c81c46a35ce411e5fbc1191a0a52ef"
    k = "2b7e151628aed2a6abf7158809cf4f3c"
    c = "43b1cd7f598ece23881b00e3ed030688"
    actual = AES.encrypt(k, p)
    assert actual == c

    p = "f69f2445df4f9b17ad2b417be66c3710"
    k = "2b7e151628aed2a6abf7158809cf4f3c"
    c = "7b0c785e27e8ad3f8223207104725dd4"
    actual = AES.encrypt(k, p)
    assert actual == c
コード例 #4
0
def encrypt_files(key, path, out_path):
    if os.path.exists(out_path):
        shutil.rmtree(out_path)
    shutil.copytree(path, out_path)
    for root, dirs, files in os.walk(out_path):
        for name in files:
            p = (os.path.join(root, name))
            print(p)
            aes.encrypt(key, p)
            os.remove(p)
コード例 #5
0
def encrypt_file(key, file, out=None):
    if out is None:
        out = tempfile.gettempdir()
    else:
        if not os.path.isdir(out):
            os.makedirs(out)
    filename = os.path.basename(file)
    print(filename)
    aes.encrypt(key, file, os.path.join(out, filename))
    webbrowser.open(out)
コード例 #6
0
ファイル: crypto2.py プロジェクト: 435vic/crypto2
def AES():
    while True:
        title('AES Encryption / Decryption', fillchar='-')
        [print() for i in range(5)]
        print('Do you want to...')
        print('1. Encrypt a file')
        print('2. Decrypt a file')
        print('3. Exit')
        print('_' * utils.get_terminal_size()[0])
        print()
        action = input('>> ').lower()
        if action in ['1', 'encrypt', 'e']:
            title('AES Encryption / Decryption', fillchar='-')
            print()
            print()
            print('Please select a file in the dialog box.')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Choose a file to encrypt...')
            password = getpass('Enter password for file: ').encode('utf-8')
            print('Choose the name for the encrypted file.')
            outfilename = asksaveasfilename(
                initialdir=cwd,
                title='Choose the name for the encrypted file...')
            chunksize = input('Enter encryption chunksize: ') or 64 * 1024
            if chunksize:
                chunksize = int(chunksize)
            aes.encrypt(password, filename, outfilename, chunksize)

        elif action in ['2', 'decrypt', 'd']:
            title('AES Encryption / Decryption', fillchar='-')
            print()
            print()
            print('Please select a file in the dialog box.')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Choose a file to decrypt...')
            password = getpass('Enter password to decrpyt file: ').encode(
                'utf-8')
            print('Choose the name for the output file.')
            outfilename = asksaveasfilename(
                initialdir=cwd,
                title='Choose the name for the decrypted file...')
            chunksize = input('Enter decryption chunksize: ') or 24 * 1024
            if chunksize:
                chunksize = int(chunksize)

            aes.decrypt(password, filename, outfilename, chunksize)

        elif action in ['3', 'exit', 'quit', 'q']:
            exit(0)

        else:
            clear()
            _tmp = input('That is not an action.')
コード例 #7
0
def sendEncryptedFile(f, sock):
    """ Send the file in batches of size BLOCK_SIZE. Else, larger data will be
        inconsistent on the client side.
    """
    # batch must be less than BLOCK_SIZE for AES padding function to work properly.
    batch = f.read(BLOCK_SIZE - 1)
    while batch != b'':
        padLen = BLOCK_SIZE - len(batch)
        sock.send(aes.encrypt(str(padLen).encode()))
        sock.send(aes.encrypt(batch))
        batch = f.read(BLOCK_SIZE - 1)
コード例 #8
0
def user_upload():
    global user_name
    auth_url = "yourproject_id"
    password = "******"
    project_id = "yourproject_id"
    user_id = "youruser_id"
    region_name = "your_region"
    conn = swiftclient.Connection(key=password,
                                  authurl=auth_url,
                                  auth_version='3',
                                  os_options={
                                      "project_id": project_id,
                                      "user_id": user_id,
                                      "region_name": region_name
                                  })
    container_name = 'original_folder'

    file = request.files['get_myfile']
    print file

    print container_name

    filename = file.filename
    filecontent = file.read()

    fo = open("output.txt", "w")
    fo.write(filecontent)
    print fo

    fo = open("output.txt")
    output_content = fo.read()
    print output_content

    temp_name = fo.name
    print 'temporar name' + temp_name

    aes.encrypt(temp_name, "test", outputfile=None)
    target = open(temp_name + '.aes')
    target_content = target.read()

    print target_content
    print target

    conn.put_object(container_name,
                    filename + user_name + '.aes',
                    contents=target_content,
                    content_type='text/plain')

    target.close()
    fo.close()
    os.remove(temp_name + '.aes')
    os.remove(temp_name)
    return container_name
コード例 #9
0
ファイル: CSecreteAes.py プロジェクト: Alcasser/C
def mixColumnsEffectTest():
    aes = AesWoMixColumns(master_key)
    m = 0x1597C4EF331CC28B7E6D1B2EB3EA3B95
    c = aes.encrypt(m)
    for i in range(4):
        mi = m ^ (1 << i * 32)
        ci = aes.encrypt(mi)
        print("Only one byte modified")
        printMatrix(asHexMatrix(c))
        print("")
        printMatrix(asHexMatrix(ci))
        print("")
コード例 #10
0
ファイル: CSecreteAes.py プロジェクト: Alcasser/C
def byteSubEffectTest():
    aes = AesWoByteSub(master_key)
    m = 0x1597C4EF331CC28B7E6D1B2EB3EA3B95
    c = aes.encrypt(m)
    print("Byte substitution effect in progress...")
    for i in range(128):
        for j in range(128):
            if (i != j):
                ci = aes.encrypt(m ^ (1 << i))
                cj = aes.encrypt(m ^ (1 << j))
                cij = aes.encrypt(m ^ (1 << i ^ 1 << j))
                #print(hex(cij), end="\r", flush=True)
                assert (c == ci ^ cj ^ cij)
    print("Byte substitution effect tested   ", flush=True)
コード例 #11
0
ファイル: test_aes.py プロジェクト: olbat/o1b4t
    def test_encrypt(self):
        iio = BytesIO()
        oio = BytesIO()
        for tv in self.__class__.TEST_VECTORS:
            iio.truncate(0)
            iio.seek(0)
            oio.truncate(0)
            oio.seek(0)

            iio.write(tv.text)
            iio.seek(0)
            aes.encrypt(iio, oio, tv.key, tv.moo, tv.iv)
            oio.seek(0)

            self.assertEqual(tv.cipher.hex(), oio.read().hex())
コード例 #12
0
    def run(self):
        try:
            with open(self.filepath, 'rb') as f:
                # Open the file in binary and send it to client.
                filename = os.path.basename(self.filepath)
                self.sock.send(aes.encrypt(b'f'))
                sendEncryptedFile(f, self.sock)

        except FileNotFoundError:
            # Inform file not found.
            self.sock.send(aes.encrypt(b't'))
            self.sock.send(aes.encrypt(b'File not found!\n'))

        finally:
            self.sock.close()
コード例 #13
0
def encrypt(file, passwd):
    assert str(type(file)) == '<class \'_io.TextIOWrapper\'>'
    try:
        assert len(passwd) == 16
    except AssertionError:
        print('Failed!')
        return True
    content = file.read()
    content = aes.encrypt(passwd, content)
    str_len = len(content)
    width = math.ceil(str_len ** 0.5)
    img = Image.new('RGB', (width, width), 0x0)
    passwd_sha512 = hashlib.sha512(passwd.encode('utf-8')).hexdigest()
    passwd_img = Image.new('RGB', (len(passwd_sha512), 1), 0x0)
    x, y = 0, 0
    for i in passwd_sha512:
        index = ord(i)
        rgb = (0, (index & 0xFF00) >> 8, index & 0xFF)
        passwd_img.putpixel((x, y), rgb)
        x += 1
    x = 0
    for i in content:
        index = ord(i)
        rgb = (0, (index & 0xFF00) >> 8, index & 0xFF)
        img.putpixel((x, y), rgb)
        if x == width - 1:
            x = 0
            y += 1
        else:
            x += 1
    return {
        'passwd_img': passwd_img,
        'img': img
    }
コード例 #14
0
def encrypt_message(message):
    #Turn the string length into a some multiple of 16
    padding = 16 - (len(message) % 16)
    factor16len = padding + len(message)
    message = message.ljust(factor16len)

    #Divide the message into blocks of 16 chars
    messageblocks = list(map(''.join, zip(*[iter(message)] * 16)))
    allciphers = []
    #messageblock = 'microprogramming'
    for messageblock in messageblocks:
        if API_DEBUG: print messageblock + "|"
        #msg_hex = [0x73L 0x61L 0x67L 0x65L 0x20L 0x66L 0x6fL 0x72L 0x20L 0x65L 0x6eL 0x63L 0x72L 0x79L 0x70L 0x74L]
        msg_hex = map(lambda x: int(binascii.hexlify(x), 16),
                      list(messageblock))

        #cipher = [0x40L 0x9eL 0xb4L 0x5L 0x3bL 0x66L 0x27L 0xc3L 0x4dL 0xdaL 0x5cL 0x70L 0x63L 0xcfL 0x50L 0xb7L]
        cipher = aes.encrypt(msg_hex)

        allciphers = allciphers + cipher

        if API_DEBUG: print "messageblock:" + messageblock
        if API_DEBUG: print "msg_hex:" + str(np.array(msg_hex))
        if API_DEBUG: print "cipher:" + str(np.array(cipher))

    #allciphers = [8, 46, 162] ==> concat = [0008, 0046, 0162] ==> 000800460162
    if API_DEBUG: print allciphers
    concat = reduce(lambda x, y: str(x).zfill(4) + str(y).zfill(4), allciphers)
    if API_DEBUG: print concat
    return concat
コード例 #15
0
 def enc():
     try:
         ciphertext = aes.encrypt(entry_password.get(), entry_text.get(), entry_aad.get())
         print(ciphertext)
         salt, nonce, cipher_text = map(unhexlify, ciphertext.split("-"))
         salt = hexlify(salt).decode("utf8")
         nonce = hexlify(nonce).decode("utf8")
         cipher_text = hexlify(cipher_text).decode("utf8")
         text_to_save = str(ciphertext)
         x = open(save_filename_address, 'w')
         x.write(text_to_save + '\n')
         x.write('Aad: ' + entry_aad.get() + '\n')
         x.write('salt: ' + salt + '\n')
         x.write('nonce: ' + nonce + '\n')
         x.write('cipher_text: ' + cipher_text + '\n')
         x.close()
         messagebox.showinfo("Complete", 'Your text was encrypted \n\nsalt: ' + salt + '\n\nnonce: ' + nonce +
                             '\n\nciphertext: ' + cipher_text)
         encrypt_win.destroy()
         win.deiconify()
     except exceptions.InvalidTag:
         messagebox.showerror("Error", 'Your data is inavlid')
         entry_text.delete(0, END)
         entry_password.delete(0, END)
         entry_aad.delete(0, END)
コード例 #16
0
ファイル: encrypt.py プロジェクト: ericfu88/partner_crypto
def encrypt(senderPrivateKeyFile,
            receiverPublicKeyFile,
            message,
            base64Encode=False):

    # encrypt message with AES
    # ---------------------------------------------------
    (aes_key, iv, aes_encrypted_message) = aes.encrypt(message)
    # print 'aes-key:' + asHex(aes_key)
    # print 'iv:', asHex(iv)
    # print 'aes_encrypted_message-' + str(len(aes_encrypted_message)) + ':', asHex(aes_encrypted_message)
    # sign the aes key and IV with public key of receiver
    # ---------------------------------------------------
    receiverPubKeyObj = RSA.importKey(open(receiverPublicKeyFile).read())
    cipher = PKCS1_OAEP.new(receiverPubKeyObj)
    encrypted_aes_key = cipher.encrypt(aes_key + iv)

    # hash the combined encrypted aes_key and encrypted message
    # ---------------------------------------------------
    combined_aes_key_and_message = b''.join(
        [encrypted_aes_key, aes_encrypted_message])
    sha1_hash = SHA256.new(combined_aes_key_and_message)

    # sign the hash with private key of sender
    # ---------------------------------------------------
    senderPrivateKeyObj = RSA.importKey(open(senderPrivateKeyFile).read())
    signer = PKCS1_v1_5.new(senderPrivateKeyObj)
    signed_hash = signer.sign(sha1_hash)

    # returned the whole blob
    # ---------------------------------------------------
    encrypted = b''.join([signed_hash, combined_aes_key_and_message])
    if base64Encode:
        encrypted = base64.b64encode(encrypted)
    return encrypted
コード例 #17
0
def encrypt(file_path, key_file):
    """Encrypts data with given key."""
    padding.add(file_path, 4 * constants.NB)

    key = Key.load(key_file)

    offset = 0
    while True:
        state = State.load(file_path, offset)
        if state is None:
            break

        aes.encrypt(state, key)
        state.dump(file_path, offset)

        offset += 4 * constants.NB
コード例 #18
0
        def enc():
            try:
                nonce, cipher, tag, salt = aes.encrypt(entry_password.get(),
                                                       entry_text.get(),
                                                       entry_aad.get())

                x = open(save_filename_address, 'wb')

                x.write(('Aad: ' + entry_aad.get() + '\n').encode())
                x.write(salt + ('\n').encode())
                x.write(nonce + ('\n').encode())
                x.write(cipher + ('\n').encode())
                x.write(tag + ('\n').encode())

                x.write(
                    ('The avove data in the foem string:\nsalt: ' + str(salt) +
                     '\nnonce: ' + str(nonce) + '\ncipher_text: ' +
                     str(cipher) + '\ntag: ' + str(tag)).encode())
                x.close()
                messagebox.showinfo(
                    "Complete", 'Your text was encrypted \n\nsalt: ' +
                    str(salt) + '\n\nnonce: ' + str(nonce) +
                    '\n\nciphertext: ' + str(cipher))
                encrypt_win.destroy()
                win.deiconify()
            except exceptions.InvalidTag:
                messagebox.showerror("Error", 'Your data is inavlid')
                entry_text.delete(0, END)
                entry_password.delete(0, END)
                entry_aad.delete(0, END)
コード例 #19
0
    def encryptvote(self):
        """
        the data of the vote (in the votedata list) will be first hashed by SHA-256
        and then, the data will be converted into bytes and signed by voter's private key
        and that hashed signature will be appended with votedata itself
        """
        self.votedata.append(
            enc.sign(
                voterkeys['sk'],
                bytes(
                    sha256(
                        str('---'.join(str(x) for x in self.votedata)).encode(
                            'utf-8')).hexdigest(), 'utf-8')))
        """
        now that whole data (the new votedata list) will be encrypted by AES encryption
        and the shared key of AES will be encrypted with admin's public key
        this data will be broadcasted and saved into the unconfirmed votepool and will be added in the block
        """
        voterpk = self.get_voter_pk()

        #--byte value of voter public key pickle object is converted to string
        #--then added to list
        return [
            str(voterpk)[2:-1],
            aes.encrypt('***'.join(str(i) for i in self.votedata),
                        voterkeys['aeskey']),
            enc.encrypt(Blockchain.adminpub, voterkeys['aeskey'])
        ]
コード例 #20
0
    def fetch (self):
        """ Fetch & respond to valid emails """
        # query to fetch the right emails
        q = "is:unread subject:" + self.subject_q.replace (" ", "+") + (" after:" + str(self.last_fetch) if self.last_fetch else "")
        messages = gmail_fetch (self.service, q) # fetch the emails
        self.last_fetch = int (time.time())-5 # refresh last fetch time, subtract five to account for emails received during the fetch

        print (f"got {len(messages)} emails")
        for message in messages:
            if message['subject'].lower() != self.subject_q: # if the subject does not strictly match, ignore the email
                continue 

            name, email = extract_name_email (message['from']) # extract the email from the RF-2822 format (name <*****@*****.**>)

            if not self.is_valid_email (email): # if the email is not valid, respond accordingly
                print (email + ', invalid address')
                txt = self.responses['invalid_email']
            elif self.has_sent_acceptance_email(email): # if the email has already been validated, its a duplicate request
                print (email + ', got duplicate email')
                txt = self.responses['duplicate_email']
            else: # all good, otherwise
                print (email + ' requested to join, sending code')
                
                code = encrypt (email, self.encryption_key)
                txt: str = self.responses['valid_email']
                txt = txt.replace('[code]', code)

            txt = (self.responses.get('wrapper') or '[content]').replace('[content]', txt)
            txt = txt.replace('[name]', name)
            
            read_email (self.service, message['id']) # mark the email read
            send_reply (self.service, txt, message) # reply
コード例 #21
0
    def sendMsg(self, tracker):
        """
        Método para enviar mensagens, seja para o tracker, seja para outro peer
        """
        try:
            while True:
                msg = input()

                # caso a mensagem possua esse prefixo, ela será enviada ao tracker
                if msg[:5] == '-con ':
                    cripted_msg = aes.encrypt(self.simKey,
                                              msg.encode())  ######
                    tracker.send(cripted_msg)

                # caso comece com -q, enviará o código ao outro peer e encerrará a conexão
                elif msg == '-q':
                    cripted_msg = rsa.encrypt(self.connection['pKey'],
                                              msg.encode())
                    self.connection['conn'].send(cripted_msg)
                    self.connection['conn'].close()
                    self.connection = {}
                    print('You left the chat.')
                    print('[Client]>> Current peers list:', self.peers)
                    print('[Client]>> Type -con <user> to connect to a peer')

                # senão é uma mensagem normal e envia para o outro peer
                elif self.connection:
                    cripted_msg = rsa.encrypt(self.connection['pKey'],
                                              msg.encode())
                    self.connection['conn'].send(cripted_msg)
        except:
            exit()
コード例 #22
0
ファイル: encrypt.py プロジェクト: ericfu88/partner_crypto
def encrypt(senderPrivateKeyFile, receiverPublicKeyFile, message, base64Encode=False):

    # encrypt message with AES
    # ---------------------------------------------------
    (aes_key, iv, aes_encrypted_message) = aes.encrypt(message)
    # print 'aes-key:' + asHex(aes_key)
    # print 'iv:', asHex(iv)
    # print 'aes_encrypted_message-' + str(len(aes_encrypted_message)) + ':', asHex(aes_encrypted_message)
    # sign the aes key and IV with public key of receiver
    # ---------------------------------------------------
    receiverPubKeyObj = RSA.importKey(open(receiverPublicKeyFile).read())
    cipher = PKCS1_OAEP.new(receiverPubKeyObj)
    encrypted_aes_key = cipher.encrypt(aes_key + iv)

    # hash the combined encrypted aes_key and encrypted message
    # ---------------------------------------------------
    combined_aes_key_and_message = b''.join([encrypted_aes_key, aes_encrypted_message])
    sha1_hash = SHA256.new(combined_aes_key_and_message)

    # sign the hash with private key of sender
    # ---------------------------------------------------
    senderPrivateKeyObj = RSA.importKey(open(senderPrivateKeyFile).read())
    signer = PKCS1_v1_5.new(senderPrivateKeyObj)
    signed_hash = signer.sign(sha1_hash)

    # returned the whole blob
    # ---------------------------------------------------
    encrypted = b''.join([signed_hash, combined_aes_key_and_message])
    if base64Encode:
        encrypted = base64.b64encode(encrypted)
    return encrypted
コード例 #23
0
ファイル: server.py プロジェクト: defund/ctf
    def handle(self):
        req = self.request

        def receive():
            buf = ''
            while not buf.endswith('\n'):
                buf += req.recv(1)
            return buf[:-1]

        signal.alarm(60)

        req.sendall('Welcome to the Goldwasser-Micali key exchange!\n')
        req.sendall('Please send us an encrypted 128 bit key for us to use.\n')
        req.sendall(
            'Each encrypted bit should be sent line by line in integer format.\n'
        )

        enckey = []
        for i in range(128):
            enckey.append(int(receive()))
        key = gm.decrypt(enckey, sk)
        encmessage = aes.encrypt(key, message)

        req.sendall(base64.b64encode(encmessage) + '\n')
        req.close()
コード例 #24
0
ファイル: crypto.py プロジェクト: kpberry/crypto
 def encrypt_message(message, key):
     '''
     Encrypt a message using AES
     :param message: the message to be encrypted
     :param key: the encryption key to use
     :return: the encrypted message
     '''
     return encrypt(message, int_key_to_n_char_arr(key))
コード例 #25
0
ファイル: aes_tests.py プロジェクト: fredgj/aes
    def test_128bit_key_encrypt(self):
        key = '2b7e151628aed2a6abf7158809cf4f3c'
        block = '6bc1bee22e409f96e93d7e117393172a'

        encrypted = encrypt(block,key, format_='x')
        expected = '3ad77bb40d7a3660a89ecaf32466ef97'

        self.assertEqual(encrypted, expected)
コード例 #26
0
ファイル: aes_tests.py プロジェクト: fredgj/aes
    def test_256bit_key_encrypt(self):
        key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
        block = '6bc1bee22e409f96e93d7e117393172a'

        encrypted = encrypt(block,key, format_='x')
        expected = 'f3eed1bdb5d2a03c064b5a7e3db181f8'

        self.assertEqual(encrypted, expected)
コード例 #27
0
ファイル: aes_tests.py プロジェクト: fredgj/aes
    def test_192bit_key_encrypt(self):
        key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b'
        block = '6bc1bee22e409f96e93d7e117393172a'

        encrypted = encrypt(block,key, format_='x')
        expected = 'bd334f1d6e45f25ff712a214571fa5cc'

        self.assertEqual(encrypted, expected)
コード例 #28
0
ファイル: rpc.py プロジェクト: entone/Automaton
 def send(self, ob, key):
     self.logger.info("Calling: %s" % ob)
     st = aes.encrypt(json.dumps(ob, cls=ComplexEncoder), key)
     self.socket.send(st)
     res = self.socket.recv()
     res = aes.decrypt(res, key)
     self.socket.close()
     self.context.destroy()
     return json.loads(res)
コード例 #29
0
ファイル: store.py プロジェクト: psorus/git-pay
def save_store(nam, mne, pwd):
    ciph, tag, nonce = encrypt(mne, pwd)
    with open(fnam(nam), "w") as f:
        f.write(
            json.dumps({
                "ciph": ciph,
                "tag": tag,
                "nonce": nonce
            }, indent=2))
コード例 #30
0
ファイル: onewayhashchains.py プロジェクト: lschoe/mpyc
async def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-k',
                        '--order',
                        type=int,
                        metavar='K',
                        help='order K of hash chain, length n=2**K')
    parser.add_argument('--recursive',
                        action='store_true',
                        help='use recursive pebbler')
    parser.add_argument('--no-one-way',
                        action='store_true',
                        default=False,
                        help='use dummy one-way function')
    parser.add_argument('--no-random-seed',
                        action='store_true',
                        default=False,
                        help='use fixed seed')
    parser.set_defaults(order=1)
    args = parser.parse_args()

    await mpc.start()

    if args.recursive:
        Pebbler = P
    else:
        Pebbler = p

    IV = [[aes.secfld(3)] * 4] * 4  # IV as 4x4 array of GF(256) elements
    global f
    if args.no_one_way:
        D = aes.circulant_matrix([3, 0, 0, 0])
        f = lambda x: mpc.matrix_prod(D, x)
    else:
        K = aes.key_expansion(IV)
        f = lambda x: mpc.matrix_add(aes.encrypt(K, x), x)

    if args.no_random_seed:
        x0 = IV
    else:
        x0 = [[mpc.random.getrandbits(aes.secfld, 8) for _ in range(4)]
              for _ in range(4)]

    k = args.order
    print(f'Hash chain of length {2**k}:')
    r = 1
    for v in Pebbler(k, x0):
        if v is None:  # initial stage
            print(f'{r:4}', '-')
            await mpc.throttler(0.1
                                )  # raise barrier roughly every 10 AES calls
        else:  # output stage
            await aes.xprint(f'{r:4} x{2**(k+1) - 1 - r:<4} =', v)
        r += 1

    await mpc.shutdown()
コード例 #31
0
    def get_file_contents(self, filename, encrypt=False):
        with open(filename, 'rb') as f:
            data = f.read()
            
        if encrypt:
            iv = self.generate_key(16)
            key = self.generate_key(16)
            data = iv + key + aes.encrypt(data, key, iv)

        return data
コード例 #32
0
    def PEKS(self, A_Pub, word):
        sen_priv_key, sen_pub_key = ecdh.make_keypair()
        s2 = ecdh.scalar_mult(sen_priv_key, A_Pub)
        hashGen = hashlib.sha256()
        hashGen.update(str(s2[0]).encode())
        hash = hashGen.hexdigest()

        M = Random.new().read(3)
        x = aes.encrypt(M, hash[:32])
        return sen_pub_key, x, M
コード例 #33
0
ファイル: CSecreteAes.py プロジェクト: Alcasser/C
def shiftRowsEffectTest():
    aes = AesWoShiftRows(master_key)
    m = 0x1597C4EF331CC28B7E6D1B2EB3EA3B95
    c = aes.encrypt(m)
    hexC = hex(c)
    for i in range(4):
        mi = m ^ (1 << i * 32)
        ci = aes.encrypt(mi)
        hexCi = hex(ci)
        a = 8 * (3 - i) + 2
        # accedir a la columna que varia
        # +2 per eliminar el 0x
        b = a + 8
        print("Only columns: {} and {} different".format(
            hexC[a:b], hexCi[a:b]))
        printMatrix(asHexMatrix(c))
        print("")
        printMatrix(asHexMatrix(ci))
        print("")
コード例 #34
0
    def get_file_contents(self, filename, encrypt=False):
        with open(filename, 'rb') as f:
            data = f.read()

        if encrypt:
            iv = self.generate_key(16)
            key = self.generate_key(16)
            data = iv + key + aes.encrypt(data, key, iv)

        return data
コード例 #35
0
 def encrypt2(self, text):
     """Encrypts 'text' text with a expanded key using implemented AES algorithm"""
     # add padd
     text = self._pad(text)
     key=aes.expand_key(self.key)
     # choose random initialization vector (IV)
     iv = Random.new().read(AES.block_size)
     # create AES CBC mode cipher
     cipher = AES.new(self.key, AES.MODE_CBC, iv)
     # encrypt
     return base64.b64encode(iv + aes.encrypt(key,iv,text))
コード例 #36
0
def requestFromServer(serverAddr, serverPort, cmdLine, filename):
    clientSock = library.CreateClientSocket(serverAddr, serverPort)

    try:
        # Send the command line request to server and return the response.
        rttStart = time.time()
        clientSock.send(aes.encrypt(cmdLine.encode()))
        processResponse(serverAddr, clientSock, filename, rttStart)

    finally:
        clientSock.close()
コード例 #37
0
def buildchunk(chunk, partnum, type, todir, doc):
    filename = os.path.join(todir, ('part%04d' % partnum))
    if type == 'w':
        fileobj = open(filename, 'wb')
    if type == 'a':
        fileobj = open(filename, 'a+')
    fileobj.write(chunk)
    fileobj.close()  # or simply open(  ).write(  )
    if partnum == 1:
        k1 = randomword(10)
        doc.key1 = k1
        key = aes.getKey(k1)
        aes.encrypt(key, filename, doc)
    if partnum == 2:
        k2 = random.randint(8, 15)
        doc.key2 = str(k2)
        trans.encrypt(filename, k2, doc)
    if partnum == 3:
        k3 = randomword(10)
        doc.key3 = k3
        blow.encrypt(filename, filename + "(encrypted)", k3, doc)
コード例 #38
0
ファイル: rsa.py プロジェクト: olbat/o1b4t
def encrypt(readable, writable, e, n):
    """
    Encrypt message from _readable_ to _writable_ using the public exponent_e_,
    the modulus _n_ and the AES algorithm
    """
    import aes
    s = _bytesize(n)
    # the RSA modulus is too small to encrypt the AES key
    if s < (AES_KEY_SIZE // 8):
        raise ValueError

    # generate the key for the AES algorithm
    k = aes.genkey(AES_KEY_SIZE)

    # encrypt and save it using the RSA algorithm
    b = int.from_bytes(k, byteorder='little', signed=False)
    v = pow(b, e, n)
    writable.write(v.to_bytes(s, byteorder='little', signed=False))

    # encrypt the message from the input IO using AES
    aes.encrypt(readable, writable, k)
コード例 #39
0
def encrypt(pubKeyPath,
            filename,
            encfilename=None,
            keyfilename=None,
            chunksize=64 * 1024):
    if not encfilename:
        encfilename = filename + '.crypt'
    if not keyfilename:
        keyfilename = filename + '.key'

    aeskey = get_random_bytes(32)
    with open(pubKeyPath, 'rb') as f:
        pubKey = RSA.import_key(f.read())

    rsa_enc = PKCS1_OAEP.new(pubKey)
    encKey = rsa_enc.encrypt(aeskey)
    PEMKey = PEM.encode(encKey, 'ENCRYPTED KEY')
    with open(keyfilename, 'w') as out:
        out.write(PEMKey)

    aes.encrypt(aeskey, filename, encfilename, chunksize)
コード例 #40
0
def Cripto():
	a_texto = askopenfilename(filetypes=[("Arquivos de Texto","*.txt")])
	f = open(a_texto)
	plaintext = f.read()
	print plaintext	
	
	blocksize = 256 #128, 192, 256
 	key = tkSimpleDialog.askstring('Criptografia AES', 'Digite a chave:')
	crypted = aes.encrypt( plaintext, key, blocksize ) 
	print 'o Texto Criptografado:'
	print crypted

	return crypted
コード例 #41
0
ファイル: chat_app.py プロジェクト: KangShiang/VPN
 def send_message(self):
     msg = self.message.text
     if True:
     #try:
         self.connection
         self.print_message("Me: " + msg)
         if msg and self.connection:
             text = aes.encrypt(msg, str(k_s))
             hmac = aes.hmac(msg, str(k_s))
             print str(datetime.utcnow()) + " -- Encrypthing messsages"
             print msg
             print ""
             self.connection.write(text + hmac)
             self.message.text = ""
コード例 #42
0
ファイル: daemon.py プロジェクト: fortran95/orichalcum
def push_message(server,sender,secret,receiver,message,bits=22):
    hc = hashcash.hashcash(sender,receiver,bits).strip()
    secret = str(secret)

    auth = hmac.HMAC(secret,hashlib.sha1(hc).hexdigest().lower(),hashlib.sha512).hexdigest().lower()

    html = StringIO.StringIO()
    url = str("https://%s/push.php" % server)
    
    # encrypt message using SECRET
    message_encrypted = aes.encrypt(message,secret,128)
    message_hmac = hmac.HMAC(secret,message_encrypted,hashlib.sha1).hexdigest()
    
    post = {'hashcash':hc,'message':message_encrypted,'auth':auth,'hmac':message_hmac}
#    print urllib.urlencode(post)
#    exit()
    retrived = curlhttp.http(url,post)

    if retrived == '':
        return False

    return retrived
コード例 #43
0
ファイル: server.py プロジェクト: Priyankadmehta/TwitterMap
def authCallback():
    oauth_token = request.args.get('oauth_token')
    oauth_verifier = request.args.get('oauth_verifier')
#     print "called back!"
    try:
        request_secret = sessions[oauth_token]
        del sessions[oauth_token]
    except KeyError:
        return "request token not recognized"
    #now rebuild auth state
    auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
    auth.set_request_token(oauth_token, request_secret)
    #now try to get access token
    try:
        auth.get_access_token(oauth_verifier)
    except tweepy.TweepError:
        print 'access fail'
        return "failed to get access token."
    #now we need to securely return the access token and secret to the os x app
    access_key = auth.access_token.key
    access_secret = auth.access_token.secret
    message = access_key + " " + access_secret
    return Response(aes.encrypt(message), mimetype = 'text/plain')
コード例 #44
0
ファイル: tests.py プロジェクト: boppreh/aes
 def setUp(self):
     self.key = b'master key'
     self.message = b'secret message'
     # Lower workload then default to speed up tests.
     self.encrypt = lambda key, ciphertext: encrypt(key, ciphertext, 10000)
     self.decrypt = lambda key, ciphertext: decrypt(key, ciphertext, 10000)
コード例 #45
0
ファイル: cookie.py プロジェクト: anty-zhang/mypy
def make_token(uid):
    '''
    生成用户cookie
    '''
    return aes.encrypt(aes.AES_KEY, json.dumps({'id': uid}))
コード例 #46
0
ファイル: ptd.py プロジェクト: Samuirai/python
 def encrypt(self,msg):
     self.log(3,"encrypt string: "+str(msg))
     return aes.encrypt(msg, self._aes_key, 256)
コード例 #47
0
ファイル: test.py プロジェクト: ams2378/aes_core
import aes
import sys
text = "6bc1bee22e409f96e93d7e117393172a"
password = "******" 
blocksize = 128   # can be 128, 192 or 256
crypted = aes.encrypt( text, password, blocksize )
sys.stdout.write(crypted)
# do something
decrypted = aes.decrypt( crypted, password, blocksize )
sys.stdout.write(decrypted)
コード例 #48
0
ファイル: main.py プロジェクト: swordfish43/aes
def crypt_my_file(filename):
    with open(filename, 'r') as file_to_crypt:
        crypted = aes.encrypt(file_to_crypt.read(), password, blocksize)
    with open(filename, 'w') as file_to_crypt:
        file_to_crypt.write(crypted)
コード例 #49
0
ファイル: aes_test.py プロジェクト: dot-Sean/cscd27
 def test_encrypt_1(self):
     ntk='000102030405060708090a0b0c0d0e0f'
     ntp='00112233445566778899aabbccddeeff'
     ntc=aes.encrypt(ntk,ntp)
     self.assertEqual(ntc,'69c4e0d86a7b0430d8cdb78070b4c55a',\
                      "sample encryption from FIPS-197 Appendix C.1")
コード例 #50
0
ファイル: chat_app.py プロジェクト: KangShiang/VPN
def encrypt_auth( data, key ):
    return aes.encrypt(msg=data, key=key)
コード例 #51
0
ファイル: aes_test.py プロジェクト: dot-Sean/cscd27
 def test_encrypt_0(self):
     ntk='2b7e151628aed2a6abf7158809cf4f3c'
     ntp='3243f6a8885a308d313198a2e0370734'
     ntc=aes.encrypt(ntk,ntp)
     self.assertEqual(ntc,'3925841d02dc09fbdc118597196a0b32',\
                      "sample encryption from FIPS-197 Appendix 2")
コード例 #52
0
ファイル: session.py プロジェクト: bengheng/SEAL
m = params.getvalue('m')
n = params.getvalue('n')

# Create new cloak service
cfg = Config()
db = DB(cfg)

# Get user password from database
usr = db.get_user_from_username(u)
if usr == False:
	print "INVALID USER"
	sys.exit(0)
password = getUserPassword(usr)

# Verifies password
decrypted = aes.decrypt( c, password, 256 )
if decrypted != m:
	print "AUTH ERR"
	sys.exit(0)

# Generates random session key and save to database
sessionkey = base64.b64encode( os.urandom(64) )
wid = db.insert_websession( usr[0], sessionkey )

# Send session key in JSON
js = json.dumps( {'k': sessionkey, 'n' : n, 'w' : wid} )
crypted = aes.encrypt( ('%04x'%len(js))+js, password, 256 )
#print crypted
sys.stdout.write(crypted)

コード例 #53
0
ファイル: gui.py プロジェクト: GregDMeyer/PWman
	def save_data(self):
		if not self.data is None:
			with open( home+'/Dropbox/.pwman/data', 'w' ) as f:
				f.write( aes.encrypt( cPickle.dumps([self.data, self.config]), self.password) )
		return
コード例 #54
0
ファイル: gen.py プロジェクト: defund/ctf
from Crypto import Random

import aes
import gm

flag = open('flag').read()

key = Random.new().read(16)
pk, sk = gm.generate()

encflag = aes.encrypt(key, flag)
enckey = gm.encrypt(key, pk)

with open('pk', 'w') as f:
	f.write('\n'.join([str(x) for x in pk]))

with open('sk', 'w') as f:
	f.write('\n'.join([str(x) for x in sk]))

with open('key.enc', 'w') as f:
	f.write('\n'.join([str(x) for x in enckey]))

with open('flag.enc', 'w') as f:
	f.write(encflag)
コード例 #55
0
ファイル: aes_test.py プロジェクト: dot-Sean/cscd27
 def test_encrypt_2(self):
     ntk='00000000000000000000000000000000'
     ntp='00000000000000000000000000000000'
     ntc=aes.encrypt(ntk,ntp)
     self.assertEqual(ntc,'66e94bd4ef8a2c3b884cfa59ca342b2e',\
                      "sample encryption all 0 case")