8c36a258edc00616122a31373a8f028ef7d8b37b.svn-base 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package io.agora.media;
  2. import java.io.ByteArrayOutputStream;
  3. /**
  4. * Created by hefeng on 15/8/10.
  5. * Util to generate Agora media dynamic key.
  6. */
  7. public class DynamicKey {
  8. /**
  9. * Generate Dynamic Key for media channel service
  10. * @param appID App ID assigned by Agora
  11. * @param appCertificate App Certificate assigned by Agora
  12. * @param channelName name of channel to join, limited to 64 bytes and should be printable ASCII characters
  13. * @param unixTs unix timestamp in seconds when generating the Dynamic Key
  14. * @param randomInt salt for generating dynamic key
  15. * @return String representation of dynamic key
  16. * @throws Exception
  17. */
  18. public static String generate(String appID, String appCertificate, String channelName, int unixTs, int randomInt) throws Exception {
  19. String unixTsStr = ("0000000000" + Integer.toString(unixTs)).substring(Integer.toString(unixTs).length());
  20. String randomIntStr = ("00000000" + Integer.toHexString(randomInt)).substring(Integer.toHexString(randomInt).length());
  21. String signature = generateSignature(appID, appCertificate, channelName, unixTsStr, randomIntStr);
  22. return String.format("%s%s%s%s", signature, appID, unixTsStr, randomIntStr);
  23. }
  24. private static String generateSignature(String appID, String appCertificate, String channelName, String unixTsStr, String randomIntStr) throws Exception {
  25. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  26. baos.write(appID.getBytes());
  27. baos.write(unixTsStr.getBytes());
  28. baos.write(randomIntStr.getBytes());
  29. baos.write(channelName.getBytes());
  30. byte[] sign = DynamicKeyUtil.encodeHMAC(appCertificate, baos.toByteArray());
  31. return DynamicKeyUtil.bytesToHex(sign);
  32. }
  33. }