| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- #if UNITY_EDITOR
- using System;
- using System.Security.Cryptography;
- using System.Text;
- using UnityEngine;
- 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 (string.IsNullOrEmpty(value) || !value.StartsWith("v2:"))
- {
- throw new ArgumentException("Invalid encrypted string format >> " + value);
- }
- 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)
- {
- try
- {
- return DecryptString(encrypted);
- }
- catch (Exception e)
- {
- Debug.LogError($"error: {e}");
- return string.Empty;
- }
- }
- 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);
- }
- }
- #endif
|