import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashEncrypt {
private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* 对字符串进行加密
*
* @param text
* 签名原文
* @return 签名后密文
*/
public static String doEncrypt(String text, String algorithm, String inputCharset) {
MessageDigest msgDigest = null;
try {
msgDigest = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(
"System doesn't support this algorithm.");
}
try {
msgDigest.update(text.getBytes(inputCharset)); // 注意改接口是按照指定编码形式签名
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(
"System doesn't support your EncodingException.");
}
byte[] bytes = msgDigest.digest();
String md5Str = new String(encodeHex(bytes));
return md5Str;
}
public static char[] encodeHex(byte[] data) {
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
out[j++] = DIGITS[0x0F & data[i]];
}
return out;
}
}
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* base64 加解密
* @author
*
*/
public class Base64Util {
private final static Logger logger = LoggerFactory.getLogger(Base64Util.class);
/**
* base64 编码
*
* @param str
* @return
*/
public static String encoder(String str){
final Base64.Encoder encoder = Base64.getEncoder();
String strEncoder = null;
try {
strEncoder = encoder.encodeToString(str.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.error("系统错误:",e);
}
return strEncoder;
}
/**
* base64 解码
*
* @param str
* @return
*/
public static String decoder(String str){
final Base64.Decoder decoder = Base64.getDecoder();
String strEncoder = null;
try {
strEncoder = new String(decoder.decode(str), "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("系统错误:",e);
}
return strEncoder;
}
/**
* test
*
* @param args
*/
public static void main(String[] args){
String testStr = "qwerqwfavavaegfgbsd#*#-asdfasd-asdf-fasdf-asd";
String encoderStr = encoder(testStr);
//System.out.println(encoderStr);
String decoderStr = decoder(encoderStr);
//System.out.println(decoderStr);
}
}
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.isoftstone.common.utils.StringUtil;
public class SingUtils {
private static Logger logger = LoggerFactory.getLogger(SingUtils.class);
/**签名方式*/
private static final String ALG_MD5 = "MD5";
/**字符编码*/
private static final String inputCharset = "UTF-8";
/**
* SHA256加密方式
* @param clientId
* @param clientSecret
* @param date
* @return
*/
public static String mtBasicAuth(String clientId,String clientSecret,Long date) {
logger.info("============正在使用SHA256加密==============");
String stringToSign=clientId+clientSecret+date+"%xuP@!tye";
logger.info("============加密串:"+stringToSign);
try {
return hashSHA256(stringToSign).toString();
} catch (NoSuchAlgorithmException e) {
logger.info("============SHA256加密异常:"+e.getMessage());
return "";
}
}
/**
* hashSHA256加密
* @param input
* @return
* @throws NoSuchAlgorithmException
*/
private static String hashSHA256(String input) throws NoSuchAlgorithmException {
MessageDigest mDigest=MessageDigest.getInstance("SHA-256");
byte[] shaByteArr=mDigest.digest(input.getBytes(Charset.forName(inputCharset)));
StringBuilder hexStrBuilder=new StringBuilder();
for (int i = 0; i < shaByteArr.length; i++) {
//原来这里有一个问题,会导致0被去掉 http://stackoverflow.com/questions/23066005/sha256-in-php-java
//byte b = shaByteArr[i];
hexStrBuilder.append(String.format("%02x", shaByteArr[i]));
}
return hexStrBuilder.toString();
}
/**
* 生成MD5方式签名的签名结果
* @param params 要签名的数组
* @return 签名结果字符串
*/
public static String getMd5SignMsg(Map params) {
String signSource = getSignSourMsg(params);
String signMsg = HashEncrypt.doEncrypt(signSource, ALG_MD5, inputCharset);
logger.info("签名串:"+signMsg);
return signMsg;
}
/**
* 得到签名源数据
* @param sArray 要签名的参数数组
* @return 签名源字符串
*/
private static String getSignSourMsg(Map params) {
//格式化参数 “参数=参数值”的模式用“|”字符拼接成字符串
String signSource = createLinkString(params);
logger.info("签名原数据:"+signSource);
return signSource;
}
/**
* 把数组所有元素去掉空值与签名参数后
* 按照“参数=参数值”的模式用“|”字符拼接成字符串
* @param params 需要排序并参与字符拼接的参数组
* @return 拼接后字符串
*/
private static String createLinkString(Map params) {
List keys = new ArrayList(params.keySet());
Collections.sort(keys);
StringBuffer prestr = new StringBuffer("");
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
/*//过滤签名数据
if ("hmac".equalsIgnoreCase(key) || "signMsg".equalsIgnoreCase(key)
|| "cert".equalsIgnoreCase(key)) {
continue;
}*/
if (StringUtil.isNull(value)) {
continue;
}
if (i == keys.size() - 1) {// 拼接时,不包括最后一个|字符
prestr.append(key).append("=").append(value);
} else {
prestr.append(key).append("=").append(value).append("|");
}
}
return prestr.toString();
}
/**
* 加密工具类(对称,非对称,不可逆)
* @author leon
*
*/
public class HexUtil {
private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/**
* 将byte数组转为16进制
* @param src
* @return
*/
public static String bytes2Hex(byte[] src){
char[] res = new char[src.length*2];
final char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
for(int i=0,j=0; i>>4 & 0x0f];
res[j++] = hexDigits[src[i] & 0x0f];
}
return new String(res);
}
/**
* 将16进制转为byte数组
* @param src
* @return
*/
public static byte[] hex2Bytes(String src){
byte[] res = new byte[src.length()/2];
char[] chs = src.toCharArray();
int[] b = new int[2];
for(int i=0,c=0; i='0' && chs[i+j]<='9'){
b[j] = (chs[i+j]-'0');
}else if(chs[i+j]>='A' && chs[i+j]<='F'){
b[j] = (chs[i+j]-'A'+10);
}else if(chs[i+j]>='a' && chs[i+j]<='f'){
b[j] = (chs[i+j]-'a'+10);
}
}
b[0] = (b[0]&0x0f)<<4;
b[1] = (b[1]&0x0f);
res[c] = (byte) (b[0] | b[1]);
}
return res;
}
public static byte[] decodeHex(final char[] data) throws Exception {
final int len = data.length;
if ((len & 0x01) != 0) {
throw new Exception("Odd number of characters.");
}
final byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f = f | toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
protected static int toDigit(final char ch, final int index)
throws Exception {
final int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new Exception("Illegal hexadecimal character " + ch
+ " at index " + index);
}
return digit;
}
public static char[] encodeHex(final byte[] data) {
return encodeHex(data, true);
}
public static char[] encodeHex(final byte[] data, final boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
protected static char[] encodeHex(final byte[] data, final char[] toDigits) {
final int l = data.length;
final char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
}
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.isoftstone.common.log.utils.StringUtils;
public class AESUtil {
private final static Logger logger = LoggerFactory.getLogger(AESUtil.class);
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
//加密
public static String AES_cbc_encrypt(String srcData)
{
byte[] key= "Ay#g$12(3K=yt*e&".getBytes();
byte[] iv = "Ay#g$12(3K=yt*e&".getBytes();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = null;
byte[] encData = null;
try {
cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
encData = cipher.doFinal(srcData.getBytes());
} catch (Exception e) {
logger.error("系统错误:",e);
}
return Base64.getEncoder().encodeToString(encData);
}
//解密
public static String AES_cbc_decrypt(String encData)
{
byte[] key= "Ay#g$12(3K=yt*e&".getBytes();
byte[] iv = "Ay#g$12(3K=yt*e&".getBytes();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = null;
byte[] decbbdt = null;
try {
cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
decbbdt = cipher.doFinal(Base64.getDecoder().decode(encData));
} catch (Exception e) {
logger.error("系统错误:",e);
}
return new String(decbbdt);
}
public static void main(String[] args) {
String srcStr = "/20180401/pdf/pdf_334434-dfsdf-dfsdf.pdf";
System.out.println(srcStr);
//
String encbt = AES_cbc_encrypt(srcStr);
System.out.println(encbt);
String decbt = AES_cbc_decrypt(encbt);
System.out.println(decbt);
//
// if(srcStr.equals(decbt))
// {
// System.out.println("TEST PASS");
// }else
// {
// System.out.println("TEST NO PASS");
// }
}
}