How do I Generate MD5 Hash

Asked

Viewed 173 times

2

We need to generate an MD5 hash to pass an encrypted password. Could someone give us an example?

  • 1

    I do not understand Java so I have no way to answer. But I need to leave this here: MD5 is not a form of encryption. If you want to "pass" a password and need the MD5 so it is not seen, you have two serious security holes at hand.

2 answers

1


tries to run this example class:

 public class DigestTest extends MainWindow
{
   private Edit edtInput;
   private ComboBox cboDigests;
   private Button btnGo;
   private ListBox lboResults;
   private Object[] comboItems;

   public DigestTest()
   {
      super("Digest Test", TAB_ONLY_BORDER);

      try
      {
         comboItems = new Object[] {new MD5Digest(), new SHA1Digest(), new SHA256Digest()};
      }
      catch (NoSuchAlgorithmException e)
      {
         e.printStackTrace();
      }
   }

   public void initUI()
   {
      edtInput = new Edit();
      edtInput.setText("0123456789ABCDEF");
      cboDigests = new ComboBox(comboItems);
      cboDigests.setSelectedIndex(0);
      btnGo = new Button("Go!");
      lboResults = new ListBox();
      lboResults.enableHorizontalScroll();

      add(edtInput, LEFT + 2, TOP + 2, FILL - (btnGo.getPreferredWidth() + cboDigests.getPreferredWidth() + 6), PREFERRED);
      add(cboDigests, AFTER + 2, SAME, PREFERRED, PREFERRED);
      add(btnGo, AFTER + 2, SAME, PREFERRED, PREFERRED);
      add(lboResults, LEFT + 2, AFTER + 2, FILL - 2, FILL - 2);
   }

   public void onEvent(Event e)
   {
      switch (e.type)
      {
         case ControlEvent.PRESSED:
            if (e.target == btnGo)
            {
               Digest alg = (Digest)cboDigests.getSelectedItem();
               String message = edtInput.getText();

               alg.reset();
               alg.update(message.getBytes());
               byte[] digest = alg.getDigest();

               lboResults.add("Message: " + message);
               lboResults.add("Digest: " + Convert.bytesToHexString(digest) + " (" + digest.length + " bytes)");
               lboResults.add("=========================");
               lboResults.repaintNow();
            }
            break;
      }
   }
}

1

Take a look at the code below:

public static String toMD5(byte[] bytes){

    MessageDigest md = null;

    try {
        md = MessageDigest.getInstance("MD5");   
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    md.update(bytes);

    BigInteger hash = new BigInteger(1, md.digest()); 

    return hash.toString(16);    
} 

See you around.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.