예제 #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)
    def runTest(self):

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

        # Encryption
        data_ba = bytearray(data)
        key_ba = bytearray(key)
        nonce_ba = bytearray(nonce)

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

        cipher2 = Salsa20.new(key=key_ba, nonce=nonce_ba)
        key_ba[:1] = b'\xFF'
        nonce_ba[:1] = b'\xFF'
        ct_test = cipher2.encrypt(data_ba)

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

        # Decryption
        key_ba = bytearray(key)
        nonce_ba = bytearray(nonce)
        ct_ba = bytearray(ct)

        cipher3 = Salsa20.new(key=key_ba, nonce=nonce_ba)
        key_ba[:1] = b'\xFF'
        nonce_ba[:1] = b'\xFF'
        pt_test = cipher3.decrypt(ct_ba)

        self.assertEqual(data, pt_test)
 def decrypt1(self, data, key1):
     nonc = data[:8]
     encrypted = data[8:]
     decryption_suite = Salsa20.new(key1, nonce=nonc)
     plain_text = decryption_suite.decrypt(encrypted)
     #print(plain_text)
     return plain_text
def encrypt(plaintext):
    secret = os.urandom(32)
    # Stream cipher
    # Encrypts by doing ciphertext = plaintext XOR rand_stream()
    # Does not shift order of bytes!
    cipher = Salsa20.new(key=secret)
    return cipher.nonce + cipher.encrypt(plaintext)
예제 #5
0
    def send_message_to_user(self, user, message, from_diffi=False):
        if not from_diffi and not self._K.get(user):
            self.diffi_with_user(user)
            while not self._K.get(user):
                time.sleep(1)
        if not from_diffi:
            key = int_to_bytes(self._K.get(user))[-32:]
            cipher = Salsa20.new(key=key)
            message = b64encode(cipher.nonce + cipher.encrypt(message.encode('utf-8'))).decode('utf-8')

        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": "send", "login": self._login, "password": password, "user": user, "message": message})).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": "send", "login": self._login, "password": self._password, "user": user,
                 "message": message})).json()
        if data["error"] != "OK":
            print(data["error"])
            return
        self._R3 = data["R3"]
예제 #6
0
def test_public_params_derive(bits, key):
    length = FFI.sizeof("struct umash_params")

    umash_key = b"Do not use UMASH VS adversaries."
    if key is not None:
        umash_key = key
    nonce = struct.pack("<Q", bits)

    expected = FFI.new("struct umash_params[1]")
    salsa_bytes = Salsa20.new(umash_key, nonce).encrypt(b"\x00" * length)
    FFI.memmove(expected, salsa_bytes, length)
    assert C.umash_params_prepare(expected)

    actual = FFI.new("struct umash_params[1]")
    if key is None:
        C.umash_params_derive(actual, bits, FFI.NULL)
    else:
        buf = FFI.new("char[]", len(key))
        FFI.memmove(buf, key, len(key))
        C.umash_params_derive(actual, bits, buf)

    # The values should all be the same.
    assert length % 8 == 0
    for i in range(length // 8):
        assert FFI.cast("uint64_t *",
                        actual)[i] == FFI.cast("uint64_t *", expected)[i]
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

    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)

    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
예제 #8
0
 def decryptPart(self, data):
     nonc = data[:8]
     encrypted = data[8:]
     decryption_suite = Salsa20.new(
         PASSWD.encode(), nonce=nonc)  #b'0123456789012345',nonce=nonc)
     plain_text = decryption_suite.decrypt(encrypted)
     return plain_text
예제 #9
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
예제 #10
0
def encrypt(key, data, salsa):
    if salsa:
        enc = Salsa20.new(key=key)
    else:
        enc = ChaCha20.new(key=key)

    return enc.nonce + enc.encrypt(data)
예제 #11
0
def decrypt(key, data, salsa):
    if salsa:
        dec = Salsa20.new(key=key, nonce=data[:8])
    else:
        dec = ChaCha20.new(key=key, nonce=data[:8])

    return dec.decrypt(data[8:])
