public void CanInitEncryptionServiceWithoutKeyAndIV()
        {
            var service = new EncryptionService();

            Assert.IsNotNull(service.Key);
            Assert.IsNotNull(service.InitializationVector);
        }
        public void CanEncryptToBase64()
        {
            var service = new EncryptionService();

            var encrytedString = service.EncryptToBase64String("test");

            Assert.IsNotNull(encrytedString);
        }
 public AuthenticationService(
         TenantRepository tenantRepository,
         UserRepository userRepository,
         EncryptionService encryptionService)
 {
     this.EncryptionService = encryptionService;
     this.TenantRepository = tenantRepository;
     this.UserRepository = userRepository;
 }
        public void CanDecryptSecretKeyToString()
        {
            var service = new EncryptionService();

            var encryptedBytes = service.EncryptToBytes("lc8Pe7M+XsbGyzTCmpkpREOHMd85H35WsF+CJhwS");

            var decryptedString = service.DecryptToString(encryptedBytes);

            Assert.AreEqual("lc8Pe7M+XsbGyzTCmpkpREOHMd85H35WsF+CJhwS", decryptedString);
        }
        public void CanDecryptBase64StringToString()
        {
            var service = new EncryptionService();
            var encrytedString = service.EncryptToBase64String("test");

            var decryptionService = new EncryptionService(service.Key, service.InitializationVector);
            var decryptedString = decryptionService.DecryptBase64StringToString(encrytedString);

            Assert.AreEqual("test", decryptedString);
        }
        public void CanDecryptToStringUsingAsciiEncoding()
        {
            var service = new EncryptionService();
            Encode.Encoding = Encoding.ASCII;
            service.Encoding = Encoding.ASCII;

            var encryptedBytes = service.EncryptToBytes("test");

            var decryptedString = service.DecryptToString(encryptedBytes);

            Assert.AreEqual("test", decryptedString);
        }
예제 #7
0
        ///GENMHASH:383E4E95C2764D4EF94A2DE388852F09:53DCC067101B13A21EE567A072307B56
        public DateTime?LastEnabledTime()
        {
            EncryptionService encryptionService = this.EncryptionService();

            if (encryptionService == null)
            {
                return(null);
            }
            else
            {
                return(encryptionService.LastEnabledTime);
            }
        }
예제 #8
0
        private static ValidationResult ValidateParentHash(Block blockchain)
        {
            if (blockchain.Parent.IsGenesis)
            {
                return(new ValidationResult(true));
            }

            var parentHash = EncryptionService.GetSha256Hash(blockchain.Parent.BlockJson);

            return(parentHash != blockchain.Header.ParentHash
                ? new ValidationResult(false, $"The parent hash is invalid for block with id: {blockchain.Id}")
                : new ValidationResult(true));
        }
예제 #9
0
        public void CanGenerateNewKey()
        {
            var service = new EncryptionService();

            service.GenerateKeyToString();

            var encrytedString = service.EncryptToBase64String("test");

            var decryptionService = new EncryptionService(service.Key, service.InitializationVector);
            var decryptedString   = decryptionService.DecryptBase64StringToString(encrytedString);

            Assert.AreEqual("test", decryptedString);
        }
예제 #10
0
        public void CanDecryptToStringUsingAsciiEncoding()
        {
            var service = new EncryptionService();

            Encode.Encoding  = Encoding.ASCII;
            service.Encoding = Encoding.ASCII;

            var encryptedBytes = service.EncryptToBytes("test");

            var decryptedString = service.DecryptToString(encryptedBytes);

            Assert.AreEqual("test", decryptedString);
        }
        public void IsPlainText_True_WhenPlainText()
        {
            //Arrange
            File.WriteAllText(@".\IsNotPlainText_False_WhenPlainText", "Oooogabooga!");
            EncryptionService encryptionService = new EncryptionService(_keyInfo, _consolePrinter);
            bool expected = true;

            //Act
            bool actual = encryptionService.IsPlainText(@".\IsNotPlainText_False_WhenPlainText");

            //Assert
            Assert.AreEqual(expected, actual);
        }
