rmichael has asked for the wisdom of the Perl Monks concerning the following question:

Perl's MIME::Base64::encode() generates 76-character lines. I would like to generate 64-character lines (PEM format base64). The encode method does not have a line length parameter.

It appears I could use Convert::PEM to specifically generate PEM content, although in that case, I need to investigate ASN.1 descriptions too.

I don't have much history with Perl, so before I dive in I wanted to ask for suggestions. Thank you!

Replies are listed 'Best First'.
Re: How to generate 64-character length lines in base64?
by thundergnat (Deacon) on Mar 19, 2013 at 13:45 UTC

    Specify a blank eol character when you encode it, then break it up however you want.

    Update: oops, removed bogus double quotes

    use MIME::Base64; my $str = 'Whatever'; my $encoded = encode_base64($str, ''); $encoded =~ s/(.{1,64})/$1\n/g; print $encoded;

      Thank you!

      I did wonder about this, but was unsure about '=' padding if/when required. encode with the default EOL would handle that for me, I believe. Perhaps breaking it up myself could necessitate change some line endings?

      I'll read a few more spec details and play with this.

Re: How to generate 64-character length lines in base64?
by kschwab (Vicar) on Mar 19, 2013 at 21:30 UTC
    MIME::Base64 is a very small module, and the encode method is particularly small, since pack() does most of the work. They use pack to create a uuencoded string, then tr// to translate from the uuencode charset to the Base64 charset: Copying the source, then, with a few minor modifications
    sub b6464 { my $orig=shift; my $string = pack("u",$orig); $string =~ s/^.//mg; $string =~ s/\n//g; # use tr to translate from UUE to Base64 $string =~ tr|` -_|AA-Za-z0-9+/|; # fix padding at the end my $padding = (3 - length($orig) % 3) % 3; $string =~ s/.{$padding}$/'=' x $padding/e if $padding; # break string into lines of 64 chars or less $string =~ s/(.{1,64})/$1\n/g; return $string; }

      I've got a bit of time now, and am looking at this again.

      Thank you for your help!