diff --git a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs index fe23c07..968cd06 100644 --- a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs +++ b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs @@ -50,4 +50,24 @@ public IEnumerator logout(LogoutApiRequest logoutApiRequest, Action cal else callback(null); } + + public IEnumerator createSession(LogoutApiRequest logoutApiRequest, Action callback) + { + WWWForm data = new WWWForm(); + data.AddField("key", logoutApiRequest.key); + data.AddField("data", logoutApiRequest.data); + data.AddField("signature", logoutApiRequest.signature); + data.AddField("timeout", logoutApiRequest.timeout.ToString()); + + var request = UnityWebRequest.Post($"{baseAddress}/store/set", data); + yield return request.SendWebRequest(); + + if (request.result == UnityWebRequest.Result.Success) + { + string result = request.downloadHandler.text; + callback(Newtonsoft.Json.JsonConvert.DeserializeObject(result)); + } + else + callback(null); + } } diff --git a/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs b/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs index 20cf345..fd321de 100644 --- a/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs +++ b/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs @@ -6,6 +6,10 @@ using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities.Encoders; using System.Runtime.InteropServices; +using Org.BouncyCastle.Security; +using Org.BouncyCastle.OpenSsl; +using Org.BouncyCastle.Crypto; +using System.Text; public class KeyStoreManagerUtils { @@ -76,6 +80,36 @@ public static void deletePreferencesData(string key) #endif } + public static AsymmetricCipherKeyPair generateECKeyPair() + { + var secureRandom = new SecureRandom(); + var curve = SecNamedCurves.GetByName("secp256k1"); + var domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed()); + + var keyGenParam = new ECKeyGenerationParameters(domainParams, secureRandom); + var generator = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); + generator.Init(keyGenParam); + + return generator.GenerateKeyPair(); + } + + public static string generateRandomSessionKey() { + var keyPair = generateECKeyPair(); + var privateKey = (ECPrivateKeyParameters)keyPair.Private; + var publicKey = (ECPublicKeyParameters)keyPair.Public; + + string privateKeyHex = privateKey.D.ToString(16).PadLeft(64, '0'); + return privateKeyHex; + } + + public static byte[] generateRandomBytes() + { + var secureRandom = new SecureRandom(); + byte[] bytes = new byte[16]; + secureRandom.NextBytes(bytes); + return bytes; + } + public static string getECDSASignature(string privateKey, string data){ var curve = SecNamedCurves.GetByName("secp256k1"); var domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H); @@ -108,4 +142,15 @@ public static string getECDSASignature(string privateKey, string data){ return Hex.ToHexString(derSignature); } + + public static string convertByteToHexadecimal(byte[] byteArray) + { + string hex = ""; + // Iterating through each byte in the array + foreach (byte b in byteArray) + { + hex += $"{b:X2}"; + } + return hex.ToLowerInvariant(); + } } diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 5a60124..0d3a2d5 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -46,7 +46,7 @@ void Start() { verifier = "your_verifierid_from_web3auth_dashboard", typeOfLogin = TypeOfLogin.GOOGLE, - clientId = "your_clientid_from_google_or_etc" + clientId = "your_clientId_from_web3auth_dashboard" }; web3Auth = GetComponent(); @@ -54,11 +54,11 @@ void Start() { whiteLabel = new WhiteLabelData() { - name = "Web3Auth Sample App", + appName = "Web3Auth Sample App", logoLight = null, logoDark = null, - defaultLanguage = "en", - dark = true, + defaultLanguage = Language.en, + mode = ThemeModes.dark, theme = new Dictionary { { "primary", "#123456" } @@ -72,7 +72,10 @@ void Start() {"CUSTOM_VERIFIER", loginConfigItem} } */ - network = Web3Auth.Network.TESTNET + clientId = "BG4pe3aBso5SjVbpotFQGnXVHgxhgOxnqnNBKyjfEJ3izFvIVWUaMIzoCrAfYag8O6t6a6AOvdLcS4JR2sQMjR4", + buildEnv = BuildEnv.PRODUCTION, + redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity/auth"), + network = Web3Auth.Network.SAPPHIRE_DEVNET }); web3Auth.onLogin += onLogin; web3Auth.onLogout += onLogout; diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.unity b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.unity index 982df56..fd56440 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.unity +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 0} - m_IndirectSpecularColor: {r: 0.4439372, g: 0.49315345, b: 0.5721989, a: 1} + m_IndirectSpecularColor: {r: 0.44657844, g: 0.49641222, b: 0.57481676, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -896,7 +896,7 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 3eab2a0bf902d6e4b9c2e968ad89f528, type: 3} m_Name: m_EditorClassIdentifier: - clientId: BJ6l3_kIQiy6YVL7zDlCcEAvGpGukwFgp-C_0WvNI_fAEeIaoVRLDrV5OjtbZr_zJxbyXFsXMT-yhQiUNYvZWpo + clientId: BG4pe3aBso5SjVbpotFQGnXVHgxhgOxnqnNBKyjfEJ3izFvIVWUaMIzoCrAfYag8O6t6a6AOvdLcS4JR2sQMjR4 redirectUri: torusapp://com.torus.Web3AuthUnity/auth network: 1 --- !u!1 &529774071 diff --git a/Assets/Plugins/Web3AuthSDK/Types/AES256CBC.cs b/Assets/Plugins/Web3AuthSDK/Types/AES256CBC.cs index bf02ba3..2d4ea8c 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/AES256CBC.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/AES256CBC.cs @@ -4,6 +4,9 @@ using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using System.Security.Cryptography; +using System.IO; +using System; +using System.Text; public class AES256CBC { @@ -11,6 +14,9 @@ public class AES256CBC private byte[] AES_ENCRYPTION_KEY; private byte[] ENCRYPTION_IV; + private byte[] MAC_KEY; + private byte[] ENCRYPTION_EPHEM_KEY; + public AES256CBC(string privateKeyHex, string ephemPublicKeyHex, string encryptionIvHex) { using (SHA512 shaM = new SHA512Managed()) @@ -24,12 +30,16 @@ public AES256CBC(string privateKeyHex, string ephemPublicKeyHex, string encrypti System.Array.Copy(hash, encKeyBytes, 32); AES_ENCRYPTION_KEY = encKeyBytes; - ENCRYPTION_IV = toByteArray(encryptionIvHex); + MAC_KEY = new byte[hash.Length - 32]; + System.Array.Copy(hash, 32, MAC_KEY, 0, MAC_KEY.Length); + + ENCRYPTION_IV = toByteArray(encryptionIvHex); + ENCRYPTION_EPHEM_KEY = toByteArray(ephemPublicKeyHex); } } - public string encrypt(byte[] src) + public byte[] encrypt(byte[] src) { var key = ParameterUtilities.CreateKeyParameter("AES", AES_ENCRYPTION_KEY); var parametersWithIv = new ParametersWithIV(key, ENCRYPTION_IV); @@ -37,22 +47,22 @@ public string encrypt(byte[] src) var cipher = CipherUtilities.GetCipher(TRANSFORMATION); cipher.Init(true, parametersWithIv); - return System.Text.Encoding.UTF8.GetString( - cipher.DoFinal(src) - ); + return cipher.DoFinal(src); } - public string decrypt(byte[] src) + public byte[] decrypt(byte[] src, string mac) { + if (!hmacSha256Verify(MAC_KEY, getCombinedData(src), mac)) + { + throw new SystemException("Bad MAC error during decrypt"); + } var key = ParameterUtilities.CreateKeyParameter("AES", AES_ENCRYPTION_KEY); var parametersWithIv = new ParametersWithIV(key, ENCRYPTION_IV); var cipher = CipherUtilities.GetCipher(TRANSFORMATION); cipher.Init(false, parametersWithIv); - return System.Text.Encoding.UTF8.GetString( - cipher.DoFinal(src) - ); + return cipher.DoFinal(src); } @@ -97,4 +107,35 @@ public static byte[] toByteArray(BigInteger bi) } return b; } + + public byte[] getCombinedData(byte[] cipherTextBytes) + { + using (MemoryStream outputStream = new MemoryStream()) + { + outputStream.Write(ENCRYPTION_IV, 0, ENCRYPTION_IV.Length); + outputStream.Write(ENCRYPTION_EPHEM_KEY, 0, ENCRYPTION_EPHEM_KEY.Length); + outputStream.Write(cipherTextBytes, 0, cipherTextBytes.Length); + return outputStream.ToArray(); + } + } + + public byte[] getMac(byte[] cipherTextBytes) + { + return hmacSha256Sign(MAC_KEY, getCombinedData(cipherTextBytes)); + } + + public byte[] hmacSha256Sign(byte[] key, byte[] data) + { + using (HMACSHA256 hmac = new HMACSHA256(key)) + { + return hmac.ComputeHash(data); + } + } + + public bool hmacSha256Verify(byte[] key, byte[] data, string sig) + { + byte[] expectedSig = hmacSha256Sign(key, data); + string expectedSigHex = BitConverter.ToString(expectedSig).Replace("-", "").ToLower(); + return expectedSigHex.Equals(sig); + } } diff --git a/Assets/Plugins/Web3AuthSDK/Types/MfaSetting.cs b/Assets/Plugins/Web3AuthSDK/Types/MfaSetting.cs new file mode 100644 index 0000000..0f1add4 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/MfaSetting.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +public class MfaSetting +{ + public bool enable { get; set; } + public int? priority { get; set; } + public bool? mandatory { get; set; } + + // Constructor + public MfaSetting(bool enable, int? priority, bool? mandatory) + { + enable = enable; + priority = priority; + mandatory = mandatory; + } +} \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/MfaSettings.cs b/Assets/Plugins/Web3AuthSDK/Types/MfaSettings.cs new file mode 100644 index 0000000..19e42df --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/MfaSettings.cs @@ -0,0 +1,44 @@ +public class MfaSettings +{ + private MfaSetting deviceShareFactor; + private MfaSetting backUpShareFactor; + private MfaSetting socialBackupFactor; + private MfaSetting passwordFactor; + + public MfaSetting DeviceShareFactor + { + get { return deviceShareFactor; } + set { deviceShareFactor = value; } + } + + public MfaSetting BackUpShareFactor + { + get { return backUpShareFactor; } + set { backUpShareFactor = value; } + } + + public MfaSetting SocialBackupFactor + { + get { return socialBackupFactor; } + set { socialBackupFactor = value; } + } + + public MfaSetting PasswordFactor + { + get { return passwordFactor; } + set { passwordFactor = value; } + } + + // Constructors + public MfaSettings( + MfaSetting deviceShareFactor = null, + MfaSetting backUpShareFactor = null, + MfaSetting socialBackupFactor = null, + MfaSetting passwordFactor = null) + { + deviceShareFactor = deviceShareFactor; + backUpShareFactor = backUpShareFactor; + socialBackupFactor = socialBackupFactor; + passwordFactor = passwordFactor; + } +} \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs b/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs index c2eb6fe..9de1c61 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs @@ -11,4 +11,5 @@ public string idToken { get; set; } public string oAuthIdToken { get; set; } public string oAuthAccessToken { get; set; } + public bool isMfaEnabled { get; set; } } diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 3c12142..1cd6be6 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -4,19 +4,25 @@ public class Web3AuthOptions { public string clientId { get; set; } public Web3Auth.Network network { get; set; } + + public Web3Auth.BuildEnv buildEnv { get; set; } = Web3Auth.BuildEnv.PRODUCTION; public Uri redirectUrl { get; set; } public string sdkUrl { get { - if (network == Web3Auth.Network.TESTNET) - return "https://dev-sdk.openlogin.com"; - else - return "https://sdk.openlogin.com"; + if (buildEnv == Web3Auth.BuildEnv.STAGING) + return "https://staging-auth.web3auth.io/{openLoginVersion}"; + else if (buildEnv == Web3Auth.BuildEnv.TESTING) + return "https://develop-auth.web3auth.io"; + else + return "https://auth.web3auth.io/{openLoginVersion}"; } set { } } + public const string openLoginVersion = "v5"; - public WhiteLabelData whiteLabel { get; set; } - public Dictionary loginConfig { get; set; } + public WhiteLabelData? whiteLabel { get; set; } + public Dictionary? loginConfig { get; set; } public bool? useCoreKitKey { get; set; } = false; public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.EIP155; + public MfaSettings? mfaSettings { get; set; } = null; } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/WhiteLabelData.cs b/Assets/Plugins/Web3AuthSDK/Types/WhiteLabelData.cs index 0d2d617..c9cf47f 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/WhiteLabelData.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/WhiteLabelData.cs @@ -1,10 +1,13 @@ using System.Collections.Generic; +using Newtonsoft.Json; -public class WhiteLabelData { - public string name { get; set; } - public string logoLight { get; set; } - public string logoDark { get; set; } - public string defaultLanguage { get; set; } = "en"; - public bool dark { get; set; } = false; - public Dictionary theme { get; set; } +public class WhiteLabelData { + public string? appName { get; set; } + public string? logoLight { get; set; } + public string? logoDark { get; set; } + public Web3Auth.Language? defaultLanguage { get; set; } = Web3Auth.Language.en; + public Web3Auth.ThemeModes? mode { get; set; } = Web3Auth.ThemeModes.light; + public Dictionary? theme { get; set; } + public string? appUrl { get; set; } + public bool? useLogoLoader { get; set; } = false; } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index c633a28..dba4939 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json; +using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Text; @@ -8,12 +9,13 @@ using System.Collections; using Org.BouncyCastle.Math; using Newtonsoft.Json.Linq; +using System.Threading.Tasks; public class Web3Auth : MonoBehaviour { public enum Network { - MAINNET, TESTNET, CYAN, AQUA + MAINNET, TESTNET, CYAN, AQUA, SAPPHIRE_DEVNET, SAPPHIRE_MAINNET } public enum ChainNamespace @@ -21,6 +23,21 @@ public enum ChainNamespace EIP155, SOLANA } + public enum BuildEnv + { + PRODUCTION, STAGING, TESTING + } + + public enum ThemeModes + { + light, dark, auto + } + + public enum Language + { + en, de, ja, ko, zh, es, fr, pt, nl + } + private Web3AuthOptions web3AuthOptions; private Dictionary initParams; @@ -69,12 +86,16 @@ public void Awake() // this.setResultUrl(new Uri($"http://localhost#{code}")); // } #endif - - authorizeSession(); + authorizeSession(""); } public void setOptions(Web3AuthOptions web3AuthOptions) { + JsonSerializerSettings settings = new JsonSerializerSettings + { + Converters = new List { new StringEnumConverter() }, + Formatting = Formatting.Indented + }; this.web3AuthOptions = web3AuthOptions; @@ -82,16 +103,18 @@ public void setOptions(Web3AuthOptions web3AuthOptions) this.initParams["redirectUrl"] = this.web3AuthOptions.redirectUrl; if (this.web3AuthOptions.whiteLabel != null) - this.initParams["whiteLabel"] = JsonConvert.SerializeObject(this.web3AuthOptions.whiteLabel); + this.initParams["whiteLabel"] = JsonConvert.SerializeObject(this.web3AuthOptions.whiteLabel, settings); if (this.web3AuthOptions.loginConfig != null) - this.initParams["loginConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.loginConfig); + this.initParams["loginConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.loginConfig, settings); if (this.web3AuthOptions.clientId != null) this.initParams["clientId"] = this.web3AuthOptions.clientId; - this.initParams["network"] = this.web3AuthOptions.network.ToString().ToLower(); + if (this.web3AuthOptions.buildEnv != null) + this.initParams["buildEnv"] = this.web3AuthOptions.buildEnv.ToString().ToLower(); + this.initParams["network"] = this.web3AuthOptions.network.ToString().ToLower(); if (this.web3AuthOptions.useCoreKitKey.HasValue) this.initParams["useCoreKitKey"] = this.web3AuthOptions.useCoreKitKey.Value; @@ -215,16 +238,19 @@ private void IncomingHttpRequest(IAsyncResult result) } #endif - private void request(string path, LoginParams loginParams = null, Dictionary extraParams = null) + private async void request(string path, LoginParams loginParams = null, Dictionary extraParams = null) { #if UNITY_STANDALONE || UNITY_EDITOR this.initParams["redirectUrl"] = StartLocalWebserver(); #elif UNITY_WEBGL this.initParams["redirectUrl"] = Utils.GetCurrentURL(); #endif + + loginParams.redirectUrl = new Uri(StartLocalWebserver()); Dictionary paramMap = new Dictionary(); - paramMap["init"] = this.initParams; + paramMap["options"] = this.initParams; paramMap["params"] = loginParams == null ? (object)new Dictionary() : (object)loginParams; + paramMap["actionType"] = "login"; if (extraParams != null && extraParams.Count > 0) foreach (KeyValuePair item in extraParams) @@ -232,17 +258,31 @@ private void request(string path, LoginParams loginParams = null, Dictionary)[item.Key] = item.Value; } - string hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(paramMap, Newtonsoft.Json.Formatting.None, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore - }))); - - UriBuilder uriBuilder = new UriBuilder(this.web3AuthOptions.sdkUrl); - uriBuilder.Path = path; - uriBuilder.Fragment = hash; - - Utils.LaunchUrl(uriBuilder.ToString(), this.initParams["redirectUrl"].ToString(), gameObject.name); + string loginId = await createSession(JsonConvert.SerializeObject(paramMap, Newtonsoft.Json.Formatting.None, + new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }), 600); + + if(!string.IsNullOrEmpty(loginId)) { + var loginIdObject = new Dictionary + { + { "loginId", loginId } + }; + string hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(loginIdObject, Newtonsoft.Json.Formatting.None, + new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }))); + + UriBuilder uriBuilder = new UriBuilder(this.web3AuthOptions.sdkUrl); + uriBuilder.Path = path; + uriBuilder.Fragment = "b64Params=" + hash; + + Utils.LaunchUrl(uriBuilder.ToString(), this.initParams["redirectUrl"].ToString(), gameObject.name); + } else { + throw new Exception("Some went wrong. Please try again later."); + } } public void setResultUrl(Uri uri) @@ -256,30 +296,18 @@ public void setResultUrl(Uri uri) throw new UserCancelledException(); #endif hash = hash.Remove(0, 1); - Dictionary queryParameters = Utils.ParseQuery(uri.Query); if (queryParameters.Keys.Contains("error")) throw new UnKnownException(queryParameters["error"]); - this.web3AuthResponse = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(Utils.DecodeBase64(hash))); - if (!string.IsNullOrEmpty(this.web3AuthResponse.error)) - throw new UnKnownException(web3AuthResponse.error); + string sessionId = hash.Split('&')[0].Split('=')[1]; - if (string.IsNullOrEmpty(this.web3AuthResponse.privKey) || string.IsNullOrEmpty(this.web3AuthResponse.privKey.Trim('0'))) - this.Enqueue(() => this.onLogout?.Invoke()); - else - this.Enqueue(() => this.onLogin?.Invoke(this.web3AuthResponse)); + //save new sessionId + this.Enqueue(() => KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.SESSION_ID, sessionId)); - if (!string.IsNullOrEmpty(this.web3AuthResponse.sessionId)) - this.Enqueue(() => KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.SESSION_ID, this.web3AuthResponse.sessionId)); - - if (!string.IsNullOrEmpty(web3AuthResponse.userInfo?.dappShare)) - { - KeyStoreManagerUtils.savePreferenceData( - web3AuthResponse.userInfo?.verifier, web3AuthResponse.userInfo?.dappShare - ); - } + //call authorize session API + this.Enqueue(() => authorizeSession(sessionId)); #if !UNITY_EDITOR && UNITY_WEBGL if (this.web3AuthResponse != null) @@ -302,7 +330,7 @@ public void login(LoginParams loginParams) } } - request("login", loginParams); + request("start", loginParams); } public void logout(Dictionary extraParams) @@ -322,9 +350,15 @@ public void logout(Uri redirectUrl = null, string appState = null) logout(extraParams); } - private void authorizeSession() + private void authorizeSession(string newSessionId) { - string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); + string sessionId = ""; + if(string.IsNullOrEmpty(newSessionId)) { + sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); + } else { + sessionId = newSessionId; + } + if (!string.IsNullOrEmpty(sessionId)) { var pubKey = KeyStoreManagerUtils.getPubKey(sessionId); @@ -341,13 +375,10 @@ private void authorizeSession() ); var encryptedShareBytes = AES256CBC.toByteArray(new BigInteger(shareMetadata.ciphertext, 16)); - var share = aes256cbc.decrypt(encryptedShareBytes); - var tempJson = JsonConvert.DeserializeObject(share); - tempJson.Add("userInfo", tempJson["store"]); - tempJson.Remove("store"); + var share = aes256cbc.decrypt(encryptedShareBytes, shareMetadata.mac); + var tempJson = JsonConvert.DeserializeObject(System.Text.Encoding.UTF8.GetString(share)); this.web3AuthResponse = JsonConvert.DeserializeObject(tempJson.ToString()); - if (this.web3AuthResponse != null) { if (this.web3AuthResponse.error != null) @@ -355,6 +386,17 @@ private void authorizeSession() throw new UnKnownException(this.web3AuthResponse.error ?? "Something went wrong"); } + if (!string.IsNullOrEmpty(this.web3AuthResponse.sessionId)) { + KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.SESSION_ID, this.web3AuthResponse.sessionId); + } + + if (!string.IsNullOrEmpty(web3AuthResponse.userInfo?.dappShare)) + { + KeyStoreManagerUtils.savePreferenceData( + web3AuthResponse.userInfo?.verifier, web3AuthResponse.userInfo?.dappShare + ); + } + if (string.IsNullOrEmpty(this.web3AuthResponse.privKey) || string.IsNullOrEmpty(this.web3AuthResponse.privKey.Trim('0'))) this.Enqueue(() => this.onLogout?.Invoke()); else @@ -389,7 +431,7 @@ private void sessionTimeOutAPI() { iv = shareMetadata.iv, ephemPublicKey = shareMetadata.ephemPublicKey, - ciphertext = encryptedData, + ciphertext = KeyStoreManagerUtils.convertByteToHexadecimal(encryptedData), mac = shareMetadata.mac }; var jsonData = JsonConvert.SerializeObject(encryptedMetadata); @@ -427,6 +469,59 @@ private void sessionTimeOutAPI() } } + private async Task createSession(string data, long sessionTime) { + TaskCompletionSource createSessionResponse = new TaskCompletionSource(); + var newSessionKey = KeyStoreManagerUtils.generateRandomSessionKey(); + var ephemKey = KeyStoreManagerUtils.getPubKey(newSessionKey); + var ivKey = KeyStoreManagerUtils.generateRandomBytes(); + + var aes256cbc = new AES256CBC( + newSessionKey, + ephemKey, + KeyStoreManagerUtils.convertByteToHexadecimal(ivKey) + ); + var encryptedData = aes256cbc.encrypt(System.Text.Encoding.UTF8.GetBytes(data)); + var mac = aes256cbc.getMac(encryptedData); + var encryptedMetadata = new ShareMetadata() + { + iv = KeyStoreManagerUtils.convertByteToHexadecimal(ivKey), + ephemPublicKey = ephemKey, + ciphertext = KeyStoreManagerUtils.convertByteToHexadecimal(encryptedData), + mac = KeyStoreManagerUtils.convertByteToHexadecimal(mac) + }; + var jsonData = JsonConvert.SerializeObject(encryptedMetadata); + StartCoroutine(Web3AuthApi.getInstance().createSession( + new LogoutApiRequest() + { + key = KeyStoreManagerUtils.getPubKey(newSessionKey), + data = jsonData, + signature = KeyStoreManagerUtils.getECDSASignature( + newSessionKey, + jsonData + ), + timeout = Math.Min(sessionTime, 7 * 86400) + }, result => + { + if (result != null) + { + try + { + this.Enqueue(() => KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.SESSION_ID, newSessionKey)); + createSessionResponse.SetResult(newSessionKey); + } + catch (Exception ex) + { + createSessionResponse.SetException(new Exception("Something went wrong. Please try again later.")); + Debug.LogError(ex.Message); + } + } else { + createSessionResponse.SetException(new Exception("Something went wrong. Please try again later.")); + } + } + )); + return await createSessionResponse.Task; + } + public string getPrivKey() { if (web3AuthResponse == null)