项目对外提供接口时都会要求调用方根据服务器制定的加密规则传入签名字符串,再进行校验来判断请求来源的合法性,而SHA
加密是比较常用的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import java.security.MessageDigest;
public class SHAEncryptUtil {
public final String SHA256 = "SHA-256"; public final String SHA512 = "SHA-512";
public String getSHA256Str(String str) { return encryptSHA(str, SHA256); }
public String getSHA512Str(String str) { return encryptSHA(str, SHA512); }
private String encryptSHA(String str, String encType) { String encryptStr = null;
try { MessageDigest messageDigest = MessageDigest.getInstance(encType); messageDigest.update(str.getBytes("UTF-8")); byte[] bytes = messageDigest.digest();
StringBuffer strBufferHex = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hexStr = Integer.toHexString(bytes[i] & 0xFF); if (hexStr.length() == 1) { strBufferHex.append("0"); } strBufferHex.append(hexStr); }
encryptStr = strBufferHex.toString(); } catch (Exception e) { e.printStackTrace(); } return encryptStr; } }
|