开发者

Implementation of MySQL’s PASSWORD() Function in Java

Hello I am loo开发者_运维问答king 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


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();
}


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


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.


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();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