Ejemplo n.º 1
0
def cryptography_chacha20poly1305(keysize=32, data_size=1024):
    plaintext = get_random_bytes(data_size * 1024)
    aad = get_random_bytes(data_size * 1024)
    key = ChaCha20Poly1305.generate_key()
    chacha = ChaCha20Poly1305(key)
    nonce = get_random_bytes(12)
    _ = chacha.encrypt(nonce, plaintext, aad)
def encrypter(fname):
	tools.empty_folder('./encrypted/' + fname + '/files/' )
	tools.empty_folder('./key/')
	key_1 = Fernet.generate_key()
	key_1_1 = Fernet.generate_key()
	key_1_2 = Fernet.generate_key()
	key_2 = ChaCha20Poly1305.generate_key()
	key_3 = AESGCM.generate_key(bit_length=128)
	key_4 = AESCCM.generate_key(bit_length=128)
	nonce13 = os.urandom(13)
	nonce12 = os.urandom(12)
	files = sorted(tools.list_dir('files'))
	for index in range(0,len(files)):
		if index%4 == 0:
			Algo1_extented(files[index],key_1_1,key_1_2, fname)
		elif index%4 == 1:
			Algo2(files[index],key_2,nonce12, fname)
		elif index%4 == 2:
			Algo3(files[index],key_3,nonce12, fname)
		else:
			Algo4(files[index],key_4,nonce13, fname)
	secret_information = (key_1_1)+":::::"+(key_1_2)+":::::"+(key_2)+":::::"+(key_3)+":::::"+(key_4)+":::::"+(nonce12)+":::::"+(nonce13)
	Algo1(secret_information,key_1, fname)

	# Static path to the image file for Steganography
	in_f = "./static/png.png"
	#out_f = './encrypted/' + fname + '/key/'  + fname + '.png'
	out_f = './key/'  + fname + '.png'
	in_img = cv2.imread(in_f)
	steg = Steganography(in_img)

	res = steg.encode_binary(key_1)
	cv2.imwrite(out_f, res)

	tools.empty_folder('files')
Ejemplo n.º 3
0
def encrypter():
    tools.empty_folder('key')
    tools.empty_folder('encrypted')
    key_1 = Fernet.generate_key()
    key_1_1 = Fernet.generate_key()
    key_1_2 = Fernet.generate_key()
    key_2 = ChaCha20Poly1305.generate_key()
    key_3 = AESGCM.generate_key(bit_length=128)
    key_4 = AESCCM.generate_key(bit_length=128)
    nonce13 = os.urandom(13)
    nonce12 = os.urandom(12)
    files = sorted(tools.list_dir('files'))
    for index in range(0, len(files)):
        if index % 4 == 0:
            Algo1_extented(files[index], key_1_1, key_1_2)
        elif index % 4 == 1:
            Algo2(files[index], key_2, nonce12)
        elif index % 4 == 2:
            Algo3(files[index], key_3, nonce12)
        else:
            Algo4(files[index], key_4, nonce13)
    secret_information = (key_1_1) + ":::::" + (key_1_2) + ":::::" + (
        key_2) + ":::::" + (key_3) + ":::::" + (key_4) + ":::::" + (
            nonce12) + ":::::" + (nonce13)
    Algo1(secret_information, key_1)
    public_key = open("./key/Taale_Ki_Chabhi.pem", "wb")
    public_key.write(key_1)
    public_key.close()
    tools.empty_folder('files')
Ejemplo n.º 4
0
def insertMessage(img, msg, aad):

    alteredImg = img.copy()

    #Generate psuedo random order of pixels to modify based on length of msg
    order = random.sample(range(0, img.width * img.height), len(msg) * 2)

    pixels = list(img.getdata())  #Flatten RGBA arrays into a list

    binaryMsg = convertStringToBinary(msg)

    for i in range(0, len(order)):
        for j in range(0, 4):

            pixels[order[i]] = changeLSB(pixels[order[i]],
                                         binaryMsg[(i * 4):((i * 4) + 4)])

    alteredImg.putdata(pixels)  #Place modified pixels into another image
    print(img)
    pyplot.figure(1)

    pyplot.imshow(np.concatenate((img, alteredImg), axis=1))
    pyplot.show()

    orderString = " ".join(map(
        str, order))  #Concatenate pixel coordinates into one whole string
    byteString = bytes(orderString, "ascii")  #Must be byte array to encrpt

    key = ChaCha20Poly1305.generate_key()
    print("Here is your private key: ", key)
    chacha = ChaCha20Poly1305(key)
    nonce = os.urandom(12)
    ct = chacha.encrypt(nonce, byteString, bytes(aad, "ascii"))

    print("Using key to decrypt image associated with", aad, "\n")

    decryptString = chacha.decrypt(nonce, ct, bytes(aad, "ascii"))

    decodeString = decryptString.decode("ascii")

    decryptOrder = list(map(int, decodeString.split()))

    decryptMsg = ""

    alteredPixels = list(alteredImg.getdata())

    for i in range(0, len(decryptOrder)):
        for j in range(0, 4):
            decryptMsg = decryptMsg + findLSB(
                alteredPixels[decryptOrder[i]][j])

        if (i % 2 == 1):
            decryptMsg = decryptMsg + " "

    decryptMsg = decryptMsg.split()

    decryptMsg = "".join(list(map(lambda x: chr(int(x, 2)), decryptMsg)))

    print("Here is the decrypted message: ", decryptMsg)
