1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * SHA256安全散列算法 * * @author 冯龙生 */ public class Sha256Util { /** * 安全散列算法摘要 * * @param plainText 明文 * @return 密文 */ public static String encrypt(String plainText) { MessageDigest messageDigest; String result = ""; try { messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(plainText.getBytes(StandardCharsets.UTF_8)); result = byteToHex(messageDigest.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; } /** * 将byte转为16进制 * * @param bytes 字节码 * @return 16进制字符串 */ private static String byteToHex(byte[] bytes) { StringBuilder result = new StringBuilder(); String temp; for (byte item : bytes) { temp = Integer.toHexString(item & 0xFF); if (temp.length() == 1) { result.append("0"); } result.append(temp); } return result.toString(); } public static void main(String[] args) { String sha256Str = encrypt("111111"); System.out.println(sha256Str); } } |