Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encoded string differs in perl and Java

Tags:

java

base64

perl

when i encode a pdf file into base64 binary(using commons lib) in java , I got string(sample) like "SGVsbG8gV_29y-bGQ="

But if i encode the same file using perl , I got like "SGVsbG8gV/29y+bGQ="

Difference in string: / instead of _ , + instead of -

Why i am getting like this? Or, Is there any way to fix without string replace ?

in java

byte[] data;
        try (java.io.FileInputStream fin = new java.io.FileInputStream(new java.io.File("file.pdf"))) {
            data = new byte[fin.available()];
            fin.read(data);
        }
        return data;
System.out.println("ecncoded value is " + DatatypeConverter.printBase64Binary(data));

In Perl

use MIME::Base64;

open (PDF, "file.pdf") or die "$!";

$raw_string = do{ local $/ = undef; <PDF>; };
$encoded = encode_base64( $raw_string );

print " \n";
print " $encoded ";

// Java

enter image description here

// Perl

enter image description here

like image 548
prashanth-g Avatar asked Jun 17 '26 08:06

prashanth-g


1 Answers

The Java code is giving you URL-safe base64, i.e the output can be used in URLs. The Perl version is not. You can blindly replace the characters with the other values.

like image 197
James Avatar answered Jun 19 '26 21:06

James