Ejemplo n.º 5
0
    def test_nonce_not_12_bytes(self, backend):
        key = ChaCha20Poly1305.generate_key()
        chacha = ChaCha20Poly1305(key)
        with pytest.raises(ValueError):
            chacha.encrypt(b"00", b"hello", b"")

        with pytest.raises(ValueError):
            chacha.decrypt(b"00", b"hello", b"")
Ejemplo n.º 6
0
    def test_nonce_not_12_bytes(self, backend):
        key = ChaCha20Poly1305.generate_key()
        chacha = ChaCha20Poly1305(key)
        with pytest.raises(ValueError):
            chacha.encrypt(b"00", b"hello", b"")

        with pytest.raises(ValueError):
            chacha.decrypt(b"00", b"hello", b"")
Ejemplo n.º 7
0
def send(conf, receive_name, filename):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_host, server_port = get_address(conf, receive_name)
    print('connecting to {}:{}'.format(server_host, server_port))
    sock.connect((server_host, server_port))
    # Receive Public Key
    pk = b''
    print("receiving public key...")
    while True:
        resp = sock.recv(4096)
        pk += resp
        if len(resp) < 4096:
            break
    pk = pk.decode()
    print("public key received is {}".format(pk))
    if receive_name not in conf["publicKeys"]:
        print(
            "This peer has not a Public Key registered. Want to register this PK? (Y/n)"
        )
        if input() == "n":
            print("Could not verify PK, ending connection...")
            sock.close()
            exit(1)
        else:
            print("Accepting PK received as {}'s Public Key".format(
                receive_name))
            add_public_key(conf, receive_name, pk)
    else:
        if conf["publicKeys"][receive_name] != pk:
            print("public key mismatch. MITM!")
            exit(1)
        else:
            print("PK received matches with registered PK for {}".format(
                receive_name))
            # Key is ok, send symmetric encryption key and then the file
    print(
        "Generating shared key for ChaCha20Poly1305 authenticated encryption..."
    )
    key = ChaCha20Poly1305.generate_key()  # 32 bytes
    encrypted_shared_key = get_encrypted_shared_key(key, pk)
    chacha20 = ChaCha20Poly1305(key)
    print("Generating encrypted shared key to receiver...")
    sock.sendall(encrypted_shared_key)
    i = 0
    filesize = os.path.getsize(filename)
    print("sending total filesize ({} bytes) in 8 bytes and in plain text".
          format(filesize))
    sock.sendall(filesize.to_bytes(8, byteorder="big"))
    print("Sending encrypted file to receiver")
    with open(filename, 'rb') as f:
        for chunk in iter(partial(f.read, CHUNK_SIZE), b''):
            encrypted = chacha20.encrypt(i.to_bytes(12, byteorder="big"),
                                         chunk, None)
            print("sending package of size {}...".format(len(encrypted)))
            i += 1
            sock.sendall(encrypted)
    sock.close()
    print("done!")
Ejemplo n.º 8
0
    def test_params_not_bytes_encrypt(self, nonce, data, associated_data,
                                      backend):
        key = ChaCha20Poly1305.generate_key()
        chacha = ChaCha20Poly1305(key)
        with pytest.raises(TypeError):
            chacha.encrypt(nonce, data, associated_data)

        with pytest.raises(TypeError):
            chacha.decrypt(nonce, data, associated_data)
Ejemplo n.º 9
0
    def test_params_not_bytes_encrypt(self, nonce, data, associated_data,
                                      backend):
        key = ChaCha20Poly1305.generate_key()
        chacha = ChaCha20Poly1305(key)
        with pytest.raises(TypeError):
            chacha.encrypt(nonce, data, associated_data)

        with pytest.raises(TypeError):
            chacha.decrypt(nonce, data, associated_data)
Ejemplo n.º 10
0
def chacha20algo_encrypt(text):
    data = bytes(text,'utf-8')
    aad = bytes("Research",'utf-8')
    key = ChaCha20Poly1305.generate_key()  
    chacha = ChaCha20Poly1305(key)
    nonce = os.urandom(12)
    ct = chacha.encrypt(nonce, data, aad)
    plain_text = chacha.decrypt(nonce, ct, aad)
    return True  