예제 #12
0
def get_stream_cipher(key1, header):
    """
    given a key and an 80 byte header, return a new cipher for decryption

    The Header contains a 32 byte HMAC which will be validated to ensures
    the correct decryption key is used
    """

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

    if len(header) < HEADER_SIZE:
        raise ValueError("Invalid header size: %d" % len(header))
    tag = header[:8]

    # if needed, version could change how the cipher is generated.
    version = struct.unpack("<I", header[4:8])[0]

    nonce = header[8:16]
    key2 = header[16:48]
    digest = header[48:HEADER_SIZE]

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

    hmac.update(tag)
    hmac.update(nonce)
    hmac.update(key2)
    hmac.verify(digest)

    cipher = Salsa20.new(skey1, nonce)
    return cipher
예제 #13
0
 def __salsa20(self, message: bytes):
     cipher = Salsa20.new(SALSA20_KEY)
     ct_bytes = cipher.encrypt(message)
     nonce = b64encode(cipher.nonce).decode(DEFAULT_ENCODING)
     ct = b64encode(ct_bytes).decode(DEFAULT_ENCODING)
     result = {"nonce": nonce, "cipher": ct}
     return b64encode(bytes(json.dumps(result), encoding=DEFAULT_ENCODING))
예제 #14
0
def descifrarSalsa(key, datos):
    msg_nonce = datos[:8]
    ciphertext = datos[8:]
    cipher = Salsa20.new(key, nonce=msg_nonce)
    descifrado = cipher.decrypt(ciphertext)

    return descifrado
    def encrypt(cls, method='AES'):
        plaintext = pyip.inputStr('enter data for encryption :  ')
        plaintext = str.encode(plaintext)

        key = stdiomask.getpass()
        key = str.encode(key)

        if (method == 'AES'):
            if (len(key) < 16):
                key = key + str.encode((16 - len(key)) * 'a')
            elif (len(key) > 16):
                key = key[:16]
            cipher = AES.new(key, AES.MODE_EAX)

            nonce = cipher.nonce
            ciphertext, tag = cipher.encrypt_and_digest(plaintext)

            print('nonce: \n' + str(nonce),
                  '\nciphertext: \n' + str(ciphertext), '\ntag: \n' + str(tag))
            return (nonce, ciphertext, tag)

        elif (method == 'Salsa20'):
            if (len(key) < 32):
                key = key + str.encode((32 - len(key)) * 'a')
            elif (len(key) > 32):
                key = key[:32]
            cipher = Salsa20.new(key=key)
            ciphertext = cipher.nonce + cipher.encrypt(plaintext)
            print('ciphertext: \n' + str(ciphertext))
            return ciphertext
예제 #16
0
    def _reset_salsa(self):
        """
		Clear the salsa buffer and reset algorithm
		"""
        self._salsa_buffer = bytearray()
        iv = bytes(bytearray.fromhex('e830094b97205d2a'))
        self.salsa = Salsa20.new(crypto.sha256(self.protected_stream_key), iv)
    def decrypt(cls, nonce=None, ciphertext=None, tag=None, method='AES'):
        key = stdiomask.getpass()
        key = str.encode(key)

        if (method == 'AES'):
            if (len(key) < 16):
                key = key + str.encode((16 - len(key)) * 'a')
            elif (len(key) > 16):
                key = key[:16]
            cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
            plaintext = cipher.decrypt(ciphertext)
            try:
                cipher.verify(tag)
                print("\nThe message is authentic:", plaintext)
            except ValueError:
                print("Key incorrect or message corrupted")

        elif (method == 'Salsa20'):
            if (len(key) < 32):
                key = key + str.encode((32 - len(key)) * 'a')
            elif (len(key) > 32):
                key = key[:32]
            msg_nonce = ciphertext[:8]
            ciphertext = ciphertext[8:]
            try:
                cipher = Salsa20.new(key=key, nonce=msg_nonce)
                plaintext = cipher.decrypt(ciphertext)
                print("The message is authentic:", plaintext)
            except ValueError:
                print("Key incorrect or message corrupted")
    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)
예제 #19
0
    def encrypt(self, c, p, k):
        #Generating new cipher based on key
        cipher = Salsa20.new(k)
        #Encrypting cipher
        ciphertext = c.encrypt(p)

        #Returning ciphertext and nonce used for decryption
        return ciphertext, c.nonce
