如何通俗的解释MD5加盐

MD5自身是不可逆的,但是目前网路上有很多数据库支持反查询。如果用户密码数据库不小心被泄露黑客就可以通过反查询方式获得用户密码或者对于数据库中出现频率较高的hash码(即很多人使用的)进行暴力破解(因为它通常都是弱口令)。

盐值就是在密码hash过程中添加的额外的随机值,比如我的id是abc,密码是123456,存在数据库中的时候就可以对字符串123456idabc进行hash,而验证密码的时候也以字符串(要验证的密码)+idabc进行验证。

这样有另外一个用户密码是123456的时候,依然能构造出不同的hash值,并且能成功的验证,但这时候我的id就作为盐值为密码进行复杂hash了。

可见,盐值最大的作用之一就是减少数据库泄露带来的损失。

Java摘要算法

package com.neohope.utils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class NDigest
{
	/**
	 * Bytes to Hex String
	 * 
	 * @param hexBytes
	 * 
	 * @return hex string
	 */
	private static String bytesToHexString(byte[] hexBytes)
	{
		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < hexBytes.length; i++)
		{
			if ((hexBytes[i] & 0xff) < 0x10)
			{
				buf.append("0");
			}

			buf.append(Long.toString(hexBytes[i] & 0xff, 16));
		}

		return buf.toString();
	}

	/**
	 * calc MD5 for string
	 * 
	 * @param textIn
	 * 
	 * @return md5 digest string
	 * @throws NoSuchAlgorithmException
	 */
	public static String MD5Digest(String textIn)
			throws NoSuchAlgorithmException
	{
		byte[] textData = textIn.getBytes();

		MessageDigest md = null;
		md = MessageDigest.getInstance("MD5");
		md.reset();
		md.update(textData);

		byte[] encodedData = md.digest();
		return bytesToHexString(encodedData);
	}

	/**
	 * calc SHA1 for string
	 * 
	 * @param textIn
	 * 
	 * @return sha1 digest string
	 * @throws NoSuchAlgorithmException
	 */
	public static String SHA1Digest(String textIn)
			throws NoSuchAlgorithmException
	{
		byte[] textData = textIn.getBytes();

		MessageDigest md = null;
		md = MessageDigest.getInstance("SHA1");
		md.reset();
		md.update(textData);

		byte[] encodedData = md.digest();
		return bytesToHexString(encodedData);
	}

	/**
	 * Encode a string using Base64 encoding.
	 * 
	 * @param textIn
	 * @return String
	 */
	public static String base64Encode(String textIn)
	{
		sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
		return encoder.encodeBuffer(textIn.getBytes()).trim();
	}

	/**
	 * Decode a string using Base64 encoding.
	 * 
	 * @param textIn
	 * @return String
	 * @throws IOException
	 */
	public static String decodeString(String textIn) throws IOException
	{
		sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
		return new String(dec.decodeBuffer(textIn));
	}

	/**
	 * 使用 HMAC-SHA-1 签名方法对对textIn进行摘要
	 * 
	 * @param textIn
	 * @param keyIn
	 * @return
	 * @throws Exception
	 */
	public static String HmacSHA1Digest(String textIn, String keyIn)
			throws Exception
	{
		final String MAC_NAME = "HmacSHA1";
		final String ENCODING = "UTF-8";

		byte[] keyData = keyIn.getBytes(ENCODING);
		SecretKey secretKey = new SecretKeySpec(keyData, MAC_NAME);
		Mac mac = Mac.getInstance(MAC_NAME);
		mac.init(secretKey);

		byte[] textData = textIn.getBytes(ENCODING);
		byte[] encodedData = mac.doFinal(textData);

		return bytesToHexString(encodedData);
	}

	// 我就是那个测试函数。。。
	public static void main(String args[]) throws Exception
	{
		String key = "Y9zTQxRvxwrHOi45OoKNnIoxboerNqt3";
		String text = "Good good study, day day up.";
		String hmacSHA1 = HmacSHA1Digest(text, key );
		String base64 = base64Encode(hmacSHA1);
		System.out.println(hmacSHA1 );
		System.out.println(cbase64);
	}
}

VC计算CString摘要

1、VC计算字符串MD5摘要

