def encode_vault_size(self, lhs, n): v = self.G.get(lhs, {}) n = str(n) try: i = v.keys().index(n) x = sum(v.values()[:i]) y = x + v.values()[i] except ValueError: return convert2group(0, v['__total__']) return convert2group(random.randint(x, y - 1), v['__total__'])
def encode_password(self, password): # 首先得到我们的密码的密码树 ptree = self.lParseTree(password) print("our password is ", end='') print(ptree) if not ptree: print("encode failed,change") # 然后将这个密码树映射到不同的数字中: encd = [] # print(ptree) for each_node in ptree: try: encd.append(self.encode_encd(*each_node)) # print(encd) except ValueError as e: print("Error in encoding: \"{}\"".format(password)) print(e) return [] # 假如不出错的话此时就完成了加密,然后注意此时我们的密码可能没有填充完(因为密码本身过短,我们需要使用空白值来填充) length = PASSWORD_MAX_LENGTH - len(encd) # 此时,如果length的长度还是len(encd),那么说明加密失败,返回空列表 if length == PASSWORD_MAX_LENGTH: return [] for i in range(length): encd.append(convert2group(0, 1)) # 映射完成,返回加密完成的数字 return encd
def generate_and_encode_password(self, size=10): """ Generates and encodes a password of size @size. first choose size+1 random numbers, where first one is to encode the length, and the rest are to encode the passwords """ assert size<self.MAX_ALLOWED, "Size of asked password={}, which is bigger"\ "than supported {}".format(size, self.MAX_ALLOWED) size = max(size, self.MIN_PW_LENGTH) N = random.randints(0, MAX_INT, size + 1) N[0] += (size - self.MIN_PW_LENGTH) - N[0] % ( self.MAX_ALLOWED - self.MIN_PW_LENGTH ) # s.t., N[0] % MAX_ALLOWED = size P = [s[N[i + 1] % len(s)] for i, s in enumerate(self.must_set)] # must set characters P.extend(self.All[n % len(self.All)] for n in N[len(self.must_set) + 1:]) n = random.randint(0, MAX_INT) password = self.decode2string(n, P) N.append(n) extra = hny_config.PASSWORD_LENGTH - len(N) N.extend([convert2group(0, 1) for x in range(extra)]) return password, N
def getVal(arr, val): """ arr -> is a list of values of type same as 'val' and also has a frequency e.g. arr: [['a',0,123], ['asd', 1, 31], ['ADR', 1, 345]] val -> is a value of same type of values in arr, e.g. 'asd' returns: a random number between, cumulative probability of 'asd' and the element just before it, i.e. 'a'. """ c = 0 found = False totalC = 0; t = -1; for i, x in enumerate(arr): # print x c += x[2] totalC += x[2] if not found and x[0] == val: if i == 0: a = 0; else: a = c - x[2] t = random.randint(a, c - 1) found = True print(x, t) if t > -1: # to deal with floating this is used, basically converted the numebrs in # (mod totalC) ASSUMPTION: max value of sum of frequency is # 4,294,967,295, i.e. ~ 4.29 billion!! return convert2group(t, totalC) return t
def encode_grammar(self, G): """ Encodes a sub-grammar @G under the current grammar. Note: Does not record the frequencies. G->[ """ vd = VaultDistPCFG() stack = ['G'] code_g = [] done = list(G.default_keys()) while stack: head = stack.pop() assert head not in done, "head={} already in done={}".format( head, done) done.append(head) rule_dict = G[head] t_set = [] for rhs in rule_dict.keys(): if rhs != '__total__': r = [ x for x in self.get_actual_NonTlist(head, rhs) if x not in done + stack ] for x in r: if x not in t_set: t_set.append(x) t_set.reverse() stack.extend(t_set) n = len(list(rule_dict.keys())) - 1 code_g.append(vd.encode_vault_size(head, n)) if n < 0: print( "Sorry I cannot encode your password ({!r})! \nPlease choose" " something different, like password12!! (Just kidding.)". format((head, list(rule_dict.keys())))) exit(0) assert n == vd.decode_vault_size(head, code_g[-1]), \ "Vault size encoding mismatch.\nhead: {!r}, code_g: {}, n: {}, "\ "decoded_vault_size: {}"\ .format(head, code_g[-1], n, vd.decode_vault_size(head, code_g[-1])) code_g.extend([ self.encode_rule(head, r) for r in rule_dict.keys() if r != '__total__' ]) # i = 0 # for r in rule_dict.keys(): # if r == '__total__': continue # nr = self.decode_rule(head, code_g[-n+i]) # print("Decoding:", code_g[-n+i], head, nr) # i += 1 # if nr != r: # print(">>> Mismatch: nr={}, r={}, code_g={}".format(nr, r, code_g[-n+i])) extra = hny_config.HONEY_VAULT_GRAMMAR_SIZE - len(code_g) code_g.extend(convert2group(0, 1, extra)) return code_g
def encode_pw(self, pw): pt = self.l_parse_tree(pw) try: code_g = [self.encode_rule(*p) for p in pt] except ValueError as ex: print("Error in encoding: {!r}".format(pw)) # raise ValueError(ex) extra = hny_config.PASSWORD_LENGTH - len(code_g) code_g.extend(convert2group(0, 1, extra)) return code_g
def encode_pw(self, pw): pt = self.l_parse_tree(pw) try: code_g = [self.encode_rule(*p) for p in pt] except ValueError: print "Error in encoding: \"{}\"".format(pw) raise ValueError return [] extra = hny_config.PASSWORD_LENGTH - len(code_g); code_g.extend([convert2group(0,1) for x in range(extra)]) return code_g
def main(): dte = DTE() print("Resource:", resource.getrusage(resource.RUSAGE_SELF).ru_maxrss); for p in ['(NH4)2Cr2O7', 'iloveyou69']: c = dte.encode_pw(p) m = dte.decode_pw(c) print("After Decoding(encoding of {}): {}".format(p, m)) for s in range(0000): E = [] E.extend([convert2group(0, 1) for x in range(hny_config.PASSWORD_LENGTH)]) c_struct = struct.pack('%sI' % len(E), *E) m = dte.decode_pw(c_struct) print(s, ":", m)
def encode_rule(self, l, r): rhs_dict = self.G[l] try: i = rhs_dict.keys().index(r) if DEBUG: c = rhs_dict.keys()[i] assert c==r, "The index is wrong" except ValueError: print "'{}' not in the rhs_dict (l: '{}', rhs_dict: {})".format(r, l, self.G[l]) raise ValueError l_pt = sum(rhs_dict.values()[:i]) r_pt = l_pt + rhs_dict[r]-1 return convert2group(random.randint(l_pt,r_pt), rhs_dict['__total__'])
def Encode_spcl(m, grammar): print("Special Encoding::::", m) return None # TODO W = m # break_into_words(m, trie) P = ['%s%d' % (whatchar(w), len(w)) for w in W] E = []; for w, p in zip(W[:-1], P[:-1]): E.append(getVal(grammar['S'], p + ',S')) E.append(getVal(grammar[p], w)); E.append(getVal(grammar['S'], P[-1])) E.append(getVal(grammar[P[-1]], W[-1])); if hny_config.PASSWORD_LENGTH > 0: extra = hny_config.PASSWORD_LENGTH - len(E) E.extend([convert2group(0, 1) for x in range(extra)]) return E
def encode_rule(self, l, r): rhs_dict = self.G[l] try: i = list(rhs_dict.keys()).index(r) if DEBUG: c = list(rhs_dict.keys())[i] assert c == r, "The index is wrong" except ValueError: raise ValueError("'{}' not in the rhs_dict (l: '{}')".format(r, l)) l_pt = sum(list(rhs_dict.values())[:i]) r_pt = l_pt + rhs_dict[r] - 1 assert l_pt <= r_pt, "Rule with zero freq! rhs_dict[{}] = {} (l={})\n{}"\ .format(r, rhs_dict, l, self.G) return convert2group(random.randint(l_pt, r_pt), rhs_dict['__total__'])
def encode_pw(self, pw): p = list(pw[:]) must_4 = [DTE_random.get_char(p, m) for m in must_set] for x in must_4: del p[x[0]] pw_random_order = DTE_random.decode2string( random.randint(0, self.fact_map[len(p) - 1]), p) code_g = [random.randint(0, MAX_INT/self.MAX_ALLOWED) * \ self.MAX_ALLOWED + len(pw)] for i, x in enumerate(must_4): code_g.append(DTE_random.get_random_for_this(x[1], must_set[i])) for p in pw_random_order: code_g.append(DTE_random.get_random_for_this(p, All)) code_g.append(encode2number(pw)) extra = hny_config.PASSWORD_LENGTH - len(code_g) code_g.extend([convert2group(0, 1) for x in range(extra)]) return code_g
def main(): dte = DTE() scanner = Scanner() print "Resource:", resource.getrusage(resource.RUSAGE_SELF).ru_maxrss #p='(NH4)2Cr2O7' # sys.stdin.readline().strip() p = u'iloveyou69' c = Encode(p, scanner, dte) #print "Encoding:", c m = Decode(c, dte) # print "After Decoding:", m #return # if PASSWORD_LENGTH>0: for s in range(0000): E = [] E.extend([convert2group(0, 1) for x in range(PASSWORD_LENGTH)]) c_struct = struct.pack('%sI' % len(E), *E) m = Decode(c_struct, dte) print s, ":", m
def encode_grammar(self, G): """ Encodes a sub-grammar @G under the current grammar. """ vd = VaultDistPCFG() stack = ['G'] code_g = [] done = list(G.default_keys()) while stack: head = stack.pop() assert head not in done, "head={} already in done={}".format(head, done) done.append(head) rule_dict = G[head] t_set = [] for rhs, f in rule_dict.items(): if rhs != '__total__': r = filter(lambda x: x not in done+stack, self.get_actual_NonTlist(head, rhs)) if r: for x in r: if (x not in t_set): t_set.append(x) t_set.reverse() stack.extend(t_set) n = len(rule_dict.keys())-1 code_g.append(vd.encode_vault_size(head, n)) if n<0: print "Sorry I cannot encode your password ('{}')! \nPlease choose"\ " something different, like password12".format((head, rule_dict.keys())) exit(0) assert n == vd.decode_vault_size(head, code_g[-1]), "Vault size encoding mismatch. "\ "\nhead: \"{}\", code_g: {}, n: {}, decoded_vault_size: {}"\ .format(head, code_g[-1], n, vd.decode_vault_size(head, code_g[-1])) code_g.extend([self.encode_rule(head, r) for r in rule_dict.keys() if r != '__total__']) extra = hny_config.HONEY_VAULT_GRAMMAR_SIZE - len(code_g); code_g.extend([convert2group(0,1) for x in range(extra)]) return code_g
def encode_encd(self, l, r): # 临时字典,存储此l规则对应的值 rhs_dict = self.G[l] # print(rhs_dict[r]) # 然后获得r的下标 i = list(rhs_dict.keys()).index(r) # 然后开始循环,将其之前的数字进行相加 l_hs = 0 r_hs = 0 for each_index in range(i): l_hs += list(rhs_dict.values())[each_index] # 然后记录下随机数的右侧 r_hs = l_hs + rhs_dict[r] - 1 # 最后调用随机函数,生成介于两者之间的随机数(这里记得把最大值也放上) rn = random.randint(l_hs, r_hs) # print("l_hs is %d,r_hs is %d and the random is %d"%(l_hs,r_hs,rn)) # wn = rn + random.randint(0, int((3000000-rn)/rhs_dict['__total__'])) * rhs_dict['__total__'] wn = convert2group(rn, rhs_dict['__total__']) # print("the wn is %d and it come back is %d"%(wn,wn%rhs_dict['__total__'])) return wn