package ay.util; import java.security.MessageDigest; public class SecurityEncryptUtil { private static java.security.SecureRandom random = new java.security.SecureRandom(); public static String md5(String source, int times) { String result = source; for (int i = 0; i < times; i++) { result = md5(source); } return result; } public static String sha1(String source, int times) { String result = source; for (int i = 0; i < times; i++) { result = sha1(source); } return result; } public static String sha256(String source, int times) { String result = source; for (int i = 0; i < times; i++) { result = sha256(source); } return result; } public static String sha384(String source, int times) { String result = source; for (int i = 0; i < times; i++) { result = sha384(source); } return result; } public static String sha512(String source, int times) { String result = source; for (int i = 0; i < times; i++) { result = sha512(source); } return result; } public static String md5(String source) { return hash("MD5", source); } public static String sha1(String source) { return hash("SHA-1", source); } public static String sha256(String source) { return hash("SHA-256", source); } public static String sha384(String source) { return hash("SHA-384", source); } public static String sha512(String source) { return hash("SHA-512", source); } public static String hash(String algorithm, String source) { try { StringBuilder result = new StringBuilder(); MessageDigest md = MessageDigest.getInstance(algorithm); byte[] bytes = md.digest(source.getBytes("utf-8")); for (byte b : bytes) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) result.append("0"); result.append(hex); } return result.toString(); } catch (Exception e) { throw new RuntimeException(e); } } private static String toHex(byte[] bytes) { StringBuilder result = new StringBuilder(); for (byte b : bytes) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) result.append("0"); result.append(hex); } return result.toString(); } /** * md5 128bit 16bytes *
* sha1 160bit 20bytes *
* sha256 256bit 32bytes *
* sha384 384bit 48bites *
* sha512 512bit 64bites */ public static String generateSalt(int numberOfBytes) { byte[] salt = new byte[numberOfBytes]; random.nextBytes(salt); return toHex(salt); } }