コード例 #1
0
    def runTest(self):

        data = b"0123"
        key = b"9" * 32
        nonce = b"t" * 8

        # Encryption
        data_mv = memoryview(bytearray(data))
        key_mv = memoryview(bytearray(key))
        nonce_mv = memoryview(bytearray(nonce))

        cipher1 = Salsa20.new(key=key, nonce=nonce)
        ct = cipher1.encrypt(data)

        cipher2 = Salsa20.new(key=key_mv, nonce=nonce_mv)
        key_mv[:1] = b'\xFF'
        nonce_mv[:1] = b'\xFF'
        ct_test = cipher2.encrypt(data_mv)

        self.assertEqual(ct, ct_test)
        self.assertEqual(cipher1.nonce, cipher2.nonce)

        # Decryption
        key_mv = memoryview(bytearray(key))
        nonce_mv = memoryview(bytearray(nonce))
        ct_mv = memoryview(bytearray(ct))

        cipher3 = Salsa20.new(key=key_mv, nonce=nonce_mv)
        key_mv[:1] = b'\xFF'
        nonce_mv[:1] = b'\xFF'
        pt_test = cipher3.decrypt(ct_mv)

        self.assertEqual(data, pt_test)
コード例 #2
0
    def runTest(self):
        # Encrypt/Decrypt data and test output parameter

        key = b'4' * 32
        nonce = b'5' * 8
        cipher = Salsa20.new(key=key, nonce=nonce)

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

        output = bytearray(16)
        cipher = Salsa20.new(key=key, nonce=nonce)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        cipher = Salsa20.new(key=key, nonce=nonce)
        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(16))
            cipher = Salsa20.new(key=key, nonce=nonce)
            cipher.encrypt(pt, output=output)
            self.assertEqual(ct, output)
        
            cipher = Salsa20.new(key=key, nonce=nonce)
            cipher.decrypt(ct, output=output)
            self.assertEqual(pt, output)

        cipher = Salsa20.new(key=key, nonce=nonce)
        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
        
        cipher = Salsa20.new(key=key, nonce=nonce)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)

        shorter_output = bytearray(7)
        
        cipher = Salsa20.new(key=key, nonce=nonce)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        
        cipher = Salsa20.new(key=key, nonce=nonce)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
コード例 #3
0
 def run(self):
     global recieved
     global salsakey
     global salsanonce
     while True:
         x = recieved
         salsaenc = Salsa20.new(salsakey,
                                nonce=(salsanonce +
                                       bytes(str("%07d" % x), "utf_8")))
         salsadec = Salsa20.new(salsakey,
                                nonce=(salsanonce +
                                       bytes(str("%07d" % x), "utf_8")))
         mlen = int(str(salsadec.decrypt(self.client.recv(20)),
                        'utf_8'))
         response = str(salsadec.decrypt(self.client.recv(mlen)),
                        'utf_8')
         lock.acquire()
         recieved += 1
         lock.release()
         if not response == "BYE!":
             print(response)
         if response == "BYE!":
             final.set()
             break
コード例 #4
0
def new_stream_cipher(key1, nonce=None, key2=None):
    """
    returns a new cipher for encryption and returns a
    string of bytes containing the nonce and an HMAC checksum.

    the HMAC is solely to validate that the correct password
    is given before attempting to decrypt the content, and will
    not protect against modification of the cipher text.

    the cipher returned is a streaming cipher (Salsa20) meant to be used
    to encrypt or decrypt data in a streaming context

    key1 is intended to be the output from decryptkey, 32 bytes, and
    no password hardening is provided at this level

    key2 is a cryptographic randomly generate 32 bytes used to mix in
    with the given key. this ensures that a different key is used for the
    cipher and the mac, and that keys are not reused with different files.

    security / usefulness trade-off:
        files encrypted in this way are not encrypted in the best possible way
    a third party could tamper with the contents.
    """

    if len(key1) != 32:
        raise ValueError("key1 should be 32 bytes")

    if key2 is None:
        key2 = get_random_bytes(32)

    if len(key2) != 32:
        raise ValueError("key2 should be 32 bytes")

    skey1, skey2 = sha512_kdf(key1, key2)
    cipher = Salsa20.new(skey1, nonce)
    hmac = HMAC.new(skey2, digestmod=SHA256)

    tag = b"EYUE" + struct.pack("<I", 1)
    hmac.update(tag)
    hmac.update(cipher.nonce)
    hmac.update(key2)

    # generate a 32 byte digest which will be used to validate that
    # the correct password was given at decryption time
    digest = hmac.digest()

    header = tag + cipher.nonce + key2 + digest
    return cipher, header
