java中常用接口对接加密方式

hmac生成码

/**
*
* @param message 加密的内容
* @param secret 第三方接口提供的密钥
* @return
*/
private static String sha256_HMAC(String message, byte[] secret) {
  String hash = "";
  try {
      Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
      SecretKeySpec secret_key = new SecretKeySpec(secret, "HmacSHA256");
      sha256_HMAC.init(secret_key);
      byte[] bytes = sha256_HMAC.doFinal(message.getBytes(StandardCharsets.UTF_8));
      hash = new String(java.util.Base64.getEncoder().encode(bytes), StandardCharsets.UTF_8);
      System.out.println(hash);
  } catch (Exception e) {
      System.out.println("Error HmacSHA256 ===========" + e.getMessage());
  }
  return hash;
}

md5加密

import org.apache.commons.codec.digest.DigestUtils;

@Test
public void genreateMd5() {
    String message = "chenrui"; //要加密的内容
    String salt = "chenrui";    //随机的盐
    String key = "key";
    String sign = DigestUtils.md5Hex(message+salt+key);
    System.out.println(sign);
}

java对url进行encode

java.net.URLEncoder.encode(value, "UTF-8")
	.replace("+", "%20").replace("*", "%2A").replace("%7E", "~");

HmacSHA1 加密

//stringToSign url拼接的请求参数
public static String sign(String accessSecret, String stringToSign) {
 javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
 mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
 byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
 return new sun.misc.BASE64Encoder().encode(signData);
 }

base64编码

private static String base64(String accountSid, String timestamp) {
    String ecodeString = accountSid+":"+timestamp;
    String authorization = null;
    try {
        byte[] autData = ecodeString.getBytes("UTF-8");
        authorization = new sun.misc.BASE64Encoder().encode(autData);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return authorization;
}

使用到了一些常用的加密方式,我们在用到这些加密方式,通常的场景是在调用一些RESTFul接口。点击查看该博客

水平原因可能存在错误,希望指正 [email protected]

你可能感兴趣的:(实际开发笔记)