java.security.MessageDigest 信息加密

package com.conan.javase.encrypt;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Conan on 2016/11/24.
 */
public class MessageDigestTest {
    private static final String SHA = "SHA-1";
    private static final String[] HEX_DIGEST = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

    public static void main(String[] args) {
        new MessageDigestTest().testDigest();
    }

    public void testDigest() {
        try {
            String info = "测试信息";
            MessageDigest digest = MessageDigest.getInstance("MD5");
            // MessageDigest digest = MessageDigest.getInstance("SHA-1");

            // 使用要加密的信息来更新digest
            digest.update(info.getBytes());
            // 填充摘要信息,使其达到固定长度
            byte[] digest_b = digest.digest();
            System.out.println("本摘要信息 : " + byteArrayToHexString(digest_b));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("非法摘要算法");
        }
    }

    public String byteArrayToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (int n = 0; n < b.length; n++) {
            sb.append(byteToHexString(b[n]));
        }
        return sb.toString();
    }

    private String byteToHexString(byte b) {
        int ret = b;
        if (ret < 0)
            ret += 256;
        int m = ret / 16;
        int n = ret % 16;
        return HEX_DIGEST[m] + HEX_DIGEST[n];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值