コード例 #5
0
def decryption_RSA_key():
    for file in os.listdir('.'):
        if '-MANUAL.txt' in file:
            ext = file.split('-')[0].lower()
            ransom_path = os.getcwd() + '/' + file

    priv = CryptImportKey(rsa)
    if priv is None:
        print("[X] ERROR: unable to read private RSA master key",
              file=sys.stderr)
        sys.exit(1)

    rkey = get_ransom_data(ransom_path, "GANDCRAB KEY")
    privateKeySize = struct.unpack("<I", rkey[:4])[0]
    print("[+] Priv key size: %d" % privateKeySize)
    # Next 256 bytes are RSA-encrypted salsa key
    salsakey = rkey[4:(4 + 256)]
    salsakey = CryptDecrypt(priv, salsakey)[:32]
    print("[+] Salsa key: %s" % salsakey.hex())
    # Next 256 bytes are RSA-encrypted
    salsanonce = rkey[(4 + 256):(4 + 2 * 256)]
    salsanonce = CryptDecrypt(priv, salsanonce)[:8]
    print("[+] Salsa nonce: %s" % salsanonce.hex())

    print("[+] Decrypting RSA private user key...")
    encrRsaPriv = rkey[(4 + 2 * 256):]
    assert (len(encrRsaPriv) == privateKeySize)
    rsaPriv = Salsa20.new(key=salsakey, nonce=salsanonce).decrypt(encrRsaPriv)
    PK = CryptImportKey(rsaPriv)
    if not PK.valid:
        print(
            "[X] ERROR: invalid RSA private key after decryption. Has this ransom been generated by Gandcrab 5.2?"
        )
        sys.exit(1)

    print("[+] RSA private key details:")
    print("[+] p  = %s" % hex(PK.p))
    print("[+] q  = %s" % hex(PK.q))
    print("[+] d  = %s" % hex(PK.d))
    print("[+] dp = %s" % hex(PK.dP))
    print("[+] dq = %s" % hex(PK.dQ))
    print("[+] iq = %s" % hex(PK.iQ))
    print("[+] N  = %s" % hex(PK.N))

    print("[+] RSA private user key captured!")

    return rsaPriv, ext
コード例 #6
0
def downloader(pk):
    url = "http://127.0.0.1:8000/api/v1/api-download/" + str(pk) + "/"
    r = client.get(url)
    #print(r)
    a = r.json()
    for f in a["files"]:
        url1 = "http://127.0.0.1:8000/files/download/?name=" + f[0]
        filename = wget.download(url1, out="./")
        print(filename)
        file_in = open(filename, "rb")
        print(str(f[3]))
        url5 = "http://127.0.0.1:8000/file/delete/" + str(f[3]) + "/"
        client.get(url5)

        if scho == '1':
            nonce, tag, ciphertext = [file_in.read(x) for x in (16, 16, -1)]
            cipher = AES.new(userkeyo, AES.MODE_EAX, nonce)
            plaintext = cipher.decrypt_and_verify(ciphertext, tag)

        if scho == '2':
            json_input = file_in.read()
            b64 = json.loads(json_input)
            nonce = b64decode(b64['nonce'])
            ciphertext = b64decode(b64['ciphertext'])
            cipher = ChaCha20.new(key=userkeyo, nonce=nonce)
            plaintext = cipher.decrypt(ciphertext)

        if scho == '3':
            msg = file_in.read()
            msg_nonce = msg[:8]
            ciphertext = msg[8:]
            cipher = Salsa20.new(key=userkeyo, nonce=msg_nonce)
            plaintext = cipher.decrypt(ciphertext)

        os.remove(filename)

        file_out = open(filename, 'wb')
        file_out.write(plaintext)

    for f in a["folders"]:
        os.mkdir(f[0])
        os.chdir(f[0])
        downloader(f[1])
        os.chdir("..")
        url4 = "http://127.0.0.1:8000/file/delete/fol/" + str(f[1]) + "/"
        client.get(url4)
