JavaBouncyCastle实现MD5加密

JavaBouncyCastle实现MD5加密

  1. 导入 pom 包
    <dependency>
        <groupId>bouncycastle</groupId>
        <artifactId>bcpg-jdk15</artifactId>
        <version>140</version>
    </dependency>

  1. 创建一个 Util 类
package com.runbrick.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

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

/**
 * {@code EncryptUtil} <加密类>
 *
 * @author chow
 * @version 1.0
 * @since 1.8
 */
public class EncryptUtil {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * md5 加密
     *
     * @param ciphertext
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String md5(String ciphertext) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] digest = Hex.encode(md5.digest(ciphertext.getBytes()));
        return new String(digest);
    }
}

  1. 测试调用
    public static void main(String[] args) {
        try {
            System.out.println(EncryptUtil.md5("123456")); 
            // 结果 e10adc3949ba59abbe56e057f20f883e
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

BouncyCastle 有很多加密方式,需要的时候可以去查询它的手册

# Java  加密 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×