Java 如何解码我的 md5 加密以及如何正确调用该函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19258344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I decode my md5 encryption and how do I call the function properly?
提问by user2030485
I have two questions 1 I have the following code and I don't know how to use it from another part of my code, i.e when the user registers to encrypt my string password
我有两个问题 1 我有以下代码,但我不知道如何从代码的另一部分使用它,即当用户注册以加密我的字符串密码时
public static final String md5(final String toEncrypt) {
try {
final MessageDigest digest = MessageDigest.getInstance("md5");
digest.update(toEncrypt.getBytes());
final byte[] bytes = digest.digest();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%02X", bytes[i]));
}
return sb.toString().toLowerCase();
}
catch (Exception exc) { return ""; // Impossibru! }
}
Second question is how would I decrypt that string when I pull it from my database to match what a user types in a editbox.
第二个问题是,当我从数据库中提取该字符串以匹配用户在编辑框中键入的内容时,我将如何解密该字符串。
回答by Doorknob
- You're not supposed to "decrypt" MD5. The whole point of a hashing function is to make it very hard to unhash it. (of course, hackers try and sometimes succeed, but that's a different topic.)You hash the user's input, and thencompare it with the hashed password in the database.
- To call it, simply use
String hashedPassword = md5("some person's password");
. Just like a normal method. - You should probably actually do some exception handling, rather than just ignoring them. At leastlog them, at the very minimum. Or return
null
, or use athrows
clause. Just don't completely ignore them. I don't even know what's going on on line 3... you should probably make those separate lines. Also, your indentation is
a bitextremely strange. You will spend muchmore time reading your code than writing it, so make it readable now, and you'll thank your past self later. In fact, I already see a bug:catch (Exception exc) { return ""; // Impossibru! }
The close bracket is commented out.
- 你不应该“解密”MD5。散列函数的全部意义在于使其很难解散。(当然,黑客会尝试,有时会成功,但这是一个不同的话题。)您对用户的输入进行散列,然后将其与数据库中的散列密码进行比较。
- 要调用它,只需使用
String hashedPassword = md5("some person's password");
. 就像正常的方法一样。 - 您实际上应该进行一些异常处理,而不是仅仅忽略它们。在至少记录他们,在最起码。或 return
null
,或使用throws
子句。只是不要完全忽略它们。 我什至不知道第 3 行发生了什么……您可能应该单独制作这些行。另外,你的缩进是
有点怪异之极。你会花很多更多的时间阅读你的代码比编写,所以让它现在可读的,以后你会感谢你的过去的自己。事实上,我已经看到了一个错误:catch (Exception exc) { return ""; // Impossibru! }
右括号被注释掉。
回答by Seth McClaine
md5 is a one way encryption method. The only way to find what the encrypted version is, is to md5 hash combinations of characters until the results match
md5 是一种单向加密方法。找到加密版本的唯一方法是对字符进行 md5 哈希组合,直到结果匹配