//输入:要计算摘要的字符串
//输出:128位MD5摘要
#include <wincrypt.h>
CString szResult;

CString CDigestDlg::CalcMD5(CString strContent)
{
  DWORD dwLength=0;
  BYTE* pbContent=NULL;

  dwLength = (DWORD)strContent.GetLength();
  pbContent = new BYTE[dwLength];
  memcpy(pbContent,strContent.GetBuffer(dwLength),dwLength);

  //计算MD5编码
  HCRYPTPROV hCryptProv; 
  HCRYPTHASH hHash; 
  BYTE byteMD5[16]; 
  DWORD dwHashLen=16;
  CString szResult;

  if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) 
  {
    if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) 
    {
      if(CryptHashData(hHash, pbContent, dwLength, 0))
      {

        if(CryptGetHashParam(hHash, HP_HASHVAL, byteMD5, &dwHashLen, 0)) 
        {
          szResult.Format(TEXT("%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"),
            byteMD5[0],byteMD5[1],byteMD5[2],byteMD5[3],byteMD5[4],byteMD5[5],byteMD5[6],byteMD5[7]
            ,byteMD5[8],byteMD5[9],byteMD5[10],byteMD5[11],byteMD5[12],byteMD5[13],byteMD5[14],byteMD5[15]);
        }
        else
        {
          szResult=TEXT("Error getting hash param");
        }

      }
      else
      {
        szResult=TEXT("Error hashing data");
      }
    }
    else
    {
      szResult=TEXT("Error creating hash");
    }
  }
  else
  {
    szResult=TEXT("Error acquiring context");
  }

  CryptDestroyHash(hHash); 
  CryptReleaseContext(hCryptProv, 0); 
  delete[] pbContent;
  pbContent=NULL;

  return szResult;
}

2、VC计算字符串SHA1摘要

//输入:要计算摘要的字符串
//输出:160位SHA1摘要
#include <wincrypt.h>
CString szResult;

CString CDigestDlg::CalcSHA1(CString strContent)
{
  DWORD dwLength=0;
  BYTE* pbContent=NULL;

  dwLength = (DWORD)strContent.GetLength();
  pbContent = new BYTE[dwLength];
  memcpy(pbContent,strContent.GetBuffer(dwLength),dwLength);

  //计算MD5编码
  HCRYPTPROV hCryptProv; 
  HCRYPTHASH hHash; 
  BYTE byteSHA1[20]; 
  DWORD dwHashLen=20;
  CString szResult;

  if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) 
  {
    if(CryptCreateHash(hCryptProv, CALG_SHA1, 0, 0, &hHash)) 
    {
      if(CryptHashData(hHash, pbContent, dwLength, 0))
      {

        if(CryptGetHashParam(hHash, HP_HASHVAL, byteSHA1, &dwHashLen, 0)) 
        {
          szResult.Format(TEXT("%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"),
            byteSHA1[0],byteSHA1[1],byteSHA1[2],byteSHA1[3],byteSHA1[4],byteSHA1[5],byteSHA1[6],byteSHA1[7],
            byteSHA1[8],byteSHA1[9],byteSHA1[10],byteSHA1[11],byteSHA1[12],byteSHA1[13],byteSHA1[14],byteSHA1[15],
            byteSHA1[16],byteSHA1[17],byteSHA1[18],byteSHA1[19]);
        }
        else
        {
          szResult=TEXT("Error getting hash param");
        }

      }
      else
      {
        szResult=TEXT("Error hashing data");
      }
    }
    else
    {
      szResult=TEXT("Error creating hash");
    }
  }
  else
  {
    szResult=TEXT("Error acquiring context");
  }

  CryptDestroyHash(hHash); 
  CryptReleaseContext(hCryptProv, 0); 
  delete[] pbContent;
  pbContent=NULL;

  return szResult;
}

VC计算文件摘要

1、VC计算文件MD5摘要

//输入:文件路径
//输出:128位MD5摘要
#include <wincrypt.h>
CString szResult;