예제 #12
0
        public IActionResult PatientRecords()
        {
            ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName);
            if (HttpContext.Session.GetString(Globals.currentDSPriK) == null || HttpContext.Session.GetString(Globals.currentDAPriK) == null)
            {
                return(RedirectToAction("Login"));
            }
            else if (HttpContext.Session.GetString(Globals.currentPSPubK) == null || HttpContext.Session.GetString(Globals.currentPAPubK) == null)
            {
                return(RedirectToAction("PatientLookUp"));
            }
            else
            {
                Assets <PatientCredAssetData> userAsset = _bigChainDbService.GetPatientAssetFromID(HttpContext.Session.GetString(Globals.currentPPHN));

                var doctorSignPrivateKey  = HttpContext.Session.GetString(Globals.currentDSPriK);
                var doctorAgreePrivateKey = HttpContext.Session.GetString(Globals.currentDAPriK);
                var doctorSignPublicKey   = EncryptionService.getSignPublicKeyStringFromPrivate(doctorSignPrivateKey);
                var patientSignPublicKey  = HttpContext.Session.GetString(Globals.currentPSPubK);

                PatientCredMetadata userMetadata = _bigChainDbService.GetMetadataFromAssetPublicKey <PatientCredMetadata>(userAsset.id, patientSignPublicKey);

                var prescriptionsList = _bigChainDbService.GetAllTypeRecordsFromDPublicPPublicKey <string, PrescriptionMetadata>
                                            (AssetType.Prescription, doctorSignPublicKey, patientSignPublicKey);
                var prescriptions = new List <PrescriptionFullData>();
                foreach (var prescription in prescriptionsList)
                {
                    var hashedKey         = prescription.metadata.AccessList[doctorSignPublicKey];
                    var dataDecryptionKey = EncryptionService.getDecryptedEncryptionKey(hashedKey, doctorAgreePrivateKey);
                    var data     = EncryptionService.getDecryptedAssetData(prescription.data.Data, dataDecryptionKey);
                    var newEntry = new PrescriptionFullData
                    {
                        assetData = JsonConvert.DeserializeObject <Prescription>(data),
                        Metadata  = prescription.metadata.data,
                        transID   = prescription.transID,
                        assetID   = prescription.id
                    };
                    prescriptions.Add(newEntry);
                }
                var patientInfo = userAsset.data.Data;
                var patientOverviewViewModel = new PatientOverviewViewModel
                {
                    PatientAsset    = patientInfo,
                    PatientMetadata = userMetadata,
                    PatientAge      = patientInfo.DateOfBirth.CalculateAge(),
                    Prescriptions   = prescriptions.OrderByDescending(p => p.assetData.PrescribingDate).ToList()
                };

                return(View(patientOverviewViewModel));
            }
        }
예제 #13
0
        public void GetUserRolesTest()
        {
            var ctx = new Mock <IContext>();

            List <Role> roles = new List <Role>
            {
                new Role()
                {
                    Id = 1, Name = "Role1"
                },
                new Role()
                {
                    Id = 2, Name = "Role2"
                }
            };
            List <UserRole> userRoles = new List <UserRole>
            {
                new UserRole()
                {
                    Id = 1, RoleId = 1, UserId = 1, Role = roles[0]
                },
                new UserRole()
                {
                    Id = 2, RoleId = 2, UserId = 1, Role = roles[1]
                }
            };
            List <User> users = new List <User>
            {
                new User()
                {
                    Id = 1, Username = "******", UserRoles = userRoles
                }
            };

            var rolesMockDbSet     = ServiceTestsHelper.GetMockDbSet <Role>(roles);
            var usersMockDbSet     = ServiceTestsHelper.GetMockDbSet <User>(users);
            var userRolesMockDbSet = ServiceTestsHelper.GetMockDbSet <UserRole>(userRoles);

            ctx.Setup(c => c.Set <Role>()).Returns(rolesMockDbSet.Object);
            ctx.Setup(c => c.Set <User>()).Returns(usersMockDbSet.Object);
            ctx.Setup(c => c.Set <UserRole>()).Returns(userRolesMockDbSet.Object);

            IUserService       userService       = new UserService(ctx.Object);
            IRoleService       roleService       = new RoleService(ctx.Object);
            IUserRoleService   userRoleService   = new UserRoleService(ctx.Object);
            IEncryptionService encryptionService = new EncryptionService();
            IMembershipService service           = new MembershipService(userService, encryptionService, roleService, userRoleService);
            List <Role>        result            = service.GetUserRoles("testUser1");

            Assert.Equal(2, result.Count);
        }
