MD5 là gì? Code ví dụ MD5 với Java

MD5 là gì? Code ví dụ MD5 với Java.

(Xem thêm: SHA là gì? Code ví dụ SHA1, SHA2 với Java)

(Xêm thêm: Bcrypt là gì? Code ví dụ BCrypt bằng Java – JBCrypt)

MD5 là gì?

MD5 (Message-Digest algorithm 5) là một hàm băm (thuật toán băm/hash) không khóa.

Tất cả đầu vào (file, text,…) sau khi được băm bằng thuật toán MD5 sẽ cho ra một chuỗi đầu ra 128bit và thường được biểu diễn thành 32 số hexa.

Ứng dụng của MD5:

  • Đảm bảo tính toàn vẹn, tạo chuỗi kiểm tra lỗi. (Ví dụ khi download 1 file trên mạng bạn thường thấy người ta cung cấp kèm 1 chuỗi MD5 tương ứng, sau khi download về ta sẽ băm lại file để kiểm tra chuỗi MD5 có bị thay đổi không, nếu đã bị thay đổi tức là trong quá trình download file đã bị thiếu một phần nào đó hoặc file đã bị chỉnh sửa (chèn virus, crack…)).
  • Mã hóa mật khẩu. (Các thông tin nhạy cảm như mật khẩu, thẻ ngân hàng… thường sẽ được mã hóa trước khi lưu vào database, nếu hacker truy cập được vào database cũng sẽ không lấy được các thông tin đó. Khi sử dụng, ví dụ khi đăng nhập ta sẽ băm mật khẩu thành một chuỗi MD5 và so sánh nó với chuỗi MD5 trong database để xác thực)

Code ví dụ MD5

Để băm một đối tượng trong Java sử dụng MD5 ta sử dụng class java.security.MessageDigest. Nó nhận đầu vào là một mảng byte và kết quả trả về là một mảng byte đã được băm.

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(dataInput);
byte[] hashedData= md.digest();

Sau đó để hiển thị ta sẽ chuyển mảng byte sau khi băm thành một chuỗi hexa.

Ở đây mình giới thiệu 3 cách để chuyển mảng byte sang dạng hexa:

public static String convertByteToHex1(byte[] data) {
  BigInteger number = new BigInteger(1, data);
  String hashtext = number.toString(16);
  // Now we need to zero pad it if you actually want the full 32 chars.
  while (hashtext.length() < 32) {
    hashtext = "0" + hashtext;
  }
  return hashtext;
}

public static String convertByteToHex2(byte[] data) {
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < data.length; i++) {
    sb.append(Integer.toString((data[i] & 0xff) + 0x100, 16).substring(1));
  }
  return sb.toString();
}

public static String convertByteToHex3(byte[] data) {
  StringBuffer hexString = new StringBuffer();
  for (int i = 0; i < data.length; i++) {
    String hex = Integer.toHexString(0xff & data[i]);
    if (hex.length() == 1)
      hexString.append('0');
    hexString.append(hex);
  }
  return hexString.toString();
}

Nếu muốn băm text thì ta chuyển text sang dạng byte, một băm file thì ta đọc file thành mảng byte và thực hiện băm.

Ví dụ băm text:

public static String getMD5(String input) {
  try {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] messageDigest = md.digest(input.getBytes());
    return convertByteToHex1(messageDigest);
  } catch (NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}

Ví dụ băm file:

public static String getMD5(File file) {
  MessageDigest md;
  try {
    md = MessageDigest.getInstance("MD5");
    FileInputStream fis = new FileInputStream(file);
    byte[] dataBytes = new byte[1024];
    int nread = 0;
    while ((nread = fis.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    }
    byte[] byteData = md.digest();
    fis.close();
    return convertByteToHex1(byteData);
  } catch (NoSuchAlgorithmException | IOException e) {
    e.printStackTrace();
    throw new RuntimeException(e);
  }
}

Demo:

package stackjava.com.demomd5.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Hashing {
  public static void main(String[] args) throws Exception {
    String password = "stackjava.com";
    String hashedText = getMD5(password);
    System.out.println("Digest(in hex format): " + hashedText);
  }

  public static String getMD5(String input) {
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      byte[] messageDigest = md.digest(input.getBytes());
      return convertByteToHex(messageDigest);
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
  }

  public static String getMD5(File file) {
    MessageDigest md;
    try {
      md = MessageDigest.getInstance("MD5");
      FileInputStream fis = new FileInputStream(file);
      byte[] dataBytes = new byte[1024];
      int nread = 0;
      while ((nread = fis.read(dataBytes)) != -1) {
        md.update(dataBytes, 0, nread);
      }
      byte[] byteData = md.digest();
      fis.close();
      return convertByteToHex(byteData);
    } catch (NoSuchAlgorithmException | IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }

  public static String convertByteToHex(byte[] data) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < data.length; i++) {
      sb.append(Integer.toString((data[i] & 0xff) + 0x100, 16).substring(1));
    }
    return sb.toString();
  }


}