CString CMD5AndSHA1Dlg::CalcMD5(CString strFilePath)
{
  //读取文件
  CFile inFile;
  CFileException ex;
  DWORD dwLength=0;
  BYTE* pbContent=NULL;
  BOOL bRet;

  bRet=inFile.Open(strFilePath,CFile::modeRead | CFile::typeBinary | CFile::shareDenyWrite,&ex);
  if(bRet==FALSE)
  {
    return TEXT("Error opening file");;
  }

  dwLength = (DWORD)inFile.GetLength();
  pbContent = new BYTE[dwLength];
  if(pbContent==NULL)
  {
    return TEXT("Error not enough memory");;
  }
  inFile.Read(pbContent,dwLength);
  inFile.Close();

  //计算MD5编码
  HCRYPTPROV hCryptProv; 
  HCRYPTHASH hHash; 
  BYTE byteMD5[16]; 
  DWORD dwHashLen=16;
  CString szResult;

  if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) 
  {
    if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) 
    {
      if(CryptHashData(hHash, pbContent, dwLength, 0))
      {

        if(CryptGetHashParam(hHash, HP_HASHVAL, byteMD5, &dwHashLen, 0)) 
        {
          szResult.Format(TEXT("%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"),
            byteMD5[0],byteMD5[1],byteMD5[2],byteMD5[3],byteMD5[4],byteMD5[5],byteMD5[6],byteMD5[7]
            ,byteMD5[8],byteMD5[9],byteMD5[10],byteMD5[11],byteMD5[12],byteMD5[13],byteMD5[14],byteMD5[15]);
        }
        else
        {
          szResult=TEXT("Error getting hash param");
        }

      }
      else
      {
        szResult=TEXT("Error hashing data");
      }
    }
    else
    {
      szResult=TEXT("Error creating hash");
    }
  }
  else
  {
    szResult=TEXT("Error acquiring context");
  }

  CryptDestroyHash(hHash); 
  CryptReleaseContext(hCryptProv, 0); 
  delete[] pbContent;
  pbContent=NULL;

  return szResult;
}

2、VC计算文件SHA1摘要

//输入:文件路径(文件必须小于2^64bit)
//输出:160位SHA1摘要
#include <wincrypt.h>
CString szResult;

CString CMD5AndSHA1Dlg::CalcSHA1(CString strFilePath)
{
  //读取文件
  CFile inFile;
  CFileException ex;
  DWORD dwLength=0;
  BYTE* pbContent=NULL;
  BOOL bRet;

  bRet=inFile.Open(strFilePath,CFile::modeRead | CFile::typeBinary | CFile::shareDenyWrite,&ex);
  if(bRet==FALSE)
  {
    return TEXT("Error opening file");;
  }

  dwLength = (DWORD)inFile.GetLength();
  pbContent = new BYTE[dwLength];
  if(pbContent==NULL)
  {
    return TEXT("Error not enough memory");;
  }
  inFile.Read(pbContent,dwLength);
  inFile.Close();

  //计算MD5编码
  HCRYPTPROV hCryptProv; 
  HCRYPTHASH hHash; 
  BYTE byteSHA1[20]; 
  DWORD dwHashLen=20;
  CString szResult;

  if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) 
  {
    if(CryptCreateHash(hCryptProv, CALG_SHA1, 0, 0, &hHash)) 
    {
      if(CryptHashData(hHash, pbContent, dwLength, 0))
      {

        if(CryptGetHashParam(hHash, HP_HASHVAL, byteSHA1, &dwHashLen, 0)) 
        {
          szResult.Format(TEXT("%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"),
            byteSHA1[0],byteSHA1[1],byteSHA1[2],byteSHA1[3],byteSHA1[4],byteSHA1[5],byteSHA1[6],byteSHA1[7],
            byteSHA1[8],byteSHA1[9],byteSHA1[10],byteSHA1[11],byteSHA1[12],byteSHA1[13],byteSHA1[14],byteSHA1[15],
            byteSHA1[16],byteSHA1[17],byteSHA1[18],byteSHA1[19]);
        }
        else
        {
          szResult=TEXT("Error getting hash param");
        }

      }
      else
      {
        szResult=TEXT("Error hashing data");
      }
    }
    else
    {
      szResult=TEXT("Error creating hash");
    }
  }
  else
  {
    szResult=TEXT("Error acquiring context");
  }

  CryptDestroyHash(hHash); 
  CryptReleaseContext(hCryptProv, 0); 
  delete[] pbContent;
  pbContent=NULL;

  return szResult;
}