コード例 #7
0
def encrypt_plaintext(plaintext, key):
    """Takes a plaintext message and encrypts it using a Salsa20 key
    
    Arguments:
        plaintext {string} -- unencrypted message
        key {bytes} -- a Salsa20 key
    
    Returns:
        encrypted_message {bytes} -- the encrypted message
    """
    # encodes the plaintext into bytes so that it can be encrypted
    byte_plaintext = plaintext.encode()
    # makes a Salsa20 cipher from the key
    cipher = Salsa20.new(key)
    # turns the plaintext message into the encrtyped version
    encrypted_message = cipher.nonce + cipher.encrypt(byte_plaintext)
    return encrypted_message
コード例 #8
0
 def recv_message(self):
     m = hashlib.sha256()
     m.update(int_to_bytes(self._password))
     m.update(int_to_bytes(self._R3))
     password = m.digest()
     password = bytes_to_int(password)
     data = requests.post(SERVER_ADDR,
                          data=json.dumps({"type": "recv", "login": self._login, "password": password})).json()
     if data["error"] != "OK":
         r = requests.post(SERVER_ADDR, data=json.dumps({"type": "getR3", "login": self._login}))
         data = r.json()
         self._R3 = data["R3"]
         m = hashlib.sha256()
         m.update(int_to_bytes(self._password))
         m.update(int_to_bytes(self._R3))
         password = m.digest()
         password = bytes_to_int(password)
         data = requests.post(SERVER_ADDR,
                              data=json.dumps({"type": "recv", "login": self._login, "password": password})).json()
     if data["error"] != "OK":
         print(data["error"])
         return
     self._R3 = data["R3"]
     if (data["message"].strip()):
         m = re.match(
             r"\s*(?P<name>\S+):\s*razrabotchyk_pidor90585355972355049027130019104418304977474815248020730362080159511218759452819\s+(?P<text>\d*)",
             data["message"].strip())
         m2 = re.match(r"\s*(?P<name>\S+):\s*(?P<text>.*)", data["message"].strip())
         if m:
             user = m.group("name")
             self._B[user] = int(m.group("text"))
             if not self._A.get(user):
                 self.diffi_with_user(user)
             self._K[user] = fast_power(self._B[user], self._a[user], self._p)
         elif m2 and self._K.get(m2.group("name")):
             user = m2.group("name")
             text = m2.group("text")
             msg = b64decode(text)
             msg_nonce = msg[:8]
             ciphertext = msg[8:]
             cipher = Salsa20.new(key=int_to_bytes(self._K[user])[-32:], nonce=msg_nonce)
             plaintext = cipher.decrypt(ciphertext)
             print(user + ":_ ", plaintext.decode('utf-8'))
         else:
             print(data["message"].strip())  # fixme good enough for demo lol( 1 message per second)
コード例 #9
0
 def encrypt_file(self):
     start_setup_time = time.time()
     cipher = Salsa20.new(key=self.key)
     finish_setup_time = time.time()
     print("Setup completed in:", finish_setup_time - start_setup_time,
           "seconds")
     input_file_name = self.input_file_name
     input_file = open(input_file_name)
     start_cipher_file_time = time.time()
     for word in input_file.read().split():
         self.gather_metrics()
         cipher.encrypt(word)
         self.gather_metrics()
     finish_cipher_file_time = time.time()
     print("File encrypted in:",
           finish_cipher_file_time - start_cipher_file_time, "seconds")
     input_file.close()
     self.metrics_file.close()
コード例 #10
0
def dec(key, msg):
    """
    key, msg are a bytes object
    returns bytes object
    """
    if not msg:  # bad, very bad, use exceptions
        return False
    msg_nonce = msg[:8]
    ciphertext = msg[8:]
    cipher = Salsa20.new(key=key, nonce=msg_nonce)
    plaintext = cipher.decrypt(ciphertext)
    md5hash = plaintext[:16]
    data = plaintext[16:]

    if md5hash != MD5.new(data).digest():
        return False
    else:
        return data
