Search code examples
javarubyencryptionmd5

How to translate custom md5 password + salt function in java to ruby?


I have the following java function:

public static String customPasswordFunction(String value, String salt) {
    
    byte[] input = null;
    
    try {
        byte[] valueBytes = value.getBytes();
        byte[] saltBytes = salt.getBytes();

        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.reset();
        digest.update(saltBytes);
        input = digest.digest(valueBytes);
        for(int i=0; i < 1000; i++) {
            digest.reset();
            input = digest.digest(input);
        }
    }
    catch (NoSuchAlgorithmException ex) {
        logger.error(ex.toString(), ex);        
        return null;
    }
    
    //convert digest to alphanumeric
    String alphaNumReturn = "";
    String tmp = null; 
    for (int i = 0; i < input.length; i++) {
        tmp = (Integer.toHexString(0xFF & input[i]));
        if (tmp.length() == 1) {
            alphaNumReturn += "0" + tmp;
        }
        else {
            alphaNumReturn += tmp;
        }
    }

    return alphaNumReturn;
}

We have the quick ability in ruby to hash the salt and password as follows:

hashed_password = OpenSSL::Digest::MD5.hexdigest(salt+password)

But how would I re-produce the following java code in ruby?

    for(int i=0; i < 1000; i++) {
        digest.reset();
        input = digest.digest(input);
    }

Solution

  • So I don't know Java but it appears this part

    digest = MessageDigest.getInstance("MD5");
    digest.reset();
    digest.update(saltBytes);
    input = digest.digest(valueBytes);
    for(int i=0; i < 1000; i++) {
      digest.reset();
      input = digest.digest(input);
    }
    

    Should translate to

    require 'digest'
    digest = Digest::MD5.new
    digest.reset.update(salt)
    input = digest.digest(value)
    input = 1000
      .times
      .reduce(input) do |input,_|
        digest.reset.digest(input)
      end
    

    Docs:

    As a sidenote: MD5 is a hashing algorithm not an encryption.