def on_post(self, req, resp):
        """Encrypts data"""
        data = json.dumps(req.media['data'])
        password = req.media['password']

        result = encryptData(data, password)

        resp.media = {"OK": "true", "result": result}
def encrypt(event, context):
    #pylint: disable=unused-argument
    """Encrypt a given string with the password, return lambda response with
  base64 encoded encrypted string"""

    request = None

    try:
        request = getLambdaRequest(event)
    except ValueError as error:
        return {"statusCode": 422, "body": json.dumps({"messaage": error})}

    result = encryptData(json.dumps(request['data']), request['password'])

    response = {"statusCode": 200, "body": json.dumps({"message": result})}

    return response
 def OnSendClick(self, event):
     global key,cipherMark
     global public_key,private_key,peer_public
     ifmasAttack()
     self.plaintext=self.InputText.GetValue()
     self.send_data = crypto.encryptData(self.plaintext,private_key,peer_public)
     try:
         self.client.send(self.send_data)
         self.DisplayText.AppendText('\nYour Text:  [')
         self.DisplayText.AppendText(self.plaintext)
         self.DisplayText.AppendText(']\n')
         if cipherMark==1:
            self.DisplayText.AppendText('\nYour cipher:  [')
            self.DisplayText.AppendText(self.send_data)
            self.DisplayText.AppendText(']\n')
     except  socket.error,e:
         self.DisplayText.AppendText('Pls connect to chat server @%d firstly\n' % self.port)
Esempio n. 4
0
    def makeBitstring(self, encrypted=False, password=None):

        payload = bytes()
        salt = bytes()

        #Here begins the data to be encrypted (if applicable)
        unencrypted_bytes = bytearray()

        #Adding the length of the file extension
        unencrypted_bytes += bytes([len(self.extension)])

        #Adding the file extension
        unencrypted_bytes += self.extension.encode('ascii')

        #Appending the data
        unencrypted_bytes += self.data

        #Appending the checksum
        chksum = int2bytes(binascii.crc32(self.data))
        unencrypted_bytes += bytes(File.CHKSUM_BYTES - len(chksum)) + chksum

        if encrypted:
            salt, payload = crypto.encryptData(bytes(unencrypted_bytes),
                                               password)
        else:
            payload = bytes(unencrypted_bytes)

        header_bytes = bytearray()

        #First byte: Whether there is encryption or not
        header_bytes += bytes([0b11111111]) if encrypted == True else bytes(
            [0])

        #Next 16 bytes: Salt, if encrypted. Otherwise, nothing.
        if encrypted:
            header_bytes += salt

        #Next <LENGTH_BYTES> bytes: length of the payload
        payload_length = len(payload)
        len_bytes = int2bytes(payload_length)
        header_bytes += bytes(File.LENGTH_BYTES - len(len_bytes)) + len_bytes

        header_bytes += payload

        return bytes2bin(header_bytes)
