content: package mqtt.demo;
  
  import android.util.Base64;
  
  import java.nio.charset.Charset;
  import java.security.InvalidKeyException;
  import java.security.NoSuchAlgorithmException;
  
  import javax.crypto.Mac;
  import javax.crypto.spec.SecretKeySpec;
  
  public class Tool {
      /**
       * @param text      要签名的文本
       * @param secretKey 阿里云MQ secretKey
       * @return 加密后的字符串
       * @throws InvalidKeyException
       * @throws NoSuchAlgorithmException
       */
      public static String macSignature(String text, String secretKey) throws InvalidKeyException, NoSuchAlgorithmException {
          Charset charset = Charset.forName("UTF-8");
          String algorithm = "HmacSHA1";
          Mac mac = Mac.getInstance(algorithm);
          mac.init(new SecretKeySpec(secretKey.getBytes(charset), algorithm));
          byte[] bytes = mac.doFinal(text.getBytes(charset));
          // android的base64编码注意换行符情况, 使用NO_WRAP
          String s = new String(Base64.encode(bytes, Base64.NO_WRAP), charset);
          return s;
      }
  }
  