コード例 #11
0
def decryptSalsa(message, key):

    message = str(message.data)  #Converts the message's ciphertext to a string
    message = message.split(
        "SPACE"
    )  #Splits the message by the word 'SPACE' to seperate the peer public key and ciphertext message

    peer_public_key = message[
        0]  #Assigns the portion before SPACE to variable peer_public_key
    loaded_public_key = serialization.load_pem_public_key(
        peer_public_key, backend=default_backend(
        ))  #Unserialized the peer public key so that is usable for decryption
    ciphertext = message[
        1]  #Assigns the portion after SPACE to variable ciphertext
    shared_key = key.exchange(
        ec.ECDH(), loaded_public_key
    )  #Generates a shared key using the local private key and the senders public key
    mode = message[2]
    if mode == "1":
        derived_key = HKDF(  #Derives key to be used for decryption from shared key
            algorithm=hashes.SHA256(),
            length=32,
            salt=None,
            info=None,
            backend=default_backend()).derive(shared_key)
    if mode == "2":
        derived_key = HKDF(  #Derives key to be used for decryption from shared key
            algorithm=hashes.SHA256(),
            length=16,
            salt=None,
            info=None,
            backend=default_backend()).derive(shared_key)

    msg_nonce = ciphertext[:8]  #Seperates the nonce from the ciphertext
    cipher_text = ciphertext[8:]  #Seperates the cipher text from the nonce

    cipher = Salsa20.new(
        key=derived_key, nonce=msg_nonce
    )  #Creates Salsa20 cipher object from derived key and nonce
    result = cipher.decrypt(
        cipher_text
    )  #decrypts the message using the cipher object and stores result in variable named 'result'

    return result  #returns plaintext message
コード例 #12
0
ファイル: main.py プロジェクト: danchik1155/ServerDB
def create_pok():
    if db.session.query(Roles).filter_by(id_role=current_user.id_role).first().name != "Продавец" and \
            db.session.query(Roles).filter_by(id_role=current_user.id_role).first().name != "Менеджер":
        return 'What are you doing here?'
    if request.method == 'GET':
        return render_template('create_pok.html',
                               role=db.session.query(Roles).filter_by(
                                   id_role=current_user.id_role).first().name)
    if request.method == 'POST':
        cipher = Salsa20.new(key=secret)
        fio = request.form['fio']
        created = time.strftime('%d/%m/%Y',
                                time.localtime())  # использовать дату
        dob = request.form['dob']  # определить формат
        role = 0
        email = request.form['email']
        phone = request.form['phone']
        company = request.form['company']
        hash_password = generate_password_hash(request.form['password'])
        hash_address = request.form['address']
        hash_card = str(cipher.nonce +
                        cipher.encrypt(bytes(request.form['card'], 'utf-8')))
        amount = request.form['amount']
        new_Client = Clients(email=email,
                             fio=fio,
                             created=created,
                             dob=dob,
                             id_role=role)
        db.session.add(new_Client)
        db.session.commit()
        new_Contactdetailsclients = Contactdetailsclients(
            id_clients=new_Client.id_clients, phone=phone, company=company)
        new_Secretdate = Secretdate(id_clients=new_Client.id_clients,
                                    hash_password=hash_password,
                                    hash_address=hash_address)
        new_Card = Card(id_clients=new_Client.id_clients,
                        hash_card=hash_card,
                        amount=amount)
        db.session.add(new_Contactdetailsclients)
        db.session.add(new_Secretdate)
        db.session.add(new_Card)
        db.session.commit()
        return redirect('/login')
コード例 #13
0
def tcp_echo_client(loop=None):
    if loop is None:
        loop = asyncio.get_event_loop()

    reader, writer = yield from asyncio.open_connection('127.0.0.1',
                                                        8887,
                                                        loop=loop)
    # Envio e criação do protocolo de chaves Diffie Hellman
    # ---------------------------------
    a_pr, msg_pk, private_key = dhPK()

    writer.write(b'y' + msg_pk[0])
    data = yield from reader.read(100)
    writer.write(b'p' + msg_pk[1])
    data = yield from reader.read(100)
    writer.write(b'g' + msg_pk[2])
    data = yield from reader.read(100)

    if data[:1] == b'K':
        servidor_public_key = int.from_bytes(data[1:], 'big')
        shared_key = dhShared(a_pr, servidor_public_key, private_key)
    # ---------------------------------
    data = b'S'
    client = Client("Cliente 1")
    msg = client.initmsg()
    while len(data) > 0:
        if msg:
            cipher = Salsa20.new(key=shared_key)
            msg = cipher.nonce + cipher.encrypt(msg)
            msg = b'M' + msg
            writer.write(msg)
            if msg[:1] == b'E': break
            data = yield from reader.read(100)
            if len(data) > 0:
                msg = client.respond(cipher.decrypt(data[1:]))
            else:
                break
        else:
            break
    writer.write(b'E')
    print('Socket closed!')
    writer.close()
