2012-05-10 18 views
2

我與RC4加密證書的文件, 這件作品的負責寫這樣的證書對文件代碼如下:在Perl中,同時使用RC4我無法找回密文

sub dummyFunction() { 
    # Useless stuff for the scope of the problem 
    # ... 
    my $dbHost = "localhost"; 
    my $passphrase = "123"; # For example purposes, logic is different. 
    my $cipher = Crypt::RC4->new($passphrase); 
    return unpack('H*',$cipher->RC4($dbHost)); 
} 

所以這段代碼會返回類似:3F9FDCE3891C6B8851 ,但如果我嘗試以下方法:

sub anotherDummyFunction() { 
    my $ciphered_text = &dummyFunction(); 
    my $passphrase = "123"; 
    my $cipher = Crypt::RC4->new($passphrase); 
    print $cipher->RC4(pack('H*',$ciphered_text)); 
} 

我期待看到localhost但相反,我得到了一堆字節,所以我會怎麼弄回原文?

我已經在線檢查了一個RC4解密器,用我的密碼和我的十六進制編碼的字符串和RC4在線解密器確實返回localhost,所以我確信加密的字符串是正確的。

謝謝!

P.S.:上面的例子在一個孤立的環境中工作,但是當涉及到我的腳本時,它不會。我無法取回原始字符串。

+2

請勿向我們展示可用的示例代碼,並告訴我們它在某些其他上下文中不起作用。我們唯一知道的是,在你向我們展示的任何東西中,問題*都不是。 – hobbs

+0

我將使用我的心理調試技巧來說明在你的實際腳本中有一些空白已經進入'$ ciphered_text'。 'pack('H *',$ ciphered_text)'不會**只打包十六進制數字;它抓取'$ ciphered_text'中每個字符的低4位,包括空格字符。 – cjm

+0

我已經找到問題的根源。起初我以爲這是一個空白,但事實並非如此。 我之前正在加密另一個字符串,但那個正在被正確加密。 我有一個頓悟,我認爲RC4可以緩存的東西,所以我undef它,它的工作。 – ILikeTacos

回答

0

如果有人遇到這種再次:

如果你有這樣的:


TEST.PL


#!/usr/bin/perl 
use strict; 
use warnings; 
use Crypt::RC4; 

my $cipher = Crypt::RC4->new("passphrase123"); 
print unpack('H*',$cipher->RC4("encrypt-me"))."\n"; 
print unpack('H*',$cipher->RC4("encrypt-me"))."\n"; 

你會發現,你最終會與兩個不同的編碼字符串:

./test.pl 
25d2aa557cccc3951074 
1e87a5db7830a0b1cabd 

爲了避免這種行爲我所做的:

undef $cipher

權試圖加密另一個字符串,然後前再次實例化對象。

如果你試試這個:

my $cipher = Crypt::RC4->new("passphrase123"); 
print unpack('H*',$cipher->RC4("encrypt-me"))."\n"; 
undef($cipher); 
$cipher = Crypt::RC4->new("passphrase123"); 
print unpack('H*',$cipher->RC4("encrypt-me"))."\n"; 

你會得到相同的字符串:

./test.pl 
25d2aa557cccc3951074 
25d2aa557cccc3951074 

這也可以包裹在子過程,以避免定義和遍地取消定義對象。

sub encryptString() 
{ 
    my ($string,$passphrase) = @_; 
    my $cipher = Crypt::RC4->new($passphrase); 
    return unpack('H*',$cipher->RC4($string)); 
} 
+1

讀這個東西,碰到這個。 perl note:'undef($ cipher);'是不必要的分心。刪除它,示例運行顯示相同的輸出('25d2aa557cccc3951074'兩次)。第二個'new'調用正在創建一個「乾淨的」'$ cipher',因此具有與第一個相同的內容/輸出。 – Ashley

+1

謝謝@Ashley。我記得在我與Perl合作的第二天發佈了這篇文章。從那以後,我學到了很多東西! – ILikeTacos