GenerateTestUserSig.swift 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. //
  2. // GenerateTestUserSig.swift
  3. // TRTCKaraokeApp
  4. //
  5. // Created by abyyxwang on 2021/5/7.
  6. //
  7. import Foundation
  8. import CommonCrypto
  9. import zlib
  10. /**
  11. * Tencent Cloud SDKAppID. Set it to the SDKAppID of your account.
  12. * You can view your `SDKAppID` after creating an application in the [TRTC console](https://console.trtc.io/).
  13. * SDKAppID uniquely identifies a Tencent Cloud account.
  14. */
  15. let SDKAppID: Int = 0
  16. /**
  17. * Signature validity period, which should not be set too short
  18. * Time unit: Second
  19. * Default value: 604800 (7 days)
  20. */
  21. let EXPIRETIME: Int = 604_800
  22. /**
  23. * Follow the steps below to obtain the key required for UserSig calculation.
  24. * Step 1. Log in to the [TRTC console](https://console.trtc.io/). If you don't have an application yet, create one.
  25. * Step 2. Click your application and find “Basic Information”.
  26. * Step 3. Click “Display Key” to view the key used for UserSig calculation. Copy and paste the key to the variable below.
  27. * Note: This method is for testing only. Before commercial launch,
  28. * please migrate the UserSig calculation code and key to your backend server to prevent key disclosure and traffic stealing.
  29. * Documentation: https://trtc.io/document/35166
  30. */
  31. let SDKSecretKey = ""
  32. /**
  33. * XMagic License【Optional】
  34. *
  35. * Tencent Effect
  36. * Documentation://cloud.tencent.com/document/product/616/65878
  37. */
  38. let XMagicLicenseURL = ""
  39. let XMagicLicenseKey = ""
  40. class GenerateTestUserSig {
  41. class func genTestUserSig(identifier: String) -> String {
  42. let current = CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970
  43. let TLSTime: CLong = CLong(floor(current))
  44. var obj: [String: Any] = [
  45. "TLS.ver": "2.0",
  46. "TLS.identifier": identifier,
  47. "TLS.sdkappid": SDKAppID,
  48. "TLS.expire": EXPIRETIME,
  49. "TLS.time": TLSTime,
  50. ]
  51. let keyOrder = [
  52. "TLS.identifier",
  53. "TLS.sdkappid",
  54. "TLS.time",
  55. "TLS.expire",
  56. ]
  57. var stringToSign = ""
  58. keyOrder.forEach { (key) in
  59. if let value = obj[key] {
  60. stringToSign += "\(key):\(value)\n"
  61. }
  62. }
  63. print("string to sign: \(stringToSign)")
  64. guard var sig = hmac(stringToSign) else {
  65. print("hmac error: \(stringToSign)")
  66. return ""
  67. }
  68. obj["TLS.sig"] = sig
  69. print("sig: \(String(describing: sig))")
  70. guard let jsonData = try? JSONSerialization.data(withJSONObject: obj, options: .sortedKeys) else {
  71. print("jsonData error: \(obj)")
  72. return ""
  73. }
  74. let bytes = jsonData.withUnsafeBytes { (result) -> UnsafePointer<Bytef>? in
  75. return result.bindMemory(to: Bytef.self).baseAddress
  76. }
  77. let srcLen: uLongf = uLongf(jsonData.count)
  78. let upperBound: uLong = compressBound(srcLen)
  79. let capacity: Int = Int(upperBound)
  80. let dest: UnsafeMutablePointer<Bytef> = UnsafeMutablePointer<Bytef>.allocate(capacity: capacity)
  81. var destLen = upperBound
  82. let ret = compress2(dest, &destLen, bytes, srcLen, Z_BEST_SPEED)
  83. if ret != Z_OK {
  84. print("[Error] Compress Error \(ret), upper bound: \(upperBound)")
  85. dest.deallocate()
  86. return ""
  87. }
  88. let count = Int(destLen)
  89. let result = self.base64URL(data: Data(bytesNoCopy: dest, count: count, deallocator: .free))
  90. return result
  91. }
  92. class func hmac(_ plainText: String) -> String? {
  93. guard let cKey = SDKSecretKey.cString(using: String.Encoding.ascii) else {
  94. print("hmac SDKSecretKey error: \(SDKSecretKey)")
  95. return nil
  96. }
  97. print("hmac SDKSecretKey: \(SDKSecretKey)")
  98. print("hmac cKey: \(cKey)")
  99. guard let cData = plainText.cString(using: String.Encoding.ascii) else{
  100. print("hmac plainText error: \(plainText)")
  101. return nil
  102. }
  103. print("hmac plainText: \(plainText)")
  104. print("hmac cData: \(cData)")
  105. let cKeyLen = SDKSecretKey.lengthOfBytes(using: .ascii)
  106. let cDataLen = plainText.lengthOfBytes(using: .ascii)
  107. var cHMAC = [CUnsignedChar].init(repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
  108. let pointer = cHMAC.withUnsafeMutableBufferPointer { (unsafeBufferPointer) in
  109. return unsafeBufferPointer
  110. }
  111. CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), cKey, cKeyLen, cData, cDataLen, pointer.baseAddress)
  112. guard let adress = pointer.baseAddress else {
  113. print("adress error: \(String(describing: pointer))")
  114. return nil
  115. }
  116. let data = Data(bytes: adress, count: cHMAC.count)
  117. print("cHMAC.count: \(String(describing: cHMAC.count))")
  118. print("data: \(String(describing: data))")
  119. let result = data.base64EncodedString(options: [])
  120. return result
  121. }
  122. class func base64URL(data: Data) -> String {
  123. let result = data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
  124. var final = ""
  125. result.forEach { (char) in
  126. switch char {
  127. case "+":
  128. final += "*"
  129. case "/":
  130. final += "-"
  131. case "=":
  132. final += "_"
  133. default:
  134. final += "\(char)"
  135. }
  136. }
  137. return final
  138. }
  139. }