Java - SHA消息摘要算法

in TCEHJava with 0 comment
package com.back.web;

import java.security.MessageDigest;

/**
 * SHA签名
 * 
 * @author Back
 *
 */
public class SHATest {
    private final static String CHARSETNAME = "UTF-8";
    private final static String ALGORITHM_SHA = "SHA";
    private final static String ALGORITHM_SHA_256 = "SHA-256";
    private final static String ALGORITHM_SHA_384 = "SHA-384";
    private final static String ALGORITHM_SHA_512 = "SHA-512";

    /**
     * @param inputStr
     *            待签名内容
     * @param charsetName
     *            字符集
     * @param algorithm
     *            签名模式
     * @return 签名
     * @throws Exception
     */
    public static String shaEncode(String inputStr, String charsetName, String algorithm) throws Exception {
        MessageDigest sha = MessageDigest.getInstance(algorithm);
        byte[] byteArray = inputStr.getBytes(charsetName);
        byte[] shaBytes = sha.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < shaBytes.length; i++) {
            int val = (shaBytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static void main(String[] args) throws Exception {
        String inputStr = "待签名内容!!!";
        String shaStr = shaEncode(inputStr, CHARSETNAME, ALGORITHM_SHA);

        System.out.println("sha签名:" + shaStr);// sha签名:88afb919a792bf28921f7cd975dbc2477bfd91f6
        System.out.println("sha签名长度:" + shaStr.length());// sha签名长度:40

        String sha256Str = shaEncode(inputStr, CHARSETNAME, ALGORITHM_SHA_256);
        System.out.println("sha256签名:" + sha256Str);// sha256签名:066dac11c904784ed83595216a3343aa091499d6dde9c1d99e758d931c5f09a2
        System.out.println("sha256签名长度:" + sha256Str.length());// sha256签名长度:64

        String sha384Str = shaEncode(inputStr, CHARSETNAME, ALGORITHM_SHA_384);
        System.out.println("sha384签名:" + sha384Str);// sha384签名:0c3e0daf864e62ab2a0f3ceeb0f73d58658659eb9404319bfc63f08b1a5f55b3a83fc8f0530acb0ccc6793504156aa9a
        System.out.println("sha384签名长度:" + sha384Str.length());// sha384签名长度:96

        String sha512Str = shaEncode(inputStr, CHARSETNAME, ALGORITHM_SHA_512);
        System.out.println("sha512签名:" + sha512Str);// sha512签名:50b4af492701521866a8001a81a4bf7811927ac0e803b55ef42a6766d4cc35c6b797bf98adaddd28db63ebef880522bc42daf9c675c98054c728583b3677f879
        System.out.println("sha512签名长度:" + sha512Str.length());// sha512签名长度:128

    }

}
Comments are closed.