コード例 #14
0
def input_password(readData, inputMPW, readMode, siteName, siteID, sitePW):
    pwBin = bytearray(sitePW, encoding='utf-8')
    mpwHash = SHA256.new()
    mpwHash.update(bytearray(inputMPW, encoding='utf-8'))

    sal = Salsa20.new(key=mpwHash.digest())
    pwEnc = sal.nonce + sal.encrypt(pwBin)

    idpwDict = {"id": siteID, "pw": pwEnc.hex()}
    readData["test"][siteName] = idpwDict
    if readMode == 'b':
        readData["view"][siteName] = idpwDict
    print(readData)

    with open(jsonName, 'w', encoding='utf-8') as json_f:
        json.dump(readData,
                  json_f,
                  ensure_ascii=False,
                  indent=4,
                  sort_keys=True)
コード例 #15
0
ファイル: document_key.py プロジェクト: tantalum7/dictata
    def decrypt(self, packed_crypt_text: str, encoding: str = "utf-8") -> str:
        """
        Decrypts the packed crypt text string, expecting the format from the encrypt method above.
        If the encryption payload start marker isn't found, it assumes the string isn't encrypted and returns it as is
        :param packed_crypt_text:
        :param encoding:
        :return:
        """
        # If we can't find the encryption start marker, just return the string as is
        if not packed_crypt_text.startswith(self._payload.START_MARKER):
            return packed_crypt_text

        # Unpickle payload string
        payload = self._payload(pickle=packed_crypt_text)

        # Create new cipher instance, with our key and the payload nonce
        cipher = Salsa20.new(self._key, payload.nonce)

        # Decrypt the payload, apply the string encoding specified and return
        return cipher.decrypt(payload.crypt_text).decode(encoding)
コード例 #16
0
ファイル: salsa20.py プロジェクト: mod6991/DotNetToolBox
def main():
    with open(r'C:\Temp\testData\salsa20.dat', 'wb') as file:
        for i in range(1, 300 + 1):
            with BytesIO() as ms:
                key = get_random_bytes(32)
                iv = get_random_bytes(8)
                data = get_random_bytes(i)
                write_lv(ms, key)
                write_lv(ms, iv)
                write_lv(ms, data)

                cipher = Salsa20.new(key=key, nonce=iv)
                enc = cipher.encrypt(data)
                write_lv(ms, enc)

                ms.seek(0)
                record = ms.read()

            write_lv(file, record)
        write_lv(file, b'')
コード例 #17
0
def decrypt_passwords(mpwd: str) -> Optional[Dict[str, str]]:
    salt: bytes = storage.read_salt()
    secret: bytes = hashlib.pbkdf2_hmac(
        'sha512', mpwd.encode(), salt,
        10**5)[:32]  # Salsa20 key length must be 32 bytes

    # first 8 bytes of `pwds_encrypted` are cipher nonce
    pwds_encrypted: bytes = storage.read_encrypted_passwords()
    nonce: bytes = pwds_encrypted[:8]
    pwds_encrypted = pwds_encrypted[8:]

    cipher = Salsa20.new(key=secret, nonce=nonce)
    pwds_json: str = cipher.decrypt(pwds_encrypted).decode()

    # return None if JSON decoder throws exception
    try:
        pwds: Dict[str, str] = json.loads(pwds_json)
        return pwds
    except json.decoder.JSONDecodeError:
        return None
コード例 #18
0
ファイル: token.py プロジェクト: nsetzer/yue-react-flask
    def validate(secret, token):

        b16mac = token[:64]
        b16nonce = token[64:80]
        b16text = token[80:]

        mac = bytes.fromhex(b16mac)
        nonce = bytes.fromhex(b16nonce)
        enctext = bytes.fromhex(b16text)

        key1, key2 = sha512_kdf(secret)
        hmac = HMAC.new(key1, digestmod=SHA256)
        cipher = Salsa20.new(key2, nonce)

        hmac.update(nonce)
        hmac.update(enctext)
        hmac.verify(mac)

        text = cipher.decrypt(enctext)

        return text
