1. 程式人生 > >python2中實現sah-1加密

python2中實現sah-1加密

在java中實現對字串進行雜湊sah-1加密過程如下:

public static String getExpandUserID(String UID) throws Exception
	{
		return "EU" + Base64.getEncoder().encodeToString(Test.doDigestSHA1(UID.getBytes("UTF-8")));
	}

	/**
	 * 對給定位元組陣列計算SHA-1雜湊值
	 * 
	 * @param bSrc
	 * @return
	 * @throws Exception
	 */
	public static byte[] doDigestSHA1(byte[] bSrc) throws Exception
	{
		try
		{
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(bSrc);
			return digest.digest();
		}
		catch (Exception e)
		{
			throw new Exception("SHA1Digest:" + e.getMessage());
		}
	}



 

將其在python2.7中實現的過程如下:

import hashlib
import base64
def sha1_str(data):
    '''
    將字串進行sha-1家嗎
    :param data: 加密前字串
    :return: 加密後的字串
    '''
    return hashlib.sha1(data).digest()
def b64encode_str(data):
    '''
    將字串進行b64位轉碼
    :param data: 轉碼前字串
    :return: 轉碼後字串
    '''
    return base64.b64encode(data)

print  b64encode_str(sha1_str("123456"))