2017-08-26 83 views
0

我試圖將Python腳本轉換爲PowerShell,並且我正在理解Python腳本中的循環中發生了什麼。這是一個Python腳本的例子。將Python循環轉換爲PowerShell

import time 

def obfuscateApiKey() : 
    seed = 'f1avad34567a' 
    now = str(long(time.time() * 1000)) 
    n = now[-6:] 
    r = str(int(n) >> 1).zfill(6) 
    key = "" 
    for i in range(0, len(n), 1): 
     key += seed[int(n[i])] 
    for j in range(0, len(r), 1): 
     key += seed[int(r[j])+2] 

    print "Timestamp:%s  Key:%s" % (now, key) 

obfuscateApiKey() 

這是我想出迄今PowerShell的轉換,但我沒有任何的Python經驗,並已碰了壁瞭解什麼是發生在環。

$seed = 'f1avad34567a' 
$Now = ([int](get-date -UFormat %s) *1000).ToString() 
$n = $now.Substring([math]::Max(0, $now.Length – 6)) 
$r = $n -shr 1 
$key = @() 

任何人都有關於如何在PowerShell中執行此部分的提示?

for i in range(0, len(n), 1): 
    key += seed[int(n[i])] 
for j in range(0, len(r), 1): 
    key += seed[int(r[j])+2] 
+2

正如一個方面說明,'範圍(0,LEN(n)的,1)'只是'範圍(LEN(n))的'。 –

回答

1

這是如何混淆密鑰的?它不需要參數,取決於當前時間,因此它看起來不可逆並且不可重複。如果唯一的東西是「可驗證的」 - 即其他人可以讀取打印的時間戳,則知道種子並檢查生成的密鑰。如果這是真的,說運行一次是非常誘人的,只需要用永久有效的固定打印語句'Timestamp:1503715652844 Key:3da5aada53aa'替換該函數。

原件:

def obfuscateApiKey(): 
    seed = 'f1avad34567a'    # string 
    now = str(long(time.time() * 1000)) # current timestamp with 
             # milliseconds rolled in, as string 
    n = now[-6:]      # last 6 chars 
    r = str(int(n) >> 1).zfill(6)  # right bit shift 1 and 
             # left pad to len 6 with zeros 

    key = ""       # empty string 

    for i in range(0, len(n), 1):  # 0,1,2,3,4,5 (because n is len 6) 
     key += seed[int(n[i])]   # string index in n, lookup in seed 

    for j in range(0, len(r), 1):  # 0,1,2,3,4,5 again (?), r is len 6 
     key += seed[int(r[j])+2]  # string index in r, lookup in seed 

    print "Timestamp:%s  Key:%s" % (now, key) # print 

的PowerShell:

$seed = 'f1avad34567a' 

# Bit of a mess, to handle get-date returning local time 
# but Unix timestamps needing to be in UTC timezone 
$now = [string][math]::Floor([double](Get-Date -Date (Get-Date).ToUniversalTime() -UFormat %s) * 1000) 

# Your substring line 
$n = $now.Substring([math]::Max(0, $now.Length–6)) 

# Your shift-right, but $n was a string, so convert to [int] 
# and PadLeft is the equivalent of zfill 
$r = "$([int]$n -shr 1)".PadLeft(6, '0') 

# string concatenation works in PS, for small uses it's fine. 
$key = '' 

# The loops and indexing almost translate. I've made them fixed 
# ranges because it seems the lengths of the strings are fixed. 
# The casting is awkward, but the result of looking up a character 
# from a string is type [char] and they cast to int as the 
# ascii/unicode codepoint value, not the numeric value of the content. 
0..5 | ForEach-Object { 
    $key += $seed[[int][string]$n[$_]] 
} 

0..5 | ForEach-Object { 
    $key += $seed[[int][string]$r[$_]+2] 
} 

'Timestamp:{0} Key:{1}' -f $now, $key 
+0

這很好,我真的很感謝所有的細節和解釋。提交帖子時,它包含時間戳和密鑰。他們知道種子。如果時間戳超過兩個小時,則不會被接受。 我不太確定使用'zfill'。如果'n'取自'now'的最後6個字符,那麼由於'zfill'中的寬度是6,所以原始字符串不會始終返回嗎? – YEMyslf