in reply to Converting Java to Perl (MD5)

I believe in the Java example you should be applying .getBytes("UTF-8") to the plaintext string; not to the digest. This is because Java strings are UTF-16.

The following two programs both seem to output the same MD5 sum...

use Digest::MD5 'md5_hex'; use Math::BigInt; my $plain = "abcd1234"; my $digest = Math::BigInt::->from_hex(md5_hex $plain); print $digest, "\n";

(Run the above using perl hash.pl.)

import java.security.MessageDigest; import java.math.BigInteger; public class Hash { public static void main( String[] args ) throws Exception { MessageDigest md5 = MessageDigest.getInstance("MD5"); String plain = "abcd1234"; BigInteger digest = new BigInteger(1, md5.digest(plain.getB +ytes("UTF-8"))); System.out.println( digest.abs() ); } }

(Run the above using javac Hash.java && java -cp . Hash.)

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Replies are listed 'Best First'.
Re^2: Converting Java to Perl (MD5)
by kunimihk (Initiate) on Feb 26, 2013 at 01:29 UTC
    Thank you! definitely two programs both seem to output the same MD5 sum
    -----------------------------------------------------------
    Java
    String plain = "abcd1234";
    BigInteger digest = new BigInteger(1, md5.digest(plain.getB +ytes("UTF-8")));

    Perl
    my $plain = "abcd1234";
    my $digest = Math::BigInt::->from_hex(md5_hex $plain);
    -----------------------------------------------------------

    But i want something different
    -----------------------------------------------------------
    Java
    String plain = "abcd1234";
    BigInteger digest = new BigInteger(md5.digest(plain.getB +ytes("UTF-8")));

    Perl
    my $plain = "abcd1234";
    my $digest = Math::BigInt::->from_hex(md5_hex $plain);
    -----------------------------------------------------------
    its two programs output diffrent MD5 sum.. my $digest = Math::BigInt::->from_hex(md5_hex $plain); <--
     

      The one argument form of the Java BigInteger constructor assumes you're passing in a binary two's complement integer.

      Math::BigInt doesn't have a two's complement constructor. You'd need to write one.

      package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
        Oh, I get it. Thank you for your answer!