直接上代码

  1. importClass(javax.crypto.spec.SecretKeySpec);
  2. importClass(javax.crypto.Mac);
  3. /*
  4. *@param encryptText 待加密的字符串
  5. *@param encryptKey 秘钥
  6. *@return 返回加密后的字符串
  7. */
  8. function HmacSHA256Encrypt(encryptText, encryptKey) {
  9. let rawHmac;
  10. log("encryptText = " + encryptText);
  11. log("encryptKey = " + encryptKey);
  12. encryptText = java.lang.String(encryptText);
  13. encryptKey = java.lang.String(encryptKey);
  14. let data = encryptKey.getBytes("UTF-8");
  15. let secretKey = new SecretKeySpec(data, "hmacsha256");
  16. let mac = Mac.getInstance("hmacsha256");
  17. mac.init(secretKey);
  18. let text = encryptText.getBytes("UTF-8");
  19. rawHmac = mac.doFinal(text);
  20. let oauth = android.util.Base64.encodeToString(rawHmac, 2);
  21. return oauth;
  22. }
  23. log(HmacSHA256Encrypt("测试","QQ7323650"))