如何使用MD5散列密码 [英] how to hash an password using MD5

查看:48
本文介绍了如何使用MD5散列密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我实现了这个代码来哈希用户密码,但是当我再次尝试哈希相同的密码时,它会生成另一个哈希!

这是我的代码:

Hi all, i implemented this code to hash user password, but when i try to hash the same password again, it generates another hash!
this is my code:

public static String ConvertToHash(String password)
	{
		try {
			MessageDigest ms = MessageDigest.getInstance("MD5");
			byte[] pass = password.getBytes();
			byte[] hashedpass = ms.digest(password.getBytes("UTF-8"));
			String hashed = hashedpass.toString();
			return hashed;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
		
	}



错误原因是什么?

提前感谢!


what is the error causes that?
thanks in advance!

推荐答案

这个有效:



This one works:

import java.security.MessageDigest;
import java.security.Security;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;

public class HelloWorld{
    public static String ConvertToHash(String password)
	{
		try {
			MessageDigest ms = MessageDigest.getInstance("MD5");
			byte[] pass = password.getBytes();
			byte[] byteData = ms.digest(password.getBytes("UTF-8"));
			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();
		} catch (NoSuchAlgorithmException e) {
			return null;
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}
     
     public static void main(String []args){
        System.out.println(ConvertToHash("password"));
        System.out.println(ConvertToHash("password"));
     }
}


请参阅我对问题的评论:不要使用MD5!例如,您可以通过类 java.security.MessageDigest 使用SHA-256:

http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html [ ^ ] 。



-SA
Please see my comment to the question: don't use MD5! For example, you can use SHA-256 through the class java.security.MessageDigest:
http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html[^].

—SA


这篇关于如何使用MD5散列密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