def hideDataToImage(inputImagePath: str, fileToHidePath: str, outputImagePath: str, password: str, hidingMode: str) -> None:
    """
    This function hides the fileToHidePath file inside the image located at inputImagePath,
    and saves this modified image to outputImagePath.
    """
    fp = open(fileToHidePath, "rb")

    data = fp.read()
    print("[*] {} file size : {} bytes".format(fileToHidePath, len(data)))

    if hidingMode == "lsb":
        image = Image.open(inputImagePath).convert('RGB')
        pixels = image.load()

        if password:
            data = crypto.encryptData(data, password)
            print("[*] Encrypted data size: {} bytes".format(len(data)))
            data = (magicBytes["encryptedLSB"]).to_bytes(4, byteorder='big') + filesizeToBytes(data) + data
            print("[*] Magic bytes used: {}".format(hex(magicBytes["encryptedLSB"])))
        else:
            data = (magicBytes["unencryptedLSB"]).to_bytes(4, byteorder='big') + filesizeToBytes(data) + data
            print("[*] Magic bytes used: {}".format(hex(magicBytes["unencryptedLSB"])))

        if len(data) > (image.size[0] * image.size[1] * 6) // 8:
            print("[*] Maximum hidden file size exceeded")
            print("[*] Maximum hidden file size for this image: {}".format((image.size[0] * image.size[1] * 6) // 8))
            print("[~] To hide this file, choose a bigger resolution")
            exit()

        print("[*] Hiding file in image")
        data = serializeData(data, padding=3)
        data.reverse()

        imageX, imageY = 0, 0
        while data:
            # Pixel at index x and y
            pixel_val = pixels[imageX, imageY]

            # Hiding data in all 3 channels of each Pixel
            pixel_val = (changeLast2Bits(pixel_val[0], data.pop()),
                         changeLast2Bits(pixel_val[1], data.pop()),
                         changeLast2Bits(pixel_val[2], data.pop()))

            # Save pixel changes to Image
            pixels[imageX, imageY] = pixel_val

            if imageX == image.size[0] - 1:          # If reached the end of X Axis
                # Increment on Y Axis and reset X Axis
                imageX = 0
                imageY += 1
            else:
                # Increment on X Axis
                imageX += 1

        if not outputImagePath:
            outputImagePath = ".".join(inputImagePath.split(".")[:-1]) + "_with_hidden_file" + "." + inputImagePath.split(".")[-1]

        print(f"[+] Saving image to {outputImagePath}")
        image.save(outputImagePath)
    elif hidingMode == "endian":
        if password:
            data = crypto.encryptData(data, password)
            print("[*] Encrypted data size: {} bytes".format(len(data)))
            data = data + filesizeToBytes(data) + (magicBytes["encrypted"]).to_bytes(4, byteorder='big')
            print("[*] Magic bytes used: {}".format(hex(magicBytes["encrypted"])))
        else:
            print("[!] Warning: You should encrypt file if using endian mode")
            data = data + filesizeToBytes(data) + (magicBytes["unencrypted"]).to_bytes(4, byteorder='big')
            print("[*] Magic bytes used: {}".format(hex(magicBytes["unencrypted"])))

        inputImage = open(inputImagePath, "rb").read()
        inputImage += data

        outputImage = open(outputImagePath, "wb")
        outputImage.write(inputImage)
        outputImage.close()
Esempio n. 6
0
def sendData(dstIp, data, title, sourceIp):
    global startAES
    startAES = 0
    global startRSA
    startRSA = 0
    global startYiao
    startYiao = 0
    key = 8
    info = title +"\"" + data
    print(info)
    print (var.get())
    encryptedText2 = b''
    if var.get() == 1:
        print("We want AES encryption!")
        startAES = time.time()
        encryptedText2 = crypto.aesEncrypt(info.encode("utf8"))
        print(encryptedText2)
        decryptedText2 = crypto.aesDecrypt(encryptedText2)
        print(decryptedText2)


    elif var.get() == 2:
        startRSA = time.time()
        print("We are doing RSA Encryption!")
        encryptedText2 = crypto.RSAEncrypt(info)
        print(encryptedText2)
        print("Encrypted above")

        #decrypted22= encryptedText2[:-1]
        #rsaDecrypt = crypto.RSADecrypt(decrypted22)
        #print(rsaDecrypt)
        #print("Decrypted above")


    elif var.get() == 3:
        print("We are doing Yiao's Encryption!")
        startYiao = time.time()
        encryptedText = crypto.encryptData(info)
        print(encryptedText)
        print("Encrypted text")
        encrypted = crypto.encryptData2(key, encryptedText)
        print(encrypted)

        print("Encrypted text again")

        byteArray = bytearray(encrypted)
        byteArray.append(9)
        encryptedText2 = bytes(byteArray)
        print(encryptedText2)

    else:
        print("We want AES encryption!")
        encryptedText2 = crypto.aesEncrypt(info.encode("utf8"))
        print(encryptedText2)

        #decryptedText2 = crypto.aesDecrypt(key, encryptedText2)
        #print(decryptedText2)
        



    pkt = IP(src=sourceIp, dst=dstIp)/UDP(dport=8000, sport=8505)/encryptedText2    
    send(pkt, verbose=0)
    print("Sent packet 1")