Ejemplo n.º 1
0
def encoder(input_image, output_image, input_data_file, seed):

    img = Image.open(input_image)  # open source image as PIL/Pillow object
    hdatareader = open(input_data_file,
                       'rb')  # open input data file to be read as a bytearray
    input_data = hdatareader.read()

    r, g, b, a = img.convert(
        'RGBA').split()  # split the color/alpha channels into individual lists

    input_data_len = len(input_data) * 4  # get length of input data

    print("original size of input data (in pixels used): ", input_data_len)

    input_data_iter = 0
    input_data_bit_iter = 0

    data_len_serialized = fixedint.UInt32(input_data_len).to_bytes(
    )  # turn the length of the input data into a bytearray to it can be prepended to the input data during encoding
    input_data = data_len_serialized + input_data  # prepend the length to the input data

    input_data_len = len(
        input_data
    ) * 4  # update value to include total length of data that will be encoded

    print("image mode before conversion: ", img.mode)
    if input_data_len > img.width * img.height:  # check if everything fits
        print("input data too large")
        return
    print("input data will affect ", input_data_len, " of ",
          img.width * img.height, "pixels in the image")

    for x, y in generate_pattern(
            seed, img.width, img.height, input_data_len
    ):  # generate image x,y coordinates where bits encoded in the green and blue pixel data
        encode_bits(
            g, b, (x, y), input_data, input_data_iter, input_data_bit_iter
        )  # pass g and b color channel list, pixel coordinates, and the indexes of the byte and bits to encode
        input_data_bit_iter += 2
        if input_data_bit_iter > 6:  # move forward to the next byte
            #print(input_data[input_data_iter], end=' ')
            input_data_iter += 1
            input_data_bit_iter = 0

    newimage = Image.merge(
        'RGBA',
        (r, g, b, a))  # make new image to export by combining the channels
    newimage.save(output_image, 'PNG')

    img.close()
    newimage.close()
    hdatareader.close()
Ejemplo n.º 2
0
def calcH(T1, e, f, g, k, m):
    T1 = fixedint.UInt32(T1)
    e = fixedint.UInt32(e)
    f = fixedint.UInt32(f)
    g = fixedint.UInt32(g)
    k = fixedint.UInt32(k)
    m = fixedint.UInt32(m)
    return T1 - __Sigma1(e) - __Ch(e, f, g) - k - m