예제 #14
0
    public void CallBack(string s)
    {
        try
        {
            if (s != null && s != "")
            {
                //解密
                if (EncryptionService.IsSecret)
                {
                    s = EncryptionService.Decrypt(s);
                }

                NetWorkMessage msg = new NetWorkMessage();

                s = s.Replace(c_endCharReplaceString, c_endChar.ToString());
                Dictionary <string, object> data = Json.Deserialize(s) as Dictionary <string, object>;

                msg.m_data        = data;
                msg.m_MessageType = data["MT"].ToString();

                if (data.ContainsKey("MsgCode"))
                {
                    msg.m_MsgCode = int.Parse(data["MsgCode"].ToString());

                    if (m_msgCode != msg.m_MsgCode)
                    {
                        Debug.LogError("MsgCode error currentCode " + m_msgCode + " server code " + msg.m_MsgCode);
                        if (msg.m_MsgCode > m_msgCode)
                        {
                            m_msgCode = msg.m_MsgCode;
                            m_msgCode++;
                            m_messageCallBack(msg);
                        }
                    }
                    else
                    {
                        m_msgCode++;
                        m_messageCallBack(msg);
                    }
                }
                else
                {
                    m_messageCallBack(msg);
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Message error ->" + s + "<-\n" + e.ToString());
        }
    }
예제 #15
0
        private void HashDefaultCustomerPassword(string defaultUserEmail, string defaultUserPassword)
        {
            var adminUser = _ctx.Set <Customer>().Where(x => x.Email == _config.DefaultUserName).Single();

            var encryptionService = new EncryptionService(new SecuritySettings());

            string saltKey = encryptionService.CreateSaltKey(5);

            adminUser.PasswordSalt   = saltKey;
            adminUser.PasswordFormat = PasswordFormat.Hashed;
            adminUser.Password       = encryptionService.CreatePasswordHash(defaultUserPassword, saltKey, new CustomerSettings().HashedPasswordFormat);

            _ctx.SaveChanges();
        }
        public async Task <User> Login(User model, string password)
        {
            var user = await Context
                       .Users.FirstOrDefaultAsync(m => m.Username == model.Username);

            if (user != null)
            {
                if (EncryptionService.CheckPassword(user, password))
                {
                    return(user);
                }
            }
            return(null);
        }
예제 #17
0
        public void GetSha256Hash_DifferentValue_DifferentHash()
        {
            // Arrange
            const string value = "{ \"testProperty\": \"test data 1\" }";

            // Act
            var resultOne = EncryptionService.GetSha256Hash(value);
            var resultTwo = EncryptionService.GetSha256Hash(value);

            // Assert
            Assert.NotNull(resultOne);
            Assert.NotNull(resultTwo);
            Assert.Equal(resultOne, resultTwo);
        }
예제 #18
0
        public IActionResult Authenticate([FromBody] AuthenticateRequest request)
        {
            request.Password = EncryptionService.Encrypt(request.Password, jwtOptions.Secret);
            User user = _context.Users.FirstOrDefault(x => x.Email == request.Email && x.Password == request.Password);

            if (user == null)
            {
                return(BadRequest(new AuthResponse
                {
                    Message = "Prisijungti nepavyko, patikrinti įvestį."
                }));
            }
            return(Ok(GenerateAuthentificationResultForUser(user)));
        }
예제 #19
0
 public ActionResult Add(UserModel model)
 {
     if (ModelState.IsValid)
     {
         if (!String.IsNullOrWhiteSpace(model.Password))
         {
             model.Password = EncryptionService.EncryptCRSPassword(model.Password);
         }
         Users User = model.MapTo <UserModel, Users>();
         _userService.Insert(User);
         return(RedirectToAction("Index"));
     }
     return(View(model));
 }
예제 #20
0
        public void Should_throw_when_encrypt_and_decrypt_keys_are_too_similar()
        {
            var key     = Encoding.ASCII.GetBytes("gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e6");
            var service = new EncryptionService
            {
                Key         = key,
                ExpiredKeys = new List <byte[]> {
                    key
                }                                      //note that we use the same key to get the code to throw
            };
            var exception = Assert.Throws <Exception>(service.VerifyKeysAreNotTooSimilar);

            Assert.AreEqual("The new Encryption Key is too similar to the Expired Key at index 0. This can cause issues when decrypting data. To fix this issue please ensure the new encryption key is not too similar to the existing Expired Keys.", exception.Message);
        }
예제 #21
0
        public static async Task CreateNewUserAsync(
            Domain.Entities.User user,
            string requesterAddress,
            IRepositoryManager repositoryManager,
            SmtpSettings smtpSettings,
            EmailSettings emailSettings)
        {
            var(emailExists, _) = await CheckUserExistsWithEmailAsync(user.Email, repositoryManager.UserRepository)
                                  .ConfigureAwait(false);

            var(usernameExists, _) = await CheckUserExistsWithUsernameAsync(user.Username, repositoryManager.UserRepository)
                                     .ConfigureAwait(false);

            if (emailExists)
            {
                throw (new EmailAlreadyRegisteredException(
                           "A User with this email address already exists",
                           "A User with this email address already exists"
                           ));
            }
            if (usernameExists)
            {
                throw (new UsernameAlreadyRegisteredException(
                           "A User with this username already exists",
                           "A User with this username already exists"
                           ));
            }

            user.DisplayName = $"{user.FirstName} {user.LastName}";
            user.Password    = HashingHelper.HashPassword(user.Password);
            user.UserSecret  = EncryptionService.EncryptString(ModelHelpers.GenerateUniqueIdentifier(IdentifierConsts.UserIdentifierLength));
            user.CreatedOn   = DateTime.Now;

            try
            {
                await repositoryManager.UserRepository.AddAsync(user);

                await CreateNewVerficationAsync(
                    user.Email,
                    requesterAddress,
                    repositoryManager,
                    smtpSettings,
                    emailSettings,
                    isFirstContact : true).ConfigureAwait(false);
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #22
0
        public async Task <IActionResult> decrypt(EncryptionModel model)
        {
            var service = EncryptionService.DecryptString(model.text);

            var response = new GenericResponse <string>()
            {
                IsSuccess    = true,
                Message      = "Bucket created successfully.",
                ResponseCode = 200,
                Result       = service
            };

            return(Ok(response));
        }
 /// <summary>
 /// Dont stored passwords in plain text - store them in encrypted field
 /// </summary>
 private void EncryptSharepointPassword()
 {
     if (IsMessage(PluginMessage.Create, PluginMessage.Update) && IsStage(PluginStage.PreOperationEvent))
     {
         if (FieldChanging(Fields.jmcg_sis_sharepointsettings_.jmcg_sis_sharepointpasswordreset) &&
             GetField(Fields.jmcg_sis_sharepointsettings_.jmcg_sis_sharepointpasswordreset) != null)
         {
             //encrypt the password into these fields
             var encrypt = EncryptionService.Encrypt(GetStringField(Fields.jmcg_sis_sharepointsettings_.jmcg_sis_sharepointpasswordreset));
             SetField(Fields.jmcg_sis_sharepointsettings_.jmcg_sis_sharepointpasswordencrypted, encrypt);
             SetField(Fields.jmcg_sis_sharepointsettings_.jmcg_sis_sharepointpasswordreset, null);
         }
     }
 }
        public static async Task RunAsync([ServiceBusTrigger("userregistration", Connection = "ServiceBusConnectionString")] string myQueueItem, string messageId, ILogger log)
        {
            log.LogInformation($"C# ServiceBus queue trigger function processed message: {messageId}");

            //Load the encryption module
            var encryptionService = new EncryptionService();
            //Get the Object from the ServiceBus
            var registrationRequest = encryptionService.DecryptRegistrationRequest(JsonConvert.DeserializeObject <UserRegistrationRequest>(myQueueItem));
            //Get attendee service for table storage communication
            var attendeeService = new AttendeeService();
            //GetEmailService
            var emailService = new EmailService();
            //GetGraphApiService
            var graphApiService = new GraphApiService();

            //Save Attendee information to the table storage --> may be crypted
            var attendee = encryptionService.DecryptÁttendeeRecord(attendeeService.CreateAttendeeRecord(registrationRequest));

            //Register Attendee in AzureAD

            //Build AdUser Object
            string tenantDomainName = System.Environment.GetEnvironmentVariable("tenantDomainName");
            var    AdUser           = new User
            {
                AccountEnabled = true,
                //Generated user name with @<tenant>.onmicrosoft.com at the end
                UserPrincipalName = attendee.Username + tenantDomainName,
                DisplayName       = attendee.Name + "  " + attendee.Surname,
                Surname           = attendee.Surname,
                GivenName         = attendee.Name,
                UserType          = "Guest",
                UsageLocation     = "DE",
                CompanyName       = "JHV-Mitglieder",
                MailNickname      = attendee.Name + "" + attendee.Surname,
                PasswordProfile   = new PasswordProfile
                {
                    ForceChangePasswordNextSignIn = false,
                    Password = attendee.Password
                },
            };

            //ToDo: Create error handling!
            //CreateAdUser
            var createdUser = await graphApiService.graphClient.Users
                              .Request()
                              .AddAsync(AdUser);

            //Inform Attendee via Mail
            await emailService.SendRegistrationSucceededMail(attendee.Email, attendee.Name + " " + attendee.Surname, attendee.Username, attendee.Password);
        }
예제 #25
0
        public async Task Post_Password_Should_Change_Password()
        {
            var jwtService = new JwtService()
            {
                Configuration          = GuiApiTestStartup.Configuration,
                Logger                 = new FakeLogger(),
                RepositoriesFactory    = null,
                StringLocalizerFactory = new FakeStringLocalizerFactory()
            };

            var token             = jwtService.GenerateMailToken(_sammyUser.UserName);
            var idUser            = _sammyUser.Id;
            var newPasswordString = "newPassword#1234";

            User myUser = null;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                myUser = context.Users.FirstOrDefault(u => u.Id.Equals(idUser));
            }
            Assert.IsNotNull(myUser);

            var actualPassword = myUser.Password;

            var newPasswordDto = new NewPasswordDto()
            {
                NewPassword       = newPasswordString,
                NewPasswordRepeat = newPasswordString,
                Token             = token.Token
            };

            var httpResponseMessage = await _client.PostAsJsonAsync("users/password", newPasswordDto);

            Assert.IsTrue(httpResponseMessage.IsSuccessStatusCode);

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                myUser = context.Users.FirstOrDefault(u => u.Id.Equals(idUser));
            }
            Assert.IsNotNull(myUser);

            Assert.IsFalse(actualPassword.SequenceEqual <byte>(myUser.Password));

            var encryptonService = new EncryptionService();

            var newPassword = encryptonService.Sha256Hash($"{GuiApiTestStartup.Configuration.PasswordSalt}{newPasswordString}");

            Assert.IsTrue(newPassword.SequenceEqual <byte>(myUser.Password));
        }
예제 #26
0
        public ActionResult <ReturnUserViewModel> CreateUser(CreateUsuarioViewModel usuario)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                if (!usuario.Contraseña.Equals(usuario.ContraseñaConfirmada))
                {
                    return(BadRequest(new Response
                    {
                        Code = Models.Response.ResponseCode.Error.ToString(),
                        Message = "Error: Las contraseñas no coinciden",
                        Description = "Contraseña y ContraseñaConfirmada son diferentes"
                    }));
                }

                var encryptedPassword = EncryptionService.GetSHA256(usuario.Contraseña);

                var userToCreate = new Usuario
                {
                    NombreUsuario  = usuario.NombreUsuario,
                    NombreCompleto = usuario.NombreCompleto,
                    Edad           = usuario.Edad,
                    Contraseña     = encryptedPassword
                };

                _usuarioRepository.AddUsuario(userToCreate);

                return(Ok(new ReturnUserViewModel
                {
                    Id = userToCreate.Id,
                    Edad = userToCreate.Edad,
                    NombreCompleto = userToCreate.NombreCompleto,
                    NombreUsuario = userToCreate.NombreUsuario
                }));
            }
            catch (Exception e)
            {
                return(BadRequest(new Response
                {
                    Code = Models.Response.ResponseCode.Error.ToString(),
                    Message = "Error: Ah ocurrido un error",
                    Description = e.Message
                }));
            }
        }
