EncryptString.java 1.13 KB
package com.subsidy.util;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;

import java.nio.charset.StandardCharsets;

/**
 * 密码加密
 *
 * @author Date: 2019/08/28 20:59
 */
@Slf4j
public class EncryptString {

    /**
     * 对字符串进行SM3哈希计算
     * @param input 待加密的字符串
     * @return 哈希结果(十六进制字符串,64位)
     */
    public static String encrypt(String input) {
        // 1. 创建SM3摘要计算器
        SM3Digest digest = new SM3Digest();

        // 2. 将输入字符串转为UTF-8字节数组,更新摘要
        byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
        digest.update(inputBytes, 0, inputBytes.length);

        // 3. 计算哈希结果(32字节)
        byte[] hashBytes = new byte[digest.getDigestSize()];
        digest.doFinal(hashBytes, 0);

        // 4. 将字节数组转为十六进制字符串
        return Hex.toHexString(hashBytes);
    }


    public static void main(String[] args) {
        System.out.println(encrypt("catschina00002O9S8Z"));
    }
}