I am having a problem with the base64_decode output in Perl being truncated

Viewed 91

I am attempting to base64_decode a key that was initially base64 encoded by another program. I am not getting back to the original value which is causing my program to fail. Could someone help me to understand what I am doing incorrectly?

The original key is stored in the file key_e.bin:

hexdump key_e.bin 0000000 8e48 7360 9641 3c4a a2ed d804 2525 c629 0000010 28e2 cb6d 0f60 5a73 b8b0 f7c2 f98b cfaf 0000020 2780 bbea 3860 0a90
0000028

When I use the bash prompt version of base64 it works fine.

base64 -w0 key_e.bin > key_e.b64 cat key_e.b64 SI5gc0GWSjztogTYJSUpxuIobctgD3NasLjC94v5r8+AJ+q7YDiQCg== base64 -d -w0 key_e.b64 > resultant_key_e.bin hexdump resultant_key_e.bin 0000000 8e48 7360 9641 3c4a a2ed d804 2525 c629 0000010 28e2 cb6d 0f60 5a73 b8b0 f7c2 f98b cfaf 0000020 2780 bbea 3860 0a90
0000028

In perl, I do not get this same result. My code:

open IN, '<', "key_e.bin" or die "Can't read key_e.bin file $!";
my $key_e_from_file = <IN>;
close IN;

my $key_e_b64 = encode_base64($key_e_from_file);
print "The base64 encoded key e is:\n\t$key_e_b64\n";

# Now attempt to base64 decode this value
my $key_e_bin = decode_base64($key_e_b64);
open OUT, '>', "key_e_from_perl.bin" or die "Can't write to output file $!";
binmode OUT;
print OUT "key_e_bin";
close OUT;

Back at the bash prompt, I see the b64 version as the same value as before: SI5gc0GWSjztogTYJSUpxuIobctgD3NasLjC94v5r8+AJ+q7YDiQCg== However, the bin file contains incorrect data:

hexdump key_e_from_perl.bin 0000000 8e48 7360 9641 3c4a a2ed d804 2525 c629 0000010 28e2 cb6d 0f60 5a73 b8b0 f7c2 f98b cfaf 0000020 2780 bbea 3860 0090
0000028

Note that byte 0x26 is 00, not 0a.

1 Answers

The code you posted just writes the name of the variable key_e_bin instead of its value to the file key_e_from_perl.bin. If indeed the value is printed, the outcome is correct, provided that a missing use MIME::Base64; is prepended to the code. The described data with only byte 0x26 (actually byte 0x27, since the word's MSB comes second) incorrect must come from a quite different program.

Related