public int EndReceive(IAsyncResult ar, out bool sendback) { int bytesRead = _socket.EndReceive(ar); sendback = false; if (bytesRead > 0) { CallbackState st = (CallbackState)ar.AsyncState; st.size = bytesRead; lock (_decryptionLock) { int bytesToSend = 0; int obfsRecvSize; byte[] remoteRecvObfsBuffer = _obfs.ClientDecode(st.buffer, bytesRead, out obfsRecvSize, out sendback); if (obfsRecvSize > 0) { _encryptor.Decrypt(remoteRecvObfsBuffer, obfsRecvSize, ReceiveDecryptBuffer, out bytesToSend); int outlength; byte[] buffer = _protocol.ClientPostDecrypt(ReceiveDecryptBuffer, bytesToSend, out outlength); Array.Copy(buffer, 0, st.buffer, 0, outlength); return(outlength); } } return(0); } else { _close = true; } return(bytesRead); }
private void RunEncryptionRound(IEncryptor encryptor, IEncryptor decryptor) { byte[] plain = new byte[16384]; byte[] cipher = new byte[plain.Length + 16 + IVEncryptor.ONETIMEAUTH_BYTES + IVEncryptor.AUTH_BYTES]; byte[] plain2 = new byte[plain.Length + 16]; int outLen = 0; int outLen2 = 0; var random = new Random(); random.NextBytes(plain); encryptor.Encrypt(plain, plain.Length, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(plain.Length, outLen2); for (int j = 0; j < plain.Length; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 1000, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(1000, outLen2); for (int j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 12333, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(12333, outLen2); for (int j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } }
public static Payment DecryptedPayment(this Payment payment, IEncryptor encryptor) { payment.CardNumber = encryptor.Decrypt(payment.CardNumber); payment.Cvv = encryptor.Decrypt(payment.Cvv); return(payment); }
private void RunStreamEncryptionRound(IEncryptor encryptor, IEncryptor decryptor) { byte[] plain = new byte[16384]; const int IV = 16; byte[] cipher = new byte[plain.Length + IV]; byte[] plain2 = new byte[plain.Length + IV]; int outLen = 0; int outLen2 = 0; _random.NextBytes(plain); encryptor.Encrypt(plain, plain.Length, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(plain.Length, outLen2); for (int j = 0; j < plain.Length; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 1000, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(1000, outLen2); for (int j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 12333, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(12333, outLen2); for (int j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } }
public override byte[] ClientUdpPostDecrypt(byte[] plaindata, int datalength, out int outlength) { if (datalength <= 8) { outlength = 0; return(plaindata); } MbedTLS.HMAC md5 = CreateHMAC(user_key); byte[] md5data = md5.ComputeHash(plaindata, 0, datalength - 1); if (md5data[0] != plaindata[datalength - 1]) { outlength = 0; return(plaindata); } md5 = CreateHMAC(Server.key); md5data = md5.ComputeHash(plaindata, datalength - 8, 7); int rand_len = UdpGetRandLen(random_server, md5data); outlength = datalength - rand_len - 8; encryptor = EncryptorFactory.GetEncryptor("chacha20", System.Convert.ToBase64String(user_key) + System.Convert.ToBase64String(md5data, 0, 16), false); { int temp; byte[] iv = new byte[8]; Array.Copy(Server.key, iv, 8); encryptor.Decrypt(iv, 8, plaindata, out temp); } encryptor.Decrypt(plaindata, outlength, plaindata, out outlength); return(plaindata); }
private void RunEncryptionRound(IEncryptor encryptor, IEncryptor decryptor) { byte[] plain = new byte[16384]; byte[] cipher = new byte[plain.Length + 16]; byte[] plain2 = new byte[plain.Length + 16]; int outLen = 0; int outLen2 = 0; var random = new Random(); random.NextBytes(plain); encryptor.Encrypt(plain, plain.Length, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(plain.Length, outLen2); for (int j = 0; j < plain.Length; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 1000, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(1000, outLen2); for (int j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 12333, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(12333, outLen2); for (int j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } }
private void RunEncryptionRound(IEncryptor encryptor, IEncryptor decryptor) { RNG.Reload(); byte[] plain = new byte[16384]; byte[] cipher = new byte[plain.Length + 16]; byte[] plain2 = new byte[plain.Length + 16]; int outLen = 0; int outLen2 = 0; var random = new Random(); random.NextBytes(plain); encryptor.Encrypt(plain, plain.Length, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.Equal(plain.Length, outLen2); for (int j = 0; j < plain.Length; j++) { Assert.Equal(plain[j], plain2[j]); } encryptor.Encrypt(plain, 1000, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.Equal(1000, outLen2); for (int j = 0; j < outLen2; j++) { Assert.Equal(plain[j], plain2[j]); } }
private void RunEncryptionRound(IEncryptor encryptor, IEncryptor decryptor) { var plain = new byte[16384]; var cipher = new byte[plain.Length + 16]; var plain2 = new byte[plain.Length + 16]; Rng.RandBytes(plain); encryptor.Encrypt(plain, plain.Length, cipher, out var outLen); decryptor.Decrypt(cipher, outLen, plain2, out var outLen2); Assert.AreEqual(plain.Length, outLen2); for (var j = 0; j < plain.Length; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 1000, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(1000, outLen2); for (var j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 12333, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(12333, outLen2); for (var j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } }
public int Receive(byte[] recv_buffer, int size, SocketFlags flags, out int bytesRead, out int protocolSize, out bool sendback) { bytesRead = _socket.Receive(recv_buffer, size, flags); protocolSize = 0; if (bytesRead > 0) { lock (_decryptionLock) { int bytesToSend = 0; int obfsRecvSize; byte[] remoteRecvObfsBuffer = _obfs.ClientDecode(recv_buffer, bytesRead, out obfsRecvSize, out sendback); if (obfsRecvSize > 0) { Util.Utils.SetArrayMinSize(ref ReceiveDecryptBuffer, obfsRecvSize); _encryptor.Decrypt(remoteRecvObfsBuffer, obfsRecvSize, ReceiveDecryptBuffer, out bytesToSend); int outlength; protocolSize = bytesToSend; byte[] buffer = _protocol.ClientPostDecrypt(ReceiveDecryptBuffer, bytesToSend, out outlength); TcpMSS = _protocol.GetTcpMSS(); //if (recv_buffer.Length < outlength) //ASSERT Array.Copy(buffer, 0, recv_buffer, 0, outlength); return(outlength); } } return(0); } else { sendback = false; _close = true; } return(bytesRead); }
public LockReleaseResult ReleaseLock(string @lock, string lockOwner) { var lockName = ToSafeLockName(@lock, MaxLockNameLength, s => s); // otherwise issue the release command var connection = GetConnection(); if (_connectionString != null) { connection.Open(); } else if (connection == null) { throw new InvalidOperationException("The transaction had been disposed"); } else if (connection.State != ConnectionState.Open) { throw new InvalidOperationException("The connection is not open"); } var id = Guid.Parse(_encryptor.Decrypt(lockOwner)); using (var checkCommand = SqlHelpers.CreateCheckApplicationLockCommand(connection, 1000, lockName, id)) { var exists = (int)checkCommand.ExecuteScalar() > 0; if (!exists) { return(new LockReleaseResult { Success = false, Reason = ReleaseLockFailure.OwnerNotMatching }); } SqlParameter deleteReturnValue; using ( var releaseCommand = SqlHelpers.CreateDeleteApplicationLockCommand(connection, 1000, lockName, id, out deleteReturnValue)) { releaseCommand.ExecuteNonQuery(); } var success = (int)deleteReturnValue.Value == 0; return(success ? new LockReleaseResult { Success = true, Reason = ReleaseLockFailure.Undefined } : new LockReleaseResult { Success = false, Reason = ReleaseLockFailure.ReleaseError }); } }
public async Task <IActionResult> ChangeKeyStorage([FromBody] ChangeKeyStorageViewModel model) { if (ModelState.IsValid) { var storage = storageContext.Storages .Where(s => s.Name == model.Name && s.User == User.Identity.Name) .FirstOrDefault(); var word = storageContext.Words .Where(w => w.Storage == model.Name && w.User == User.Identity.Name) .FirstOrDefault(); if (storage == null) { return(new BadRequestObjectResult("Хранилище не найдено")); } if (word == null) { return(new BadRequestObjectResult("Контрольное слово отсутствует")); } if (!model.NewKey.Equals(model.ConfirmKey)) { return(new BadRequestObjectResult("Пароли не совпадают")); } if (model.OldKey.Equals(model.NewKey)) { return(new BadRequestObjectResult("Старый и новый пароли совпадают")); } if (!encryptor.CheckSizeKey(model.NewKey) || !encryptor.CheckSizeKey(model.OldKey)) { return(new BadRequestObjectResult("Размер ключа [16, 24, 32]")); } var controlWord = encryptor.Decrypt(encryptor.ToByte(model.OldKey), storage.IV, word.ControlWord); if (controlWord == null) { return(new BadRequestObjectResult("Ключ неверный")); } storage.IV = encryptor.GenerateIV(); word.ControlWord = encryptor.Encrypt(encryptor.ToByte(model.NewKey), storage.IV, controlWord); storageContext.Storages.Update(storage); storageContext.Words.Update(word); storageContext.Storages.Update(storage); await storageContext.SaveChangesAsync(); return(new OkObjectResult("Пароль хранилища обновлен")); } return(new BadRequestObjectResult("Модель данных не корректна")); }
public async Task <PaymentRecord?> GetPaymentAsync(Guid paymentId, Guid companyId) { var innerResult = await _innerRepository.GetPaymentAsync(paymentId, companyId); if (innerResult != null) { innerResult.CardNumber = _encryptor.Decrypt(innerResult.CardNumber); innerResult.CardName = _encryptor.Decrypt(innerResult.CardName); } return(innerResult); }
private Dictionary <string, string> GetEquivalents(string json, out string secondKey) { var equivalentsResult = new Dictionary <string, string>(); var equivalentsProperties = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); secondKey = $"{KEY_PREFIX}:{string.Join("", equivalentsProperties.Select(item => item.Key))}"; foreach (var item in equivalentsProperties) { var decrypt = _encryptor.Decrypt(item.Value, secondKey); equivalentsResult.Add(item.Key, decrypt); } return(equivalentsResult); }
/// <summary> Get the initial response from the execution properties. </summary> /// <returns>initial response string</returns> internal String GetLastOfflineInitialResponse() { //Extract and decode the initial response from the execution properties IEncryptor encryptor = PersistentOnlyCacheManager.GetInstance(); String initialResponseString = null; int lastOfflineFileVersion = LastOfflineFileVersion; byte[] initialResponseBytes = Encoding.Default.GetBytes(LastOfflineExecutionProperties[ConstInterface.INITIAL_RESPONSE]); if (encryptor.EncryptionDisabled) { initialResponseString = Encoding.UTF8.GetString(initialResponseBytes, 0, initialResponseBytes.Length); } else { if (lastOfflineFileVersion == 1) { initialResponseBytes = Base64.decodeToByte(Encoding.ASCII.GetString(initialResponseBytes, 0, initialResponseBytes.Length)); } initialResponseBytes = encryptor.Decrypt(initialResponseBytes); initialResponseString = Encoding.UTF8.GetString(initialResponseBytes, 0, initialResponseBytes.Length); } return(initialResponseString); }
public string DecodeJson(Cookie cookie) { var json = cookie.Value; var value = HttpUtility.UrlDecode(json); return(_encryptor.Decrypt(value)); }
public void RecvFromCallback(IAsyncResult ar) { try { EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); int bytesRead = _remote.EndReceiveFrom(ar, ref remoteEndPoint); byte[] dataOut = new byte[bytesRead]; int outlen; IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password, _server.auth, true); encryptor.Decrypt(_buffer, bytesRead, dataOut, out outlen); byte[] sendBuf = new byte[outlen + 3]; Array.Copy(dataOut, 0, sendBuf, 3, outlen); Logging.Debug(_localEndPoint, _remoteEndPoint, outlen, "UDP Relay"); _local.SendTo(sendBuf, outlen + 3, 0, _localEndPoint); Receive(); } catch (ObjectDisposedException) { // TODO: handle the ObjectDisposedException } catch (Exception) { // TODO: need more think about handle other Exceptions, or should remove this catch(). } finally { } }
private T ConvertFatEntity(FatEntity fat) { T result; var data = fat.GetData(); if (data.Length == 0) { result = default(T); } else { if (_decryptor != null) { using (var ms = new MemoryStream()) { using (var dc = _decryptor.Decrypt(ms, false)) { dc.Write(data, 0, data.Length); } data = ms.ToArray(); } } result = JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(data)); } return(result); }
/// <summary> /// Fluent step final - Use configured reader to read file /// </summary> /// <param name="path"></param> /// <returns></returns> IReaderResult IInitializedAndSecurizedReader.ReadFile(string path) { var accessGranted = true; if (_accessManager != null) { accessGranted = _accessManager.CanAccess(path, _identity); } if (!accessGranted) { return(new ReaderResult(false, string.Empty)); } var fileContent = File.ReadAllText(path); if (_encryptor != null) { fileContent = _encryptor.Decrypt(fileContent); } var contentRead = _textReader.Read(fileContent); return(new ReaderResult(true, contentRead)); }
private static IDictionary DecryptPayload(IEncryptor encryptor, byte[] key, byte[] payloadEncryptedBytes) { byte[] bytes = encryptor.Decrypt(payloadEncryptedBytes, key); string @string = stringEncoding.GetString(bytes); return(JsonParser.FromJson <Dictionary <string, object> >(@string)); }
public static ServerTransferTotal Load() { try { string config_str = File.ReadAllText(LOG_FILE); ServerTransferTotal config = new ServerTransferTotal(); try { if (GlobalConfiguration.config_password.Length > 0) { byte[] cfg_encrypt = System.Convert.FromBase64String(config_str); IEncryptor encryptor = EncryptorFactory.GetEncryptor("aes-256-cfb", GlobalConfiguration.config_password, false); byte[] cfg_data = new byte[cfg_encrypt.Length]; int data_len; encryptor.Decrypt(cfg_encrypt, cfg_encrypt.Length, cfg_data, out data_len); config_str = UTF8Encoding.UTF8.GetString(cfg_data, 0, data_len); } } catch { } config.servers = SimpleJson.SimpleJson.DeserializeObject <Dictionary <string, object> >(config_str, new JsonSerializerStrategy()); config.Init(); return(config); } catch (Exception e) { if (!(e is FileNotFoundException)) { Console.WriteLine(e); } return(new ServerTransferTotal()); } }
public static Configuration Load(string config_str) { try { if (GlobalConfiguration.config_password.Length > 0) { byte[] cfg_encrypt = System.Convert.FromBase64String(config_str); IEncryptor encryptor = EncryptorFactory.GetEncryptor("aes-256-cfb", GlobalConfiguration.config_password); byte[] cfg_data = new byte[cfg_encrypt.Length]; int data_len; encryptor.Decrypt(cfg_encrypt, cfg_encrypt.Length, cfg_data, out data_len); config_str = UTF8Encoding.UTF8.GetString(cfg_data, 0, data_len); } } catch { } try { Configuration config = SimpleJson.SimpleJson.DeserializeObject <Configuration>(config_str, new JsonSerializerStrategy()); config.FixConfiguration(); return(config); } catch { } return(null); }
public FileResult GetDecryptFile(string name) { try { var storageName = HttpContext.Session.GetString("StorageName"); if (storageName == null) { return(null); } //LoadStorages(ref storageDB, storageName); var file = dataLite.Files.Get(f => f.Name == name); var storage = storageContext.Storages .Where(s => s.Name == storageName) .FirstOrDefault(); dataLite.Close(); if (file == null) { return(null); } var path = GetDirFile() + file.Path; FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read); BinaryReader br = new BinaryReader(fs); var decrypted = encryptor.Decrypt(br.ReadBytes((int)fs.Length)); MemoryStream ms = new MemoryStream(decrypted); string fileType = file.Group + "/" + file.Type; string fileName = name + "." + file.Type; return(File(ms, fileType, fileName)); } catch (Exception ex) { return(null); } }
public void RecvFromCallback(IAsyncResult ar) { try { EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); int bytesRead = _remote.EndReceiveFrom(ar, ref remoteEndPoint); byte[] dataOut = new byte[bytesRead]; int outlen; IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password); encryptor.Decrypt(_buffer, bytesRead, dataOut, out outlen); byte[] sendBuf = new byte[outlen + 3]; Array.Copy(dataOut, 0, sendBuf, 3, outlen); _local.SendTo(sendBuf, outlen + 3, 0, _localEndPoint); Receive(); } catch (ObjectDisposedException) { } catch (Exception) { } finally { } }
private void PipeRemoteReceiveCallback(IAsyncResult ar) { if (closed) { return; } try { int bytesRead = remote.EndReceive(ar); totalRead += bytesRead; if (bytesRead > 0) { this.lastActivity = DateTime.Now; int bytesToSend; lock (decryptionLock) { if (closed) { return; } if (encryptor != null) { encryptor.Decrypt(remoteRecvBuffer, bytesRead, remoteSendBuffer, out bytesToSend); } else { remoteSendBuffer = remoteRecvBuffer; bytesToSend = bytesRead; } } connection.BeginSend(remoteSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeConnectionSendCallback), null); IStrategy strategy = controller.GetCurrentStrategy(); if (strategy != null) { strategy.UpdateLastRead(this.server); } } else { //Console.WriteLine("bytesRead: " + bytesRead.ToString()); connection.Shutdown(SocketShutdown.Send); connectionShutdown = true; CheckClose(); if (totalRead == 0) { // closed before anything received, reports as failure // disable this feature // controller.GetCurrentStrategy().SetFailure(this.server); } } } catch (Exception e) { Logging.LogUsefulException(e); this.Close(); } }
override public Users Get(string id) { var entity = _crud.GetItem(id); entity.Password = null; entity.FirstName = _encryptor.Decrypt(entity.FirstName); entity.LastName = _encryptor.Decrypt(entity.LastName); return(entity); }
public void Run() { Console.WriteLine("##### CRIPTOGRAFANDO #####\n"); _encryptor.Encrypt(); Console.WriteLine("##### DESCRIPTOGRAFANDO #####\n"); _encryptor.Decrypt(); }
/// <summary> /// Decrypt data from <see cref="string"/> to <see cref="byte"/> array using <see cref="Convert.FromBase64String(string)"/> /// </summary> /// <param name="encryptor">Specific encryptor</param> /// <param name="encryptedData">Encrypted data for decryption</param> /// <returns>Decrypted data</returns> public static byte[] DecryptFromBase64String(this IEncryptor encryptor, string encryptedData) { encryptedData.StringNullOrEmptyValidate(nameof(encryptedData)); var encryptedByteData = Convert.FromBase64String(encryptedData); return(encryptor.Decrypt(encryptedByteData)); }
public string GetSystemClientId(string token) { try { string data = encryptor.Decrypt(token); var arr = data.Split('|'); string sign = arr[0]; if (sign != "SAT") { return(null); } var client = arr[1]; return(client); } catch { return(null); } }
/// <summary> /// 从ss服务器接收数据后的回调方法, /// 接收数据后, 发送回客户端的udp socket /// </summary> /// <param name="ar"></param> public void RecvFromCallback(IAsyncResult ar) { /* +-------+--------------+ | IV | PAYLOAD | +-------+--------------+ | Fixed | Variable | +-------+--------------+ | ->decrypt 解密 | +------+----------+----------+----------+ | ATYP | DST.ADDR | DST.PORT | DATA | +------+----------+----------+----------+ | 1 | Variable | 2 | Variable | +------+----------+----------+----------+ | ->add 包装协议内容 | +----+------+------+----------+----------+----------+ |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA | +----+------+------+----------+----------+----------+ | 2 | 1 | 1 | Variable | 2 | Variable | +----+------+------+----------+----------+----------+ */ try { EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); int bytesRead = _remote.EndReceiveFrom(ar, ref remoteEndPoint); byte[] dataOut = new byte[bytesRead]; int outlen; // 解密 IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password, _server.auth, true); encryptor.Decrypt(_buffer, bytesRead, dataOut, out outlen); // 包装socks5协议 byte[] sendBuf = new byte[outlen + 3]; Array.Copy(dataOut, 0, sendBuf, 3, outlen); Logging.Debug($"======Send Local Port, size:" + (outlen + 3)); // 将数据转发给客户端socket _local.SendTo(sendBuf, outlen + 3, 0, _localEndPoint); // 继续等待ss服务器的数据 Receive(); } catch (ObjectDisposedException) { // TODO: handle the ObjectDisposedException } catch (Exception) { // TODO: need more think about handle other Exceptions, or should remove this catch(). } finally { } }
public void TestValidation_Should_Right_Decrypt() { //Arrange //Act var result = _encryptionByPleyfer.Decrypt("итйицкаудрпш"); //Assert Assert.That(result == "криптография"); }
public ActionResult Decrypt(string token, bool base64) { if (base64) { token = token.Base64Decode(); } return(Content(_encryptor.Decrypt(token))); }