def is_valid(self):

		message = self.__gather()

		total_input = 0
		for address, amount in self.inputs:
			if amount < 0:
				return False
			found = False
			for s in self.signatures:
				if signature.verify(message, s, address):
					found = True
			if not found:
				return False
			total_input += amount

		for address in self.reqd:
			found = False
			for s in self.signatures:
				if signature.verify(message, s, address):
					found = True
			if not found:
				return False

		total_output = 0
		for address, amount in self.outputs:
			if amount < 0:
				return False
			total_output += amount

		#if total_output > total_input:
		#	return False

		return True
Exemple #2
0
    def is_valid(self):
        total_in = 0
        total_out = 0
        message = self.__gather()
        for addr, amount in self.inputs:
            found = False
            for s in self.sigs:
                if signature.verify(message, s, addr):
                    found = True
            if not found:
                #print ("No good sig found for " + str(message))
                return False
            if amount < 0:
                return False
            total_in = total_in + amount
        for addr in self.requireds:
            found = False
            for s in self.sigs:
                if signature.verify(message, s, addr):
                    found = True
            if not found:
                return False
        for addr, amount in self.outputs:
            if amount < 0:
                return False
            total_out = total_out + amount

        #if total_out > total_in:
        #print("Outputs exceed inputs")
        #    return False

        return True
Exemple #3
0
def recieve():
        # this two lines are for loading the videos.
        # in this case the video are named as: cut1.mp4, cut2.mp4, ..., cut15.mp4
    os.chdir('C:/Users/Кирилл/Desktop/video')
    videofiles = [n for n in os.listdir('.') if n[0] == 'v' and n[-4:] == '.avi']

    videofiles = sorted(videofiles, key=lambda item: int(item.partition('.')[0][3:]))
    #print(videofiles)
    video_index = 0
    openkey = signature.readopenkey(videofiles[0])
    print(openkey)
    signa = signature.readsignature(videofiles[0])
    if(signature.verify(signa,openkey, videofiles[0]) == 1):

        cap = cv2.VideoCapture(str(videofiles[0]))
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        # video resolution: 1624x1234 px
        out = cv2.VideoWriter("./newvid/video.avi",
                              fourcc,
                              15, (640, 480), 1)

        while (cap.isOpened()):
            videofiles = [n for n in os.listdir('.') if n[0] == 'v' and n[-4:] == '.avi']
            videofiles = sorted(videofiles, key=lambda item: int(item.partition('.')[0][3:]))

            ret, frame = cap.read()
            if frame is None:
                print("end of video " + str(video_index) + " .. next one now")
                video_index += 1
                openkey = signature.readopenkey(videofiles[video_index])
                signa = signature.readsignature(videofiles[video_index])
                if video_index >= len(videofiles):
                    break
                if (signature.verify(signa, openkey, videofiles[video_index]) == 0):
                    print('Video is under attack in part ' + str(video_index+1))
                    exit()

                cap = cv2.VideoCapture(videofiles[video_index])
                ret, frame = cap.read()
            cv2.imshow('stream', frame)
            out.write(frame)
            if cv2.waitKey(20) & 0xFF == ord('q'):
                break

        cap.release()
        out.release()
        cv2.destroyAllWindows()

        print
        "end."
    else:
        print('smth is wrong')
        exit()
Exemple #4
0
    def test_verify(self):
        public_key = get_key('../../priv/public.pem')

        for test_case in self.valid_test_cases:
            signature = test_case['expected']
            msg = test_case['input']
            self.assertTrue(verify(public_key, msg, signature),
                            "should be true")
Exemple #5
0
def verify_response(address, challenge, response):
    try:
        verify_challenge(address, challenge)
        assert signature.verify(address, challenge, response)
    except e:
        return False
    finally:
        return True
 def bt_valid(self):
     controlValues.control_all()
     if self.excel_file.get() != "" and self.sign_file.get() != "":
         if signature.verify(self.excel_file.get(),
                             self.sign_file.get()) is None:
             win = tkinter.Toplevel()
             win.title("Hello word")
             app = true_key.c_key(win, self.excel_file.get())
             win.mainloop()
