2013-10-22 24 views
-1

我製作了一個程序來對長URL進行編碼和解碼。編碼將需要n個字符並輸出一個36位字符串。解碼將採用36位字符串並輸出一個長字符串。如何使用僞隨機數生成器(PRNG)重新排列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 
+3

你想縮短像tinyurl的URL嗎?另外,爲什麼解碼輸出「36位」,但編碼需要「6個字符」? – justhalf

+0

如果我理解正確,你正在嘗試做一個可逆的散列函數,對吧?或者,也許像壓縮功能? – matan7890

+0

我已經成功縮短了網址。而且,對不起,我並不是說它只能編碼6個字符。它可以編碼任何長度的字符。我試圖做的是隨機化編碼和解碼操作的輸出。 – eshing10

回答

1

的PRNG是確定性對於任何給定的種子,所以是絕對有可能創建一種使用PRNG與給定的種子以編碼數據的功能,並且然後如果原始種子和PRNG功能是解碼該數據衆所周知。事實上,這就是爲什麼某些密碼功能存在弱點(如手機中的GSM A5/1)。

您可以探索創建這種方案(說A5/1)的一個可能的途徑是使用Linear Feedback Shift Register。我建議這樣做的前提是你並沒有試圖創建一個密碼安全的東西。如果你想創造一些安全的東西,你不應該發明自己的方案,而應該使用現有的經過充分測試的方案。