コード例 #19
0
def decrypt_message(encrypted_message, key):
    """Takes an encrypted message and converts it back into plaintext using a Salsa20 key
    
    Arguments:
        encrypted_message {bytes} -- the encrypted message that needs to be converted into plaintext
        key {bytes} -- the Salsa20 key
    
    Returns:
        plaintext {string} -- the unencrypted message
    """
    # takes the nonce from the message
    msg_nonce = encrypted_message[:8]
    # takes the actual ciphertext from the message
    ciphertext = encrypted_message[8:]
    # generates a cipher from the key and the nonce
    cipher = Salsa20.new(key, nonce=msg_nonce)
    # decrypts the encrypted message back into plaintext
    byte_plaintext = cipher.decrypt(ciphertext)
    # converts the plaintext bytes into a string
    plaintext = byte_plaintext.decode()
    return plaintext
コード例 #20
0
def salsaEncypt(message, serial_peer_public_key):
    private_key = ec.generate_private_key(ec.SECP384R1(), default_backend()) #Generates private key
    public_key = private_key.public_key() #Generates public key from private key

    serial_public_key = public_key.public_bytes(encoding=serialization.Encoding.PEM,format=serialization.PublicFormat.SubjectPublicKeyInfo) #Serializes public key so it can be sent as a ROS message
    peer_public_key = serialization.load_pem_public_key(serial_peer_public_key, backend=default_backend()) #Deserializes the public key from the peer so it can be used to derive shared key

    shared_key = private_key.exchange(ec.ECDH(), peer_public_key) #Shared key generated from local private key and the peer's public key
    

    derived_key = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=None,
        info=None,
        backend=default_backend()).derive(shared_key) #Key to be used to encrypt the data is dericed using HKDF
    

    cipher = Salsa20.new(key=derived_key) #A new Salsa20 cipher object is created using the derived key
    msg = cipher.nonce + cipher.encrypt(message) #The ROS message is encrypted and the cipher's nonce is added to the beginning of the message

    return serial_public_key +"SPACE"+ msg #Return public key and encrypted message seperated with 'SPACE'
コード例 #21
0
def _crypt_cipher(salt, password, nonce=None):
    """ derive a encryption key using a password, using bcrypt
    return an object implementing encrypt(x) and decrypt(x)
    """
    # bcrypt has a maximum input length of 50-72 bytes
    # use the sha256 digest (32 bytes) then base 64 encode (44 bytes)
    # to prevent null bytes in the string
    digest = base64.b64encode(sha256(password.encode("utf-8")))
    hashed = bcrypt.hashpw(digest, salt)
    # hash the bcrypt output, which is only 248 bits.
    #   known values including the salt are 29 bytes
    #   while the hashed value is 31 bytes
    # use sha512, so that two 256 bit keys can be derived.
    key = sha512(hashed)
    # the first 32 bytes are used as the hmac key
    # the digest is SHA256 to minimize the final output byte size
    key1 = key[:32]
    hmac = HMAC.new(key1, digestmod=SHA256)
    # the last 32 bytes are used for the cipher key
    key2 = key[32:]
    cipher = Salsa20.new(key2, nonce)
    return hmac, cipher
コード例 #22
0
ファイル: main.py プロジェクト: danchik1155/ServerDB
def registration():
    if request.method == 'GET':
        return render_template('registration.html')
    if request.method == 'POST':
        cipher = Salsa20.new(key=secret)
        fio = request.form['fio']
        created = time.strftime('%d/%m/%Y',
                                time.localtime())  # использовать дату
        dob = request.form['dob']  # определить формат
        role = 0
        email = request.form['email']
        phone = request.form['phone']
        company = request.form['company']
        hash_password = generate_password_hash(request.form['password'])
        print(hash_password)
        hash_address = request.form['address']
        hash_card = str(cipher.nonce +
                        cipher.encrypt(bytes(request.form['card'], 'utf-8')))
        amount = request.form['amount']
        new_Client = Clients(email=email,
                             fio=fio,
                             created=created,
                             dob=dob,
                             id_role=role)
        db.session.add(new_Client)
        db.session.commit()
        new_Contactdetailsclients = Contactdetailsclients(
            id_clients=new_Client.id_clients, phone=phone, company=company)
        new_Secretdate = Secretdate(id_clients=new_Client.id_clients,
                                    hash_password=hash_password,
                                    hash_address=hash_address)
        new_Card = Card(id_clients=new_Client.id_clients,
                        hash_card=hash_card,
                        amount=amount)
        db.session.add(new_Contactdetailsclients)
        db.session.add(new_Secretdate)
        db.session.add(new_Card)
        db.session.commit()
        return redirect('/login')
