|
|
@@ -0,0 +1,710 @@
|
|
|
+# 前端调用 API 文档
|
|
|
+
|
|
|
+## 根据渠道获取平台 ID 和 Token
|
|
|
+
|
|
|
+地址:`POST http://IP/api/platform/credentials`,请求头 `Content-Type: application/json`。
|
|
|
+
|
|
|
+请求加密前示例:
|
|
|
+
|
|
|
+```json
|
|
|
+{"channel":"121","language":"zh-CN","region":"SG","timezone":"Asia/Singapore"}
|
|
|
+```
|
|
|
+
|
|
|
+只有 channel 必填,其他参数可选。沿用下文 AES-256-CBC、SHA-256 密钥派生、随机 IV 和 v2 Base64URL 算法,将上述 JSON 字符串加密后提交:
|
|
|
+
|
|
|
+```json
|
|
|
+{"payload":"v2:请求密文"}
|
|
|
+```
|
|
|
+
|
|
|
+成功响应只有 `data` 字段:
|
|
|
+
|
|
|
+```json
|
|
|
+{"data":"v2:响应密文"}
|
|
|
+```
|
|
|
+
|
|
|
+沿用获取链接接口的解密函数。本接口不判断后台 B 面开关,通过原有 IP/地区判断时,解密后的文本为 JSON:
|
|
|
+
|
|
|
+```json
|
|
|
+{"platform_id":"1001","platform_token":"示例Token"}
|
|
|
+```
|
|
|
+
|
|
|
+字段未配置时对应值为 null。IP/地区判断不通过时,解密文本为 `0`;客户端先判断该值,再解析 JSON。后台 B 面关闭不影响本接口返回 ID 和 Token。原 `/api/platform` 仍判断 B 面开关,解密后仍为 URL 文本或 `0`。
|
|
|
+
|
|
|
+客户端处理伪代码(encrypt/decrypt 使用下文各语言的现有算法):
|
|
|
+
|
|
|
+```text
|
|
|
+payload = encrypt(JSON.stringify({channel: "121", region: "SG"}))
|
|
|
+response = POST("http://IP/api/platform/credentials", {payload: payload})
|
|
|
+if response.status != 200: 处理请求失败
|
|
|
+plaintext = decrypt(response.data)
|
|
|
+if plaintext == "0": 处理不可用状态
|
|
|
+else:
|
|
|
+ credentials = JSON.parse(plaintext)
|
|
|
+ platformId = credentials.platform_id
|
|
|
+ platformToken = credentials.platform_token
|
|
|
+```
|
|
|
+
|
|
|
+参数错误返回 HTTP 422,渠道不存在返回 HTTP 404,错误响应沿用明文 JSON。请求和响应沿用平台接口日志,增加 path 区分接口;IP 查询继续使用 24 小时缓存和独立 IP 日志。Token 属于敏感数据,客户端存储使用系统安全存储;缓存按渠道区分,并与 URL 缓存分开。
|
|
|
+
|
|
|
+## 基础地址
|
|
|
+
|
|
|
+```text
|
|
|
+http://IP/api
|
|
|
+```
|
|
|
+
|
|
|
+## 获取平台配置
|
|
|
+
|
|
|
+请求链接支持普通 HTTPS 地址及两端成对双引号,例如 `"https://abc.com"` 或 `“https://abc.com”`。数据库保留输入格式,API 解密后也保留引号;需要打开链接的客户端应先移除一对外层双引号,再校验 HTTPS 地址并存储或打开。普通链接保持不变,关闭时仍返回 `0`。弯双引号形式不是 JSON,不要直接用 JSON.parse 解析。
|
|
|
+
|
|
|
+```http
|
|
|
+POST /platform
|
|
|
+```
|
|
|
+
|
|
|
+请求参数必须先加密,再放到 JSON body 的 `payload` 字段里。加密前的 JSON 必须包含 `channel`,也可以附带客户端语言、地区和时区。
|
|
|
+
|
|
|
+| 参数 | 类型 | 必填 | 说明 |
|
|
|
+| --- | --- | --- | --- |
|
|
|
+| `channel` | string | 是 | 渠道标识,例如 `243`、`ios` |
|
|
|
+| `language` | string | 否 | 客户端语言,例如 `zh-CN`、`en-US` |
|
|
|
+| `region` | string | 否 | 客户端地区,例如 `CN`、`US` |
|
|
|
+| `timezone` | string | 否 | 客户端时区,例如 `Asia/Shanghai`、`America/New_York` |
|
|
|
+
|
|
|
+接口只按 `channel` 查询平台。`language`、`region`、`timezone` 是客户端上下文参数,会进入接口日志,但不参与平台匹配。
|
|
|
+
|
|
|
+### 请求示例
|
|
|
+
|
|
|
+```http
|
|
|
+POST http://IP/api/platform
|
|
|
+Content-Type: application/json
|
|
|
+
|
|
|
+{
|
|
|
+ "payload": "v2:..."
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+`payload` 解密后的内容:
|
|
|
+
|
|
|
+```json
|
|
|
+{
|
|
|
+ "channel": "243",
|
|
|
+ "language": "zh-CN",
|
|
|
+ "region": "CN",
|
|
|
+ "timezone": "Asia/Shanghai"
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+### 成功响应
|
|
|
+
|
|
|
+`data` 是加密后的字符串,客户端需要使用下方解密函数还原为 URL 字符串。
|
|
|
+
|
|
|
+```json
|
|
|
+{
|
|
|
+ "data": "v2:..."
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+`data` 解密后的内容:
|
|
|
+
|
|
|
+```text
|
|
|
+http://example.com
|
|
|
+```
|
|
|
+
|
|
|
+URL 返回规则:
|
|
|
+
|
|
|
+- 后台开启“开放 B 面”:`data` 解密后是完整 `http://` 地址。
|
|
|
+- 后台关闭“开放 B 面”:`data` 解密后是字符串 `"0"`。
|
|
|
+- 请求 IP 所在国家/地区不是美国或新加坡:`data` 解密后是字符串 `"0"`。
|
|
|
+- 请求 IP 的 `isp`、`org`、`as`、`asname`、`reverse` 等信息命中 Apple、Amazon/AWS、Google、Microsoft/Azure、Cloudflare、Alibaba/阿里云:`data` 解密后是字符串 `"0"`。
|
|
|
+- 没有获取到请求 IP、IP 查询接口失败、没有配置 key,或 IP 查询结果缺少国家/地区信息:使用客户端传入的 `region` 兜底判断。
|
|
|
+- 兜底判断时,`region` 是 `US`、`SG`、`United States`、`Singapore` 才允许返回真实 URL;其他值或未传 `region` 都返回字符串 `"0"`。
|
|
|
+- 同一个请求 IP 的查询结果缓存 24 小时,不会每次都请求 `ip-api.com`。
|
|
|
+- 客户端只在解密后的 `data` 是完整 `http://` 地址时覆盖本地缓存。
|
|
|
+
|
|
|
+### 未传 channel
|
|
|
+
|
|
|
+HTTP 状态码:`422`
|
|
|
+
|
|
|
+```json
|
|
|
+{
|
|
|
+ "message": "请传入 channel 参数"
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+### 未找到平台
|
|
|
+
|
|
|
+HTTP 状态码:`404`
|
|
|
+
|
|
|
+```json
|
|
|
+{
|
|
|
+ "message": "未找到匹配的平台"
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+## 日志记录
|
|
|
+
|
|
|
+接口会记录每次请求和返回结果,日志写入 Laravel 默认日志文件:
|
|
|
+
|
|
|
+```text
|
|
|
+storage/logs/laravel.log
|
|
|
+```
|
|
|
+
|
|
|
+日志事件名:
|
|
|
+
|
|
|
+```text
|
|
|
+platform_api_request_response
|
|
|
+```
|
|
|
+
|
|
|
+日志内容包含:
|
|
|
+
|
|
|
+- 请求 IP、User-Agent、加密后的 `payload`
|
|
|
+- 解密后的请求参数:`channel`、`language`、`region`、`timezone`
|
|
|
+- 返回状态码
|
|
|
+- 返回 JSON body
|
|
|
+- 成功时额外记录加密前的平台返回数据,便于排查 B 面开关和 URL 返回问题
|
|
|
+
|
|
|
+## 加密和解密算法
|
|
|
+
|
|
|
+算法说明:
|
|
|
+
|
|
|
+- 加密字段格式:`v2:{base64url字符串}`
|
|
|
+- 密钥口令:`ios-platform-api-v2`
|
|
|
+- 密钥派生:对密钥口令做 `SHA-256`,得到 32 字节 AES key
|
|
|
+- 加密方式:`AES-256-CBC`
|
|
|
+- IV:每次加密随机生成 16 字节 IV
|
|
|
+- 输出内容:`Base64URL(IV + ciphertext)`
|
|
|
+- 解密方式:Base64URL 解码后,前 16 字节作为 IV,剩余字节作为 ciphertext,用相同密钥解密
|
|
|
+
|
|
|
+这个算法会使用随机 IV,同一份数据每次加密出来的字符串都可能不同。因为客户端持有加密/解密逻辑和密钥,所以它仍然不等于服务端保密,但请求参数和响应数据都不会直接以明文出现在接口里。
|
|
|
+
|
|
|
+## JavaScript 加解密
|
|
|
+
|
|
|
+浏览器环境使用 `crypto.subtle` 时通常需要安全上下文或 localhost;App、Unity、iOS 原生不受这个限制。
|
|
|
+
|
|
|
+```js
|
|
|
+function bytesToBase64Url(bytes) {
|
|
|
+ let binary = '';
|
|
|
+
|
|
|
+ for (let i = 0; i < bytes.length; i += 1) {
|
|
|
+ binary += String.fromCharCode(bytes[i]);
|
|
|
+ }
|
|
|
+
|
|
|
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
|
+}
|
|
|
+
|
|
|
+function base64UrlToBytes(value) {
|
|
|
+ const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
|
|
|
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
|
|
|
+ const binary = atob(padded);
|
|
|
+ const bytes = new Uint8Array(binary.length);
|
|
|
+
|
|
|
+ for (let i = 0; i < binary.length; i += 1) {
|
|
|
+ bytes[i] = binary.charCodeAt(i);
|
|
|
+ }
|
|
|
+
|
|
|
+ return bytes;
|
|
|
+}
|
|
|
+
|
|
|
+async function getClientCryptoKey() {
|
|
|
+ const secret = 'ios-platform-api-v2';
|
|
|
+ const keyBytes = await crypto.subtle.digest(
|
|
|
+ 'SHA-256',
|
|
|
+ new TextEncoder().encode(secret)
|
|
|
+ );
|
|
|
+
|
|
|
+ return crypto.subtle.importKey(
|
|
|
+ 'raw',
|
|
|
+ keyBytes,
|
|
|
+ { name: 'AES-CBC' },
|
|
|
+ false,
|
|
|
+ ['encrypt', 'decrypt']
|
|
|
+ );
|
|
|
+}
|
|
|
+
|
|
|
+async function encryptClientString(value) {
|
|
|
+ const iv = crypto.getRandomValues(new Uint8Array(16));
|
|
|
+ const key = await getClientCryptoKey();
|
|
|
+ const ciphertext = await crypto.subtle.encrypt(
|
|
|
+ { name: 'AES-CBC', iv },
|
|
|
+ key,
|
|
|
+ new TextEncoder().encode(value)
|
|
|
+ );
|
|
|
+ const bytes = new Uint8Array(iv.length + ciphertext.byteLength);
|
|
|
+
|
|
|
+ bytes.set(iv, 0);
|
|
|
+ bytes.set(new Uint8Array(ciphertext), iv.length);
|
|
|
+
|
|
|
+ return 'v2:' + bytesToBase64Url(bytes);
|
|
|
+}
|
|
|
+
|
|
|
+async function decryptClientString(value) {
|
|
|
+ if (!value || !value.startsWith('v2:')) {
|
|
|
+ return value;
|
|
|
+ }
|
|
|
+
|
|
|
+ const bytes = base64UrlToBytes(value.slice(3));
|
|
|
+ const iv = bytes.slice(0, 16);
|
|
|
+ const ciphertext = bytes.slice(16);
|
|
|
+ const key = await getClientCryptoKey();
|
|
|
+ const decrypted = await crypto.subtle.decrypt(
|
|
|
+ { name: 'AES-CBC', iv },
|
|
|
+ key,
|
|
|
+ ciphertext
|
|
|
+ );
|
|
|
+
|
|
|
+ return new TextDecoder().decode(decrypted);
|
|
|
+}
|
|
|
+
|
|
|
+async function encryptClientData(data) {
|
|
|
+ return encryptClientString(JSON.stringify(data));
|
|
|
+}
|
|
|
+
|
|
|
+async function decryptClientData(value) {
|
|
|
+ return JSON.parse(await decryptClientString(value));
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+### JavaScript 请求示例
|
|
|
+
|
|
|
+```js
|
|
|
+const PLATFORM_REQUEST_URL_CACHE_PREFIX = 'platform_request_url:';
|
|
|
+
|
|
|
+function getPlatformUrlCacheKey(channel) {
|
|
|
+ return PLATFORM_REQUEST_URL_CACHE_PREFIX + channel;
|
|
|
+}
|
|
|
+
|
|
|
+function isCompleteHttpUrl(value) {
|
|
|
+ return typeof value === 'string' && value.startsWith('http://');
|
|
|
+}
|
|
|
+
|
|
|
+function readCachedRequestUrl(channel) {
|
|
|
+ return localStorage.getItem(getPlatformUrlCacheKey(channel));
|
|
|
+}
|
|
|
+
|
|
|
+function writeCachedRequestUrl(channel, requestUrl) {
|
|
|
+ if (isCompleteHttpUrl(requestUrl)) {
|
|
|
+ localStorage.setItem(getPlatformUrlCacheKey(channel), requestUrl);
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+async function requestPlatform(channel) {
|
|
|
+ const payload = await encryptClientData({
|
|
|
+ channel,
|
|
|
+ language: navigator.language || 'zh-CN',
|
|
|
+ region: 'CN',
|
|
|
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
|
|
|
+ });
|
|
|
+ const response = await fetch('http://IP/api/platform', {
|
|
|
+ method: 'POST',
|
|
|
+ headers: {
|
|
|
+ Accept: 'application/json',
|
|
|
+ 'Content-Type': 'application/json'
|
|
|
+ },
|
|
|
+ body: JSON.stringify({ payload })
|
|
|
+ });
|
|
|
+
|
|
|
+ const body = await response.json();
|
|
|
+
|
|
|
+ if (!response.ok) {
|
|
|
+ throw new Error(body.message || '平台配置获取失败');
|
|
|
+ }
|
|
|
+
|
|
|
+ return decryptClientString(body.data);
|
|
|
+}
|
|
|
+
|
|
|
+async function fetchPlatformUrlWithBackup(channel) {
|
|
|
+ const cachedRequestUrl = readCachedRequestUrl(channel);
|
|
|
+
|
|
|
+ try {
|
|
|
+ const requestUrl = await requestPlatform(channel);
|
|
|
+
|
|
|
+ if (isCompleteHttpUrl(requestUrl)) {
|
|
|
+ writeCachedRequestUrl(channel, requestUrl);
|
|
|
+
|
|
|
+ return requestUrl;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (cachedRequestUrl) {
|
|
|
+ return cachedRequestUrl;
|
|
|
+ }
|
|
|
+
|
|
|
+ return requestUrl;
|
|
|
+ } catch (error) {
|
|
|
+ if (cachedRequestUrl) {
|
|
|
+ return cachedRequestUrl;
|
|
|
+ }
|
|
|
+
|
|
|
+ throw error;
|
|
|
+ }
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+客户端使用建议:
|
|
|
+
|
|
|
+- 请求 API 成功,并且解密后的 `data` 是完整 `http://` 地址:保存到本地缓存,并使用新的地址。
|
|
|
+- 请求 API 成功,但解密后的 `data` 是 `"0"`、空字符串或不是完整 `http://` 地址:不要覆盖本地缓存,优先使用本地缓存里的旧地址。
|
|
|
+- 请求 API 失败、超时或解析失败:优先使用本地缓存里的旧地址。
|
|
|
+- 本地没有缓存且 API 没有返回完整 URL:客户端按“暂无可用地址”处理。
|
|
|
+- 缓存建议按渠道隔离,例如 `platform_request_url:{channel}`。
|
|
|
+
|
|
|
+## PHP 加解密
|
|
|
+
|
|
|
+```php
|
|
|
+<?php
|
|
|
+
|
|
|
+const CLIENT_SECRET = 'ios-platform-api-v2';
|
|
|
+
|
|
|
+function base64UrlEncode(string $bytes): string
|
|
|
+{
|
|
|
+ return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
|
|
|
+}
|
|
|
+
|
|
|
+function base64UrlDecode(string $value): string
|
|
|
+{
|
|
|
+ $value .= str_repeat('=', (4 - strlen($value) % 4) % 4);
|
|
|
+
|
|
|
+ return base64_decode(strtr($value, '-_', '+/'));
|
|
|
+}
|
|
|
+
|
|
|
+function getClientKey(): string
|
|
|
+{
|
|
|
+ return hash('sha256', CLIENT_SECRET, true);
|
|
|
+}
|
|
|
+
|
|
|
+function encryptClientString(string $value): string
|
|
|
+{
|
|
|
+ $iv = random_bytes(16);
|
|
|
+ $ciphertext = openssl_encrypt(
|
|
|
+ $value,
|
|
|
+ 'AES-256-CBC',
|
|
|
+ getClientKey(),
|
|
|
+ OPENSSL_RAW_DATA,
|
|
|
+ $iv
|
|
|
+ );
|
|
|
+
|
|
|
+ if ($ciphertext === false) {
|
|
|
+ throw new RuntimeException('加密失败');
|
|
|
+ }
|
|
|
+
|
|
|
+ return 'v2:' . base64UrlEncode($iv . $ciphertext);
|
|
|
+}
|
|
|
+
|
|
|
+function decryptClientString(string $value): string
|
|
|
+{
|
|
|
+ if (strpos($value, 'v2:') !== 0) {
|
|
|
+ throw new InvalidArgumentException('加密字符串格式不正确');
|
|
|
+ }
|
|
|
+
|
|
|
+ $bytes = base64UrlDecode(substr($value, 3));
|
|
|
+ $iv = substr($bytes, 0, 16);
|
|
|
+ $ciphertext = substr($bytes, 16);
|
|
|
+ $plain = openssl_decrypt(
|
|
|
+ $ciphertext,
|
|
|
+ 'AES-256-CBC',
|
|
|
+ getClientKey(),
|
|
|
+ OPENSSL_RAW_DATA,
|
|
|
+ $iv
|
|
|
+ );
|
|
|
+
|
|
|
+ if ($plain === false) {
|
|
|
+ throw new RuntimeException('解密失败');
|
|
|
+ }
|
|
|
+
|
|
|
+ return $plain;
|
|
|
+}
|
|
|
+
|
|
|
+function encryptClientData(array $data): string
|
|
|
+{
|
|
|
+ return encryptClientString(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
|
|
+}
|
|
|
+
|
|
|
+function decryptClientData(string $value): array
|
|
|
+{
|
|
|
+ return json_decode(decryptClientString($value), true);
|
|
|
+}
|
|
|
+
|
|
|
+$payload = encryptClientData([
|
|
|
+ 'channel' => '243',
|
|
|
+ 'language' => 'zh-CN',
|
|
|
+ 'region' => 'CN',
|
|
|
+ 'timezone' => 'Asia/Shanghai',
|
|
|
+]);
|
|
|
+```
|
|
|
+
|
|
|
+## Unity C# 加解密
|
|
|
+
|
|
|
+Unity 可使用系统自带的 `System.Security.Cryptography`。下面代码返回的字符串和 JS/PHP/iOS 可以互相解密。
|
|
|
+
|
|
|
+```csharp
|
|
|
+using System;
|
|
|
+using System.Security.Cryptography;
|
|
|
+using System.Text;
|
|
|
+
|
|
|
+public static class ClientCrypto
|
|
|
+{
|
|
|
+ private const string Secret = "ios-platform-api-v2";
|
|
|
+
|
|
|
+ public static string EncryptString(string value)
|
|
|
+ {
|
|
|
+ using (var sha256 = SHA256.Create())
|
|
|
+ using (var aes = Aes.Create())
|
|
|
+ {
|
|
|
+ aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Secret));
|
|
|
+ aes.Mode = CipherMode.CBC;
|
|
|
+ aes.Padding = PaddingMode.PKCS7;
|
|
|
+ aes.GenerateIV();
|
|
|
+
|
|
|
+ byte[] plainBytes = Encoding.UTF8.GetBytes(value);
|
|
|
+ byte[] cipherBytes;
|
|
|
+
|
|
|
+ using (var encryptor = aes.CreateEncryptor())
|
|
|
+ {
|
|
|
+ cipherBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
|
|
|
+ }
|
|
|
+
|
|
|
+ byte[] output = new byte[aes.IV.Length + cipherBytes.Length];
|
|
|
+ Buffer.BlockCopy(aes.IV, 0, output, 0, aes.IV.Length);
|
|
|
+ Buffer.BlockCopy(cipherBytes, 0, output, aes.IV.Length, cipherBytes.Length);
|
|
|
+
|
|
|
+ return "v2:" + Base64UrlEncode(output);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public static string DecryptString(string value)
|
|
|
+ {
|
|
|
+ if (!value.StartsWith("v2:"))
|
|
|
+ {
|
|
|
+ throw new ArgumentException("加密字符串格式不正确");
|
|
|
+ }
|
|
|
+
|
|
|
+ byte[] bytes = Base64UrlDecode(value.Substring(3));
|
|
|
+ byte[] iv = new byte[16];
|
|
|
+ byte[] cipherBytes = new byte[bytes.Length - 16];
|
|
|
+
|
|
|
+ Buffer.BlockCopy(bytes, 0, iv, 0, 16);
|
|
|
+ Buffer.BlockCopy(bytes, 16, cipherBytes, 0, cipherBytes.Length);
|
|
|
+
|
|
|
+ using (var sha256 = SHA256.Create())
|
|
|
+ using (var aes = Aes.Create())
|
|
|
+ {
|
|
|
+ aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Secret));
|
|
|
+ aes.IV = iv;
|
|
|
+ aes.Mode = CipherMode.CBC;
|
|
|
+ aes.Padding = PaddingMode.PKCS7;
|
|
|
+
|
|
|
+ using (var decryptor = aes.CreateDecryptor())
|
|
|
+ {
|
|
|
+ byte[] plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
|
|
|
+
|
|
|
+ return Encoding.UTF8.GetString(plainBytes);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public static string EncryptJson(string json)
|
|
|
+ {
|
|
|
+ return EncryptString(json);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static string DecryptJson(string encrypted)
|
|
|
+ {
|
|
|
+ return DecryptString(encrypted);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static string Base64UrlEncode(byte[] bytes)
|
|
|
+ {
|
|
|
+ return Convert.ToBase64String(bytes)
|
|
|
+ .TrimEnd('=')
|
|
|
+ .Replace('+', '-')
|
|
|
+ .Replace('/', '_');
|
|
|
+ }
|
|
|
+
|
|
|
+ private static byte[] Base64UrlDecode(string value)
|
|
|
+ {
|
|
|
+ string base64 = value.Replace('-', '+').Replace('_', '/');
|
|
|
+
|
|
|
+ switch (base64.Length % 4)
|
|
|
+ {
|
|
|
+ case 2:
|
|
|
+ base64 += "==";
|
|
|
+ break;
|
|
|
+ case 3:
|
|
|
+ base64 += "=";
|
|
|
+ break;
|
|
|
+ }
|
|
|
+
|
|
|
+ return Convert.FromBase64String(base64);
|
|
|
+ }
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+Unity 请求示例:
|
|
|
+
|
|
|
+```csharp
|
|
|
+string lookupJson = "{\"channel\":\"243\",\"language\":\"zh-CN\",\"region\":\"CN\",\"timezone\":\"Asia/Shanghai\"}";
|
|
|
+string payload = ClientCrypto.EncryptJson(lookupJson);
|
|
|
+string requestBody = "{\"payload\":\"" + payload + "\"}";
|
|
|
+
|
|
|
+// 请求成功后,先解析响应 JSON,取出 body.data,再解密:
|
|
|
+// string platformJson = ClientCrypto.DecryptJson(body.data);
|
|
|
+```
|
|
|
+
|
|
|
+## iOS 原生 Swift 加解密
|
|
|
+
|
|
|
+iOS 原生 AES-CBC 可以用 `CommonCrypto`。如果项目不能直接 `import CommonCrypto`,在桥接头文件里加入:
|
|
|
+
|
|
|
+```objc
|
|
|
+#import <CommonCrypto/CommonCrypto.h>
|
|
|
+```
|
|
|
+
|
|
|
+Swift 示例:
|
|
|
+
|
|
|
+```swift
|
|
|
+import Foundation
|
|
|
+import CommonCrypto
|
|
|
+
|
|
|
+enum ClientCrypto {
|
|
|
+ static let secret = "ios-platform-api-v2"
|
|
|
+
|
|
|
+ static func encryptString(_ value: String) throws -> String {
|
|
|
+ let key = sha256(secret)
|
|
|
+ var iv = Data(count: kCCBlockSizeAES128)
|
|
|
+ let status = iv.withUnsafeMutableBytes { bytes in
|
|
|
+ SecRandomCopyBytes(kSecRandomDefault, kCCBlockSizeAES128, bytes.baseAddress!)
|
|
|
+ }
|
|
|
+
|
|
|
+ guard status == errSecSuccess else {
|
|
|
+ throw NSError(domain: "ClientCrypto", code: -1)
|
|
|
+ }
|
|
|
+
|
|
|
+ let plainData = Data(value.utf8)
|
|
|
+ let cipherData = try crypt(
|
|
|
+ operation: CCOperation(kCCEncrypt),
|
|
|
+ data: plainData,
|
|
|
+ key: key,
|
|
|
+ iv: iv
|
|
|
+ )
|
|
|
+
|
|
|
+ var output = Data()
|
|
|
+ output.append(iv)
|
|
|
+ output.append(cipherData)
|
|
|
+
|
|
|
+ return "v2:" + base64UrlEncode(output)
|
|
|
+ }
|
|
|
+
|
|
|
+ static func decryptString(_ value: String) throws -> String {
|
|
|
+ guard value.hasPrefix("v2:") else {
|
|
|
+ throw NSError(domain: "ClientCrypto", code: -2)
|
|
|
+ }
|
|
|
+
|
|
|
+ let bytes = try base64UrlDecode(String(value.dropFirst(3)))
|
|
|
+ let iv = Data(bytes.prefix(kCCBlockSizeAES128))
|
|
|
+ let cipherData = Data(bytes.dropFirst(kCCBlockSizeAES128))
|
|
|
+ let plainData = try crypt(
|
|
|
+ operation: CCOperation(kCCDecrypt),
|
|
|
+ data: cipherData,
|
|
|
+ key: sha256(secret),
|
|
|
+ iv: iv
|
|
|
+ )
|
|
|
+
|
|
|
+ guard let plain = String(data: plainData, encoding: .utf8) else {
|
|
|
+ throw NSError(domain: "ClientCrypto", code: -3)
|
|
|
+ }
|
|
|
+
|
|
|
+ return plain
|
|
|
+ }
|
|
|
+
|
|
|
+ static func encryptData(_ data: [String: Any]) throws -> String {
|
|
|
+ let jsonData = try JSONSerialization.data(withJSONObject: data, options: [])
|
|
|
+ let json = String(data: jsonData, encoding: .utf8)!
|
|
|
+
|
|
|
+ return try encryptString(json)
|
|
|
+ }
|
|
|
+
|
|
|
+ static func decryptData(_ value: String) throws -> [String: Any] {
|
|
|
+ let json = try decryptString(value)
|
|
|
+ let data = Data(json.utf8)
|
|
|
+
|
|
|
+ return try JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:]
|
|
|
+ }
|
|
|
+
|
|
|
+ private static func sha256(_ value: String) -> Data {
|
|
|
+ let data = Data(value.utf8)
|
|
|
+ var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
|
|
|
+
|
|
|
+ data.withUnsafeBytes { bytes in
|
|
|
+ _ = CC_SHA256(bytes.baseAddress, CC_LONG(data.count), &hash)
|
|
|
+ }
|
|
|
+
|
|
|
+ return Data(hash)
|
|
|
+ }
|
|
|
+
|
|
|
+ private static func crypt(operation: CCOperation, data: Data, key: Data, iv: Data) throws -> Data {
|
|
|
+ var output = Data(count: data.count + kCCBlockSizeAES128)
|
|
|
+ var outputLength: size_t = 0
|
|
|
+
|
|
|
+ let status = output.withUnsafeMutableBytes { outputBytes in
|
|
|
+ data.withUnsafeBytes { dataBytes in
|
|
|
+ key.withUnsafeBytes { keyBytes in
|
|
|
+ iv.withUnsafeBytes { ivBytes in
|
|
|
+ CCCrypt(
|
|
|
+ operation,
|
|
|
+ CCAlgorithm(kCCAlgorithmAES),
|
|
|
+ CCOptions(kCCOptionPKCS7Padding),
|
|
|
+ keyBytes.baseAddress,
|
|
|
+ kCCKeySizeAES256,
|
|
|
+ ivBytes.baseAddress,
|
|
|
+ dataBytes.baseAddress,
|
|
|
+ data.count,
|
|
|
+ outputBytes.baseAddress,
|
|
|
+ output.count,
|
|
|
+ &outputLength
|
|
|
+ )
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ guard status == kCCSuccess else {
|
|
|
+ throw NSError(domain: "ClientCrypto", code: Int(status))
|
|
|
+ }
|
|
|
+
|
|
|
+ output.removeSubrange(outputLength..<output.count)
|
|
|
+
|
|
|
+ return output
|
|
|
+ }
|
|
|
+
|
|
|
+ private static func base64UrlEncode(_ data: Data) -> String {
|
|
|
+ return data.base64EncodedString()
|
|
|
+ .replacingOccurrences(of: "+", with: "-")
|
|
|
+ .replacingOccurrences(of: "/", with: "_")
|
|
|
+ .replacingOccurrences(of: "=", with: "")
|
|
|
+ }
|
|
|
+
|
|
|
+ private static func base64UrlDecode(_ value: String) throws -> Data {
|
|
|
+ var base64 = value
|
|
|
+ .replacingOccurrences(of: "-", with: "+")
|
|
|
+ .replacingOccurrences(of: "_", with: "/")
|
|
|
+
|
|
|
+ let padding = (4 - base64.count % 4) % 4
|
|
|
+ base64 += String(repeating: "=", count: padding)
|
|
|
+
|
|
|
+ guard let data = Data(base64Encoded: base64) else {
|
|
|
+ throw NSError(domain: "ClientCrypto", code: -4)
|
|
|
+ }
|
|
|
+
|
|
|
+ return data
|
|
|
+ }
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+iOS 请求前生成 payload:
|
|
|
+
|
|
|
+```swift
|
|
|
+let payload = try ClientCrypto.encryptData([
|
|
|
+ "channel": "243",
|
|
|
+ "language": "zh-CN",
|
|
|
+ "region": "CN",
|
|
|
+ "timezone": TimeZone.current.identifier
|
|
|
+])
|
|
|
+let body = ["payload": payload]
|
|
|
+```
|