---
title: "How to Make Java MD5 Match PHP and MySQL MD5  "
author: "zac110"
date: "2012-06-19T11:30:23Z"
tags: []
categories: ["数据库"]
slug: "how-to-make-java-md5-match-php-and-mysql-md5"
draft: false
lastmod: "2012-06-19T11:30:23Z"
id: 1563810
url: "https://zac110.iteye.com/blog/1563810"
---

Here is Java implementation of MD5 hashing that will produce exactly the same result as  
md5()  
function in PHP and MySQL:

```
public static String md5(String input) throws NoSuchAlgorithmException {
    String result = input;
    if(input != null) {
        MessageDigest md = MessageDigest.getInstance("MD5"); //or "SHA-1"
        md.update(input.getBytes());
        BigInteger hash = new BigInteger(1, md.digest());
        result = hash.toString(16);
        if ((result.length() % 2) != 0) {
            result = "0" + result;
        }
    }
    return result;
}
```