コード例 #23
0
ファイル: Servidor.py プロジェクト: zbastos/Criptography
def handle_echo(reader, writer):
    global conn_cnt
    conn_cnt += 1
    srvwrk = ServerWorker(conn_cnt)

    while True:
        data = yield from reader.read(100)
        if data[:1] == b'E': break
        # Receber os dados para o protocolo Diffie Hellman
        # -------------------------------------
        if data[:1] == b'y':
            y = int.from_bytes(data[1:], 'big')
            writer.write(b'OK')
            continue

        if data[:1] == b'p':
            p = int.from_bytes(data[1:], 'big')
            writer.write(b'OK')
            continue

        if data[:1] == b'g':
            g = int.from_bytes(data[1:], 'big')
            shared_key, b_y = dhPK(y, g, p)
            writer.write(b'K' + b_y.to_bytes(99, 'big'))
            continue
        # -------------------------------------
        if not data: continue
        addr = writer.get_extra_info('peername')
        nonce = data[1:9]
        cipher = Salsa20.new(key=shared_key, nonce=nonce)
        msg = cipher.decrypt(data[9:])
        res = srvwrk.respond(msg, addr)
        if not res: break
        res = b'M' + cipher.encrypt(res)
        writer.write(res)
        yield from writer.drain()
    print("[%d]" % srvwrk.id)
    writer.close()
コード例 #24
0
ファイル: document_key.py プロジェクト: tantalum7/dictata
    def encrypt(self, plaintext: str) -> str:
        """
        Encrypts the plaintext string, and packs it into a base64 encoded string which includes the nonce
        Empty strings are returned as is.
        :param plaintext:
        :return:
        """

        # If the string is empty, return it as is
        if not plaintext:
            return plaintext

        # Create new cipher instance (new nonce)
        cipher = Salsa20.new(self._key)

        # Encode plaintext to bytes, and encrypt
        crypt_text = cipher.encrypt(plaintext.encode())

        # Pack up message
        p = self._payload(crypt_text, cipher.nonce, self.REVISION)

        # Pickle the payload into a string and return
        return p.pickle()
コード例 #25
0
def decrypt_image(file_name):

    global key, iv

    enc_file2 = open(file_name, 'rb')
    enc_data2 = enc_file2.read()
    enc_file2.close()

    msg_nonce = enc_data2[:8]
    rem_msg = enc_data2[8:]

    decipher = Salsa20.new(key=key, nonce=msg_nonce)
    plain_data = decipher.decrypt(rem_msg)

    image_stream = io.BytesIO(plain_data)
    image_file = PIL.Image.open(image_stream)

    output_path = 'output_'

    if '.jpg' in file_name:
        image_file.save(output_path + file_name[:-8] + '.jpg')
    elif '.png' in file_name:
        image_file.save(output_path + file_name[:-8] + '.png')
コード例 #26
0
ファイル: token.py プロジェクト: nsetzer/yue-react-flask
    def new(secret, payload, nonce=None):
        key1, key2 = sha512_kdf(secret)
        hmac = HMAC.new(key1, digestmod=SHA256)
        cipher = Salsa20.new(key2, nonce)

        enctext = cipher.encrypt(payload)

        b16nonce = cipher.nonce.hex()
        b16text = enctext.hex()

        hmac.update(cipher.nonce)
        hmac.update(enctext)

        b16mac = hmac.hexdigest()

        length = 176  # 256 - 80

        if len(b16text) > 176:
            raise ValueError("payload too long")

        token = b16mac + b16nonce + b16text

        return token
