2016-04-14 60 views
3

目前我收到了一個python文件。它有以下代碼(與服務器交互):使用當前時間戳猜測python隨機種子

random.seed(time.time()) 
random.randint(0, 10000) // number 1, server gives me 
random.randint(0, 10000) // number 2, server gives me 
random.randint(0, 10000) // number 3, server gives me 
random.randint(0, 10000) // <- this is the number I have to guess, server does not give to me 

我想猜測正確的種子值,以猜測數字鏈。但time.time()返回浮點數。那麼random.seed會使用多少個點號?我知道,如果種子值是一個整數,它會容易得多,但現在這是一個浮點數,我被卡住了。

+0

您可以閱讀Python源代碼來找出下一個數字。我建議root/Lib/random.py和root/Modules/_randommodule.c –

回答

0

編輯:我的邏輯是關閉... woops。答案依然如此。 random.seed(time.time())似乎使用time.time()生成的舍入數字。

a = time.time() # say print(a) produces 1234567890.123456 
b = 1234567890.123456 

random.seed(a) # this will produce the same seed value as 
random.seed(b) # this 
+0

我不確定它是否會因爲我們在控制檯中輸入time.time()而產生16位數字。如果輸入:print「%.20f」%time.time(),它將在小數點後輸出20位數字。我想知道random.seed的最終號碼會在哪裏停止... – dekhi

0

random.seed()函數使用可哈希對象,並將所述對象的哈希值用於其種子。 (一個例外是intlong,它們直接使用而不用散列,見下面的編輯。)如果你想能夠顯式地設置種子,那麼你需要創建一個可以對其進行哈希控制的可哈希對象。例如:

#!/usr/bin/env python3               

import random 

class HashMe(float): 
    '''                   
    A test for a hashable that can have its hash set by brute force.    
    ''' 
    def __init__(self, hash_val): 
     self.hash_val = hash_val 

    def __hash__(self): 
     return self.hash_val 

a = HashMe(42) 
print('HashMe(42) hashes to: ', a.__hash__()) 

print('\nSeed with a') 
random.seed(a) 
for _ in range(4): 
    print(random.randint(0, 10000)) 

print('\nReseed with random data...') 
random.seed(random.random()) 
for _ in range(4): 
    print(random.randint(0, 10000)) 

print('\nSeed with a again - et voila!') 
random.seed(a) 
for _ in range(4): 
    print(random.randint(0, 10000)) 

產生預期:

HashMe(42) hashes to: 42 

Seed with a 
1824 
409 
4506 
4012 

Reseed with random data... 
9359 
4313 
6609 
6598 

Seed with a again - et voila! 
1824 
409 
4506 
4012 

說了這麼多,就連蹩腳的Python的PRNG週期的長度足夠長,你不可能永遠破譯基於序列猜測種子。

編輯:當然,把它們放在一起後,我瀏覽了Python源代碼,看看如果種子是int或long,它就直接使用seed值,所以不需要可排序的shuck和jive來規避它。活到老,學到老。

+0

我不知道你的意思。但是如果我知道種子,我可以產生相同的數字鏈。這很正常:) – dekhi

+0

當然是。我所說的是,如果你不知道種子,那麼在宇宙熱死之前,用Python進行反覆猜測的機率幾乎爲零。您可以通過查看PRNG來源來反向獲取種子提示,但這仍然是一項非常艱鉅的任務。 Python中的PRNG除了密碼安全以外,其實都不是微不足道的。 –