[英]how to implement php's crypt_md5 in java
I have a simple application in PHP which uses the following code to hash the password and store it in a db. 我在PHP中有一个简单的应用程序,它使用以下代码来散列密码并将其存储在数据库中。
<?php
$user_name = "admin";
$password = "1234";
$salt = substr($user_name, 0, 2);
$salt = '$1$' . $salt . '$'; //$salt = $1$ad$
$crypt_password = crypt($password, $salt);
echo $crypt_password;
?>
this code, produces the following password to store in the db: $1$ad$BH3wnQs1wym28vdzP8zyh1 此代码生成以下密码以存储在db中:$ 1 $ ad $ BH3wnQs1wym28vdzP8zyh1
I am trying to make exactly the same code with Java, but as I am new to Java, I have a lot of difficulties. 我试图用Java制作完全相同的代码,但由于我是Java的新手,我遇到了很多困难。 I checked over here http://www.java2s.com/Open-Source/Java-Document/Groupware/LibreSource/md5/MD5Crypt.java.htm#cryptStringString and it seems that it is what I need, but I didn't manage to make it work.
我在这里检查了http://www.java2s.com/Open-Source/Java-Document/Groupware/LibreSource/md5/MD5Crypt.java.htm#cryptStringString ,似乎这就是我需要的,但我没有设法让它发挥作用。 Any help would be appreciated.
任何帮助,将不胜感激。 Thank you in advance.
先感谢您。
If md5 works for you, you can try the following code: 如果md5适合您,您可以尝试以下代码:
String pass = "1234";
MessageDigest crypt = null;
try {
crypt = java.security.MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
System.out.println("MD5 not supported");
return; // depends on your method
}
byte[] digested = crypt.digest(pass.getBytes());
String crypt_password = new String();
// Converts bytes to string
for (byte b : digested)
crypt_password += Integer.toHexString(0xFF & b);
System.out.println(crypt_password);
Also, you can change "MD5" to "SHA1" and should work too. 此外,您可以将“MD5”更改为“SHA1”,也应该可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.