コード例 #27
0
ファイル: main.py プロジェクト: danchik1155/ServerDB
def edit2():
    if db.session.query(Roles).filter_by(
            id_role=current_user.id_role).first().name != "Менеджер":
        return 'What are you doing here?'
    if request.method == 'POST':
        cipher = Salsa20.new(key=secret)
        fio = request.form['fio']
        created = time.strftime('%d/%m/%Y', time.localtime())
        id_clients = request.form['id_clients']
        email = request.form['email']
        phone = request.form['phone']
        company = request.form['company']
        hash_address = request.form['address']
        hash_card = str(cipher.nonce +
                        cipher.encrypt(bytes(request.form['card'], 'utf-8')))
        amount = request.form['amount']
        new_Client = Clients.query.filter_by(id_clients=id_clients).first()
        new_Client.email = email
        new_Client.fio = fio
        new_Client.created = created
        db.session.commit()

        new_Contactdetailsclients = Contactdetailsclients.query.filter_by(
            id_clients=id_clients).first()
        new_Contactdetailsclients.phone = phone
        new_Contactdetailsclients.company = company
        new_Secretdate = Secretdate.query.filter_by(
            id_clients=id_clients).first()
        new_Secretdate.hash_address = hash_address
        new_Card = Card.query.filter_by(id_clients=id_clients).first()
        new_Card.hash_card = hash_card
        new_Card.amount = amount
        db.session.commit()
        return redirect('/all')
    else:
        return 'What are you doing here?'
コード例 #28
0
    def test_default_nonce(self):

        cipher1 = Salsa20.new(bchr(1) * 16)
        cipher2 = Salsa20.new(bchr(1) * 16)
        self.assertEqual(len(cipher1.nonce), 8)
        self.assertNotEqual(cipher1.nonce, cipher2.nonce)
コード例 #29
0
ファイル: ciphers.py プロジェクト: papaya-mobile/python-proxy
 def setup(self):
     self.cipher = Salsa20.new(key=self.key, nonce=self.iv)
コード例 #30
0
def cifarSalsa(key, cadena):
    cipher = Salsa20.new(key)
    msg = cipher.nonce + cipher.encrypt(cadena)
    return msg
コード例 #31
0
		
		General note:
		*Calling of encryption method can only be used to encrypt a single piece of plaintext
		*Python 3 only allows for text converted to bytes to be encrypted
			- Simply declare your variable and place a single 'b' before your single quoted data
			ex ====>	data = b'this is my data turned into bytes!'
			
	The same goes for when you are decrypting a piece of data (assuming the use of a symmetric cipher)
	
						cipher.decrypt(your encrypted data)
						
	
"""
#basic encryption program
from Crypto.Cipher import Salsa20

key = b'16 this the key!'
cipher = Salsa20.new(key)
ciphertext = cipher.encrypt(b'The secret message to be sent')
print(ciphertext)
"""

There are two types of symmetric ciphers:
	- Stream Ciphers
		These are the most natural kinds of ciphers and encrypt one bit of data at a time (ex: Salsa20)
		
	- Block Ciphers	
		These can only operate on fixed amounts of data and the most important block cipher algorithm
		is AES (Advanced Encryption Standard ====> block size 128 bits (16 bytes))
		
"""
コード例 #32
0
 def salsa20_encrypt(self, plaintext):
     plaintext = bytes(plaintext, 'utf-8')
     secret = b'*Thirty-two byte (256 bits) key*'
     cipher = Salsa20.new(key=secret)
     msg = cipher.nonce + cipher.encrypt(plaintext)
     return binascii.hexlify(msg).decode("utf-8")
コード例 #33
0
ファイル: cipher.py プロジェクト: ohyeah521/python-proxy-1
 def setup(self):
     from Crypto.Cipher import Salsa20
     self.cipher = Salsa20.new(key=self.key, nonce=self.iv)
コード例 #34
0
    def test_default_nonce(self):

        cipher1 = Salsa20.new(bchr(1) * 16)
        cipher2 = Salsa20.new(bchr(1) * 16)
        self.assertEqual(len(cipher1.nonce), 8)
        self.assertNotEqual(cipher1.nonce, cipher2.nonce)
コード例 #35
0
ファイル: cipher.py プロジェクト: qwj/python-proxy
 def setup(self):
     from Crypto.Cipher import Salsa20
     self.cipher = Salsa20.new(key=self.key, nonce=self.iv)