953 lines
32 KiB
C#
953 lines
32 KiB
C#
using BestHTTP.JSON;
|
||
using Newtonsoft.Json;
|
||
using Newtonsoft.Json.Linq;
|
||
using SimpleJSON;
|
||
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Net.Http;
|
||
using System.Net.Http.Headers;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
using Unity.VisualScripting;
|
||
using UnityEngine;
|
||
using UnityEngine.Networking;
|
||
using static UnityEngine.Rendering.DebugUI;
|
||
|
||
/// <summary>
|
||
///整合JSON
|
||
/// </summary>
|
||
public static class CombineJSON
|
||
{
|
||
//public static List<string> jsons = new List<string>();
|
||
public static Dictionary<string, string> jsonsDic = new Dictionary<string, string>();
|
||
|
||
#region 直连
|
||
/// <summary>
|
||
/// 获取所有设备API
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public static string GetCombineJSON()
|
||
{
|
||
//创建一个JArray对象,用于存储多个JSON 对象
|
||
JArray jsonArray = new JArray();
|
||
|
||
// 解析JSON字符串,并添加到JArray
|
||
foreach (var item in jsonsDic.Values)
|
||
{
|
||
var jsonObj = JObject.Parse(item);
|
||
jsonArray.Add(jsonObj);
|
||
}
|
||
|
||
//创建一个包含JArray的JObject对象
|
||
JObject resultObj = new JObject();
|
||
resultObj["data"] = jsonArray;
|
||
|
||
//将整合后的JSON输出成字符串
|
||
string resultJson = resultObj.ToString();
|
||
return resultJson;
|
||
}
|
||
|
||
/// <summary>
|
||
/// POST修改数据的请求
|
||
/// </summary>
|
||
/// <param name="apiUrl"></param>
|
||
/// <param name="newData"></param>
|
||
/// <returns></returns>
|
||
/// <exception cref="Exception"></exception>
|
||
public static async Task<string> UpdateJson_POST(string apiUrl, string token, string newData)
|
||
{
|
||
var client = new HttpClient();
|
||
var request = new HttpRequestMessage
|
||
{
|
||
Method = HttpMethod.Post,
|
||
RequestUri = new Uri(apiUrl),
|
||
Headers =
|
||
{
|
||
{ "X-Token", token },
|
||
},
|
||
Content = new StringContent(newData)
|
||
{
|
||
Headers =
|
||
{
|
||
ContentType = new MediaTypeHeaderValue("application/json")
|
||
}
|
||
}
|
||
};
|
||
using (var response = await client.SendAsync(request))
|
||
{
|
||
response.EnsureSuccessStatusCode();
|
||
var body = await response.Content.ReadAsStringAsync();
|
||
return body;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// POST获取数据的请求
|
||
/// </summary>
|
||
/// <param name="apiUrl"></param>
|
||
/// <param name="token"></param>
|
||
/// <returns></returns>
|
||
public static async Task<string> GetJson_POST(string apiUrl, string token)
|
||
{
|
||
using (HttpClient httpClient = new HttpClient())
|
||
{
|
||
Debug.Log(apiUrl + "=aaaaaa=");
|
||
var client = new HttpClient();
|
||
var request = new HttpRequestMessage
|
||
{
|
||
Method = HttpMethod.Post,
|
||
RequestUri = new Uri(apiUrl),
|
||
Headers =
|
||
{
|
||
{ "X-Token", token },
|
||
},
|
||
};
|
||
using (var response = await client.SendAsync(request))
|
||
{
|
||
Debug.Log(apiUrl + "=bbbbbbb=");
|
||
|
||
response.EnsureSuccessStatusCode();
|
||
var body = await response.Content.ReadAsStringAsync();
|
||
Debug.Log(body);
|
||
return (body);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取GET接口
|
||
/// </summary>
|
||
/// <param name="apiUrl"></param>
|
||
/// <returns></returns>
|
||
public static async Task<string> GetJson_GET(string apiUrl)
|
||
{
|
||
using (var httpClient = new HttpClient())
|
||
{
|
||
using (var response = await httpClient.GetAsync(apiUrl))
|
||
{
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
string jsonResult = await response.Content.ReadAsStringAsync();
|
||
// 处理返回的JSON数据
|
||
Debug.Log(jsonResult);
|
||
return jsonResult;
|
||
}
|
||
else
|
||
{
|
||
Debug.Log("请求GET接口失败: " + response.StatusCode);
|
||
return null;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
|
||
#region 协程调用接口
|
||
|
||
|
||
/// <summary>
|
||
/// POST获取数据的请求(无参)
|
||
/// </summary>
|
||
/// <param name="apiUrl"></param>
|
||
/// <param name="token"></param>
|
||
/// <param name="callback"></param>
|
||
/// <returns></returns>
|
||
public static IEnumerator GetJson_POST(string apiUrl, string token, Action<string> callback)
|
||
{
|
||
Debug.Log("请求接口:" + apiUrl);
|
||
//using (UnityWebRequest request = UnityWebRequest.Post(apiUrl, ""))
|
||
UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
|
||
{
|
||
request.SetRequestHeader("X-Token", token);
|
||
request.SetRequestHeader("Content-Type", "application/json");
|
||
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
|
||
request.downloadHandler = dH;
|
||
//request.timeout = 15;
|
||
yield return request.SendWebRequest();
|
||
|
||
if (!request.isNetworkError && !request.isHttpError)
|
||
{
|
||
// 等待一帧
|
||
yield return null;
|
||
|
||
// 检查请求是否已完成
|
||
while (!request.isDone)
|
||
{
|
||
yield return null;
|
||
}
|
||
//if (request.downloadHandler.text != null)
|
||
if (!string.IsNullOrEmpty(request.downloadHandler.text))
|
||
//byte[] responseData = request.downloadHandler.data;
|
||
//if (responseData != null && responseData.Length > 0)
|
||
{
|
||
string responseText = request.downloadHandler.text;
|
||
//responseText = Decrypt(responseText);
|
||
//Debug.Log(responseText);
|
||
//string responseText = Encoding.UTF8.GetString(responseData);
|
||
callback(responseText);
|
||
}
|
||
else
|
||
{
|
||
Debug.Log(apiUrl + " request.downloadHandler.text为null");
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Debug.Log(apiUrl + " 请求POST接口失败: " + request.error + "\nURL: " + apiUrl + "\nrequest.downloadHandler:" + /*Decrypt*/(request.downloadHandler.text));
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// POST数据的请求(有参)
|
||
/// </summary>
|
||
/// <param name="apiUrl"></param>
|
||
/// <param name="token"></param>
|
||
/// <param name="newData"></param>
|
||
/// <param name="onComplete"></param>
|
||
/// <returns></returns>
|
||
public static IEnumerator UpdateJson_POST(string apiUrl, string token, string newData, Action<string> callback)
|
||
{
|
||
//newData = AESEncryption.Encrypt(newData);
|
||
//using (UnityWebRequest request = new UnityWebRequest(apiUrl, "POST"))
|
||
UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
|
||
{
|
||
request.SetRequestHeader("X-Token", token);
|
||
request.SetRequestHeader("Content-Type", "application/json");
|
||
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(newData);
|
||
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
|
||
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
|
||
request.downloadHandler = new DownloadHandlerBuffer();
|
||
request.downloadHandler = dH;
|
||
//request.timeout = 15;
|
||
yield return request.SendWebRequest();
|
||
|
||
if (request.result == UnityWebRequest.Result.Success)
|
||
{
|
||
// 等待一帧
|
||
yield return null;
|
||
|
||
// 检查请求是否已完成
|
||
while (!request.isDone)
|
||
{
|
||
yield return null;
|
||
}
|
||
//if (request.downloadHandler.text != null)
|
||
if (!string.IsNullOrEmpty(request.downloadHandler.text))
|
||
//byte[] responseData = request.downloadHandler.data;
|
||
//if (responseData != null && responseData.Length > 0)
|
||
{
|
||
string responseText = request.downloadHandler.text;
|
||
//responseText = Decrypt(responseText);
|
||
//string responseText = Encoding.UTF8.GetString(responseData);
|
||
callback?.Invoke(responseText);
|
||
}
|
||
else
|
||
{
|
||
Debug.Log(apiUrl + " request.downloadHandler.text为空");
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Debug.Log(apiUrl + " 请求POST接口失败: " + request.error + "\nURL: " + apiUrl + "\nrequest.downloadHandler:" + /*Decrypt*/(request.downloadHandler.text));
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取GET接口
|
||
/// </summary>
|
||
/// <param name="apiUrl"></param>
|
||
/// <returns></returns>
|
||
public static IEnumerator GetJson_GET(string apiUrl, Action<string> callback)
|
||
{
|
||
using (UnityWebRequest request = UnityWebRequest.Get(apiUrl))
|
||
{
|
||
yield return request.SendWebRequest();
|
||
|
||
if (!request.isNetworkError && !request.isHttpError)
|
||
{
|
||
if (request.downloadHandler.text != null)
|
||
{
|
||
string jsonResult = request.downloadHandler.text;
|
||
//Debug.Log(jsonResult);
|
||
callback?.Invoke(jsonResult);
|
||
}
|
||
else
|
||
{
|
||
Debug.Log("request.downloadHandler.text为null");
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Debug.Log("请求GET接口失败: " + request.error);
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
}
|
||
|
||
public static IEnumerator GetJson_GET(string apiUrl, string token, Action<string> callback)
|
||
{
|
||
//using (UnityWebRequest request = UnityWebRequest.Get(apiUrl))
|
||
UnityWebRequest request = UnityWebRequest.Get(apiUrl);
|
||
{
|
||
request.SetRequestHeader("X-Token", token);
|
||
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
|
||
request.downloadHandler = dH;
|
||
//request.timeout = 15;
|
||
yield return request.SendWebRequest();
|
||
|
||
if (request.result == UnityWebRequest.Result.Success)
|
||
{
|
||
// 等待一帧
|
||
yield return null;
|
||
|
||
// 检查请求是否已完成
|
||
while (!request.isDone)
|
||
{
|
||
yield return null;
|
||
}
|
||
//string responseBody = request.downloadHandler.text;
|
||
//if (request.downloadHandler.text != null)
|
||
if (!string.IsNullOrEmpty(request.downloadHandler.text))
|
||
// byte[] responseData = request.downloadHandler.data;
|
||
//if (responseData != null && responseData.Length > 0)
|
||
{
|
||
string responseText = request.downloadHandler.text;
|
||
//string responseText = Encoding.UTF8.GetString(responseData);
|
||
callback?.Invoke(responseText);
|
||
}
|
||
else
|
||
{
|
||
Debug.Log(apiUrl + " request.downloadHandler.text为空");
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Debug.Log(apiUrl + " 请求Get接口失败: " + request.error + "\nURL: " + apiUrl + "\nrequest.downloadHandler:" + request.downloadHandler.text);
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// GET传参
|
||
/// </summary>
|
||
/// <param name="apiUrl"></param>
|
||
/// <param name="content"></param>
|
||
/// <param name="token"></param>
|
||
/// <param name="callback"></param>
|
||
/// <returns></returns>
|
||
public static IEnumerator GetJson_GET(string apiUrl, string content, string token, Action<string> callback)
|
||
{
|
||
//using (UnityWebRequest request = UnityWebRequest.Get(apiUrl))
|
||
UnityWebRequest request = UnityWebRequest.Get(apiUrl + "?json=" + content);
|
||
{
|
||
request.SetRequestHeader("X-Token", token);
|
||
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
|
||
request.downloadHandler = dH;
|
||
//request.timeout = 15;
|
||
yield return request.SendWebRequest();
|
||
|
||
if (request.result == UnityWebRequest.Result.Success)
|
||
{
|
||
// 等待一帧
|
||
yield return null;
|
||
|
||
// 检查请求是否已完成
|
||
while (!request.isDone)
|
||
{
|
||
yield return null;
|
||
}
|
||
//string responseBody = request.downloadHandler.text;
|
||
//if (request.downloadHandler.text != null)
|
||
if (!string.IsNullOrEmpty(request.downloadHandler.text))
|
||
// byte[] responseData = request.downloadHandler.data;
|
||
//if (responseData != null && responseData.Length > 0)
|
||
{
|
||
string responseText = request.downloadHandler.text;
|
||
//string responseText = Encoding.UTF8.GetString(responseData);
|
||
callback?.Invoke(responseText);
|
||
}
|
||
else
|
||
{
|
||
Debug.Log(apiUrl + " request.downloadHandler.text为空");
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Debug.Log(apiUrl + " 请求Get接口失败: " + request.error + "\nURL: " + apiUrl + "\nrequest.downloadHandler:" + request.downloadHandler.text);
|
||
callback?.Invoke(null);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取本地文本
|
||
/// </summary>
|
||
/// <param name="_url"></param>
|
||
/// <param name="_callback"></param>
|
||
/// <returns></returns>
|
||
public static IEnumerator ReadLocalText(string _url, Action<string, string> _callback = null)
|
||
{
|
||
string json = string.Empty;
|
||
using (StreamReader reader = new StreamReader(_url, System.Text.Encoding.UTF8))
|
||
{
|
||
json = reader.ReadToEnd();
|
||
}
|
||
|
||
yield return null;
|
||
|
||
Debug.Log(json);
|
||
|
||
_callback?.Invoke(null, json);
|
||
}
|
||
|
||
public static IEnumerator GetJson_POST(string apiUrl, string token, int looptime, Action<string> callback)
|
||
{
|
||
while (true)
|
||
{
|
||
|
||
UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
|
||
{
|
||
request.SetRequestHeader("X-Token", token);
|
||
request.SetRequestHeader("Content-Type", "application/json");
|
||
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
|
||
request.downloadHandler = dH;
|
||
request.timeout = 15;
|
||
yield return request.SendWebRequest();
|
||
|
||
if (!request.isNetworkError && !request.isHttpError)
|
||
{
|
||
// 等待一帧
|
||
yield return null;
|
||
|
||
// 检查请求是否已完成
|
||
while (!request.isDone)
|
||
{
|
||
yield return null;
|
||
}
|
||
//if (request.downloadHandler.text != null)
|
||
if (!string.IsNullOrEmpty(request.downloadHandler.text))
|
||
// byte[] responseData = request.downloadHandler.data;
|
||
//if (responseData != null && responseData.Length > 0)
|
||
{
|
||
string responseText = request.downloadHandler.text;
|
||
//Debug.Log(responseText);
|
||
//string responseText = Encoding.UTF8.GetString(responseData);
|
||
callback(responseText);
|
||
}
|
||
else
|
||
{
|
||
Debug.Log("request.downloadHandler.text为null");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Debug.Log("请求POST接口失败: " + request.error + "\nURL: " + apiUrl + "\nrequest.downloadHandler:" + request.downloadHandler.text);
|
||
}
|
||
}
|
||
yield return new WaitForSeconds(looptime);
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
|
||
|
||
#region Base64
|
||
/// <summary>
|
||
/// Base64转图片
|
||
/// </summary>
|
||
/// <param name="base64Str"></param>
|
||
/// <returns></returns>
|
||
public static Texture2D Base64StringToTexture(string base64Str)
|
||
{
|
||
try
|
||
{
|
||
//将base64头部信息替换
|
||
base64Str = base64Str.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "")
|
||
.Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");
|
||
byte[] bytes = Convert.FromBase64String(base64Str);
|
||
Texture2D texture = new Texture2D(10, 10);
|
||
texture.LoadImage(bytes);
|
||
return texture;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将图片转Base64
|
||
/// </summary>
|
||
/// <param name="imageUrl"></param>
|
||
/// <param name="_callback"></param>
|
||
/// <returns></returns>
|
||
public static IEnumerator SaveImageAsBase64(string imageUrl, string id, Action<string, string> _callback)
|
||
{
|
||
UnityWebRequest request = UnityWebRequestTexture.GetTexture(imageUrl);
|
||
yield return request.SendWebRequest();
|
||
|
||
if (request.result != UnityWebRequest.Result.Success)
|
||
{
|
||
Debug.LogError("下载映像出错: " + request.error);
|
||
_callback?.Invoke(null, null);
|
||
}
|
||
else
|
||
{
|
||
Texture2D texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
|
||
byte[] imageBytes = texture.EncodeToJPG(); // 根据实际需要选择其他格式进行编码
|
||
string base64String = System.Convert.ToBase64String(imageBytes);
|
||
Debug.Log($"base64String:{base64String},热成像数据记录id:{id}");
|
||
_callback?.Invoke(base64String, id);
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
|
||
|
||
#region AES
|
||
public static string Decrypt(string cipherText, string key = "1234567890adbcde", string iv = "1234567890hjlkew")
|
||
{
|
||
//return cipherText;
|
||
try
|
||
{
|
||
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
|
||
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
|
||
|
||
using (var aesAlg = System.Security.Cryptography.Aes.Create())
|
||
{
|
||
aesAlg.Key = keyBytes;
|
||
aesAlg.IV = ivBytes;
|
||
aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
|
||
aesAlg.Padding = System.Security.Cryptography.PaddingMode.None; // Set to None initially
|
||
|
||
var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
|
||
|
||
byte[] cipherBytes = Convert.FromBase64String(cipherText);
|
||
|
||
using (var msDecrypt = new System.IO.MemoryStream(cipherBytes))
|
||
{
|
||
using (var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
|
||
{
|
||
using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
|
||
{
|
||
return srDecrypt.ReadToEnd().TrimEnd('\0');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Debug.Log("解密错误: " + ex.Message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
public static string Encrypt(string plainText, string key = "1234567890adbcde", string iv = "1234567890hjlkew")
|
||
{
|
||
//return plainText;
|
||
using (AesManaged aesAlg = new AesManaged())
|
||
{
|
||
aesAlg.Key = Encoding.UTF8.GetBytes(key);
|
||
aesAlg.IV = Encoding.UTF8.GetBytes(iv);
|
||
|
||
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
|
||
|
||
byte[] encryptedBytes;
|
||
|
||
using (var msEncrypt = new System.IO.MemoryStream())
|
||
{
|
||
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
|
||
{
|
||
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
|
||
csEncrypt.Write(plainBytes, 0, plainBytes.Length);
|
||
}
|
||
|
||
encryptedBytes = msEncrypt.ToArray();
|
||
}
|
||
|
||
return Convert.ToBase64String(encryptedBytes);
|
||
}
|
||
}
|
||
|
||
public class AESEncryption
|
||
{
|
||
//private static byte[] key = Encoding.UTF8.GetBytes("1234567890adbcde");
|
||
//private static byte[] iv = Encoding.UTF8.GetBytes("1234567890hjlkew");
|
||
|
||
|
||
//public static string Encrypt(string plainText)
|
||
//{
|
||
// plainText = JsonConvert.SerializeObject(new user());
|
||
// using (var aesAlg = Aes.Create())
|
||
// {
|
||
// aesAlg.Key = key;
|
||
// aesAlg.IV = iv;
|
||
|
||
// var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
|
||
|
||
// var plainBytes = Encoding.UTF8.GetBytes(plainText);
|
||
// var cipherBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
|
||
|
||
// return Convert.ToBase64String(cipherBytes);
|
||
// }
|
||
//}
|
||
|
||
//public static string Decrypt(string encryptedText)
|
||
//{
|
||
// using (var aesAlg = Aes.Create())
|
||
// {
|
||
// aesAlg.Key = key;
|
||
// aesAlg.IV = iv;
|
||
|
||
// var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
|
||
|
||
// var cipherBytes = Convert.FromBase64String(encryptedText);
|
||
// var plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
|
||
|
||
// return Encoding.UTF8.GetString(plainBytes);
|
||
// }
|
||
//}
|
||
|
||
|
||
private const string key = "1234567890adbcde";
|
||
private const string iv = "1234567890hjlkew";
|
||
|
||
/// <summary>
|
||
/// 加密
|
||
/// </summary>
|
||
/// <param name="plainText">需要加密的字符串</param>
|
||
/// <returns></returns>
|
||
public static string EncryptString(string plainText)
|
||
{
|
||
plainText = JsonConvert.SerializeObject(new user());
|
||
byte[] encrypted;
|
||
using (Aes aesAlg = Aes.Create())
|
||
{
|
||
aesAlg.Key = Encoding.UTF8.GetBytes(Key);
|
||
aesAlg.IV = Encoding.UTF8.GetBytes(IV);
|
||
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
|
||
using (MemoryStream msEncrypt = new MemoryStream())
|
||
{
|
||
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
|
||
{
|
||
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt, Encoding.UTF8))
|
||
{
|
||
swEncrypt.Write(plainText);
|
||
}
|
||
encrypted = msEncrypt.ToArray();
|
||
}
|
||
}
|
||
}
|
||
return Convert.ToBase64String(encrypted);
|
||
}
|
||
/// <summary>
|
||
/// 解密
|
||
/// </summary>
|
||
/// <param name="cipherStr">需要解密的字符串</param>
|
||
/// <returns></returns>
|
||
public static string DecryptString(string cipherStr)
|
||
{
|
||
var cipherText = Convert.FromBase64String(cipherStr);
|
||
if (cipherText == null || cipherText.Length <= 0)
|
||
throw new ArgumentNullException("cipherText");
|
||
string plaintext = null;
|
||
using (Aes aesAlg = Aes.Create())
|
||
{
|
||
aesAlg.Key = Encoding.UTF8.GetBytes(Key);
|
||
aesAlg.IV = Encoding.UTF8.GetBytes(IV);
|
||
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
|
||
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
|
||
{
|
||
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
|
||
{
|
||
using (StreamReader srDecrypt = new StreamReader(csDecrypt, Encoding.UTF8))
|
||
{
|
||
plaintext = srDecrypt.ReadToEnd();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return plaintext;
|
||
}
|
||
|
||
|
||
public const string Key = "1234567890adbcde";
|
||
public const string IV = "1234567890hjlkew";
|
||
|
||
public static string Encrypt(string plainText)
|
||
{
|
||
byte[] encrypted;
|
||
using (Aes aes = Aes.Create())
|
||
{
|
||
aes.Key = Encoding.UTF8.GetBytes(key);
|
||
aes.IV = Encoding.UTF8.GetBytes(iv);
|
||
aes.Mode = CipherMode.CBC;
|
||
aes.Padding = PaddingMode.None;
|
||
|
||
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
|
||
|
||
using (MemoryStream msEncrypt = new MemoryStream())
|
||
{
|
||
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
|
||
{
|
||
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
|
||
{
|
||
swEncrypt.Write(plainText);
|
||
}
|
||
encrypted = msEncrypt.ToArray();
|
||
}
|
||
}
|
||
}
|
||
return Convert.ToBase64String(encrypted);
|
||
}
|
||
|
||
public static string Decrypt(string cipherText)
|
||
{
|
||
string plaintext = null;
|
||
using (Aes aes = Aes.Create())
|
||
{
|
||
aes.Key = Encoding.UTF8.GetBytes(key);
|
||
aes.IV = Encoding.UTF8.GetBytes(iv);
|
||
aes.Mode = CipherMode.CBC;
|
||
aes.Padding = PaddingMode.None;
|
||
|
||
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
|
||
|
||
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
|
||
{
|
||
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
|
||
{
|
||
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
|
||
{
|
||
plaintext = srDecrypt.ReadToEnd();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return plaintext;
|
||
}
|
||
|
||
public class user
|
||
{
|
||
public string username = "p6k5b9h9Yfp8Hxf75vO0sA==";
|
||
public string password = "It8gXWKtH3hA0hLc+q79Lg==";
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// AES 加密、解密帮助类
|
||
/// 兼容Java 加密解密
|
||
/// </summary>
|
||
public class AESEncrypt
|
||
{
|
||
private const string key = "1234567890adbcde";
|
||
private const string iv = "1234567890hjlkew";
|
||
|
||
|
||
#region ========加密========
|
||
/// <summary>
|
||
/// 加密
|
||
/// </summary>
|
||
/// <param name="Text">需要加密的内容</param>
|
||
/// <returns></returns>
|
||
public static string Encrypt(string Text)
|
||
{
|
||
//Text = JsonConvert.SerializeObject(new AESEncryption.user());
|
||
return Encrypt(Text, key);
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// AES加密
|
||
/// </summary>
|
||
/// <param name="text">加密字符</param>
|
||
/// <param name="password">加密的密码</param>
|
||
/// <param name="iv">密钥</param>
|
||
/// <returns></returns>
|
||
public static string Encrypt(string text, string password)
|
||
{
|
||
RijndaelManaged rijndaelCipher = new RijndaelManaged();
|
||
|
||
rijndaelCipher.Mode = CipherMode.CBC;
|
||
|
||
rijndaelCipher.Padding = PaddingMode.None;
|
||
|
||
rijndaelCipher.KeySize = 128;
|
||
|
||
rijndaelCipher.BlockSize = 128;
|
||
|
||
//byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
|
||
byte[] pwdBytes = getKey(password);
|
||
byte[] _ivBytes = getKey(iv);
|
||
byte[] keyBytes = new byte[16];
|
||
byte[] ivBytes = new byte[16];
|
||
|
||
int len = pwdBytes.Length;
|
||
|
||
if (len > keyBytes.Length) len = keyBytes.Length;
|
||
|
||
System.Array.Copy(pwdBytes, keyBytes, len);
|
||
|
||
System.Array.Copy(_ivBytes, ivBytes, len);
|
||
|
||
rijndaelCipher.Key = keyBytes;
|
||
|
||
rijndaelCipher.IV = ivBytes;
|
||
|
||
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
|
||
|
||
byte[] plainText = Encoding.UTF8.GetBytes(text);
|
||
|
||
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
|
||
|
||
return Convert.ToBase64String(cipherBytes);
|
||
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region ========解密========
|
||
|
||
|
||
/// <summary>
|
||
/// 解密
|
||
/// </summary>
|
||
/// <param name="Text">需要解密的内容</param>
|
||
/// <returns></returns>
|
||
public static string Decrypt(string Text)
|
||
{
|
||
if (!string.IsNullOrEmpty(Text))
|
||
{
|
||
return Decrypt(Text, key);
|
||
}
|
||
else
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// AES解密
|
||
/// </summary>
|
||
/// <param name="text"></param>
|
||
/// <param name="password"></param>
|
||
/// <param name="iv"></param>
|
||
/// <returns></returns>
|
||
public static string Decrypt(string text, string password)
|
||
{
|
||
RijndaelManaged rijndaelCipher = new RijndaelManaged();
|
||
|
||
rijndaelCipher.Mode = CipherMode.CBC;
|
||
|
||
rijndaelCipher.Padding = PaddingMode.None;
|
||
|
||
rijndaelCipher.KeySize = 128;
|
||
|
||
rijndaelCipher.BlockSize = 128;
|
||
|
||
byte[] encryptedData = Convert.FromBase64String(text);
|
||
//byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
|
||
byte[] pwdBytes = getKey(password);
|
||
byte[] _ivBytes = getKey(iv);
|
||
byte[] keyBytes = new byte[16];
|
||
byte[] ivBytes = new byte[16];
|
||
|
||
int len = pwdBytes.Length;
|
||
|
||
if (len > keyBytes.Length) len = keyBytes.Length;
|
||
|
||
System.Array.Copy(pwdBytes, keyBytes, len);
|
||
|
||
System.Array.Copy(_ivBytes, ivBytes, len);
|
||
|
||
rijndaelCipher.Key = keyBytes;
|
||
|
||
rijndaelCipher.IV = ivBytes;
|
||
|
||
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
|
||
|
||
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
|
||
|
||
return Encoding.UTF8.GetString(plainText);
|
||
|
||
}
|
||
|
||
|
||
#endregion
|
||
|
||
#region 初始化密钥
|
||
/// <summary>
|
||
/// 初始化密钥
|
||
/// </summary>
|
||
/// <param name="secret"></param>
|
||
/// <returns></returns>
|
||
public static byte[] getKey(string secret)
|
||
{
|
||
|
||
try
|
||
{
|
||
byte[] seed = Encoding.UTF8.GetBytes(secret);
|
||
using (var st = new SHA1CryptoServiceProvider())
|
||
{
|
||
//return sha1.ComputeHash(seed);
|
||
using (var nd = new SHA1CryptoServiceProvider())
|
||
{
|
||
var rd = nd.ComputeHash(st.ComputeHash(seed));
|
||
byte[] keyArray = rd.Take(16).ToArray();
|
||
return keyArray;
|
||
}
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
throw new Exception("初始化密钥出现异常");
|
||
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
|
||
}
|
||
#endregion
|
||
|
||
|
||
#region 从本地加载JSON
|
||
public static IEnumerator LoadTxtJson(string url, Action<string> _callback)
|
||
{
|
||
using (WWW www = new WWW(url))
|
||
{
|
||
yield return www;
|
||
|
||
if (string.IsNullOrEmpty(www.error))
|
||
{
|
||
_callback(www.text);
|
||
|
||
}
|
||
else
|
||
{
|
||
Debug.LogError("从本地加载JSON时出错:" + www.error);
|
||
}
|
||
}
|
||
}
|
||
#endregion
|
||
}
|