2010-08-06 54 views
1

是否有可能採取的摘要像轉換消化以base10

my $digest = Digest::SHA->new('sha1')->add('hello')->digest; 

,然後創建轉換$digest以base10(而不是十六進制或Base64?),或者你可以分割hexdigest成5 pieces,然後轉換那些成整數?那會有用嗎?試圖想出一種方法將摘要作爲整數存儲(是的,我知道有人會認爲我瘋了或愚蠢,可能都是這樣)。根據需要

更新

理論上我應該能夠採取最終編碼整數輸出和反向和重新編碼爲十六進制和BASE64。

回答

3

我覺得pack & unpack很可能會更有效:

use Digest::SHA; 

my $digest = Digest::SHA->new('sha1')->add('hello')->digest; 
my @ints = unpack('N*', $digest); 
print "@ints\n"; 

my $redone = pack('N*', @ints); 

print "match\n" if $digest eq $redone; 

my $hexdigest = sprintf '%08x' x @ints, @ints; 
print "$hexdigest\n"; 
printf "%s\n", Digest::SHA->new('sha1')->add('hello')->hexdigest; 

use MIME::Base64 'encode_base64'; 
my $b64digest = encode_base64(pack('N*', @ints)); 
print $b64digest; 
printf "%s\n", Digest::SHA->new('sha1')->add('hello')->b64digest; 

輸出:

2868168221 3703957666 3669941775 994585817 2930328397 
match 
aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d 
aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d 
qvTGHdzF6KLavt4PO0gs2a6pQ00= 
qvTGHdzF6KLavt4PO0gs2a6pQ00 

請注意,MIME::Base64填充結果,並且b64digest方法沒有。但是如果需要的話,很容易就可以去掉尾隨的=

0

這樣的事情,也許?

#!/usr/bin/perl 

use strict; use warnings; 
use Digest::SHA; 
use YAML; 

my $digest = Digest::SHA->new('sha1')->add('hello')->hexdigest; 
print "$digest\n"; 
print Dump [ map { [$_, hex] } $digest =~ /([[:xdigit:]]{8})/g ]; 

輸出:

aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d 
--- 
- 
    - aaf4c61d 
    - 2868168221 
- 
    - dcc5e8a2 
    - 3703957666 
- 
    - dabede0f 
    - 3669941775 
- 
    - 3b482cd9 
    - 994585817 
- 
    - aea9434d 
    - 2930328397
+0

類似解決方案我已經破解了(雖然可能因地圖而更好)可以顛倒嗎?通過顛倒我的意思是我可以把它從整數,並得到它的base64編碼(這是相同的摘要base64編碼),如果我想? – xenoterracide 2010-08-06 04:55:54

4

如果無論你要能夠處理任意精度的整數毫不畏縮(是的,unikely,但你永遠不知道),那麼你可以只編碼它作爲一個整數)

$ re.pl 
$ use Digest::SHA; use Math::BigInt; 

$ my $hex = Digest::SHA->new("SHA-1")->add("hello")->hexdigest; 
aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d 
$ Math::BigInt->from_hex("0x" . $hex)->bstr 
975987071262755080377722350727279193143145743181 
$ Math::BigInt->new("975987071262755080377722350727279193143145743181")->as_hex 
0xaaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d