SHA256可以使用jdk中的 MessageDigest
類生成。
MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.reset(); digest.update(input.getBytes("utf8")); toReturn = String.format("%064x", new BigInteger(1, digest.digest()));
SHA-512也可以在沒有額外的java庫的情況下生成:
MessageDigest digest = MessageDigest.getInstance("SHA-512"); digest.reset(); digest.update(input.getBytes("utf8")); toReturn = String.format("%0128x", new BigInteger(1, digest.digest()));
以下代碼使用“this is an example”作為輸入和SHA-2哈希函數來創建SHA256和SHA512。 前兩種方法是為每個散列函數創建的。 第一個用於SHA-256,並使用 MessageDigest
類生成散列。 第二種方法是以相同的方式創建的,但使用SHA-512。 驗證輸出結果,我們也使用Apache commons的 DigestUtils
類生成哈希。 所有生成的散列都寫在控制台中。
import java.math.BigInteger; import java.security.MessageDigest; public class SHA2 { public static String getSHA256(String input){ String toReturn = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.reset(); digest.update(input.getBytes("utf8")); toReturn = String.format("%064x", new BigInteger(1, digest.digest())); } catch (Exception e) { e.printStackTrace(); } return toReturn; } public static String getSHA512(String input){ String toReturn = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-512"); digest.reset(); digest.update(input.getBytes("utf8")); toReturn = String.format("%0128x", new BigInteger(1, digest.digest())); } catch (Exception e) { e.printStackTrace(); } return toReturn; } public static void main(String[] argv) { String inputValue = "this is an example"; // With the java libraries String sha256 = getSHA256(inputValue); System.out.println("The SHA-256 of \"" + inputValue + "\" is:"); System.out.println(sha256); System.out.println(); // With Apache commons sha256 = org.apache.commons.codec.digest.DigestUtils.sha256Hex(inputValue); System.out.println("The SHA-256 of \"" + inputValue + "\" is:"); System.out.println(sha256); System.out.println(); // With the java libraries String sha512 = getSHA512( inputValue ); System.out.println("The SHA-512 of \"" + inputValue + "\" is:"); System.out.println(sha512); System.out.println(); // With Apache commons sha512 = org.apache.commons.codec.digest.DigestUtils.sha512Hex(inputValue); System.out.println("The SHA-512 of \"" + inputValue + "\" is:"); System.out.println(sha512); } }
The SHA-256 of "this is an example13" is: 066f61646a92c8cf04943577b3c4d9ee6e5d125fe850b4c8c4d315ddd3aa1f50 The SHA-256 of "this is an example13" is: 066f61646a92c8cf04943577b3c4d9ee6e5d125fe850b4c8c4d315ddd3aa1f50 The SHA-512 of "this is an example4" is: 05c1649335528b45ab4965619db876e5090e42dfc526b486dde9368df2b77830c4e523cee1fd0054d9009729a6a11e697a1dd121e36be3ada593b8d76cb80ced The SHA-512 of "this is an example4" is: 05c1649335528b45ab4965619db876e5090e42dfc526b486dde9368df2b77830c4e523cee1fd0054d9009729a6a11e697a1dd121e36be3ada593b8d76cb80ced