Ejemplo n.º 3
0
def calc_r(magic_token, magic_str):
    for i in range(0, len(magic_str) - 2, 3):
        tmp = magic_str[i + 2]
        if tmp >= "a":
            pos = ord(tmp[0]) - 87
        else:
            pos = int(tmp)

        if magic_str[i + 1] == "+":
            pos = magic_token >> pos
        else:
            pos = fixedint.UInt32(magic_token << pos)

        if magic_str[i] == "+":
            magic_token += pos & 4294967295
        else:
            magic_token ^= pos
    return magic_token
    def read_data(self):
        # attempt counters which end transmission if too many consecutive errors occur
        attempt = 0
        maxAttempt = 5
        samplecount = 0
        start_time = time.time()
        self.cancel = False

        #dataWriteBuffer = []
        if (self.ser == None):
            self.status.config(text="Error Opening COM Port")
            return

        # setup and update UI
        self.status.config(text="Waiting for Device Response")
        self.sampleMessage.grid_forget()
        self.sample.grid_forget()

        self.sampleMessage = Label(self,
                                   background="white",
                                   text="Samples recieved:")
        self.sampleMessage.grid(row=2, column=0, padx=10, sticky="W")
        self.sample = Label(self, background="white", text="-               ")
        self.sample.grid(row=2, column=1, sticky=W)
        self.parent.update()

        # attempt to connect to Device
        while (attempt < maxAttempt * 2):

            if (
                    self.cancel == True
            ):  #allow while loop to break and method to return if user cancels
                self.status.config(text="Saving Canceled")

                return

            try:
                self.parent.update()
                if (self.dataType == "main"):
                    self.ser.write(bytes("SndData\n", encoding="ascii"))
                elif (self.dataType == "CO2"):
                    self.ser.write(bytes("SndDataCO2\n", encoding="ascii"))
                line = self.ser.readline()
                line = str(line).strip("b'\\r\\n")
                #print(line)

                #self.parent.update()
                if (line == "S"):
                    break
                elif (line == "BADEND"):
                    self.status.config(text="Device Error, Try again")

                    return
                else:
                    line = ""
                    attempt += 1

            except serial.SerialTimeoutException:

                attempt += 1
                if (attempt >= maxAttempt * 2):
                    self.status.config(text="No Response from Device")

                    return

            except serial.serialutil.SerialException:
                self.status.config(text="Port Error: Check Port")

                return

        if (attempt >= maxAttempt):
            self.status.config(text="No Response from Device")

            return

        #once connected, recieve data from Device
        try:
            #update UI messages
            self.status.config(text="Saving Data")
            self.parent.update()

            #setup writing recieved sample count on UI

            self.parent.update()

            attempt = 0  #reset attempt counter

            #start recieving
            while (attempt < maxAttempt):

                #update status messages etc
                self.sample.config(text=samplecount)
                self.parent.update()

                if (
                        self.cancel == True
                ):  #allow while loop to break and method to return if user cancels
                    self.status.config(text="Saving Canceled")
                    self.ser.write(bytes(
                        "END\n", encoding="ascii"))  # device Sent End command
                    return

                # reset checksum
                checksum = fixedint.MutableUInt32(0)
                # read line from com port
                line = str(self.ser.readline()).strip("b'\\r\\n")
                #print(line)

                # if single sample being sent command recieved, confirm with "OK" and recieve sample
                if (line == "SNGL"):

                    # send acknowledge
                    self.ser.write(bytes("OK\n", encoding="ascii"))
                    # read data being sent by device
                    data = str(self.ser.readline()).strip("b'\\r\\n")

                    #process data and get sent checksum to compare with
                    striped_data = data.split(",", 1)
                    recievedChecksum = fixedint.UInt32(int(striped_data[0]))

                    # calulate checksum for recieved data
                    for c in striped_data[1]:
                        checksum += fixedint.UInt32(ord(c))

                    #compare checksums. if they are the same, send acknowledge. otherwise send "RETRY" to get data resent
                    if (checksum == recievedChecksum):

                        self.filename.write(striped_data[1])
                        self.filename.write('\n')

                        self.ser.write(bytes("CHKOK\n", encoding="ascii"))

                        attempt = 0  #clear attempt counter if successfull
                        samplecount += 1  #increment counter

                    else:
                        self.ser.write(bytes("RETRY\n", encoding="ascii"))
                        self.status.config(text="checksum Differ!, Retrying.")
                        attempt += 1

                # if "ENDDATA" comand recieved, all samples have been recieved and saving should stop
                elif (line == "DATAEND"):
                    self.ser.write(bytes(
                        "OKEND\n", encoding="ascii"))  #send acknowledge comand

                    #update UI
                    self.status.config(text="Data Saved!")
                    self.sample.config(text=samplecount)
                    self.parent.update()

                    print(time.time() - start_time)

                    return True

                # if "END" command is recieved, the device terminated communication, possibly due to an error
                elif (line != "END"):
                    self.status.config(text="Saving Data Failed")
                    self.cancelbutton.grid_remove()
                    winsound.PlaySound('SystemAsterisk',
                                       winsound.SND_ALIAS | winsound.SND_ASYNC)
                    return False

        # Exception handling
        except self.ser.SerialTimeoutException:
            self.ser.write(bytes("END\n", encoding="ascii"))
            self.status.config(text="Saving Data Failed: Timeout")
            winsound.PlaySound('SystemAsterisk',
                               winsound.SND_ALIAS | winsound.SND_ASYNC)

        except Exception:
            print(Exception)
            #self.T.insert(END,'Error Saving\n')
            self.ser.write(bytes("END\n", encoding="ascii"))
            self.status.config(text="Saving Data Failed: Exception")
            winsound.PlaySound('SystemAsterisk',
                               winsound.SND_ALIAS | winsound.SND_ASYNC)

        finally:

            self.filename.close()

            self.ser.close()
Ejemplo n.º 5
0
current_sample += j
A_0_1, j = dpa.dpa_and(T[:, current_sample:], 0, A1, 2, threshold)
current_sample += j
A_0_2, j = dpa.dpa_and(T[:, current_sample:], 0, A1, 1, threshold)
current_sample += j
A_0_3, j = dpa.dpa_and(T[:, current_sample:], 0, A1, 0, threshold)
current_sample += j
A_0 = helper.byte_to_int(A_0_3, A_0_2, A_0_1, A_0_0)
if (silent != 1): print "A_0=", hex(A_0)

if (silent != 1): print 'Calculating H_0...'
# rest is pure calculation
H_0 = sha256_helper.calcH(helper.byte_to_int_array(T1[0]), E_0, F_0, G_0,
                          0x428a2f98L, helper.byte_to_int_array(message_0[0]))
if (silent != 1): print "H_0=", hex(H_0)
H_1 = fixedint.UInt32(G_0)
F_1 = fixedint.UInt32(E_0)
G_1 = fixedint.UInt32(F_0)

T1_1 = np.zeros([len(T1), 4], dtype=np.uint8)
for i in range(0, len(T1)):
    E_tmp = fixedint.UInt32(helper.byte_to_int_array(E1[i]))
    S0E1 = fixedint.UInt32(helper.byte_to_int_array(Sigma1_E1[i]))
    const = fixedint.UInt32(0x71374491L)
    mes = fixedint.UInt32(helper.byte_to_int_array(message_1[i]))
    value = H_1 + S0E1 + sha256_helper.__Ch(E_tmp, F_1, G_1) + const + mes
    T1_1[i] = helper.int_to_byte(value)
'''
 * DPA 9
 * C_0 equals D_1
 * E_2 = D_1 +T1_2
Ejemplo n.º 6
0
def Sigma1(w):
    value = fixedint.UInt32(helper.byte_to_int_array(w))
    result = __Sigma1(value)
    return helper.int_to_byte(result)
Ejemplo n.º 7
0
def Ch(x, y, z):
    x = fixedint.UInt32(x)
    y = fixedint.UInt32(y)
    z = fixedint.UInt32(z)
    result = __Ch(x, y, z)
    return helper.int_to_byte(result)