Search code examples
perlencryptionopenssldollar-sign

Openssl string decryption in Perl


I have a Perl script which takes a input string. The string contains $'s sign in it. The string is encrypted using openssl and decrypted back. enc and dec are the encrypted and decrypted strings in the below code snippet.

#! /usr/bin/perl
use strict;
use warnings;

my $input = 'build:$6$n2cR7cY/$aKv6qQRWjYMIQIyAdTsw6nPtMzEZoqHziqyrL9sn/m29k5mkQjgcwZarA.8lAte6mmDGakipjetuCiH9YF2fF0:16736:0:99999:7:::';

print "Input: $input\n";
my $enc = `openssl enc -base64 -A <<< $input`;
print "Encrypted Output: $enc\n";
my $dec = `openssl enc -base64 -A -d <<< $enc`;
print "Decrypted Output: $dec\n";

Output:

# ./temp.pl
Input: build:$6$n2cR7cY/$aKv6qQRWjYMIQIyAdTsw6nPtMzEZoqHziqyrL9sn/m29k5mkQjgcwZarA.8lAte6mmDGakipjetuCiH9YF2fF0:16736:0:99999:7:::
Encrypted Output: YnVpbGQ6Ly9tMjlrNW1rUWpnY3daYXJBLjhsQXRlNm1tREdha2lwamV0dUNpSDlZRjJmRjA6MTY3MzY6MDo5OTk5OTo3Ojo6Cg==
Decrypted Output: build://m29k5mkQjgcwZarA.8lAte6mmDGakipjetuCiH9YF2fF0:16736:0:99999:7:::

The issue I am facing is the decrypted string is not same as input string provided to encryption. I see all the characters after $ are removed. May I know what $ resembles here and how can I retain entire string back ?


Solution

  • If you want to encode and decode Base 64 strings then you should use the MIME::Base64 module

    The code would look like this

    use strict;
    use warnings;
    
    use MIME::Base64;
    
    my $input = 'build:$6$n2cR7cY/$aKv6qQRWjYMIQIyAdTsw6nPtMzEZoqHziqyrL9sn/m29k5mkQjgcwZarA.8lAte6mmDGakipjetuCiH9YF2fF0:16736:0:99999:7:::';
    
    print "Input: $input\n\n";
    
    my $enc = encode_base64($input);
    print "Encrypted Output: $enc\n";
    
    my $dec = decode_base64($enc);
    print "Decrypted Output: $dec\n";
    

    output

    Input: build:$6$n2cR7cY/$aKv6qQRWjYMIQIyAdTsw6nPtMzEZoqHziqyrL9sn/m29k5mkQjgcwZarA.8lAte6mmDGakipjetuCiH9YF2fF0:16736:0:99999:7:::
    
    Encrypted Output: YnVpbGQ6JDYkbjJjUjdjWS8kYUt2NnFRUldqWU1JUUl5QWRUc3c2blB0TXpFWm9xSHppcXlyTDlz
    bi9tMjlrNW1rUWpnY3daYXJBLjhsQXRlNm1tREdha2lwamV0dUNpSDlZRjJmRjA6MTY3MzY6MDo5
    OTk5OTo3Ojo6
    
    Decrypted Output: build:$6$n2cR7cY/$aKv6qQRWjYMIQIyAdTsw6nPtMzEZoqHziqyrL9sn/m29k5mkQjgcwZarA.8lAte6mmDGakipjetuCiH9YF2fF0:16736:0:99999:7:::