|
@@ -0,0 +1,58 @@
|
|
|
+package com.its.utils;
|
|
|
+
|
|
|
+import java.security.MessageDigest;
|
|
|
+import java.security.NoSuchAlgorithmException;
|
|
|
+import java.security.SecureRandom;
|
|
|
+import java.util.Base64;
|
|
|
+
|
|
|
+public class SHA256Util {
|
|
|
+
|
|
|
+ private static final String algorithm = "SHA-256";
|
|
|
+ private static final String saltAlgorithm = "SHA1PRNG";
|
|
|
+
|
|
|
+ public static String encrypt(String text) {
|
|
|
+ StringBuffer sb = new StringBuffer();
|
|
|
+ try {
|
|
|
+ MessageDigest md = MessageDigest.getInstance(algorithm);
|
|
|
+ md.update(text.getBytes());
|
|
|
+ byte[] data = md.digest();
|
|
|
+ for (byte b : data) {
|
|
|
+ sb.append(String.format("%02x", b & 0xFF));
|
|
|
+ }
|
|
|
+ } catch (NoSuchAlgorithmException e) {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ return sb.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String getSalt() {
|
|
|
+ String salt;
|
|
|
+ try {
|
|
|
+ SecureRandom random = SecureRandom.getInstance(saltAlgorithm);
|
|
|
+ byte[] bytes = new byte[16];
|
|
|
+ random.nextBytes(bytes);
|
|
|
+ salt = new String(Base64.getEncoder().encode(bytes));
|
|
|
+ } catch (NoSuchAlgorithmException e) {
|
|
|
+ return "1234567890";
|
|
|
+ }
|
|
|
+ return salt;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String encrypt(String text, String salt) {
|
|
|
+ String saltText = text + salt;
|
|
|
+ StringBuffer sb = new StringBuffer();
|
|
|
+ try {
|
|
|
+ MessageDigest md = MessageDigest.getInstance(algorithm);
|
|
|
+ md.update(saltText.getBytes());
|
|
|
+ byte[] data = md.digest();
|
|
|
+ for (byte b : data) {
|
|
|
+ sb.append(String.format("%02x", b & 0xFF));
|
|
|
+ }
|
|
|
+ } catch (NoSuchAlgorithmException e) {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ return sb.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+}
|
|
|
+
|