예제 #20
0
def encrypt_salsa20(key, path):
    data = open_binary(path)
    cipher = Salsa20.new(key)
    nonce = cipher.nonce
    cipher_bytes = cipher.encrypt(data)
    cipher_path = path.split(".")[0] + ".enc"
    write_binary(cipher_path, data=cipher_bytes)
    insert(cipher_path, "Salsa20", path.split(".")[1], key, nonce)
예제 #21
0
    def decrypt(self, c, n, k):
        #Generating new cipher based on key and nonce
        cipher = Salsa20.new(k, n)

        #Decrypting cipher
        plaintext = cipher.decrypt(c)

        return plaintext.decode('utf-8')
예제 #22
0
    def Salsa20(self, password: str) -> bytes:
        """Encrypt data according to Salsa20 algorithm."""
        # Generating the key according to password
        key = get_key(password, 32)

        # Encrypting the data.
        cipher_object = Salsa20.new(key)
        return (cipher_object.nonce + cipher_object.encrypt(self.data))
예제 #23
0
 def salsa20_decrypt(self, msg):
     msg = binascii.unhexlify(msg)  
     secret = b'*Thirty-two byte (256 bits) key*'
     msg_nonce = msg[:8]
     ciphertext = msg[8:]
     cipher = Salsa20.new(key=secret, nonce=msg_nonce)
     plaintext = cipher.decrypt(ciphertext)
     return plaintext
예제 #24
0
    def decryptTextSalsa20(self, ciphertext):
        msg_end = ciphertext[:8]
        msg_start = ciphertext[8:]
        cipher = Salsa20.new(key=self.key, nonce=msg_end)
        plaintext = cipher.decrypt(msg_start)
        return plaintext

        """
def salsaE(message):
  secret = #key exchange needs to be set up
  
  cipher = Salsa20.new(key=secret, nonce=None)
  
  msg = cipher.encrypt(message)
  
 
  return msg
예제 #26
0
def decrypt(text, secret):
    
	msg_nonce = text[:8]
	ciphertext = text[8:]
	cipher = Salsa20.new(key=secret, nonce=msg_nonce)
	plaintext = cipher.decrypt(ciphertext)
	print "Your decrypted shellcode is %s" %plaintext
        print "Launching shellcode..."
        execute(plaintext)
예제 #27
0
    def __salsa20_decrypt(self, message: bytes):
        text = b64decode(message)
        j = json.loads(text)
        nonce = b64decode(j['nonce'])
        ct = b64decode(j['cipher'])

        cipher = Salsa20.new(SALSA20_KEY, nonce=nonce)
        pt = cipher.decrypt(ct)
        return pt
예제 #28
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' * 300
        ct = cipher.encrypt(pt)

        output = bytearray(len(pt))
        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)

        output = memoryview(bytearray(len(pt)))
        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' * len(pt))

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

        shorter_output = bytearray(len(pt) - 1)

        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)
예제 #29
0
def encryptFile(file, key):
    try:
        print("Encrypting {}...".format(file))
        plaintext = open(file, 'rb').read()
        cipher = Salsa20.new(key=key)
        msg = cipher.nonce + cipher.encrypt(plaintext)
        open("{}.enc".format(file), "wb").write(msg)
        os.remove(file)
    except:
        print("Could not encrypt {}!".format(file))
예제 #30
0
def encode_with_key(string_to_encode, key=KEY):  # Encrypting and decrypting
    '''Encrypts string_to_encode by creating new Salsa20 cipher object with key
    as the key.

    Args:
        string_to_encode - bytes object to be encrypted by Salsa20 with key
        key - bytes object key used to encrypt string_to_encode, default is KEY'''
    new_cipher = Salsa20.new(key=key)
    encrypted_msg = new_cipher.encrypt(string_to_encode.encode())
    return new_cipher.nonce + encrypted_msg
예제 #31
0
def enc(key, data):
    """
    - 16-byte key : byte object
    - data : bytes object
    returns a bytes object
    """
    cipher = Salsa20.new(key)
    md5hash = MD5.new(data).digest()
    msg = cipher.nonce + cipher.encrypt(md5hash + data)
    return msg
예제 #32
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)
예제 #33
0
 def setup(self):
     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)