简体   繁体   English

如何使用SHA-256散列字符串

[英]How to hash a string using SHA-256

I am trying to hash my users password which is of string type using SHA-256 我试图使用SHA-256哈希我的用户密码字符串类型

I am using SHA-256 to hash the string using the following method 我使用SHA-256使用以下方法散列字符串

String text = "abc";
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes("UTF-8"));

To convert the btye array to string , I used the following method 要将btye数组转换为字符串,我使用了以下方法

String doc2 = new String(hash, "UTF-8");

When i print doc2 to output , i get rubbish 当我打印doc2输出时,我得到了垃圾

�x����AA@�]�"#�a��z���a�

What am i doing wrong ??? 我究竟做错了什么 ??? How do i hash a string using SHA-256 and convert it back to string ?? 如何使用SHA-256散列字符串并将其转换回字符串?

this will pring hex representation of hash 这将pring十六进制表示哈希

String s = DatatypeConverter.printHexBinary(hash)

you cannot get original string from hash 你不能从哈希获得原始字符串

SHA256 returns pure binary output, with all values from 00 to FF essentially equally likely for each character. SHA256返回纯二进制输出,每个字符的所有值从00到FF基本上相同。

For text output, you'll need to convert it to a text form, like Base64 encoding 对于文本输出,您需要将其转换为文本格式,如Base64编码

byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));

The only way to go from a cryptographically sound hash (or most hashes, even cryptographically unsound ones) back to the original input is to apply the hash to input after input until you get the same result - that's either the original input, or a collision. 从加密声音哈希(或大多数哈希,甚至加密不健全的哈希)回到原始输入的唯一方法是在输入之后将哈希应用于输入,直到得到相同的结果 - 即原始输入或碰撞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM