[英]Is there a Java equivalent of the PHP function “hash”?
I am trying to connect up a Java application with a web application (in PHP), where a person can register a user on either the Java application, or on the web application. 我正在尝试将Java应用程序与Web应用程序(在PHP中)连接起来,在此人可以在Java应用程序或Web应用程序上注册用户。 I'm trying to find the equivalent of the PHP "hash" function in Java. 我正在尝试找到Java中与PHP“哈希”函数等效的函数。
For creating the hash in the web app, this is the code I use: 为了在Web应用程序中创建哈希,这是我使用的代码:
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++) {
$password = hash('sha256', $password . $salt);
}
The encrypted password and salt get stored in their own columns with the user, a little bit like this: 加密的密码和盐与用户一起存储在其自己的列中,如下所示:
|=====|==========|============|==========|
| ID | Username | Password | Salt |
| 1 | Bob | x24da0el.. | 39bbc9.. |
|=====|==========|============|==========|
I've tried everything and I can't get find the same method in Java. 我已经尝试了所有方法,但在Java中找不到相同的方法。
Yes, take a look at the MessageDigest class of Java: http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html 是的,看看Java的MessageDigest类: http : //docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html
It provides 3 hashing algorithms: 它提供了3种哈希算法:
-MD5 -MD5
-SHA-1 -SHA-1
-SHA-256 -SHA-256
Example for hashing a file: 散列文件的示例:
MessageDigest md = MessageDigest.getInstance("SHA-256");
FileInputStream fis = new FileInputStream("~/Documents/Path/To/File.txt");
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
//Convert "mdbytes" to hex String:
StringBuffer hexString = new StringBuffer();
for (int i=0;i<mdbytes.length;i++) {
hexString.append(Integer.toHexString(0xFF & mdbytes[i]));
}
return hexString.toString();
Here is the example for hashing a String: 这是哈希字符串的示例:
String password = "123456";
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes());
byte byteData[] = md.digest();
//Convert "byteData" to hex String:
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.