user739396
user739396

Reputation: 23

Implementation of MySQL’s PASSWORD() Function in Java

Hello I am looking for a way to produce the same result as with MySQL's PASSWORD function in Java. There are a Implementation of MySQL’s PASSWORD() Function in Java code?

For example:

Password: 123 in MySQL PASSWORD ('123 ') -> *23AE809DDACAF96AF0FD78ED04B6A265E05AA257

I hope you can help me

Upvotes: 2

Views: 3068

Answers (4)

Ratish
Ratish

Reputation: 101

Updated itsadok's answer a bit.

public static String MySQLPassword(String plainText) throws UnsupportedEncodingException {
        byte[] utf8 = plainText.getBytes("UTF-8");
        return "*" + DigestUtils.sha1Hex(DigestUtils.sha1(utf8)).toUpperCase();
    }

Upvotes: 2

itsadok
itsadok

Reputation: 29342

According to the answer pointed to by @ypercube, MySQL PASSWORD() is just sha1, applied twice.

Using Apache Commons Codec:

public static String MySQLPassword(String plainText) throws UnsupportedEncodingException {
    byte[] utf8 = plainText.getBytes("UTF-8");
    return "*" + DigestUtils.shaHex(DigestUtils.sha(utf8)).toUpperCase();
}

EDIT: tested, added throws clause, uppercased and a prefix "*".


Working code (to replace shaHex() that was not working):

public static String MySQLPassword(String plainText)
                  throws UnsupportedEncodingException
{
    byte[] utf8 = plainText.getBytes("UTF-8");
    byte[] test = DigestUtils.sha(DigestUtils.sha(utf8));
    return "*" + convertToHex(test).toUpperCase();
}

Upvotes: 4

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115530

This question is almost the same - replace "Java" with ".NET or MS-SQL-Server" :

simulating-mysqls-password-encryption-using-net-or-ms-sql

It will give you an idea of how to convert MySQL PASSWORD() function into Java.


Please note that PASSWORD() purpose is for MySQL internal use and other, more secure methods should be used for hashing and authentication in application code. Unless you are limited somehow to use this one.

Upvotes: 1

Nikolay Antipov
Nikolay Antipov

Reputation: 920

Here is an example where MessageDigest used, plus converting to HEX string. So, just use it.

http://www.anyexample.com/programming/java/java_simple_class_to_compute_md5_hash.xml

Upvotes: 1

Related Questions