def shake256hex(b: Union[bytes, str], length: int) -> str: """ length: half of the number of hex characters you want (number of bytes) """ if isinstance(b, bytes): return hashlib.shake_256(b).hexdigest(length) elif isinstance(b, str): return hashlib.shake_256(b.encode()).hexdigest(length) else: raise TypeError(f"not sure how to hash {type(b)}")
def Decaps(self, parameters, c): (s, sk3, pk3) = parameters (c0, c1) = c m_ = self.Dec(sk3, c) r_ = shake_256(m_ + pk3).digest(self.bsidh.p_bytes) c0_ = self.bsidh.public_key_a(r_) if c0_ == c0: K = shake_256(m_ + c0 + c1).digest(self.k_bytes) else: K = shake_256(s + c0 + c1).digest(self.k_bytes) return K
def generateBallot(vid) -> bool: """ Generates a unique Ballot Id of voter if voter has not already voted. Args: - vid: Voter Id Returns: False if voter has already voted. Ballot ID if ballot generation successful. """ ballotID = hashlib.shake_256(vid.encode("utf-8")).hexdigest(5) flag = False try: with open("Files\\ballots.csv", "r") as readcsv: read_file = csv.reader(readcsv) for i in read_file: if i[1] == vid: flag = True if not flag: with open("Files\\ballots.csv", "a", newline="") as csvfile: file = csv.writer(csvfile, quoting=csv.QUOTE_ALL) file.writerow([ballotID, vid]) else: pass except FileNotFoundError: with open("Files\\ballots.csv", "w", newline="") as csvfile: file = csv.writer(csvfile, quoting=csv.QUOTE_ALL) file.writerow([ballotID, vid]) return ballotID if not flag else False
def encodeShake_256(self): x = input(Cy + "enter your text here : " + Cre) m = int( input("shake_256 needs a key , enter a number, ! what ever ! : ")) y = hashlib.shake_256(x.encode()).hexdigest(m) print(Cre + Cg + '>>>> ' + Cre + y) save('shake_256', y, 'Anas.encodeShake_256()')
def hasherFromString(s): import hashlib if s == 'sha1': return hashlib.sha1() elif s == 'sha224': return hashlib.sha224() elif s == 'sha256': return hashlib.sha256() elif s == 'sha384': return hashlib.sha384() elif s == 'sha512': return hashlib.sha512() elif s == 'blake2b': return hashlib.blake2b() elif s == 'blake2s': return hashlib.blake2s() elif s == 'md5': return hashlib.md5() elif s == 'sha3_224': return hashlib.sha3_224() elif s == 'sha3_256': return hashlib.sha3_256() elif s == 'sha3_384': return hashlib.sha3_384() elif s == 'sha3_512': return hashlib.sha3_512() elif s == 'shake_128': return hashlib.shake_128() elif s == 'shake_256': return hashlib.shake_256() else: return None
def post(self): print(g.json) req = g.json # validation if 'datetime' in req\ and 'doctor_id' in req \ and 'patient' in req \ and req['datetime'] in read_from_file(TIMESLOT_FILE)['data']: reservation_data = read_from_file(RESERVATION_FILE)['data'] for r in reservation_data: if r['datetime'] == req['datetime'] and r['doctor_id'] == req[ 'doctor_id']: return None, 409 created_reservation = { 'datetime': req['datetime'], 'doctor_id': req['doctor_id'], 'patient': req['patient'] } id = hashlib.shake_256( json.dumps(created_reservation).encode()).hexdigest(3) created_reservation['id'] = id reservation_data.append(created_reservation) write_to_file(RESERVATION_FILE, {'data': reservation_data}) return {'data': created_reservation}, 201, None else: return None, 400
def handleCacheable(self): cache_hash = shake_256( (self.domain + self.file_path).encode()).hexdigest(16) try: # Check wether the file exist in the cache cache = Path(cache_hash).read_bytes() cache_message = cache.decode() if cache_message.split()[1] == '301': self.handle304(cache) return last_modified = self.regex_last_modified.search(cache_message) last_modified = last_modified.groups()[1] self.message = self.message[: -2] + 'If-Modified-Since:' + last_modified + '\r\n\r\n' except FileNotFoundError: pass except AttributeError: pass with socket(AF_INET, SOCK_STREAM) as client_sock: client_sock.connect((self.domain, 80)) client_sock.send(self.message.encode()) buffer = client_sock.recv(self.BUFSIZE) resp_code = int(buffer.decode().split()[1]) if resp_code in (200, 301): self.handle200(client_sock, buffer, cache_hash) elif resp_code == 304: self.handle304(cache) # type: ignore else: self.handleOther(client_sock, buffer)
def _encode(circuit_id: int, secret: bytes, x: List[Any], payload: bytes = None): j = circuit_id.to_bytes(4, byteorder='big') e_s = hashlib.shake_128(secret + j + (0).to_bytes(1, byteorder='big')).digest(16) e_r = hashlib.shake_128(secret + j + (1).to_bytes(1, byteorder='big')).digest(16) k = hashlib.shake_256(secret + j + (2).to_bytes(1, byteorder='big')).digest(32) emp_utils.init_encoder(e_s, e_r) X = [] for x_i in x: if isinstance(x_i, bool): X.append(emp_utils.encode_bit(x_i)) elif isinstance(x_i, int): X.append(emp_utils.encode_int(x_i)) elif isinstance(x_i, str): X.append(emp_utils.encode_ascii_str(x_i)) elif isinstance(x_i, tuple) and isinstance(x_i[0], str) and isinstance(x_i[1], int): X.append(emp_utils.encode_ascii_str(x_i[0], x_i[1])) else: raise TypeError('Unsupported data type:', type(x_i)) X = b''.join(X) k = base64.urlsafe_b64encode(k) f = Fernet(k) payload = b'' if payload is None else payload ct = f.encrypt(payload) return j, X, ct
def EnrollCourseByPayment(request, pk, upk): course = Course.objects.get(id=pk) student = StudentProfile.objects.get(user_id=upk) print("before before") enrollment = Enrollment.objects.filter(student=student, course=course).first() print("before running") if not enrollment: print("running") c = Coupon.objects.create(course=course, coupon_key="", isValid=False, isIssued=True) print(c.id) serializer = CouponSerializer(instance=c, data=request.data) if serializer.is_valid(): coupon = str(c.id) + ":" + str(c.course.id) coupon_key = hashlib.shake_256(coupon.encode()).hexdigest(5) serializer.save(coupon_key=coupon_key) enroll = Enrollment(course=course, student=student, enroll_key=coupon_key, is_payment=True) enroll_serializer = CourseEnrollSerializer(enroll, data=request.data) if enroll_serializer.is_valid(): enroll_serializer.save() return Response(enroll_serializer.data) return Response(enroll_serializer.errors) return Response(serializer.errors) else: return Response({'message': 'You have already enrolled'}, status=403)
def run(self): """ Overrides Thread.run. Don't call this directly. It's called internally when you call Thread.start(). """ hash = None monitor = MonitorThread() monitor.start() if self._algorithm == 'blake2b': hash = hashlib.blake2b() elif self._algorithm == 'blake2s': hash = hashlib.blake2s() elif self._algorithm == 'pbkdf2_hmac': hash = hashlib.pbkdf2_hmac() elif self._algorithm == 'md5': hash = hashlib.md5() elif self._algorithm == 'sha1': hash = hashlib.sha1() elif self._algorithm == 'sha224': hash = hashlib.sha224() elif self._algorithm == 'sha256': hash = hashlib.sha256() elif self._algorithm == 'sha384': hash = hashlib.sha384() elif self._algorithm == 'sha3_224': hash = hashlib.sha3_224() elif self._algorithm == 'sha3_256': hash = hashlib.sha3_256() elif self._algorithm == 'sha3_384': hash = hashlib.sha3_384() elif self._algorithm == 'sha3_512': hash = hashlib.sha3_512() elif self._algorithm == 'sha512': hash = hashlib.sha512() elif self._algorithm == 'shake_128': hash = hashlib.shake_128() elif self._algorithm == 'shake_256': hash = hashlib.shake_256() with open(self._iFile, 'rb') as f: for block in iter(lambda: f.read(4096), b""): hash.update(block) evt = HasherEvent(myEVT_HASHER, -1, hash.hexdigest()) monitor.join() wx.PostEvent(self._parent, evt)
def test_hash_bytes(): test_string = b'hi there' assert j.data.hash.md5(test_string) == hashlib.md5(test_string).hexdigest() assert j.data.hash.sha1(test_string) == hashlib.sha1( test_string).hexdigest() assert j.data.hash.sha224(test_string) == hashlib.sha224( test_string).hexdigest() assert j.data.hash.sha256(test_string) == hashlib.sha256( test_string).hexdigest() assert j.data.hash.sha384(test_string) == hashlib.sha384( test_string).hexdigest() assert j.data.hash.sha512(test_string) == hashlib.sha512( test_string).hexdigest() assert j.data.hash.sha3_224(test_string) == hashlib.sha3_224( test_string).hexdigest() assert j.data.hash.sha3_256(test_string) == hashlib.sha3_256( test_string).hexdigest() assert j.data.hash.sha3_384(test_string) == hashlib.sha3_384( test_string).hexdigest() assert j.data.hash.sha3_512(test_string) == hashlib.sha3_512( test_string).hexdigest() assert j.data.hash.blake2b(test_string) == hashlib.blake2b( test_string).hexdigest() assert j.data.hash.blake2s(test_string) == hashlib.blake2s( test_string).hexdigest() assert j.data.hash.shake_128(test_string) == hashlib.shake_128( test_string).hexdigest(16) assert j.data.hash.shake_256(test_string) == hashlib.shake_256( test_string).hexdigest(16)
def haszowanie_shake_256(tekst): start = time.time() wynik = hashlib.shake_256(tekst.encode("utf8")).hexdigest(32) end = time.time() - start print("Skrot wygenerowany dzieki funkcji SHAKE-256: " + wynik + ", czas generacji to: " + str(end * 1000) + " ms" + ", a dlugosc ciagu wyjsciowego to: " + str(len(wynik)))
def __init__(self, engine_name=None, resman_name=None, config_file=None, workspace_dir=os.getcwd(), reuse=False, dry_run=False, quiet=False, skip_pull=False, skip_clone=False): self.workspace_dir = os.path.realpath(workspace_dir) self.reuse = reuse self.dry_run = dry_run self.quiet = quiet self.skip_pull = skip_pull self.skip_clone = skip_clone self.repo = scm.new_repo() self.workspace_sha = scm.get_sha(self.repo) wid = shake_256(self.workspace_dir.encode('utf-8')).hexdigest(4) self.wid = wid from_file = self._load_config_from_file(config_file, engine_name, resman_name) self.engine_name = from_file['engine_name'] self.resman_name = from_file['resman_name'] self.engine_opts = from_file['engine_opts'] self.resman_opts = from_file['resman_opts']
def hashfun(text): """ Converts a str object to a hash which was configured in modules.conf of the cobbler settings. :param text: The text to hash. :type text: str :return: The hash of the text. This should output the same hash when entered the same text. """ hashfunction = get_module_name("authentication", "hash_algorithm", "sha3_512") if hashfunction == "sha3_224": hashalgorithm = hashlib.sha3_224(text.encode('utf-8')) elif hashfunction == "sha3_384": hashalgorithm = hashlib.sha3_384(text.encode('utf-8')) elif hashfunction == "sha3_256": hashalgorithm = hashlib.sha3_256(text.encode('utf-8')) elif hashfunction == "sha3_512": hashalgorithm = hashlib.sha3_512(text.encode('utf-8')) elif hashfunction == "blake2b": hashalgorithm = hashlib.blake2b(text.encode('utf-8')) elif hashfunction == "blake2s": hashalgorithm = hashlib.blake2s(text.encode('utf-8')) elif hashfunction == "shake_128": hashalgorithm = hashlib.shake_128(text.encode('utf-8')) elif hashfunction == "shake_256": hashalgorithm = hashlib.shake_256(text.encode('utf-8')) else: errortext = "The hashfunction (Currently: %s) must be one of the defined in /etc/cobbler/modules.conf!" \ % hashfunction raise ValueError(errortext) return hashalgorithm.hexdigest()
def text_to_hash(cls, text, method): encoded_text = text.encode() if (method.upper() == 'MD5'): return hashlib.md5(encoded_text).hexdigest() if (method.upper() == 'SHA1'): return hashlib.sha1(encoded_text).hexdigest() if (method.upper() == 'SHA256'): return hashlib.sha256(encoded_text).hexdigest() if (method.upper() == 'SHA384'): return hashlib.sha384(encoded_text).hexdigest() if (method.upper() == 'SHA512'): return hashlib.sha512(encoded_text).hexdigest() if (method.upper() == 'SHA3_256'): return hashlib.sha3_256(encoded_text).hexdigest() if (method.upper() == 'SHA3_384'): return hashlib.sha3_384(encoded_text).hexdigest() if (method.upper() == 'SHAKE_128'): return hashlib.shake_128(encoded_text).hexdigest(128) if (method.upper() == 'SHA224'): return hashlib.sha224(encoded_text).hexdigest() if (method.upper() == 'BLAKE2B'): return hashlib.blake2b(encoded_text).hexdigest() if (method.upper() == 'BLAKE2S'): return hashlib.blake2s(encoded_text).hexdigest() if (method.upper() == 'SHAKE_256'): return hashlib.shake_256(encoded_text).hexdigest(256) if (method.upper() == 'SHA3_512'): return hashlib.sha3_512(encoded_text).hexdigest() if (method.upper() == 'SHA3_224'): return hashlib.sha3_224(encoded_text).hexdigest()
def Keygen(curve, sh=None): """ Generate a new keypair. If sh is provided, then it must be a SHAKE256 context pre-fed with a seed; the key pair is then deterministically generated from that context. If sh is not provided (or is None), then the OS-provided random generator (os.urandom()) is used. Returned value is the private key (as a scalar instance). """ if sh == None: sh = hashlib.shake_256() sh.update(os.urandom(32)) j = 0 while True: # We use a loop on the off-chance that we get a value which is # zero modulo r. This is extremely improbable and nobody knows # how to initialize a SHAKE256 context so that it outputs such # a value. # # We only extract 32 bytes (256 bits) at a time, because the # group order (on both do255e and do255s) is close enough to # 2^254 that the modulo reduction induces no statistically # detectable bias. bb = sh.digest(curve.encodedLen * (j + 1)) sk = curve.SF.DecodeReduce(bb[curve.encodedLen * j:]) if not sk.is_zero(): return sk j += 1
def poly_sample(seed, nonce): #if NEWHOPE_K != 8 #error "poly_sample in poly.c only supports k=8" #endif #buf[128], a, b; buf = [] r = [0 for i in range(params.N)] a, b = 0 #extseed[NEWHOPE_SYMBYTES+2]; extseed = [] for i in range(params.NEWHOPE_SEEDBYTES): extseed.append(seed[i]) extseed.append(nonce) for i in range(params.N / 64): extseed.append(i) hashing_algorithm = hashlib.shake_256() hashing_algorithm.update(seed) buf = hashing_algorithm.digest(128) for j in range(64): a = buf[2 * j] b = buf[2 * j + 1] r[64 * i + j] = hw(a) + params.Q - hw(b) return r
def new_keys(self, password): num = 100 has = shake_256() has.update(password.encode()) k1 = self.get_num(has.hexdigest(num)) k2 = self.get_num(has.hexdigest(num * 2)[num:]) return k1, k2
def s(n): _h = hashlib.shake_256() buf = n.encode() _h.update(buf) H = _h.hexdigest(64) print('SHAKE 256: ' + H) return H
def hasherFromString(s): import hashlib if s == 'sha1': return hashlib.sha1() elif s == 'sha224': return hashlib.sha224() elif s == 'sha256': return hashlib.sha256() elif s == 'sha384': return hashlib.sha384() elif s == 'sha512': return hashlib.sha512() elif s == 'blake2b': return hashlib.blake2b() elif s == 'blake2s': return hashlib.blake2s() elif s == 'md5': return hashlib.md5() elif s == 'sha3_224': return hashlib.sha3_224() elif s == 'sha3_256': return hashlib.sha3_256() elif s == 'sha3_384': return hashlib.sha3_384() elif s == 'sha3_512': return hashlib.sha3_512() elif s == 'shake_128': return hashlib.shake_128() elif s == 'shake_256': return hashlib.shake_256() else: raise ValueError('Unknown hash type ' + s)
def post(self): """ Ta metoda obsługuje zapytanie HTTP POST na endpoint postów. Zapytanie POST na ten endpoint służy do tworzenia nowego posta. """ args = self.post_parser.parse_args( ) # Użyj parsera do przeczytania argumentów user_id = Auth.get_user_id(args["key"]) # Zdobądź nazwę użytkownika if args["_id"] is None: # Jeśli nie podano żadnego ID posta post_id = shake_256( str(datetime.timestamp(datetime.now()), encoding="utf-8") + str(user_id, encoding="utf-8")).hexdigest( 8) # Utwórz nowe losowe ID posta if self.post_from_id( post_id ): # Jeśli wylosowane ID istnieje (niebotycznie mała szansa) abort(409, message=f"Duplicate post ID {post_id}!" ) # Zwróć 409: "Conflict" args.update({ "_id": int( post_id, 16, ), "user_id": user_id, }) # Dodaj ID i właściciela do informacji o poście mongo.db.posts.insert_one(args) # Dodaj posta do bazy danych return args # Zwróć informacje o utworzonym poście
def hash_to_point(n, message): """Hash a message to a point in Z[x] mod(Phi, q). Inspired by the Parse function from NewHope. """ salt = 'some salt' global q if q > 2**16: raise ValueError("The modulus is too large") k = (2**16) / q # We take twice the number of bits that would be needed if there was no rejection emessage = message #message.encode('utf-8') esalt = salt.encode('utf-8') hash_instance = hashlib.shake_256() hash_instance.update(esalt) hash_instance.update(emessage) digest = hash_instance.hexdigest(int(8 * n)) hashed = [0 for i in range(n)] i = 0 j = 0 while i < n: # Takes 2 bytes, transform them in a 16 bits integer elt = int(digest[4 * j:4 * (j + 1)], 16) # Implicit rejection sampling if elt < k * q: hashed[i] = elt % q i += 1 j += 1 return hashed
def test_hash_strings(): test_string = "my company is codescalers" assert j.data.hash.md5(test_string) == hashlib.md5( test_string.encode()).hexdigest() assert j.data.hash.sha1(test_string) == hashlib.sha1( test_string.encode()).hexdigest() assert j.data.hash.sha224(test_string) == hashlib.sha224( test_string.encode()).hexdigest() assert j.data.hash.sha256(test_string) == hashlib.sha256( test_string.encode()).hexdigest() assert j.data.hash.sha384(test_string) == hashlib.sha384( test_string.encode()).hexdigest() assert j.data.hash.sha512(test_string) == hashlib.sha512( test_string.encode()).hexdigest() assert j.data.hash.sha3_224(test_string) == hashlib.sha3_224( test_string.encode()).hexdigest() assert j.data.hash.sha3_256(test_string) == hashlib.sha3_256( test_string.encode()).hexdigest() assert j.data.hash.sha3_384(test_string) == hashlib.sha3_384( test_string.encode()).hexdigest() assert j.data.hash.sha3_512(test_string) == hashlib.sha3_512( test_string.encode()).hexdigest() assert j.data.hash.blake2b(test_string) == hashlib.blake2b( test_string.encode()).hexdigest() assert j.data.hash.blake2s(test_string) == hashlib.blake2s( test_string.encode()).hexdigest() assert j.data.hash.shake_128(test_string) == hashlib.shake_128( test_string.encode()).hexdigest(16) assert j.data.hash.shake_256(test_string) == hashlib.shake_256( test_string.encode()).hexdigest(16)
def load( engine_name=None, resman_name=None, config_file=None, workspace_dir=os.getcwd(), reuse=False, dry_run=False, quiet=False, skip_pull=False, skip_clone=False, pty=False, allow_undefined_secrets_in_ci=False, ): """Loads and creates a configuration, represented by a frozen Box """ workspace_dir = os.path.realpath(workspace_dir) repo = scm.new_repo(workspace_dir) # path to cache if os.environ.get("POPPER_CACHE_DIR", None): cache_dir = os.environ["POPPER_CACHE_DIR"] else: cache_dir_default = os.path.join(os.environ["HOME"], ".cache") cache_dir = os.environ.get("XDG_CACHE_HOME", cache_dir_default) cache_dir = os.path.join(cache_dir, "popper") from_file = ConfigLoader.__load_config_from_file( config_file, engine_name, resman_name ) pp_config = { "workspace_dir": workspace_dir, "reuse": reuse, "dry_run": dry_run, "quiet": quiet, "skip_pull": skip_pull, "skip_clone": skip_clone, "pty": pty, "allow_undefined_secrets_in_ci": allow_undefined_secrets_in_ci, # if no git repository exists in workspace_dir or its parents, the repo # variable is None and all git_* variables are assigned to 'na' "repo": repo, "git_commit": scm.get_sha(repo), "git_sha_short": scm.get_sha(repo, short=7), "git_branch": scm.get_branch(repo), "git_tag": scm.get_tag(repo), "git_remote_origin_url": scm.get_remote_url(repo), # wid is used to associate a unique id to this workspace. This is then # used by runners to name resources in a way that there is no name # clash between concurrent workflows being executed "wid": shake_256(workspace_dir.encode("utf-8")).hexdigest(4), "cache_dir": cache_dir, "engine_name": from_file["engine_name"], "resman_name": from_file["resman_name"], "engine_opts": from_file["engine_opts"], "resman_opts": from_file["resman_opts"], } return Box(pp_config, default_box=True, frozen_box=True)
def BLS_H(m): h = hashlib.shake_256() h.update(bytes(m, 'utf-8')) hm=big.from_bytes(h.digest(curve.EFS)) HM=ECp() while not HM.set(hm): hm = hm + 1 return HM
def encrypt(): key = b"39471025" plaintext = open("flag.mpeg", "rb").read() mask = hashlib.shake_256(key).digest(len(plaintext)) ciphertext = xor(plaintext, mask) with open(f"flag.enc.mpeg", "wb") as w: w.write(ciphertext)
def shake_256(fname): """ the parameter in the function *.hexdigest() is the size of the return digest. the length of the return digest could vary but 46 should be sufficient. """ hash_shake_256 = hashlib.shake_256() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_shake_256.update(chunk) return hash_shake_256.hexdigest(46)
def shake_256(): a = str(raw_input("Password:"******"Encoding The Password: {}".format(a)) hexhash = hashlib.shake_256(("{}".format(a)).encode('utf-8')).hexdigest() time.sleep(2) print("[+] Password Encoded: {}".format(hexhash)) b = open('robert.txt', 'w') b.write("{}".format(hexhash))
def BLS_H(m): h = hashlib.shake_256() h.update(bytes(m, 'utf-8')) hm = big.from_bytes(h.digest(curve.EFS)) HM = ECp() while not HM.set(hm): hm = hm + 1 return HM
def hashMsg(msg: str) -> str: m = hashlib.shake_256() m.update(msg.encode('utf-8')) key = '0' + str(m.hexdigest(11)) return key
def _get_message_deduplication_id(messages): unique_message_ids = sorted( list(set([str(message.event_id) for message in messages]))) combined = "-".join(unique_message_ids) m = hashlib.shake_256() m.update(combined.encode("utf-8")) return m.hexdigest( 64) # the length of a hex digest will be up to 64 * 2 or 128
def random_bits(frames, nbits=64): # RETURN: bytes object of length `nbits`/8 # assert frames.dtype == np.uint8 single_arr = np.concatenate([frame.flatten() for frame in frames]) s = hashlib.shake_256() s.update(single_arr) return s.digest(nbits // 8)
def intro2_ntor_service(intro_auth_pubkey_str, client_enc_pubkey, service_enc_privkey, service_enc_pubkey, subcredential): dh_result = service_enc_privkey.get_shared_key(client_enc_pubkey, hash_nil) secret = dh_result + intro_auth_pubkey_str + client_enc_pubkey.serialize() + service_enc_pubkey.serialize() + PROTOID assert(len(secret) == INTRO_SECRET_LEN) info = M_HSEXPAND + subcredential kdf = shake_256() kdf.update(secret + T_HSENC + info) key_material = shake_squeeze(kdf, 64*8) enc_key = key_material[0:32] mac_key = key_material[32:64] return enc_key, mac_key
def computeCryptoHash(data): ' This will currently return 128 hex characters' # s = hashlib.sha3_256() s = hashlib.shake_256() s.update(data) return s.digest(64)