def hash(self, password, salt): password = self.pre_hashing(password) # 1. Let S be the following byte sequence (called the padding): # (u = len(password) (in bytes)) # S = H_(k−2−u)(salt || password || u) k = len(encode(self.n)) u = len(password) # u must be such that u ≤ 255 and u ≤ k − 32 if u > 255 or u > k - 32: raise ValueError('Password is too long') S = self.kdf(salt + password + pack('=B', u), k - 2 - u) # 2. Let X be the following byte sequence: # X = 0x00 | | S | | π | | u X = b'\x00' + S + password + pack('=B', u) # 3. Let x be the integer obtained by decoding X with OS2IP. x = decode(X) # 4. Compute: # y = x^(2^(w+1)) (mod n) # This computation is normally performed by repeatedly squaring x modulo n; this is # done w + 1 times. y = x for _ in range(self.w + 1): y = pow(y, 2, self.n) # 5. Encode y with I2OSP into the byte sequence Y of length k bytes. Y = encode(y, k) # The primary output of MAKWA is Y return self.post_hashing(Y)
def format(self, formatstring, adddict={}, safe=False): """format song info using formatstring. Further song information in adddict is added. If safe is True, all values are cleaned of characters which are neither letters, digits, a blank or a colon. """ if self.title is None: return "DELETED" d = {} d.update(self.song_metadata.__dict__) d.update(adddict) d["minutes"], d["seconds"] = divmod(d["length"], 60) d["length"] = "%d:%02d" % (d["minutes"], d["seconds"]) if safe: allowedchars = encoding.decode(string.letters + string.digits + " :") for key, value in list(d.items()): try: l = [] for c in value: if c in allowedchars: l.append(c) d[key] = "".join(l) except TypeError: pass return str(formatstring) % d
def submit_audio(user_id, index, tick): payload = encoding.decode(request.data) segment = read_opus(payload['sound']) offset = payload['offset'] offset_sign = payload['offset-sign'] room_id = r.get('USER-ROOM:%s' % user_id).decode('utf-8') room_index = int(r.get('ROOM-INDEX:%s' % room_id)) room_song = r.get('ROOM-SONG:%s' % room_id) if room_index != index or room_song is None: return encoding.encode({ 'success': False, 'reason': 'Desynced with the bulletin' }) if not offset_sign: segment = segment[offset:] offset = 0 r.set('USER-AUDIO-%d:%s' % (tick % 2, user_id), encoding.encode( { 'offset': offset, 'sound': as_mp3(segment) }) ) r.set('USER-LAST-ACTIVE:%s' % user_id, int(time.time())) return encoding.encode({'success': True})
def format(self, formatstring, adddict={}, safe=False): """format song info using formatstring. Further song information in adddict is added. If safe is True, all values are cleaned of characters which are neither letters, digits, a blank or a colon. """ if self.title is None: return "DELETED" d = {} d.update(self.song_metadata.__dict__) d.update(adddict) d["minutes"], d["seconds"] = divmod(d["length"], 60) d["length"] = "%d:%02d" % (d["minutes"], d["seconds"]) if safe: allowedchars = encoding.decode(string.letters + string.digits + " :") for key, value in d.items(): try: l = [] for c in value: if c in allowedchars: l.append(c) d[key] = "".join(l) except TypeError: pass return unicode(formatstring) % d
def main(): cnn = CNN() cnn.eval() cnn.load_state_dict(torch.load('model.pkl')) print("load cnn net.") eval_dataloader = dataset.get_eval_data_loader() correct = 0 total = 0 for i, (images, labels) in enumerate(eval_dataloader): image = images vimage = Variable(image) predict_label = cnn(vimage) c0 = setting.ALL_CHAR_SET[np.argmax( predict_label[0, 0:setting.ALL_CHAR_SET_LEN].data.numpy())] c1 = setting.ALL_CHAR_SET[np.argmax( predict_label[0, setting.ALL_CHAR_SET_LEN:2 * setting.ALL_CHAR_SET_LEN].data.numpy())] c2 = setting.ALL_CHAR_SET[np.argmax( predict_label[0, 2 * setting.ALL_CHAR_SET_LEN:3 * setting.ALL_CHAR_SET_LEN].data.numpy())] c3 = setting.ALL_CHAR_SET[np.argmax( predict_label[0, 3 * setting.ALL_CHAR_SET_LEN:4 * setting.ALL_CHAR_SET_LEN].data.numpy())] predict_label = '%s%s%s%s' % (c0, c1, c2, c3) true_label = encoding.decode(labels.numpy()[0]) total += labels.size(0) if (predict_label == true_label): correct += 1 if (total % 200 == 0): print('Test Accuracy of the model on the %d eval images: %f %%' % (total, 100 * correct / total)) print('Test Accuracy of the model on the %d eval images: %f %%' % (total, 100 * correct / total)) return correct / total
def get_bulletin(room_id): bulletin = encoding.decode(r.get('ROOM-BULLETIN:%s' % room_id)) index = int(r.get('ROOM-INDEX:%s' % room_id)) if bulletin is None: return encoding.encode({'success': False}) return encoding.encode({ 'index': index, 'bulletin': bulletin })
def decrypt(ciphertexts, key, rounds=5, modulus=DEFAULT_MODULUS): """ usage: decrypt(ciphertexts, key, rounds=5, modulus=DEFAULT_MODULUS) => plaintext Given ciphertexts and key, return plaintexts. """ output = [] for ciphertext in slide(ciphertexts, 2 ** rounds): multiplication_subroutine(ciphertext, [modular_inverse(item | 1, modulus) for item in key], modulus) for round in range(rounds): ciphertext[:] = decode(ciphertext, modulus) output.append(ciphertext[0]) return output
def to_katakana(text, keras_model, input_encoding, output_decoding, input_length=20, output_length=20): encoder_input = encoding.transform(input_encoding, [text.lower()], input_length) decoder_input = np.zeros(shape=(len(encoder_input), output_length)) decoder_input[:, 0] = encoding.CHAR_CODE_START for i in range(1, output_length): output = keras_model.predict([encoder_input, decoder_input]).argmax(axis=2) decoder_input[:, i] = output[:, i] decoder_output = decoder_input return encoding.decode(output_decoding, decoder_output[0][1:])
def create_room(): bulletin = encoding.decode(request.data) room_id = generate_id(); # Every room has three things: # a list of users, a song, and a current tick. #r.set('ROOM-USERS:%s' % room_id, []) # Created implicitly r.set('ROOM-BULLETIN:%s' % room_id, encoding.encode(bulletin)) r.set('ROOM-INDEX:%s' % room_id, -1) return encoding.encode({'room_id': room_id})
def main(args): # for line in sys.stdin: while True: line = sys.stdin.read(5).strip() if not line: break try: words = int(line, 16) opcode = str(encoding.decode(words)) opcode = opcode.replace("\t", " ") except ValueError: opcode = "!%s" % line sys.stdout.write(opcode + "\n") sys.stdout.flush()
def decrypt(ciphertexts, key, rounds=5, modulus=DEFAULT_MODULUS): """ usage: decrypt(ciphertexts, key, rounds=5, modulus=DEFAULT_MODULUS) => plaintext Given ciphertexts and key, return plaintexts. """ output = [] for ciphertext in slide(ciphertexts, 2**rounds): multiplication_subroutine( ciphertext, [modular_inverse(item | 1, modulus) for item in key], modulus) for round in range(rounds): ciphertext[:] = decode(ciphertext, modulus) output.append(ciphertext[0]) return output
def change_wf(self, privkey, hash, diff): y = decode(hash) if diff == 0: return hash if diff > 0: return encode(pow(y, pow(2, diff), self.n)) else: if privkey is None: raise ValueError("Cant decrease without private key") p = privkey.p q = privkey.q ep = sqrtExp(p, -diff) eq = sqrtExp(q, -diff) yp = pow((y % p), ep, p) yq = pow((y % q), eq, q) return encode(chinese_remainder(p, q, privkey.invQ, yp, yq))
def decrypt(filename): original_message = "" file = open(filename, "r") letters = file.readlines() i = 0 length = file_len(filename) while(i < length): cipher = letters[i] message = str(modexp(int(cipher), priv_key, n)) original_message += decode(message) + " " i = i + 1 decoded_message = open("decoded_message.txt", "w+") decoded_message.write(original_message)
def unescrow(privateKey, hashed, salt, hashFunction, workFactor): mpriv = makeMakwaPrivateKey(privateKey) y = decode(hashed) p = mpriv.p q = mpriv.q iq = mpriv.invQ ep = sqrtExp(p, workFactor + 1) eq = sqrtExp(q, workFactor + 1) x1p = pow((y % p), ep, p) x1q = pow((y % q), eq, q) x2p = (p - x1p) % p x2q = (q - x1q) % q xc = [0] * 4 xc[0] = chinese_remainder(p, q, iq, x1p, x1q) xc[1] = chinese_remainder(p, q, iq, x1p, x2q) xc[2] = chinese_remainder(p, q, iq, x2p, x1q) xc[3] = chinese_remainder(p, q, iq, x2p, x2q) for i in range(4): buf = encode(xc[i], len(encode(mpriv.modulus))) k = len(buf) if buf[0] != 0x00: continue u = buf[k - 1] & 0xFF if u > (k - 32): continue tmp = salt + buf[k-1-u:k] S = Makwa(mpriv.modulus, hashFunction, False, 0, workFactor).kdf(tmp, k - u - 2) pi = buf[k - 1 - u:k - 1] flag = False for j in range(len(S)): if S[j] != buf[j + 1]: flag = True break if flag: continue pi = buf[k - 1 - u:k - 1] return pi
def submit_new_song(): payload = encoding.decode(request.data) last_id = r.get('GLOBAL:last-song-id') if last_id is None: last_id = 0 else: last_id = int(last_id) payload['id'] = last_id # Clip as requested segment = read_arbitrary(payload['sound'], format=payload['format']) segment = segment[payload['start-time']:payload['end-time']] r.set('SONG-NAME:%d' % last_id, payload['name']) r.set('SONG-CREDITS:%d' % last_id, payload['credits']) r.set('SONG-DATA-0:%d' % last_id, as_mp3(segment[:len(segment) // 2])) r.set('SONG-DATA-1:%d' % last_id, as_mp3(segment[len(segment) // 2:])) r.set('GLOBAL:last-song-id', last_id + 1) return encoding.encode({'success': True, 'id': last_id})
def main_old(args): stream = open("trace.log", "w") def trace(msg): stream.write(msg) stream.flush() trace("start\n") # for line in sys.stdin: while True: line = sys.stdin.read(5).strip() if not line: break trace("line=%s\n" % line) try: opcode = int(line, 16) trace("opcode=%d\n" % opcode) except ValueError: trace("invalid=%s\n" % line) sys.stdout.write("!%s\n" % line) sys.stdout.flush() continue sys.stdout.write(str(encoding.decode(opcode))) sys.stdout.write("\n") sys.stdout.flush() trace("done\n")
def generatePrivateKey(size): if size < 1273 or size > 32768: raise ValueError('Invalid modulus size: '+str(size)) k = (size - 14) // 4 x = 0 case = (size-14) & 3 if case == 0: x = 7 elif case == 1: x = 8 elif case == 2: x = 10 else: x = 12 sp = [] used = [] bp = [] length = (k+12) >> 3 mz16 = 0xFFFF >> (8 * length - k) mo16 = x << (k + 16 - 8 * length) numMR = computeNumMR(k) numMR2 = computeNumMR(k << 1) flag = True while flag: buf = os.urandom(length) buf = encode(buf[0] & (mz16 >> 8), 1) + buf[1:] buf = encode(buf[0], 1) + encode(buf[1] & mz16,1) + buf[2:] buf = encode(buf[0] | (mo16 >> 8), 1) + buf[1:] buf = encode(buf[0], 1) + encode(buf[1] | mo16,1) + buf[2:] buf = buf[:(length-1)] + encode(buf[length - 1] | 0x01) pj = decode(buf) if isMultipleSmallPrime(pj): continue if not passesMR(pj, numMR): continue flag1=False flag2=False for z in sp: if z == pj: flag1 = True break if flag1: continue for i in range(len(sp)-1,-1,-1): if used[i]: continue pi = sp[i] p = ((pi * pj) << 1) + 1 if not passesMR(p,numMR2): continue if pow(4, pi, p) == 1: continue if pow(4, pj, p) == 1: continue bp.append(p) if len(bp) == 2: flag = False break sp.append(pj) used.append(True) used[i] = True flag2 = True break if not flag: break if flag2: continue sp.append(pj) used.append(False) p = bp[0] q = bp[1] if p < q: t = p p = q q = t mk = MakwaPrivateKey(p, q, 4) if mk.modulus.bit_length() != size: raise ValueError('Key generation error') return mk
def get_mixed(room_id, user_id, tick): song = r.get('ROOM-SONG:%s' % room_id) index = r.get('ROOM-INDEX:%s' % room_id) r.set('USER-LAST-ACTIVE:%s' % user_id, int(time.time())) if index is None: return encoding.encode({'sucess': False, 'reason': 'NO_SUCH_ROOM'}) users = [user.decode('utf-8') for user in r.lrange('ROOM-USERS:%s' % room_id, 0, -1)] user_names = [r.get('USER-NAME:%s' % user).decode('utf-8') for user in users] current_time = time.time() if song is None: #TODO handle disconnection for user in users: last_time = int(r.get('USER-LAST-ACTIVE:%s' % user_id)) # As user that has been gone for 10 seconds # has probably disconnected. if current_time - last_time > 10: r.lrem('ROOM-USERS:%s' % room_id, 0, user) r.delete('USER-AUDIO-0:%s' % user) r.delete('USER-AUDIO-1:%s' % user) return encoding.encode({'success': False, 'users': user_names, 'index': index.decode('utf-8'), 'reason': 'NO_SONG_PLAYING'}) song = int(song) song_data = r.get('SONG-DATA-%d:%d' % (tick % 2, song)) segment = read_mp3(song_data) # Dynamically overlay. for user in users: # Don't give people their own audio if user == user_id: continue user_audio = r.get('USER-AUDIO-%d:%s' % (tick % 2, user)) if user_audio is not None: last_time = int(r.get('USER-LAST-ACTIVE:%s' % user)) # A user who has been absent for an entire repetition # is considered disconnected. if current_time - last_time > len(segment) // 500: r.lrem('ROOM-USERS:%s' % room_id, 0, user) r.delete('USER-AUDIO-0:%s' % user) r.delete('USER-AUDIO-1:%s' % user) user_audio = encoding.decode(user_audio) sound = user_audio['sound'] offset = user_audio['offset'] try: user_segment = read_mp3(sound) except Exception: r.delete('USER-AUDIO-%d:%s' % (tick % 2, user)) continue segment = segment.overlay(user_segment, offset) return encoding.encode({ 'success': True, 'index': index.decode('utf-8'), 'users': user_names, 'sound': as_mp3(segment) })
def watch(self): rpc = new_rpc('HN') w = web.Web() random.seed() tick = 0 next_url = None urls = {} fail_count = 0 datad = {} while True: if fail_count == 0: tick += 1 else: next_url = None if tick == 4 or next_url is None: tick = 1 if not USE_API: next_url = 'https://news.ycombinator.com/newest' elif USE_API == 2: next_url = 'http://hndroidapi.appspot.com/newest' else: next_url = 'http://api.ihackernews.com/new' print next_url if not USE_API: posts = hn_posts(next_url) elif USE_API == 2: try: r = urllib2.urlopen(next_url) data = r.read() ct = r.headers.getparam('charset') data = encoding.decode(data, ct) except: print 'network error' time.sleep(min(2 ** fail_count, 600)) fail_count += 1 continue try: datad = json.loads(data) except: print 'parse error' time.sleep(min(2 ** fail_count, 600)) fail_count += 1 continue posts = datad.get('items', []) else: try: r = urllib2.urlopen(next_url) data = r.read() ct = r.headers.getparam('charset') try: data = data.decode(ct) except: data = data.decode('utf-8') except: print 'network error' time.sleep(min(2 ** fail_count, 600)) fail_count += 1 continue try: datad = json.loads(data) except: print 'parse error' time.sleep(min(2 ** fail_count, 600)) fail_count += 1 continue posts = datad.get('items', []) if len(posts) == 0: next_url = None time.sleep(min(2 ** fail_count, 600)) fail_count += 1 continue fail_count = 0 if not USE_API: if posts[-1].get('title', '') == 'More': next_url = 'https://news.ycombinator.com' + posts[-1].get('url') elif USE_API == 2: next_url = None else: next_url = u'http://api.ihackernews.com/new/%s' % datad.get('nextId', '') points = [(int(post.get('points', 0)), i) for i, post in enumerate(posts)] points.sort() points = list(reversed(points)) for post_id in points: post = posts[post_id[1]] if USE_API == 2: score = post.get('score', 0) try: points = int(score.split(' ', 1)[0]) except: points = 0 post['points'] = points if post.get('points', 0) < 3*tick: continue if post.get('url', '') in urls: continue else: urls[post['url']] = None if post['url'].startswith('http://'): title = w.title(post['url']) subreddit = rpc.get_title_subreddit(title) keywords = rpc.get_title_keywords(title) url = post['url'] if reddit.url_output(title, subreddit, url, rpc): stats = self.rpc.get_learned_stats(title, keywords) rpc.gui_link_add('HN', title, url, subreddit, keywords, **stats) sleep_sec = random.randint(50, 70) sleep_step = sleep_sec / 10.0 for x in range(10): time.sleep(sleep_step)
from keras.models import load_model import numpy as np from encoding import encode from encoding import decode model = load_model('Model-0.1.hf') post_title = input("What do you want to know from u/rogersimon10? \n") post_title = "What’s the worst thing you’ve eaten out of politeness?" encoded_title = np.array(encode(post_title, padding=192)) encoded_title.reshape((-1)) print(encoded_title) print(encoded_title.shape) print(len(encoded_title)) encoded_answer = model.predict(encoded_title) decoded_answer = decode(encoded_answer) print(decoded_answer)
def extract_tstamp(data_arg): decoded = decode(data_arg) decoded_js = json.loads(decoded) return int(decoded_js['TSTAMP'])
def DEC(s): if config.internal_encoding == '2+RST': return encoding.decode(s) else: return unicodedata.normalize('NFC', s)