加密,对应php的代码 hash('sha256', 'xxx');
方式一、
/**
* 对字符串加密,加密算法使用MD5,SHA-1,SHA-256,默认使用SHA-256
* @param strSrc 要加密的字符串
* @param encName 加密类型
* @return
*/
public static String encrypt(String strSrc, String encName) {
MessageDigest md = null;
String strDes = null;
byte[] bt = strSrc.getBytes();
try {
if (BeanUtil.isEmpty(encName)) {
encName = "SHA-256";
}
md = MessageDigest.getInstance(encName);
md.update(bt);
strDes = bytes2Hex(md.digest()); // to HexString
} catch (NoSuchAlgorithmException e) {
return null;
}
return strDes;
}
public static String bytes2Hex(byte[] bts) {
String des = "";
String tmp = null;
for (int i = 0; i < bts.length; i++) {
tmp = (Integer.toHexString(bts[i] & 0xFF));
if (tmp.length() == 1) {
des += "0";
}
des += tmp;
}
return des;
}
方式二、
以下传入的字符串是方式一种strSrc拼接之前的参数,实际两种方式的参数比较后相当于
String strSrc = channelID + channelKey + appID + userID + nonce + timestamp;
public static String createToken(String channelId, String channelKey, String appId, String userId,String nonce, Integer timestamp) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(channelId.getBytes());
digest.update(channelKey.getBytes());
digest.update(appId.getBytes());
digest.update(userId.getBytes());
digest.update(nonce.getBytes());
digest.update(Long.toString(timestamp).getBytes());
String token = DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();
return token;
}