예제 #27
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var userExists = _userManager.FindByEmail(EncryptionService.EncryptEmail(model.Email));

                    if (userExists != null)
                    {
                        ModelState.AddModelError("Użytkownik już istnieje", "Użytkownik z podanym adresem email już istnieje.");

                        return(View(model));
                    }

                    var user = new ApplicationUser
                    {
                        UserName      = EncryptionService.EncryptEmail(model.Email),
                        Email         = EncryptionService.EncryptEmail(model.Email),
                        FirstName     = EncryptionService.Encrypt(model.FirstName),
                        Surname       = EncryptionService.Encrypt(model.LastName),
                        LastLoginDate = DateTime.Now,
                        IsActive      = true
                    };
                    var result = await _userManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                        return(RedirectToAction("Index", "Home"));
                    }
                    AddErrors(result);
                }
                catch (Exception e)
                {
                    logger.Error(e, e.Message);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #28
0
        public virtual void ProcessRequest(HttpContext context)
        {
            var dbProxy    = new MongoDBService();
            var encryption = new EncryptionService();

            _httpProxy      = new HttpContextProxy(context);
            _initData       = _httpProxy;
            _logger         = Logger.GetLogger(this.GetType().Name, _httpProxy.TransactionId, dbProxy);
            _actionExecuter = new ActionExecuter(_logger);
            CreateRoute();
            _httpContext    = context;
            _contentHandler = new WwwrootContentHandler(_httpProxy, dbProxy, _viewEngine, _actionExecuter, _logger);
            HandleAuthTokenKey(dbProxy, encryption);
            HandleSession(context);
        }
        public void UpdateSettings(Func <ISettings> getSettings)
        {
            ISettings values = getSettings();

            if (values == null)
            {
                return;
            }
            Settings.Default.GoogleUsername    = values.Username;
            Settings.Default.GooglePassword    = EncryptionService.EncryptString(EncryptionService.ToSecureString(values.Password));
            Settings.Default.MonthsInTheFuture = values.MonthsInFuture;
            Settings.Default.MonthsInThePast   = values.MonthsInPast;
            Settings.Default.UseProxyServer    = values.UseProxy;
            Settings.Default.Save();
        }
예제 #30
0
        protected override void OnStartup(StartupEventArgs e)
        {
            KernelConfig.RegisterInstance <IWindowsVolumeListenerService>(new WindowsVolumeListenerService());

            var encryptionService = new EncryptionService();
            var videoFileService  = new VideoFileService();

            KernelConfig.RegisterInstance <IWindowService>(new WindowService());
            KernelConfig.RegisterInstance <IEncryptionService>(encryptionService);
            KernelConfig.RegisterInstance <IVideoFileService>(videoFileService);
            KernelConfig.RegisterInstance <IConfigurationFileService>(new ConfigurationFileService(encryptionService, videoFileService));

            KernelConfig.RegisterInstance();
            base.OnStartup(e);
        }
예제 #31
0
        public void EncryptDecrypt()
        {
            EncryptionService service = new EncryptionService();

            String originalContents = "My content to be encrypted";

            String encContents = service.Encrypt(originalContents);

            Assert.IsNotNull(encContents);
            Assert.IsFalse(encContents.Equals(originalContents));

            String restoredContents = service.Decrypt(encContents);

            Assert.AreEqual(originalContents, restoredContents);
        }
예제 #32
0
        public bool Authorize(HttpRequestMessage request)
        {
            var encryptedPassword = request.Headers.FirstOrDefault(h => h.Key == ApiHeader).Value?.First();

            if (string.IsNullOrEmpty(encryptedPassword))
            {
                return(false);
            }
            else
            {
                var password            = EncryptionService.Decrypt(encryptedPassword, EncryptionPassword);
                var authorizationResult = password.Equals(ApiPassword);
                return(authorizationResult);
            }
        }
예제 #33
0
        protected void SetEncryptedCookie(String cookieName, Dictionary <String, String> values)
        {
            var cookie = new HttpCookie(cookieName);

            foreach (var item in values)
            {
                cookie.Values[item.Key] = EncryptionService.Encrypt(item.Value);
            }
            cookie.Expires = DateTime.Now.AddMonths(Configuration.CookieLifeTime);

            cookie.HttpOnly = true;
            cookie.Secure   = HttpContext.Request.IsSecureConnection;

            Response.SetCookie(cookie);
        }
예제 #34
0
 private void SaveButton_Click(object sender, RoutedEventArgs e)
 {
     // make sure file exists before proceeding
     if (File.Exists(FileNameTextBox.Text))
     {
         using (EncryptionService encryptionService = GetNewEncryptionService())
         {
             File.WriteAllBytes(FileNameTextBox.Text, encryptionService.Encrypt(FileContent.Text));
             OriginalFileText       = FileContent.Text;
             FileContent.Background = Brushes.White;
             settings.UpdateSettings(FileNameTextBox.Text, storeLocation.SelectedValue.ToString().ToLower(), storeName.SelectedValue.ToString().ToLower(),
                                     (certificateName.SelectedValue ?? "").ToString().Split(new string[] { " (" }, StringSplitOptions.None)[0]);
         }
     }
 }
 public static string EncryptPassword(this string value)
 {
     try
     {
         if (value.Length > 0)
         {
             value = new EncryptionService().EncryptText(value.ToString(), new Exeutive().KeyValue("encriptionkey"));
         }
         return(value);
     }
     catch (Exception ex)
     {
         return(value);
     }
 }
예제 #36
0
        private static SessionInfo Deserialize(string s)
        {
            SessionInfo uc = null;

            try
            {
                uc = (SessionInfo)(Serialization.DeserializeObjectFromBase64(EncryptionService.Decrypt(s)));
            }
            catch (Exception ex)
            {
                LogService.Error(EventCode.APP, "Error deserializing cookie.", ex, s);
            }

            return(uc);
        }
예제 #37
0
 // if invokeOnChangeObj is not null, then onChange is called via BeginInvoke on that object.
 // Otherwise it's called on a background thread (the network thread).
 public Client(string server, int port, EncryptionService encryption, string myName, Action onChange, Control invokeOnChangeObj)
 {
     // Connect to server:port, open the streams, send authentication info, send a `list` command, and boot the processing thread.
     this.encryption = encryption;
     this.onChange = onChange;
     this.invokeOnChangeObj = invokeOnChangeObj;
     incomingMessages = new Queue<KeyValuePair<string, string>>();
     client = new TcpClient(server, port);
     var stream = client.GetStream();
     reader = new BinaryReader(stream);
     writer = new BinaryWriter(stream);
     Authenticate(myName);
     UpdateKeyPairs();
     var thread = new Thread(ProcessRecv);
     thread.IsBackground = true;
     thread.Start();
 }