Kết quả:

Digest(in hex format): 29c4fdeeb3e62a969f69ad4601589fac

Demo ứng dụng băm file, text bằng MD5 – Java.

package stackjava.com.demomd5.demo;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.Font;

public class MainApp extends JFrame {

  private static final long serialVersionUID = 1L;
  private JPanel contentPane;
  private JPanel panel;
  private JLabel lblInputText;
  private JTextArea textAreaResult;
  private JButton btnHashingText;
  private JTextArea textAreaInput;
  private JPanel panel_1;
  private JButton btnOpenFile;
  private JTextField textFieldFileUrl;
  private JButton btnHashingFile;
  private JTextArea textAreaFileHashing;
  private File file;

  /**
   * Launch the application.
   */
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        try {
          MainApp frame = new MainApp();
          frame.setVisible(true);
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }

  /**
   * Create the frame.
   */
  public MainApp() {
    setTitle("MD5 Hashing - stackjava.com");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 680, 436);
    this.contentPane = new JPanel();
    this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(this.contentPane);
    this.contentPane.setLayout(null);
    
    this.panel = new JPanel();
    this.panel.setBorder(new TitledBorder(null, "Hashing String", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    this.panel.setBounds(10, 11, 644, 187);
    this.contentPane.add(this.panel);
    this.panel.setLayout(null);
    
    this.lblInputText = new JLabel("Input Text:");
    this.lblInputText.setBounds(10, 29, 93, 25);
    this.panel.add(this.lblInputText);
    
    this.textAreaResult = new JTextArea();
    this.textAreaResult.setBounds(385, 61, 249, 115);
    this.panel.add(this.textAreaResult);
    
    this.btnHashingText = new JButton("Generate >>");
    this.btnHashingText.setFont(new Font("Arial", Font.PLAIN, 12));
    this.btnHashingText.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String input = textAreaInput.getText();
        String result = MD5Hashing.getMD5(input);
        textAreaResult.setText(result);
      }
    });
    this.btnHashingText.setBounds(269, 99, 108, 31);
    this.panel.add(this.btnHashingText);
    
    this.textAreaInput = new JTextArea();
    this.textAreaInput.setBounds(10, 61, 249, 115);
    this.panel.add(this.textAreaInput);
    
    this.panel_1 = new JPanel();
    this.panel_1.setLayout(null);
    this.panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Hashing File", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
    this.panel_1.setBounds(10, 209, 644, 187);
    this.contentPane.add(this.panel_1);
    
    this.btnOpenFile = new JButton("Open File");
    this.btnOpenFile.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JFileChooser fileChooser = new JFileChooser();
        int status = fileChooser.showOpenDialog(null);
        if (status == JFileChooser.APPROVE_OPTION) {
              file = fileChooser.getSelectedFile();
              textFieldFileUrl.setText(file.getAbsolutePath());
        }
      }
    });
    this.btnOpenFile.setBounds(10, 40, 116, 23);
    this.panel_1.add(this.btnOpenFile);
    
    this.textFieldFileUrl = new JTextField();
    this.textFieldFileUrl.setBounds(136, 40, 330, 20);
    this.panel_1.add(this.textFieldFileUrl);
    this.textFieldFileUrl.setColumns(10);
    
    this.btnHashingFile = new JButton("Check MD5");
    this.btnHashingFile.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String result = MD5Hashing.getMD5(file);
        textAreaFileHashing.setText(result);
      }
    });
    this.btnHashingFile.setBounds(10, 84, 116, 23);
    this.panel_1.add(this.btnHashingFile);
    
    this.textAreaFileHashing = new JTextArea();
    this.textAreaFileHashing.setBounds(136, 82, 330, 93);
    this.panel_1.add(this.textAreaFileHashing);
  }
}

 

MD5 là gì? Code ví dụ MD5 với Java

MD5 là gì? Code ví dụ MD5 với Java

Okay, done!

Download full code ví dụ trên tại đây.

 

References:

https://vi.wikipedia.org/wiki/MD5

stackjava.com