Exemple #7
0
def verify(req=None, credentials=None):
    """
    Verify a request.

    :param req:
    :param credentials:
    :return:
    """

    req = request.normalize(req)
    params = auth_header.parse(req)
    if not params:
        return False

    return signature.verify(req, credentials, params)
from encode import encode,decode
import signature

# This is the test data to sign
data = 'test signed data'

# Generate a PyCrypto RSA key using signature module
key = signature.generate_key()

# Sign the test data with the key
sig = signature.sign(key, data)

# Dump encoded versions of the keys and data to the console
print 'private', signature.key_to_string(key)
print 'public', signature.key_to_string(key.publickey())
print 'address', signature.public_key_to_address(key.publickey())
print 'data', data
print 'signature', sig, '\n'

# Test verification code
print 'call to verify() with legit data\t\t\t%s\t(Should be True)' % signature.verify(key, sig, data)
print 'call of verify() with tampered data\t\t\t%s\t(Should be False)' % key.verify(data+'asdf',(decode(encode(sig),type='long'),None))
Exemple #9
0
def RSA(action):
    if action == '2':
        title('RSA keygen', fillchar='-')
        print()
        print()
        print('Select directory for the keys.')
        Tk().withdraw()
        while True:
            outfolder = askdirectory(
                initialdir=cwd, title='Select directory to save keys in...')
            if not outfolder:
                print('Please choose a directory.')
            else:
                if not os.path.exists(outfolder):
                    os.makedirs(outfolder, exist_ok=True)
                break

        bits = int(input('Size of the key (default is 2048): ') or 2048)
        rsa.generate(bits, outfolder)

    elif action == '3':
        title('RSA Encryption / Decryption', fillchar='-')
        [print() for i in range(5)]
        print('Do you want to...')
        print('1. Encrypt a file')
        print('2. Decrypt a file')
        print('3. Exit')
        print('_' * utils.get_terminal_size()[0])
        print()
        action = input('>> ').lower()
        if action == '1':
            title('RSA Encryption / Decryption', fillchar='-')
            print()
            print()
            print('Select a file to encrypt in the dialog box.')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Choose a file to encrypt...')
            print(filename)
            filedir = os.path.dirname(filename)
            print('Select the public key to encrypt the file with.')
            Tk().withdraw()
            keypath = askopenfilename(initialdir=cwd,
                                      title='Choose a public key...')
            print(keypath)
            keydir = os.path.dirname(keypath)
            print('Select the name for the encrypted file.')
            Tk().withdraw()
            outfile = asksaveasfilename(initialdir=filedir, title='Save as...')
            print('Select the name for the encrypted key.')
            Tk().withdraw()
            outkeyfile = asksaveasfilename(initialdir=filedir,
                                           title='Save as...')
            print(outfile)
            chunksize = input(
                'Select chunksize (leave empty for default): ') or 64 * 1024
            rsa.encrypt(keypath, filename, outfile, outkeyfile, chunksize)

        elif action == '2':
            title('RSA Encryption / Decryption', fillchar='-')
            print()
            print()
            print('Select a file to decrypt in the dialog box.')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Choose a file to decrypt...')
            print(filename)
            filedir = os.path.dirname(filename)
            print('Select the private key to decrypt the file with.')
            Tk().withdraw()
            keypath = askopenfilename(initialdir=cwd,
                                      title='Choose a private key...')
            print(keypath)
            keydir = os.path.dirname(keypath)
            print('Select the encrypted key file used to encrypt the file.')
            Tk().withdraw()
            keyfilepath = askopenfilename(
                initialdir=filedir, title='Choose the encrypted key file...')
            print(keyfilepath)
            print('Select the name for the decrypted file.')
            Tk().withdraw()
            outfile = asksaveasfilename(initialdir=filedir, title='Save as...')
            print(outfile)
            chunksize = input(
                'Select chunksize (leave empty for default): ') or 24 * 1024
            rsa.decrypt(keypath, filename, keyfilepath, outfile, chunksize)

        elif action == '3':
            exit(0)

    elif action == '4':
        title('RSA Signature / verification', fillchar='-')
        [print() for i in range(5)]
        print('Do you want to...')
        print('1. Sign a file')
        print('2. Verify a file')
        print('3. Exit')
        print('_' * utils.get_terminal_size()[0])
        print()
        action = input('>> ').lower()

        if action == '1':
            title('RSA Signature / verification', fillchar='-')
            print()
            print()
            print('Select file to sign...')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Select file to sign...')
            print(filename)
            filedir = os.path.dirname(filedir)
            print('Select private key...')
            Tk().withdraw()
            privKey = askopenfilename(initialdir=cwd,
                                      title='Select private key...')
            print(privKey)
            print('Select name for signature file...')
            signature = asksaveasfilename(
                initialdir=filedir,
                title='Select signature filename...') or None
            print(signature)
            sign(filename, privKey, signature)

        elif action == '2':
            title('RSA Signature / verification', fillchar='-')
            print()
            print()
            print('Select file to verify...')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Select file to verify...')
            print(filename)
            filedir = os.path.dirname(filename)
            print('Select public key...')
            Tk().withdraw()
            pubKey = askopenfilename(initialdir=cwd,
                                     title='Select public key...')
            print(pubKey)
            print('Select signature file...')
            signature = askopenfilename(initialdir=filedir,
                                        title='Select signature file...')
            print(signature)
            valid = verify(filename, signature, pubKey)
            if valid:
                print(
                    'Success! Signature and hash are the same, so the file has not been tampered with.'
                )
                _tmp = input('Press enter to continue...')
            elif not valid:
                clear()
                print('FILE AUTHENTICITY COULD NOT BE VERIFIED!')
                print(
                    'Do not trust the file or its sender. Did you use the correct public key?'
                )
                print(
                    'Error: Verification failed. Authenticity of file could not be verified.'
                )

        elif action == '3':
            pass

    else:
        TypeError('invalid action: \'%s\' in RSA()')
