def int_str(val, keyspace):
""" Turn a positive integer into a string. """
assert val >= 0
out = ""
while val > 0:
val, digit = divmod(val, len(keyspace))
out += keyspace[digit]
return out[::-1]
def str_int(val, keyspace):
""" Turn a string into a positive integer. """
out = 0
for c in val:
out = out * len(keyspace) + keyspace.index(c)
return out
def chaffify(val, chaff_size = 150, chaff_modulus = 7):
""" Add chaff to the given positive integer.
chaff_size defines how large the chaffing value is; the larger it is, the larger (and more unwieldy) the resulting value will be.
chaff_modulus defines the modulus value for the chaff integer; the larger this is, the less chances there are for the chaff validation in dechaffify() to yield a false "okay".
"""
chaff = random.randint(0, chaff_size / chaff_modulus) * chaff_modulus
return val * chaff_size + chaff
def dechaffify(chaffy_val, chaff_size = 150, chaff_modulus = 7):
""" Dechaffs the given chaffed value. The chaff_size and chaff_modulus parameters must be the same as given to chaffify() for the dechaffification to succeed.
If the chaff value has been tampered with, then a ValueError will (probably - not necessarily) be raised. """
val, chaff = divmod(chaffy_val, chaff_size)
if chaff % chaff_modulus != 0:
raise ValueError("Invalid chaff in value")
return val
for x in xrange(1, 11):
chaffed = chaffify(x)
print x, chaffed, dechaffify(chaffed)
def chaffify2(val, chaff_val = 87953):
""" Add chaff to the given positive integer. """
return val * chaff_val
def dechaffify2(chaffy_val, chaff_val = 87953):
""" Dechaffs the given chaffed value. chaff_val must be the same as given to chaffify2(). If the value does not seem to be correctly chaffed, raises a ValueError. """
val, chaff = divmod(chaffy_val, chaff_val)
if chaff != 0:
raise ValueError("Invalid chaff in value")
return val
考虑到您的需求,最好的选择是使用itertools.combinations有点像这样
对整数进行编码
您可以对整数使用可逆编码:
快速测试代码:
^{pr2}$输出
混淆它们并使它们成为非连续的
要使ID不连续,可以将原始值与任意值相乘,然后添加随机“chaff”作为要丢弃的数字—在我的示例中,使用简单的模数检查:
输出(随机):
编辑:再想一想,箔条的随机性可能不是一个好主意,因为你失去了每个混淆ID的典型性——这缺乏随机性,但仍有有效性(如果
chaff_val
足够大,更改一个数字可能会使整数无效)。在把它们放在一起
输出(随机)
可能比你想的长一点。在
如果使用的是sqlalchemy,那么可以定义一个uuid类型的id列,如下所示
^{pr2}$如果您使用的是Django,那么Preet的答案可能更合适,因为Django的很多东西都依赖于int的主键。在
相关问题 更多 >
编程相关推荐