Ejemplo n.º 11
0
 def test_associated_data_none_equal_to_empty_bytestring(self, backend):
     key = ChaCha20Poly1305.generate_key()
     chacha = ChaCha20Poly1305(key)
     nonce = os.urandom(12)
     ct1 = chacha.encrypt(nonce, b"some_data", None)
     ct2 = chacha.encrypt(nonce, b"some_data", b"")
     assert ct1 == ct2
     pt1 = chacha.decrypt(nonce, ct1, None)
     pt2 = chacha.decrypt(nonce, ct2, b"")
     assert pt1 == pt2
Ejemplo n.º 12
0
 def test_associated_data_none_equal_to_empty_bytestring(self, backend):
     key = ChaCha20Poly1305.generate_key()
     chacha = ChaCha20Poly1305(key)
     nonce = os.urandom(12)
     ct1 = chacha.encrypt(nonce, b"some_data", None)
     ct2 = chacha.encrypt(nonce, b"some_data", b"")
     assert ct1 == ct2
     pt1 = chacha.decrypt(nonce, ct1, None)
     pt2 = chacha.decrypt(nonce, ct2, b"")
     assert pt1 == pt2
Ejemplo n.º 13
0
    def test_data_too_large(self):
        key = ChaCha20Poly1305.generate_key()
        chacha = ChaCha20Poly1305(key)
        nonce = b"0" * 12

        with pytest.raises(OverflowError):
            chacha.encrypt(nonce, FakeData(), b"")

        with pytest.raises(OverflowError):
            chacha.encrypt(nonce, b"", FakeData())
Ejemplo n.º 14
0
    def test_data_too_large(self):
        key = ChaCha20Poly1305.generate_key()
        chacha = ChaCha20Poly1305(key)
        nonce = b"0" * 12

        with pytest.raises(OverflowError):
            chacha.encrypt(nonce, FakeData(), b"")

        with pytest.raises(OverflowError):
            chacha.encrypt(nonce, b"", FakeData())
 def encrypt(self):
     data = bytes(self.message,encoding="UTF-8")
     aad = b"authenticated but unencrypted data"
     key=ChaCha20Poly1305.generate_key()
     chacha = ChaCha20Poly1305(key)
     nonce=os.urandom(12)
     ct = chacha.encrypt(nonce, data, aad)
     #print(ct)
     new_str=str(ct).split('\\x')
     #print(new_str)
     print("".join(new_str))
     return ct  
Ejemplo n.º 16
0
    def __init__(self, params: Dict[int, Any]):
        super().__init__(params)

        # Validate alg.
        if self._alg != 24:  # ChaCha20/Poly1305
            raise ValueError(f"Unsupported or unknown alg(3) for ChaCha20: {self._alg}.")

        if not self._key:
            self._key = ChaCha20Poly1305.generate_key()
        if len(self._key) != 32:
            raise ValueError("The length of ChaCha20/Poly1305 key should be 32 bytes.")
        self._cipher = ChaCha20Poly1305(self._key)
        return
Ejemplo n.º 17
0
 def test_buffer_protocol(self, backend):
     key = ChaCha20Poly1305.generate_key()
     chacha = ChaCha20Poly1305(key)
     pt = b"encrypt me"
     ad = b"additional"
     nonce = os.urandom(12)
     ct = chacha.encrypt(nonce, pt, ad)
     computed_pt = chacha.decrypt(nonce, ct, ad)
     assert computed_pt == pt
     chacha2 = ChaCha20Poly1305(bytearray(key))
     ct2 = chacha2.encrypt(bytearray(nonce), pt, ad)
     assert ct2 == ct
     computed_pt2 = chacha2.decrypt(bytearray(nonce), ct2, ad)
     assert computed_pt2 == pt
Ejemplo n.º 18
0
 def test_buffer_protocol(self, backend):
     key = ChaCha20Poly1305.generate_key()
     chacha = ChaCha20Poly1305(key)
     pt = b"encrypt me"
     ad = b"additional"
     nonce = os.urandom(12)
     ct = chacha.encrypt(nonce, pt, ad)
     computed_pt = chacha.decrypt(nonce, ct, ad)
     assert computed_pt == pt
     chacha2 = ChaCha20Poly1305(bytearray(key))
     ct2 = chacha2.encrypt(bytearray(nonce), pt, ad)
     assert ct2 == ct
     computed_pt2 = chacha2.decrypt(bytearray(nonce), ct2, ad)
     assert computed_pt2 == pt
