如何使用伪随机数发生器(PRNG)重新排列36位字符串

时间:2013-10-22 10:13:38

标签: python url encoding random decode

我制作了一个编程和解码长URL的程序。编码将占用n个字符并输出36位字符串。解码将采用36位字符串并输出一个长字符串。

print(decode(encode(1234567890)))
'1234567890'

所以基本上,这会使36位字符串随机化并且解码相反。有没有办法使用伪随机数生成器使种子PRNG的属性可逆,并使用数字的某些不变属性来为PRNG播种。

我知道这些代码的一些部分,这些可能有所帮助。

def ls1b( x ):  

"""Return least significant bit of x that is a one. (Assume x >= 0.)"""

return x & -x

def bitson( x ):

"""Return the number of one bits in x. (Assume x >= 0.)"""

count = 0

while x != 0:

    x &= ~ls1b( x )

    count += 1

return count

这是我的编码和解码。

def token (n):
if n < 10:
    return chr( ord( '0' ) + (n) )
if n in range (10, 36):
    return chr( ord( 'A' ) - 10 + (n))
if n in range (37, 62):
    return chr( ord( 'a' ) - 36 + (n))
if n is 62:
    return '-'
if n is 63:
    return '+'


def encode (n):
a = n // 1 % 64
b = n // 64 % 64
c = n // 64 ** 2 % 64
d = n // 64 ** 3 % 64
e = n // 64 ** 4 % 64
f = n // 64 ** 5 % 64
return (token(a) + token(b) + token(c) + token(d) + token(e) + token(f))



def tokend (d):
x = ord(d)
if 48 <= x <= 57:
    return x - ord('0')
if 65 <= x <= 90:
    return x - ord('A') + 10 
if 97 <= x <= 122:
    return x - ord('a') + 36
if x is 43:
    return ('62')
if x is 45:
    return ('63')


def decode(code, base=64):
    if base>64:
            return 'error: too few symbols'
    code=str(code)
    o=0
    e=0
    for i in code:
            o=o+detoken(i)*base**e
            e=e+1
    while len(str(o))<6:
            o='0'+str(o)
    return o

1 个答案:

答案 0 :(得分:1)

PRNG对于任何给定的种子都是确定性的,所以是的,绝对有可能创建一个函数,该函数使用具有给定种子的PRNG来编码数据,然后如果原始种子和PRNG函数已知则解码该数据。事实上,这就是某些加密功能存在弱点的原因(如手机中的GSM A5 / 1)。

您可以探索创建此类计划(谈到A5 / 1)的一种可能途径是使用Linear Feedback Shift Register。我建议你不要试图创建一些加密安全的东西。如果你想创造一些安全的东西,你不应该发明自己的方案,而是使用现有的经过充分测试的方案。