Exemple #10
0
    print("Message: {}".format(message))

    # Set the key length
    # 128, 196 or 256
    N = 256
    # Default rounds is 16 rounds as the TwoFish paper define to us.
    rounds = 16

    # Generate Key and ... - TwoFish
    [K, S] = TwoFish.gen_keys(str(bob_key), N, rounds)

    bob_sig_key = (str((K[:1])[0]).encode('utf-8')).zfill(16)
    # Digital Signature
    bob_digest = sign(message, bob_sig_key)
    # Alice encrypt plaintext
    [num_C, Cypher_text] = TwoFish.encrypt_message(message, S, K, rounds=16)
    print("Enc Message: {}\n Bob digest {}".format(Cypher_text, bob_digest))

    # Alice want to know the message
    # Generate Key and ... - TwoFish
    [K, S] = TwoFish.gen_keys(str(alice_key), N, rounds)
    plain_text = TwoFish.decrypt_message(num_C, S, K, rounds=16)
    alice_sig_key = (str((K[:1])[0]).encode('utf-8')).zfill(16)
    signature_status = verify(plain_text, alice_sig_key, bob_digest)

    if signature_status:
        print(plain_text)
    else:
        print("Failed")
Exemple #11
0
 def verify(self):
     signature.verify(hash_to_scalar(self.coin), self.coin.C - self.v * Hc,
                      self.proof, Gc)
Exemple #12
0
import signature

keys = signature.generatePairKey()
priv = split(keys, 1)
pub = signature.split(keys, 0)
signature.sign(
    priv, "5a822196bf1c45b1e74c6d04e4127d0296d64695932f40909bdab3ba8a9b0528")
bool = signature.verify(
    pub, "5a822196bf1c45b1e74c6d04e4127d0296d64695932f40909bdab3ba8a9b0528",
    sig)
print(bool)