简体   繁体   English

Java中密码的MD5消息摘要的实现

[英]Implimentation for MD5 Message Digest for Passwords in Java

We made a system for a school project and our professor told us not to have passwords stored in plain text in the database. 我们为一个学校项目设计了一个系统,我们的教授告诉我们不要在数据库中以纯文本形式存储密码。 She wants us to encrypt these passwords for security since our system will be handling a lot of confidential data. 她希望我们对这些密码进行加密以确保安全,因为我们的系统将处理大量机密数据。 So we decided to use MD5 for making a hash of the passwords the problem is I don't really get how we would implement it in the login process. 因此,我们决定使用MD5对密码进行哈希处理,问题是我真的不知道如何在登录过程中实现它。

Welcome to SO. 欢迎来到SO。 I think there a post similar to yours has already been answered but I'll give you how I solved it. 我认为有一个与您相似的帖子已经得到答复,但是我会告诉您如何解决。

private String encryptPassword(String password) throws NoSuchAlgorithmException{

    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(password.getBytes());
    byte[] digest = md.digest();
    StringBuilder stringBuilder = new StringBuilder();
    for (byte b : digest) {
        stringBuilder.append(String.format("%02x", b & 0xff));
    }

    return stringBuilder.toString();
}

As you can see the method above that's how I encrypted the password which is a string passed through the parameters. 如您所见,上面的方法就是我加密密码的方式,密码是通过参数传递的字符串。 MD5 is a one way encryption so there would be no way for you to decrypt it with Java but there are a few tools. MD5是一种单向加密,因此您无法使用Java对其进行解密,但是有一些工具。

So what you should do is have the password converted when a user is registering(assuming you can add users in your system) then storing the converted value in the database as as string(varchar or text). 因此,您应该做的是在用户注册时转换密码(假设您可以在系统中添加用户),然后将转换后的值作为字符串(varchar或text)存储在数据库中。 Then when you want to login use the same method again then compare the result with whatever password is in the database. 然后,当您要登录时,再次使用相同的方法,然后将结果与数据库中的任何密码进行比较。 These generations aren't random so if you enter like "123" the generated hash will be the same everytime. 这些世代不是随机的,因此如果您输入“ 123”,则每次生成的哈希值都是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM