如何在 Java 中使用 sha256 散列一些字符串? [英] How to hash some string with sha256 in Java?

查看:42
本文介绍了如何在 Java 中使用 sha256 散列一些字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Java 中使用 sha256 散列一些字符串?有人知道有什么免费的图书馆吗?

How can I hash some string with sha256 in Java? Does anybody know of any free library for this?

推荐答案

SHA-256 不是编码"- 这是一种单向哈希.

SHA-256 isn't an "encoding" - it's a one-way hash.

您基本上会将字符串转换为字节(例如使用 text.getBytes(StandardCharsets.UTF_8)),然后对字节进行哈希处理.请注意,散列的结果是任意的二进制数据,如果你想用字符串表示它,你应该使用 base64 或十六进制...不要尝试使用 String(byte[], String) 构造函数.

You'd basically convert the string into bytes (e.g. using text.getBytes(StandardCharsets.UTF_8)) and then hash the bytes. Note that the result of the hash would also be arbitrary binary data, and if you want to represent that in a string, you should use base64 or hex... don't try to use the String(byte[], String) constructor.

例如

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));

这篇关于如何在 Java 中使用 sha256 散列一些字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