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

Hi all I have a c# code that i would like to convert to a perl script. can any one help? thanks this is the code:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; public class Program { public static void Main() { var myString = "7512"; var o = CalculateMD5Hash(myString); Console.WriteLine("Generated String is: {0}", o); } public static string CalculateMD5Hash(string input) { HashAlgorithm ha = new MD5CryptoServiceProvider(); string prefix = "MD5:"; string password = ""; UnicodeEncoding enc = new UnicodeEncoding(); password = Convert.ToBase64String(ha.ComputeHash(enc.GetBytes( +input))); return prefix+password; } }

Replies are listed 'Best First'.
Re: convert c# to perl code
by marto (Cardinal) on Jan 01, 2019 at 13:03 UTC
      Hi, Thanks for the reply.
      You are right and i will try to make my self more clear.
      I want to run this code on a linux system, that is, I want to convert a string in the same way.
      I don't know how to accomplish this in perl, and i would appreciate the help.

      when i run the code above on the string "7512" i get:
      cA5YjDeU2fOJwwnVFPCuAw==

      i tried using linux cli and openssl, like this:
      echo -ne "7512" | openssl dgst -md5 -binary | openssl base64

      but i get the following output:
      FhxcWtUfzIhBV4kFEbPIsA==

      do you have any idea how would i do that in perl?
        when i run the code above on the string "7512" i get: cA5YjDeU2fOJwwnVFPCuAw==

        Apparently, UnicodeEncoding encodes to UTF-16LE - at least that's what your sample seems to show. So in Perl, you'll have to use the Encode module for that, and then either use md5_base64 from Digest::MD5, which removes the padding at the end of the string (==), or, if you want the padding, you'll have to use MIME::Base64 separately:

        use warnings; use strict; use Encode qw/encode/; use Digest::MD5 qw/md5/; use MIME::Base64 qw/encode_base64/; my $string = "7512"; my $md5b64 = encode_base64( md5( encode( 'UTF-16LE', $string, Encode::FB_CROAK|Encode::LEAVE_SRC ) ), "" ); print "Generated String is: MD5:$md5b64\n"; my $expect = "cA5YjDeU2fOJwwnVFPCuAw=="; print $md5b64 eq $expect ? "Matches!\n" : "Doesn't match!\n"; __END__ Generated String is: MD5:cA5YjDeU2fOJwwnVFPCuAw== Matches!
Re: convert c# to perl code
by holli (Abbot) on Jan 01, 2019 at 18:34 UTC
    This should compile just fine under Mono. Did you try that?


    holli

    You can lead your users to water, but alas, you cannot drown them.