4

What methods are available to translate a base64-encoded file using Perl?

I want to view and edit the file.

$ file base64result 
base64result:   XML document

$ls -l base64result 
-rw-r--r--   1 dpadmin  appadmin     52K Oct 28 12:57 base64result

This is what I tried so far, but did not work:

#!/bin/perl

###################################################
# decode_base64.pl:
###################################################

use strict;
use MIME::Base64 qw( decode_base64 );

open INFILE,  '<', $ARGV[0];
open OUTFILE, '>', $ARGV[1];
binmode OUTFILE;
my $buf;
while ( $buf = <INFILE> ) {
    print OUTFILE decode_base64($buf);
}

close OUTFILE;
close INFILE;

Output:

$cat base64output
Æioz»"¢z{Äž÷¥¢—±šYìz{
letakeda
  • 155
  • 3
  • 12
  • Could you expand a little on transforming the file? – octopusgrabbus Oct 29 '13 at 12:36
  • I want to decode it from base64. base64 formatted is unreadeble. I want to be able to read it and edit, etc. Not sure if I'm being clear here? am I? – letakeda Oct 29 '13 at 12:42
  • What have you investigated so far? You'll want to add that to your original post, not as a comment. Do you want to translate this file to ASCII content? Do you want DOS or Unix file format (less important than translating from base 64, but still a possible question). You can start here http://www.caveofprogramming.com/articles/perl/perl-base64/ I searched using "perl base64 decode" and got quite a few hits. – octopusgrabbus Oct 29 '13 at 12:45
  • You are right, I need to provide more details. Please see what I've updated and check it's better now. Thank you! – letakeda Oct 29 '13 at 12:51
  • I'm hoping a Perl expert will answer this. I'm not quite sure what's going on. – octopusgrabbus Oct 29 '13 at 12:58
  • Base64 is a way of encoding data, including binary data, into characters that can reliably be sent by email or similar. The Base64 encoded string normally uses simple printing characters. The upper (A-Z) and lower case (a-z) letters plus the digits (0-9) give 62 characters. Two more characters (commonly `+` and `/`) complete the 64. The output generated by your command is probably correct, but may make more sense if used by something other than a print (as text) statement. – AdrianHHH Oct 29 '13 at 15:08

1 Answers1

6

Your code is correct (though I improved it below), and the fact that you got no error means the file was valid base64. You got was was there to be had.

$ cat decode_base64.pl
#!/usr/bin/perl

use strict;
use warnings;

use MIME::Base64 qw( decode_base64 );

binmode STDOUT;
while ( my $buf = <> ) {
    print decode_base64($buf);
}

$ echo 'Hello, World!' | base64
SGVsbG8sIFdvcmxkIQo=

$ echo 'Hello, World!' | base64 | decode_base64.pl
Hello, World!

If you are expecting something different, then your expectations are wrong.

If you are want to get something different, you'll need to change the data you provide.

ikegami
  • 367,544
  • 15
  • 269
  • 518