加密系列——SHA加密算法

来源:互联网 发布:杭州半包价格2017 知乎 编辑:程序博客网 时间:2024/06/06 02:40
import java.security.MessageDigest;/** * 采用SHA加密 *  * @author peipei3514 * @datetime 2017-8-11 12:00:34 */public class SHAUtil {    /***     * SHA加密 生成40位SHA码     */    public static String shaEncode(String data) throws Exception {        MessageDigest sha = MessageDigest.getInstance("SHA");        byte[] byteArray = data.getBytes("UTF-8");        // md5Bytes的长度为20        byte[] md5Bytes = sha.digest(byteArray);        // 转换成16进制字符串        StringBuffer hexValue = new StringBuffer();        for (int i = 0; i < md5Bytes.length; i++) {            int val = ((int) md5Bytes[i]) & 0xff;            // 为了满足40位长度,当值小于16时需要先添加一位0(小于16的话用一位就能表示)            if (val < 16) {                hexValue.append("0");            }            hexValue.append(Integer.toHexString(val));        }        return hexValue.toString();    }    public static void main(String args[]) throws Exception {        String str = new String("1A2B3C4D5E");        System.out.println("原始:" + str);        System.out.println("SHA后:" + shaEncode(str));    }}
阅读全文
0 0