Java Hash String using SHA-256
Hashing a string using SHA-256 in Java may seem like a straightforward task, but there are crucial differences between hashing and encoding that require clarification.
SHA-256 (Secure Hash Algorithm-256) is not an encoding mechanism; it's a one-way hash function. This means that when you hash a string, you produce an irreversible sequence of binary data.
To apply SHA-256 hashing in Java, follow these steps:
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(bytes);
byte[] hash = digest.digest();
Important Note:
The resulting hash is in binary format. If you wish to represent it as a string, consider using base64 or hexadecimal encoding. Avoid using the String(byte[], String) constructor, as it may result in garbled characters.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3