问题
I'm working on a Bitcoin brain wallet generator in Perl. I wasn't able to make the last step correctly (base58 encode) to generate the private key (import format).
I have found a very simple bash script that does the job, and I will like to have it translated to Perl so I can make the key generation entirely on Perl.
Can someone help me to translate the following bash code to a Perl sub?
#!/bin/bash
base58=({1..9} {A..H} {J..N} {P..Z} {a..k} {m..z})
bc <<<"ibase=16; n=${1^^}; while(n>0) { n%3A ; n/=3A }" |
tac |
while read n
do echo -n ${base58[n]}
done
Edit: Thank you Barmar! It's closer, but not working. What I did to get the closest result was:
sub encode_base58sp {
    my $in = shift;
    my $out = '';
    my @base58 = (1 .. 9, 'A' .. 'H', 'J' .. 'N', 'P' .. 'Z', 'a' .. 'k', 'm' .. 'z');
    my $n = hex($in);
    while ($n > 1) {
       my $remain = $n % 58;
       $out = $base58[$remain] . $out;
       $n /= 58;
    }
    return $out;
}    
With that I get the first 9 chars okay, but the rest is wrong... Any Idea?
回答1:
use bignum; # Get arbitrary precision arithmetic
# base58=({1..9} {A..H} {J..N} {P..Z} {a..k} {m..z})
my @base58 = (1 .. 9, 'A' .. 'H', 'J' .. 'N', 'P' .. 'Z', 'a' .. 'k', 'm' .. 'z');
# ibase=16; n=${1^^};
my $n = hex($ARGV[0]);
# while(n>0)
my $result = "";
while ($n > 0) {
  # n%3A, tac, and echo ${base58[n]} (hex 3A == dec 58)
  $result = $base58[$n % 58] . $result;
  # n/=3A
  $n /= 58;
}
print "$result\n";
    回答2:
Thank you Barmar,
It worked with "use bigrat;" (Transparent BigNumber/BigRational support for Perl).
Here's the solution (sub based on your translation):
 sub encode_Base58Check {
    use bigrat;
    my $in = shift;
    my $out = '';
    my @base58 = (1 .. 9, 'A' .. 'H', 'J' .. 'N', 'P' .. 'Z', 'a' .. 'k', 'm' .. 'z');
    my $n = hex($in);
    while ($n > 1) {
       $out = $base58[$n % 58] . $out;
       $n /= 58;
    }
    return $out;
}       
Thank you!
来源:https://stackoverflow.com/questions/16114307/simple-translation-from-bash-to-perl-bitcoin-private-key-import-format