public void Does_Hybrid_RSA_SHA512_AES_MasterKey_and_HmacSha256()
        {
            var request = new HelloSecure {
                Name = "World"
            };
            var msgBytes = request.ToJson().ToUtf8Bytes();

            byte[] masterKey, iv;
            AesUtils.CreateKeyAndIv(out masterKey, out iv);

            var sha512KeyBytes = masterKey.ToSha512HashBytes();

            var cryptKey = new byte[sha512KeyBytes.Length / 2];
            var authKey  = new byte[sha512KeyBytes.Length / 2];

            Buffer.BlockCopy(sha512KeyBytes, 0, cryptKey, 0, cryptKey.Length);
            Buffer.BlockCopy(sha512KeyBytes, cryptKey.Length, authKey, 0, authKey.Length);

            var encryptedBytes     = AesUtils.Encrypt(msgBytes, cryptKey, iv);
            var authEncryptedBytes = HmacUtils.Authenticate(encryptedBytes, authKey, iv);

            var aesKeyNonceBytes       = iv.Combine(masterKey);
            var rsaEncAesKeyNonceBytes = RsaUtils.Encrypt(aesKeyNonceBytes, SecureConfig.PublicKeyXml);

            var json = ValidateAndDecryptWithMasterKey(rsaEncAesKeyNonceBytes, authEncryptedBytes);

            var fromJson = json.FromJson <HelloSecure>();

            Assert.That(fromJson.Name, Is.EqualTo(request.Name));
        }
        public void Can_Send_Encrypted_Message()
        {
            var client = CreateClient();

            var request = new HelloSecure {
                Name = "World"
            };

            var aes = new AesManaged {
                KeySize = AesUtils.KeySize
            };

            var aesKeyBytes       = aes.Key.Combine(aes.IV);
            var rsaEncAesKeyBytes = RsaUtils.Encrypt(aesKeyBytes, SecureConfig.PublicKeyXml);

            var timestamp = DateTime.UtcNow.ToUnixTime();

            var requestBody = timestamp + " POST " + typeof(HelloSecure).Name + " " + request.ToJson();

            var encryptedMessage = new EncryptedMessage
            {
                EncryptedSymmetricKey = Convert.ToBase64String(rsaEncAesKeyBytes),
                EncryptedBody         = AesUtils.Encrypt(requestBody, aes.Key, aes.IV)
            };
            var encResponse = client.Post(encryptedMessage);

            var responseJson = AesUtils.Decrypt(encResponse.EncryptedBody, aes.Key, aes.IV);
            var response     = responseJson.FromJson <HelloSecureResponse>();

            Assert.That(response.Result, Is.EqualTo("Hello, World!"));
        }
        public void Does_throw_on_replayed_messages()
        {
            var client = CreateClient();

            var request = new HelloSecure {
                Name = "World"
            };

            byte[] cryptKey, iv;
            AesUtils.CreateKeyAndIv(out cryptKey, out iv);

            byte[] authKey = AesUtils.CreateKey();

            var cryptAuthKeys = cryptKey.Combine(authKey);

            var rsaEncCryptAuthKeys     = RsaUtils.Encrypt(cryptAuthKeys, SecureConfig.PublicKeyXml);
            var authRsaEncCryptAuthKeys = HmacUtils.Authenticate(rsaEncCryptAuthKeys, authKey, iv);

            var timestamp   = DateTime.UtcNow.ToUnixTime();
            var requestBody = timestamp + " POST " + typeof(HelloSecure).Name + " " + request.ToJson();

            var encryptedBytes     = AesUtils.Encrypt(requestBody.ToUtf8Bytes(), cryptKey, iv);
            var authEncryptedBytes = HmacUtils.Authenticate(encryptedBytes, authKey, iv);

            var encryptedMessage = new EncryptedMessage
            {
                EncryptedSymmetricKey = Convert.ToBase64String(authRsaEncCryptAuthKeys),
                EncryptedBody         = Convert.ToBase64String(authEncryptedBytes),
            };

            var encResponse = client.Post(encryptedMessage);

            try
            {
                client.Post(encryptedMessage);

                Assert.Fail("Should throw");
            }
            catch (WebServiceException ex)
            {
                ex.StatusDescription.Print();

                var errorResponse = (EncryptedMessageResponse)ex.ResponseDto;

                authEncryptedBytes = Convert.FromBase64String(errorResponse.EncryptedBody);
                if (!HmacUtils.Verify(authEncryptedBytes, authKey))
                {
                    throw new Exception("EncryptedBody is Invalid");
                }

                var responseBytes = HmacUtils.DecryptAuthenticated(authEncryptedBytes, cryptKey);
                var responseJson  = responseBytes.FromUtf8Bytes();
                var response      = responseJson.FromJson <ErrorResponse>();
                Assert.That(response.ResponseStatus.Message, Is.EqualTo("Nonce already seen"));
            }
        }
    public void Can_Encrypt_and_Decrypt_with_AES_bytes()
    {
        var msg = new HelloSecure {
            Name = "World"
        };

        AesUtils.CreateKeyAndIv(out var cryptKey, out var iv);

        var encryptedBytes = AesUtils.Encrypt(msg.ToJson().ToUtf8Bytes(), cryptKey, iv);

        var msgBytes = AesUtils.Decrypt(encryptedBytes, cryptKey, iv);

        var decryptedMsg = msgBytes.FromUtf8Bytes().FromJson <HelloSecure>();

        Assert.That(decryptedMsg.Name, Is.EqualTo(msg.Name));
    }
    public void Can_Encrypt_and_Decrypt_with_AES()
    {
        var msg = new HelloSecure {
            Name = "World"
        };

        AesUtils.CreateKeyAndIv(out var cryptKey, out var iv);

        var encryptedText = AesUtils.Encrypt(msg.ToJson(), cryptKey, iv);

        var decryptedJson = AesUtils.Decrypt(encryptedText, cryptKey, iv);

        var decryptedMsg = decryptedJson.FromJson <HelloSecure>();

        Assert.That(decryptedMsg.Name, Is.EqualTo(msg.Name));
    }
        public void Can_Send_Encrypted_Message()
        {
            var client = CreateClient();

            var request = new HelloSecure {
                Name = "World"
            };

            byte[] cryptKey, authKey, iv;
            AesUtils.CreateCryptAuthKeysAndIv(out cryptKey, out authKey, out iv);

            var cryptAuthKeys = cryptKey.Combine(authKey);

            var rsaEncCryptAuthKeys     = RsaUtils.Encrypt(cryptAuthKeys, SecureConfig.PublicKeyXml);
            var authRsaEncCryptAuthKeys = HmacUtils.Authenticate(rsaEncCryptAuthKeys, authKey, iv);

            var timestamp   = DateTime.UtcNow.ToUnixTime();
            var requestBody = timestamp + " POST " + typeof(HelloSecure).Name + " " + request.ToJson();

            var encryptedBytes     = AesUtils.Encrypt(requestBody.ToUtf8Bytes(), cryptKey, iv);
            var authEncryptedBytes = HmacUtils.Authenticate(encryptedBytes, authKey, iv);

            var encryptedMessage = new EncryptedMessage
            {
                EncryptedSymmetricKey = Convert.ToBase64String(authRsaEncCryptAuthKeys),
                EncryptedBody         = Convert.ToBase64String(authEncryptedBytes),
            };

            var encResponse = client.Post(encryptedMessage);

            authEncryptedBytes = Convert.FromBase64String(encResponse.EncryptedBody);

            if (!HmacUtils.Verify(authEncryptedBytes, authKey))
            {
                throw new Exception("Invalid EncryptedBody");
            }

            var decryptedBytes = HmacUtils.DecryptAuthenticated(authEncryptedBytes, cryptKey);

            var responseJson = decryptedBytes.FromUtf8Bytes();
            var response     = responseJson.FromJson <HelloSecureResponse>();

            Assert.That(response.Result, Is.EqualTo("Hello, World!"));
        }
        public void Does_Hybrid_RSA_Crypt_and_Auth_AES_with_HMAC_SHA256()
        {
            var request = new HelloSecure {
                Name = "World"
            };
            var timestamp = DateTime.UtcNow.ToUnixTime();
            var msg       = timestamp + " POST " + request.GetType().Name + " " + request.ToJson();
            var msgBytes  = msg.ToUtf8Bytes();

            byte[] cryptKey, authKey, iv;
            AesUtils.CreateCryptAuthKeysAndIv(out cryptKey, out authKey, out iv);

            var encryptedBytes = AesUtils.Encrypt(msgBytes, cryptKey, iv);

            var decryptedBytes = AesUtils.Decrypt(encryptedBytes, cryptKey, iv);

            Assert.That(decryptedBytes, Is.EquivalentTo(msgBytes));

            var authEncryptedBytes = HmacUtils.Authenticate(encryptedBytes, authKey, iv);

            var cryptAuthKeys = cryptKey.Combine(authKey);

            var rsaEncCryptAuthKeys     = RsaUtils.Encrypt(cryptAuthKeys, SecureConfig.PublicKeyXml);
            var authRsaEncCryptAuthKeys = HmacUtils.Authenticate(rsaEncCryptAuthKeys, authKey, iv);

            var decryptedMsg = ValidateAndDecrypt(authRsaEncCryptAuthKeys, authEncryptedBytes);

            var parts = decryptedMsg.SplitOnFirst(' ');

            Assert.That(long.Parse(parts[0]), Is.EqualTo(timestamp));

            parts = parts[1].SplitOnFirst(' ');
            Assert.That(parts[0], Is.EqualTo("POST"));

            parts = parts[1].SplitOnFirst(' ');
            Assert.That(parts[0], Is.EqualTo(request.GetType().Name));

            var decryptedJson    = parts[1];
            var decryptedRequest = decryptedJson.FromJson <HelloSecure>();

            Assert.That(decryptedRequest.Name, Is.EqualTo(request.Name));
        }
        public void Does_throw_on_replayed_messages()
        {
            var client = CreateClient();

            var request = new HelloSecure {
                Name = "World"
            };

            var aes = new AesManaged {
                KeySize = AesUtils.KeySize
            };

            var aesKeyBytes       = aes.Key.Combine(aes.IV);
            var rsaEncAesKeyBytes = RsaUtils.Encrypt(aesKeyBytes, SecureConfig.PublicKeyXml);

            var timestamp   = DateTime.UtcNow.ToUnixTime();
            var requestBody = timestamp + " POST " + typeof(HelloSecure).Name + " " + request.ToJson();

            var encryptedMessage = new EncryptedMessage
            {
                EncryptedSymmetricKey = Convert.ToBase64String(rsaEncAesKeyBytes),
                EncryptedBody         = AesUtils.Encrypt(requestBody, aes.Key, aes.IV)
            };
            var encResponse = client.Post(encryptedMessage);

            try
            {
                client.Post(encryptedMessage);

                Assert.Fail("Should throw");
            }
            catch (WebServiceException ex)
            {
                ex.StatusDescription.Print();

                var errorResponse = (EncryptedMessageResponse)ex.ResponseDto;
                var responseJson  = AesUtils.Decrypt(errorResponse.EncryptedBody, aes.Key, aes.IV);
                var response      = responseJson.FromJson <ErrorResponse>();
                Assert.That(response.ResponseStatus.Message, Is.EqualTo("Nonce already seen"));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 修改歌曲信息协程
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        private IEnumerator EditComment(string dirPath)
        {
            mCorRunning = true;
            mIgnoreNum  = 0;
            mAllNum     = 0;
            mFailNum    = 0;
            mDealNum    = 0;
            mMapKeyInfo.Clear();

            var pathList = new[] { dirPath };

            if (!mIsFile)
            {
                //判断单文件还是文件夹
                pathList = Directory.GetFiles(dirPath);
            }

            var startTime = Time.realtimeSinceStartup;

            mAllNum = pathList.Length;

            for (var i = 0; i < pathList.Length; i++)
            {
                var path = pathList[i];
                if (path.EndsWith("mp3"))
                {
                    var name = "";
                    var f    = File.Create(path);

                    if (!mTgCover.isOn && f.Tag.Comment.Contains("163"))
                    {
                        //不覆盖
                        Debug.LogWarning("不覆盖已经有Comment的,跳过:" + f.Tag.Title);
                        mIgnoreNum++;
                        continue;
                    }

                    if (!mTgCoverMatch.isOn && MatchTag.Equals(f.Tag.Description))
                    {
                        //不覆盖已经准确匹配过的
                        Debug.LogWarning("不覆盖已经准确匹配过的,跳过:" + f.Tag.Title);
                        mIgnoreNum++;
                        continue;
                    }


                    name = f.Tag.Title.Trim();

                    if (string.IsNullOrEmpty(name))
                    {
                        //Tag里面为空就从路径里面获取
                        name = Path.GetFileNameWithoutExtension(path);
                        // name = path.Substring(path.LastIndexOf("/") + 1);
                        // name = name.Substring(0, name.IndexOf("."));
                    }

                    Debug.Log("歌曲名字: " + name);

                    if (!string.IsNullOrEmpty(name))
                    {
                        if (f.Tag.Performers != null && f.Tag.Performers.Length > 0)
                        {
                            //搜索增加名字
                            name += " " + f.Tag.Performers[0];
                        }

                        mDealNum++;

                        mTvStatus.text = "正在处理:" + mDealNum + "/" + mAllNum + ",忽略:" + mIgnoreNum + ",失败:" + mFailNum;
                        mLog.Enqueue("正在处理 " + f.Tag.Title);

                        if (mTgDiyUrl.isOn)
                        {
                            //自定义修改
                            Debug.Log("自定义修改: " + mDiySongID);
                            mMapKeyInfo.Add(path, new SongInfo()
                            {
                                id = mDiySongID,
                            });
                        }
                        else
                        {
                            yield return(Search(f.Tag, path, name, (songInfo) =>
                            {
                                if (songInfo != null)
                                {
                                    mMapKeyInfo.Add(path, songInfo);
                                }
                                else
                                {
                                    mFailNum++;
                                }

                                f.Dispose();
                            }));
                        }


                        if (i == pathList.Length - 1 || mMapKeyInfo.Count == DetailNum)
                        {
                            //每20条内容或者最后一条了,就获取详情
                            Debug.Log("开始获取详情:" + mDealNum);
                            mLog.Enqueue("开始获取详情:" + mDealNum);
                            var idList = new List <int>();
                            foreach (var keyValuePair in mMapKeyInfo)
                            {
                                idList.Add(keyValuePair.Value.id);
                            }

                            //获取歌曲详情
                            yield return(GetSongDetail(idList.ToArray(), (songs) =>
                            {
                                if (songs != null && songs.Count > 0)
                                {
                                    var keyList = mMapKeyInfo.Keys.ToArray();
                                    foreach (var key in keyList)
                                    {
                                        mMapKeyInfo.TryGetValue(key, out var outInfo);
                                        if (outInfo != null)
                                        {
                                            var isMatch = outInfo.IsMatch;
                                            var songInfo = songs.Find(v => v.id == outInfo.id);
                                            songInfo.IsMatch = isMatch;
                                            //替换搜索的实体为详情得到的实体
                                            mMapKeyInfo[key] = songInfo;
                                        }
                                    }

                                    foreach (var keyValuePair in mMapKeyInfo)
                                    {
                                        var songInfo = keyValuePair.Value;

                                        if (songInfo != null)
                                        {
                                            var fCache = File.Create(keyValuePair.Key);
                                            songInfo.bitrate = fCache.Properties.AudioBitrate * 1000;
                                            var comment = JsonMapper.ToJson(songInfo.ToKeyInfo());
                                            fCache.Tag.Comment = "163 key(Don't modify):" +
                                                                 AesUtils.Encrypt("music:" + comment, AesKey);
                                            //定义是否完全匹配
                                            fCache.Tag.Description = (songInfo.IsMatch ? MatchTag : "");
                                            fCache.Save();
                                            fCache.Dispose();

                                            var fileName = "/" + Path.GetFileName(keyValuePair.Key);
                                            //根据文件名称来删除数据库
                                            mDataDataService?.DeleteRow(fileName);
                                        }
                                        else
                                        {
                                            mFailNum++;
                                        }
                                    }
                                }
                                else
                                {
                                    mFailNum += idList.Count;
                                }
                            }));

                            //清空当前歌曲库
                            mMapKeyInfo.Clear();
                        }
                    }
                }
            }

            mCorRunning = false;
            mBtnEdit.GetComponentInChildren <Text>().text = "开始";
            yield return(null);

            Debug.Log("搜索完毕,耗时:" + (Time.realtimeSinceStartup - startTime) + "秒");
            mTvStatus.text = "处理完毕:" + mDealNum + "/" + mAllNum + ",忽略:" + mIgnoreNum + ",失败:" + mFailNum;
            mLog.Enqueue(mTvStatus.text);

            if (mNeedReOpen)
            {
                if (mDealNum > 0)
                {
                    Debug.Log("需要重启网易云生效");
                    mLog.Enqueue("请重启网易云生效");
                }

                mDataDataService?.Close();
            }
        }
Ejemplo n.º 10
0
    /// <summary>
    /// 加密Comment
    /// </summary>
    /// <param name="ori"></param>
    private void EncryptText(string ori)
    {
        var result = AesUtils.Encrypt("music:" + ori, UIPanel163Key.AesKey);

        mIpOrigin.text = result;
    }
            //  [Category("BlockchainIntegration")]
            public void ProhibotCashOutsToHWTest()
            {
                string phonePrefix = null;
                string phoneNumber = TestData.GenerateNumbers(9);

                var currentAssetId = lykkePrivateApi.Assets.GetAssets().GetResponseObject().FirstOrDefault(a =>
                {
                    if (a.BlockchainIntegrationLayerId != null)
                    {
                        return(a.BlockchainIntegrationLayerId.ToString().ToLower() == BlockChainName.ToLower());
                    }

                    return(false);
                })?.Id;

                var blockchainSettings = cfg["BlockchainsIntegration"];

                var currentBlockchainSettings = JsonConvert.DeserializeObject <BlockchainSettings[]>(cfg["BlockchainsIntegration"]["Blockchains"].ToString()).FirstOrDefault(b => b.Type.ToLower().Contains(BlockChainName.ToLower()));

                if (currentBlockchainSettings == null)
                {
                    Assert.Ignore($"Blockchain {BlockChainName} does not present in blockchain settings {blockchainSettings}");
                }

                #region register client

                var bitcoinPrivateKey = new NBitcoin.Key().GetWif(NBitcoin.Network.TestNet);

                //STEP 0
                var getApplicationInfo = walletApi.ApplicationInfo
                                         .GetApplicationInfo()
                                         .Validate.StatusCode(HttpStatusCode.OK)
                                         .Validate.NoApiError();

                //STEP 2
                var postEmailVerification = walletApi.EmailVerification
                                            .PostEmailVerification(new PostEmailModel()
                {
                    Email = email
                })
                                            .Validate.StatusCode(HttpStatusCode.OK)
                                            .Validate.NoApiError();
                Assert.That(postEmailVerification.GetResponseObject().Error, Is.Null);

                //STEP 3
                var getEmailVerification = walletApi.EmailVerification
                                           .GetEmailVerification(email, code, null)
                                           .Validate.StatusCode(HttpStatusCode.OK)
                                           .Validate.NoApiError();
                Assert.That(getEmailVerification.GetResponseObject().Result.Passed, Is.True);

                //STEP 4
                var postRegistration = walletApi.Registration.PostRegistrationResponse(new AccountRegistrationModel()
                {
                    ClientInfo = clientInfo,
                    Email      = email,
                    Hint       = hint,
                    Password   = Sha256.GenerateHash(password)
                })
                                       .Validate.StatusCode(HttpStatusCode.OK)
                                       .Validate.NoApiError();
                Assert.Multiple(() =>
                {
                    var postRegistrationData = postRegistration.GetResponseObject();
                    Assert.That(postRegistrationData.Result.PersonalData?.Email, Is.EqualTo(email));
                    Assert.That(postRegistrationData.Result.Token, Is.Not.Null.And.Not.Empty);
                });
                token = postRegistration.GetResponseObject().Result.Token;

                //STEP 6
                var getPersonalData = walletApi.PersonalData
                                      .GetPersonalDataResponse(token)
                                      .Validate.StatusCode(HttpStatusCode.OK)
                                      .Validate.NoApiError();
                Assert.That(getPersonalData.GetResponseObject().Result
                            .Email, Is.EqualTo(email));

                //STEP 7
                var postClientFullName = walletApi.ClientFullName
                                         .PostClientFullName(new PostClientFullNameModel()
                {
                    FullName = $"{firstName} {lastName}"
                }, token)
                                         .Validate.StatusCode(HttpStatusCode.OK)
                                         .Validate.NoApiError();

                //STEP 8
                getPersonalData = walletApi.PersonalData
                                  .GetPersonalDataResponse(token)
                                  .Validate.StatusCode(HttpStatusCode.OK)
                                  .Validate.NoApiError();
                var getPersonalDataResult = getPersonalData.GetResponseObject().Result;
                Assert.That(getPersonalDataResult.FullName, Is.EqualTo($"{firstName} {lastName}"));
                Assert.That(getPersonalDataResult.FirstName, Is.EqualTo(firstName));
                Assert.That(getPersonalDataResult.LastName, Is.EqualTo(lastName));
                Assert.That(getPersonalDataResult.Country, Is.Not.Null.And.Not.Empty);
                country = getPersonalData.GetResponseObject().Result.Country;

                //STEP 9
                var getCountryPhoneCodes = walletApi.CountryPhoneCodes
                                           .GetCountryPhoneCodes(token)
                                           .Validate.StatusCode(HttpStatusCode.OK)
                                           .Validate.NoApiError();
                var getCountryPhoneCodesResult = getCountryPhoneCodes.GetResponseObject().Result;
                Assert.That(getCountryPhoneCodesResult.Current, Is.EqualTo(country));
                phonePrefix = getCountryPhoneCodesResult.CountriesList
                              .FirstOrDefault(c => c.Id == country)?.Prefix;
                Assert.That(phonePrefix, Is.Not.Null);

                //STEP 10
                var postCheckMobilePhone = walletApi.CheckMobilePhone
                                           .PostCheckMobilePhone(new PostClientPhoneModel()
                {
                    PhoneNumber = phonePrefix + phoneNumber
                }, token)
                                           .Validate.StatusCode(HttpStatusCode.OK)
                                           .Validate.NoApiError();

                //STEP 11
                var getCheckMobilePhone = walletApi.CheckMobilePhone
                                          .GetCheckMobilePhone(phonePrefix + phoneNumber, code, token)
                                          .Validate.StatusCode(HttpStatusCode.OK)
                                          .Validate.NoApiError();
                Assert.That(getCheckMobilePhone.GetResponseObject().Result
                            .Passed, Is.True);

                //STEP 12
                var getCheckDocumentsToUpload = walletApi.CheckDocumentsToUpload
                                                .GetCheckDocumentsToUpload(token)
                                                .Validate.StatusCode(HttpStatusCode.OK)
                                                .Validate.NoApiError();
                var getCheckDocumentsToUploadResult = getCheckDocumentsToUpload.GetResponseObject().Result;
                Assert.That(getCheckDocumentsToUploadResult.IdCard, Is.True);
                Assert.That(getCheckDocumentsToUploadResult.ProofOfAddress, Is.True);
                Assert.That(getCheckDocumentsToUploadResult.Selfie, Is.True);

                //STEP 13
                var postPinSecurity = walletApi.PinSecurity
                                      .PostPinSecurity(new PinSecurityChangeModel()
                {
                    Pin = pin
                }, token)
                                      .Validate.StatusCode(HttpStatusCode.OK)
                                      .Validate.NoApiError();

                //STEP 14
                var getMyLykkeSettings = walletApi.MyLykkeSettings
                                         .GetMyLykkeSettings(token)
                                         .Validate.StatusCode(HttpStatusCode.OK)
                                         .Validate.NoApiError();
                Assert.That(getMyLykkeSettings.GetResponseObject().Result.MyLykkeEnabled,
                            Is.True);

                //STEP 15
                var postClientKeys = walletApi.ClientKeys
                                     .PostClientKeys(new ClientKeysModel()
                {
                    PubKey            = bitcoinPrivateKey.PubKey.ToString(),
                    EncodedPrivateKey = AesUtils.Encrypt(bitcoinPrivateKey.ToString(), password)
                }, token)
                                     .Validate.StatusCode(HttpStatusCode.OK)
                                     .Validate.NoApiError();

                #endregion

                var clientId = lykkePrivateApi.ClientAccount.ClientAccountInformation.
                               GetClientsByEmail(email).GetResponseObject().FirstOrDefault()?.Id;

                Assert.That(clientId, Is.Not.Null, "UnExpected ClientId is null.");

                var walletId = lykkePrivateApi.ClientAccount.Wallets.GetWalletsForClientById(clientId).
                               GetResponseObject().FirstOrDefault()?.Id;
                Assert.That(walletId, Is.Not.Null, $"Dont have any wallets for client {clientId}");

                // fill wallet with manual CashIn
                var manualCashIn = new ManualCashInRequestModel
                {
                    Amount   = 10,
                    AssetId  = currentAssetId,
                    ClientId = clientId,
                    Comment  = "AutotestFund",
                    UserId   = "Autotest user"
                };
                var cryptoToWalletResponse = lykkePrivateApi.ExchangeOperation.PostManualCashIn(manualCashIn);

                // we have crypto. Go to make CashOut
                var mobileSteps = new MobileSteps(walletApi);
                var keys        = mobileSteps.Login(email, password, pin);
                var SignatureVerificationToken = mobileSteps.GetAccessToken(email, keys.token, keys.privateKey);

                //complete backup
                var backUp = walletApi.BackupCompleted.PostBackupCompleted(token);

                var cashOut = new HotWalletCashoutOperation {
                    AssetId = currentAssetId, DestinationAddress = currentBlockchainSettings.HotWalletAddress, Volume = 5
                };

                var cashOutRequest = walletApi.HotWallet.PostCashOut(cashOut, SignatureVerificationToken, token);

                if (cashOutRequest.GetResponseObject().Error.Message.ToLower().Contains("address is invalid"))
                {
                    Assert.Pass("Error message contain 'address is invalid'");
                }
                else
                {
                    var getDiscl  = walletApi.AssetDisclaimers.Get(token);
                    var postDiscl = walletApi.AssetDisclaimers.PostApproveById(getDiscl.GetResponseObject().Result.Disclaimers[0].Id, token);

                    //make cashout again
                    SignatureVerificationToken = mobileSteps.GetAccessToken(email, keys.token, keys.privateKey);
                    cashOutRequest             = walletApi.HotWallet.PostCashOut(cashOut, SignatureVerificationToken, token);

                    Assert.That(cashOutRequest.GetResponseObject().Error.Message.ToLower(), Does.Contain("address is invalid"), "Unexpected error message");
                }
            }
        public void RegisterTest()
        {
            string firstName  = "Autotest";
            string lastName   = "User";
            string clientInfo = "iPhone; Model:6 Plus; Os:9.3.5; Screen:414x736";
            string hint       = "qwe";

            string phonePrefix = null;
            string phoneNumber = TestData.GenerateNumbers(9);
            string token       = null;
            string country     = null;

            var bitcoinPrivateKey = new NBitcoin.Key().GetWif(NBitcoin.Network.TestNet);

            //STEP 0
            var getApplicationInfo = walletApi.ApplicationInfo
                                     .GetApplicationInfo()
                                     .Validate.StatusCode(HttpStatusCode.OK)
                                     .Validate.NoApiError();

            //STEP 1
            ////var getClientState = walletApi.ClientState
            ////    .GetClientState(email, null)
            ////    .Validate.StatusCode(HttpStatusCode.OK)
            ////    .Validate.NoApiError();
            ////Assert.That(getClientState.GetResponseObject().Result
            ////        .IsRegistered, Is.False);

            //STEP 2
            var postEmailVerification = walletApi.EmailVerification
                                        .PostEmailVerification(new PostEmailModel()
            {
                Email = email
            })
                                        .Validate.StatusCode(HttpStatusCode.OK)
                                        .Validate.NoApiError();

            Assert.That(postEmailVerification.GetResponseObject().Error, Is.Null);

            //STEP 3
            var getEmailVerification = walletApi.EmailVerification
                                       .GetEmailVerification(email, code, null)
                                       .Validate.StatusCode(HttpStatusCode.OK)
                                       .Validate.NoApiError();

            Assert.That(getEmailVerification.GetResponseObject().Result.Passed, Is.True);

            //STEP 4
            var postRegistration = walletApi.Registration.PostRegistrationResponse(new AccountRegistrationModel()
            {
                ClientInfo = clientInfo,
                Email      = email,
                Hint       = hint,
                Password   = Sha256.GenerateHash(password)
            })
                                   .Validate.StatusCode(HttpStatusCode.OK)
                                   .Validate.NoApiError();

            Assert.Multiple(() =>
            {
                var postRegistrationData = postRegistration.GetResponseObject();
                Assert.That(postRegistrationData.Result.PersonalData?.Email, Is.EqualTo(email));
                Assert.That(postRegistrationData.Result.Token, Is.Not.Null.And.Not.Empty);
            });
            token = postRegistration.GetResponseObject().Result.Token;

            ////STEP 5
            //getClientState = walletApi.ClientState
            //    .GetClientState(email, null)
            //    .Validate.StatusCode(HttpStatusCode.OK)
            //    .Validate.NoApiError();
            //Assert.Multiple(() =>
            //{
            //    var getClientStateData = getClientState.GetResponseObject();
            //    Assert.That(getClientStateData.Result.IsRegistered, Is.True);
            //    Assert.That(getClientStateData.Result.IsPwdHashed, Is.True);
            //});

            //STEP 6
            var getPersonalData = walletApi.PersonalData
                                  .GetPersonalDataResponse(token)
                                  .Validate.StatusCode(HttpStatusCode.OK)
                                  .Validate.NoApiError();

            Assert.That(getPersonalData.GetResponseObject().Result
                        .Email, Is.EqualTo(email));

            //STEP 7
            var postClientFullName = walletApi.ClientFullName
                                     .PostClientFullName(new PostClientFullNameModel()
            {
                FullName = $"{firstName} {lastName}"
            }, token)
                                     .Validate.StatusCode(HttpStatusCode.OK)
                                     .Validate.NoApiError();

            //STEP 8
            getPersonalData = walletApi.PersonalData
                              .GetPersonalDataResponse(token)
                              .Validate.StatusCode(HttpStatusCode.OK)
                              .Validate.NoApiError();
            var getPersonalDataResult = getPersonalData.GetResponseObject().Result;

            Assert.That(getPersonalDataResult.FullName, Is.EqualTo($"{firstName} {lastName}"));
            Assert.That(getPersonalDataResult.FirstName, Is.EqualTo(firstName));
            Assert.That(getPersonalDataResult.LastName, Is.EqualTo(lastName));
            Assert.That(getPersonalDataResult.Country, Is.Not.Null.And.Not.Empty);
            country = getPersonalData.GetResponseObject().Result.Country;

            //STEP 9
            var getCountryPhoneCodes = walletApi.CountryPhoneCodes
                                       .GetCountryPhoneCodes(token)
                                       .Validate.StatusCode(HttpStatusCode.OK)
                                       .Validate.NoApiError();
            var getCountryPhoneCodesResult = getCountryPhoneCodes.GetResponseObject().Result;

            Assert.That(getCountryPhoneCodesResult.Current, Is.EqualTo(country));
            phonePrefix = getCountryPhoneCodesResult.CountriesList
                          .FirstOrDefault(c => c.Id == country)?.Prefix;
            Assert.That(phonePrefix, Is.Not.Null);

            //STEP 10
            var postCheckMobilePhone = walletApi.CheckMobilePhone
                                       .PostCheckMobilePhone(new PostClientPhoneModel()
            {
                PhoneNumber = phonePrefix + phoneNumber
            }, token)
                                       .Validate.StatusCode(HttpStatusCode.OK)
                                       .Validate.NoApiError();

            //STEP 11
            var getCheckMobilePhone = walletApi.CheckMobilePhone
                                      .GetCheckMobilePhone(phonePrefix + phoneNumber, code, token)
                                      .Validate.StatusCode(HttpStatusCode.OK)
                                      .Validate.NoApiError();

            Assert.That(getCheckMobilePhone.GetResponseObject().Result
                        .Passed, Is.True);

            //STEP 12
            var getCheckDocumentsToUpload = walletApi.CheckDocumentsToUpload
                                            .GetCheckDocumentsToUpload(token)
                                            .Validate.StatusCode(HttpStatusCode.OK)
                                            .Validate.NoApiError();
            var getCheckDocumentsToUploadResult = getCheckDocumentsToUpload.GetResponseObject().Result;

            Assert.That(getCheckDocumentsToUploadResult.IdCard, Is.True);
            Assert.That(getCheckDocumentsToUploadResult.ProofOfAddress, Is.True);
            Assert.That(getCheckDocumentsToUploadResult.Selfie, Is.True);

            //STEP 13
            var postPinSecurity = walletApi.PinSecurity
                                  .PostPinSecurity(new PinSecurityChangeModel()
            {
                Pin = pin
            }, token)
                                  .Validate.StatusCode(HttpStatusCode.OK)
                                  .Validate.NoApiError();

            //STEP 14
            var getMyLykkeSettings = walletApi.MyLykkeSettings
                                     .GetMyLykkeSettings(token)
                                     .Validate.StatusCode(HttpStatusCode.OK)
                                     .Validate.NoApiError();

            Assert.That(getMyLykkeSettings.GetResponseObject().Result.MyLykkeEnabled,
                        Is.True);

            //STEP 15
            var postClientKeys = walletApi.ClientKeys
                                 .PostClientKeys(new ClientKeysModel()
            {
                PubKey            = bitcoinPrivateKey.PubKey.ToString(),
                EncodedPrivateKey = AesUtils.Encrypt(bitcoinPrivateKey.ToString(), password)
            }, token)
                                 .Validate.StatusCode(HttpStatusCode.OK)
                                 .Validate.NoApiError();
        }
Ejemplo n.º 13
0
        public static string Encrypt(string plainText, IDictionary <string, object> options)
        {
            var toEncrypt     = plainText;
            var encryptedText = string.Empty;

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var decodeFromBase64 = options.ContainsKey("DecodeFromBase64") &&
                                   Convert.ToBoolean(options["DecodeFromBase64"], CultureInfo.InvariantCulture);
            var encodeToBase64 = options.ContainsKey("EncodeToBase64") && Convert.ToBoolean(options["EncodeToBase64"], CultureInfo.InvariantCulture);

            var method = options.ContainsKey("Method") ? options["Method"].ToString() : string.Empty;

            switch (method)
            {
            // RSA
            case "RSA":
                var publicKeyPath = options["PublicKeyPath"].ToString();

                if (publicKeyPath.StartsWith("\"", StringComparison.InvariantCulture))
                {
                    publicKeyPath = publicKeyPath.Substring(1, publicKeyPath.Length - 1);
                }

                if (publicKeyPath.EndsWith("\"", StringComparison.InvariantCulture))
                {
                    publicKeyPath = publicKeyPath.Substring(0, publicKeyPath.Length - 1);
                }

                if (decodeFromBase64)
                {
                    toEncrypt = GeneralUtils.Base64Decode(toEncrypt);
                }

                encryptedText = encodeToBase64 ? RsaUtils.EncryptAndBase64Encode(toEncrypt, publicKeyPath) : RsaUtils.Encrypt(toEncrypt, publicKeyPath);
                break;

            // AES
            case "AES":
                var key = options["key"].ToString();
                var initializationValue = options["iniValue"].ToString();

                encryptedText = encodeToBase64 ? AesUtils.EncryptAndBase64Encode(toEncrypt, key, initializationValue) : AesUtils.Encrypt(toEncrypt, key, initializationValue);
                break;

            // Base64
            case "Base64":
                encryptedText = GeneralUtils.Base64Encode(toEncrypt);
                break;

            // Hashing
            case "Hashing":
                switch (options["hashMethod"].ToString())
                {
                case "MD5":
                    // create new instance of MD5
                    var md5 = MD5.Create();

                    try
                    {
                        // convert the input text to array of bytes
                        var hashDataMd5 = md5.ComputeHash(Encoding.Default.GetBytes(toEncrypt));

                        // return hexadecimal string
                        encryptedText = BitConverter.ToString(hashDataMd5).Replace("-", string.Empty);
                    }
                    finally
                    {
                        md5.Dispose();
                    }

                    break;

                case "SHA1":
                    // create new instance of SHA1
                    var sha1 = SHA1.Create();

                    try
                    {
                        // convert the input text to array of bytes
                        var hashDataSha1 = sha1.ComputeHash(Encoding.Default.GetBytes(toEncrypt));

                        // return hexadecimal string
                        encryptedText = BitConverter.ToString(hashDataSha1).Replace("-", string.Empty);
                    }
                    finally
                    {
                        sha1.Dispose();
                    }

                    break;

                case "SHA2":
                case "SHA256":
                    // create new instance of SHA256
                    var sha2 = SHA256.Create();

                    try
                    {
                        // convert the input text to array of bytes
                        var hashDataSha2 = sha2.ComputeHash(Encoding.Default.GetBytes(toEncrypt));

                        // return hexadecimal string
                        encryptedText = BitConverter.ToString(hashDataSha2).Replace("-", string.Empty);
                    }
                    finally
                    {
                        sha2.Dispose();
                    }

                    break;
                }

                break;
            }

            return(encryptedText);
        }