/* * FileName:HashUtil.java *

* Copyright (c) 2017-2020, hermit (794890569@qq.com). *

* Licensed under the GNU General Public License, Version 3 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.gnu.org/licenses/gpl-3.0.html *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cn.com.lzt.common.util; import org.apache.commons.lang3.Validate; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Arrays; /** * 功能:数据加密解密工具类 * 支持HMAC-SHA1消息签名 及 AES/Blowfish对称加密的工具类 * 支持Hex与Base64两种编码方式 * 支持MD5 SHA 不可逆加密 * @author xiongliang * * mobile enterprise application platform * Version 0.1 */ public class HashUtil { public static final String SHA1 = "SHA-1"; public static final String MD5 = "MD5"; private static final String AES = "AES"; private static final String AES_CBC = "AES/CBC/PKCS5Padding"; private static final String HMACSHA1 = "HmacSHA1"; private static final int DEFAULT_HMACSHA1_KEYSIZE = 160; //RFC2401 private static final int DEFAULT_AES_KEYSIZE = 128; private static final int DEFAULT_IVSIZE = 16; private static SecureRandom random = new SecureRandom(); /** * SHA加密 * @param input * @return */ public static String SHAHashing(String input){ String output = ""; MessageDigest md; try { md = MessageDigest.getInstance("SHA"); byte[] original = input.getBytes("utf-8"); byte[] bytes = md.digest(original); for (int i = 0; i 0, "numBytes argument must be a positive integer (1 or larger)", numBytes); byte[] bytes = new byte[numBytes]; random.nextBytes(bytes); return bytes; } /** * 对文件进行消息摘要签名 * @param input InputStream输入流 * @param algorithm 加密算法 HashUtil.SHA1 HashUtil.MD5 * @return * @throws IOException */ public static byte[] digest(InputStream input, String algorithm) throws IOException { try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); int bufferLength = 8 * 1024; byte[] buffer = new byte[bufferLength]; int read = input.read(buffer, 0, bufferLength); while (read > -1) { messageDigest.update(buffer, 0, read); read = input.read(buffer, 0, bufferLength); } return messageDigest.digest(); } catch (GeneralSecurityException e) { throw ExcptUtil.unchecked(e); } } }