Ejemplo n.º 19
0
def chacha20poly1305_encrypt_data(data: bytes, secret: bytes, key: bytes = None, nonce: bytes = None):
    """
    Encrypt data using secret, key and nonce. key and nonce can be None, in that case they will be generated and
    can be obtained in return.
    :param data:
    :param secret:
    :param key:
    :param nonce:
    :return: tulip of (encrypted_data, key, nonce)
    """
    if key is None:
        key = ChaCha20Poly1305.generate_key()
    if nonce is None:
        nonce = os.urandom(12)
    chacha = ChaCha20Poly1305(key)
    return chacha.encrypt(nonce, data, secret), key, nonce
Ejemplo n.º 20
0
def embed_DCT(cover, msg, keyName):
    coverSize = cover.shape

    stego = cover.copy()  #create copy of cover

    binary_msg = msg_encodeBinary(msg)

    msg_len = len(binary_msg)

    num_bits = math.floor(
        round_down(coverSize[0], n) *  #One bit per 8x8 block
        round_down(coverSize[1], n) / (n * n))

    if (msg_len > num_bits):
        raise ValueError("Message too long")

    order = random.sample(range(0, num_bits), msg_len)  #

    msg_idx = 0

    for x in order:
        i = (x // (coverSize[0] // n)) * n
        j = (x % (coverSize[1] // n)) * n

        if (msg_idx >= msg_len):
            break
        print(cover[i:(i + n), j:(j + n)])
        stego[i:(i+n), j:(j+n)] = embed_bit(cover[i:(i+n), j:(j+n)], \
                    binary_msg[msg_idx], thresh)

        msg_idx = msg_idx + 1

    orderString = " ".join(map(str, order))
    byteString = bytes(orderString, "utf-8")  #Must be byte array to encrpt
    key = ChaCha20Poly1305.generate_key()  #User keeps this
    chacha = ChaCha20Poly1305(key)
    nonce = os.urandom(12)  #User keeps this
    ct = chacha.encrypt(nonce, byteString, bytes(keyName,
                                                 "utf-8"))  #User keeps this

    return stego, ct, key, nonce
Ejemplo n.º 21
0
 def test_decrypt_data_too_short(self, backend):
     key = ChaCha20Poly1305.generate_key()
     chacha = ChaCha20Poly1305(key)
     with pytest.raises(InvalidTag):
         chacha.decrypt(b"0" * 12, b"0", None)
Ejemplo n.º 22
0
	def encrypt_ChaChaPoly(key=ChaCha20Poly1305.generate_key(), data:bytes, nonce=os.urandom(12), associated_data=None):
		chacha = ChaCha20Poly1305(key)
		encrypted_data = chacha.encrypt(nonce, data, associated_data)

		return key, encrypted_data, nonce, associated_data
Ejemplo n.º 23
0
def create_key():
    key = ChaCha20Poly1305.generate_key()

    with open(Path("C:/Users/tkaake/Desktop/enc_key.txt"), "w+") as key_file:
        key = b64encode(key).decode('utf-8')
        key_file.write(key)
Ejemplo n.º 24
0
 def test_generate_key(self):
     key = ChaCha20Poly1305.generate_key()
     assert len(key) == 32
Ejemplo n.º 25
0
def test_chacha20poly1305_unsupported_on_older_openssl(backend):
    with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
        ChaCha20Poly1305(ChaCha20Poly1305.generate_key())
Ejemplo n.º 26
0
 def test_decrypt_data_too_short(self, backend):
     key = ChaCha20Poly1305.generate_key()
     chacha = ChaCha20Poly1305(key)
     with pytest.raises(InvalidTag):
         chacha.decrypt(b"0" * 12, b"0", None)
Ejemplo n.º 27
0
 def test_generate_key(self):
     key = ChaCha20Poly1305.generate_key()
     assert len(key) == 32
Ejemplo n.º 28
0
 def new(cls):
     key = ChaCha20Poly1305.generate_key()
     return key, cls(key)
Ejemplo n.º 29
0
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
import os

# The sample code is extracted from the book Python Cryptography
# The book can be downloaded from https://leanpub.com/cryptop
# Online Crypto Playgroud https://8gwifi.org
# Author Anish Nath

backend = default_backend()

nonce = os.urandom(12)

# This AES key is 256 but long
message = "Hello 8gwifi.org"
aaed = "Not Secret "

key = ChaCha20Poly1305.generate_key()
chacha = ChaCha20Poly1305(key)

ct = chacha.encrypt(nonce, message, aaed)

assert message, chacha.decrypt(nonce, ct, aaed)
Ejemplo n.º 30
0
def test_chacha20poly1305_unsupported_on_older_openssl(backend):
    with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
        ChaCha20Poly1305(ChaCha20Poly1305.generate_key())