public ActionResult Create([Bind(Include = "Id,Title")] Article article, HttpPostedFileBase file) { if (ModelState.IsValid) { try { EncryptionUtility utility = new EncryptionUtility(); SymmetricParameters parameters = utility.GenerateSymmetricParameters("123qwe", "ijbygcrz"); string userId = User.Identity.GetUserId(); // Public and private keys are generated during user registration, stored in UserKey table string publicKey = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PublicKey; string privateKey = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PrivateKey; //Convert file into an array of bytes, results saved in memory MemoryStream ms = new MemoryStream(); file.InputStream.Position = 0; file.InputStream.CopyTo(ms); ms.Position = 0; //Signing Process string signature = utility.GenerateSignature(ms.ToArray(), privateKey); // Encryption Process string encryptedSK = utility.Encrypt(parameters.SecretKey, publicKey); string encryptedIV = utility.Encrypt(parameters.IV, publicKey); string encryptedFile = utility.Encrypt(ms.ToArray(), parameters); // Storage Process string filePath = Server.MapPath(@"\Files"); //File save location string fileName = Guid.NewGuid().ToString(); //Generate unique file name string absoluteFilePath = filePath + @"\" + fileName; //Build file data, Secret key and IV in file header utility.WriteToFile(absoluteFilePath, utility.FileMerge(encryptedSK, encryptedIV, encryptedFile)); //Database Process article.UserId = User.Identity.GetUserId(); article.DateCreated = DateTime.Now; article.StateId = 1; article.Signature = signature; article.FileName = fileName; db.Articles.Add(article); db.SaveChanges(); ViewBag.Message = "Upload & Encryption Successful"; return(RedirectToAction("Index")); } catch { return(RedirectToAction("Missing")); } } return(View()); }
static void Main(string[] args) { string plainText = string.Empty; if (args.Length > 0) { plainText = args[0]; } else { Console.Write("Enter text to encrypt: "); plainText = Console.ReadLine(); } if (plainText == string.Empty) { Console.WriteLine("No text to encrypt"); } else { string cipherText = EncryptionUtility.Encrypt(plainText); Console.WriteLine("\n" + cipherText + "\n"); } Console.WriteLine("Press any key to continue."); Console.ReadKey(); }
/// <summary> /// Registers a new user using the given password key to decrypt their password /// </summary> /// <param name="newUser"></param> /// <param name="passwordKey"></param> public void Register(User newUser, string passwordKey, string facebookAuthCode) { // check if user already exists List <User> allUsers = DataManager.GetDataContext <User>().GetAll <User>(); if (allUsers.Any(u => u.UserName == newUser.UserName)) { throw new Exception(USER_EXISTS); } if (newUser.SyncWithFacebook) { newUser.FacebookAccessToken = FacebookManager.GetFacebookAccessToken(facebookAuthCode); } // decrypt password string decrypted = EncryptionUtility.Decrypt(passwordKey, newUser.Password); // re-encrypt password with server key string serverEncrypt = EncryptionUtility.Encrypt(ServerPasswordKey, decrypted); // set the user's password to the server-encrypted version newUser.Password = serverEncrypt; // add the users to the data context and save DataManager.GetDataContext <User>().AddObjects <User>(new User[] { newUser }.ToList()); DataManager.GetDataContext <User>().Save(); // add the user the logged on users if (!LoggedOnUsers.Any(u => u.Email == newUser.Email)) { LoggedOnUsers.Add(newUser); } }
public static DatabaseDictionary LoadDatabaseDictionary(string path, string keyFile) { DatabaseDictionary dbDictionary = Utility.Read <DatabaseDictionary>(path); string connStr = dbDictionary.ConnectionString; if (connStr != null) { if (!Utility.IsBase64Encoded(connStr)) { // // connection string is not encrypted, encrypt and write it back // dbDictionary.ConnectionString = EncryptionUtility.Encrypt(connStr, keyFile); Utility.Write <DatabaseDictionary>(dbDictionary, path); dbDictionary.ConnectionString = connStr; } else { dbDictionary.ConnectionString = EncryptionUtility.Decrypt(connStr, keyFile); } } return(dbDictionary); }
private void SendEmail(string email) { string encryptedEmail = EncryptionUtility.Encrypt(email); string rootUrl = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"]; string url = string.Format(rootUrl + "/Usersettings/confirmEmail?validateToken={0}", encryptedEmail); // Create a new Exchange service object ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); // Set user login credentials string ExchangeServerEmail = ConfigurationManager.AppSettings["ExchangeServerEmailID"]; string ExchangeServerpwd = ConfigurationManager.AppSettings["ExchangeServerpwd"]; service.Credentials = new WebCredentials(ExchangeServerEmail, ExchangeServerpwd); try { //Set Office 365 Exchange Webserivce Url string serviceUrl = "https://outlook.office365.com/ews/exchange.asmx"; service.Url = new Uri(serviceUrl); EmailMessage emailMessage = new EmailMessage(service); emailMessage.Subject = "Email Confirmation for daily summary updates"; emailMessage.Body = new MessageBody("Thanks for subscribing pnp test results, please click <a href='" + url + "'> here </a> to confirm your email address "); emailMessage.ToRecipients.Add(email); emailMessage.Send(); } catch (AutodiscoverRemoteException exception) { throw; } }
private string ProtectV1(ComposerCookieDto dto) { //Serialize string json = JsonConvert.SerializeObject(dto, _jsonSettings); return(EncryptionUtility.Encrypt(json)); }
public void WHEN_null_is_encrypted_SHOULD_throw_an_argumentnullexception() { //Arrange var encryptionUtility = new EncryptionUtility(); //Act //Assert Assert.Throws <ArgumentNullException>(() => encryptionUtility.Encrypt(null)); }
public void WHEN_data_is_encrypted_SHOULD_return_a_base_64_string() { //Arrange var encryptionUtility = new EncryptionUtility(); //Act var result = encryptionUtility.Encrypt("some data"); //Assert result.Should().NotBeEmpty(); result.Should().MatchRegex("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$"); }
public void WHEN_data_is_encrypted_SHOULD_return_the_same_value_when_decrypted() { //Arrange var encryptionUtility = new EncryptionUtility(); //Act var expected = "some data"; var encrypted = encryptionUtility.Encrypt(expected); var result = encryptionUtility.Decrypt(encrypted); //Assert result.Should().Be(expected, "because this was the value originally encrypted."); }
public string ProtectFunctionCall(string functionName, Dictionary <string, string> parameters) { var lazyFunctionCall = new LazyFunctionCall() { FunctionName = functionName, Parameters = parameters, QueryString = HttpContext.Request.QueryString.ToString(), PageId = PageRenderer.CurrentPageId, }; string json = JsonConvert.SerializeObject(lazyFunctionCall); return(EncryptionUtility.Encrypt(json)); }
public void AfterEncryptingAStringItCanBeDecrypted() { // arrange const String ExpectedResult = "This is my test string"; const String Key = "aslk;djflkasdjflksdajflksjadflkjasdklfjklsadfjlkasdjflsadjfklasdjfljsadklf"; var encryptionUtility = new EncryptionUtility(); // act var encryptedText = encryptionUtility.Encrypt(ExpectedResult, Key); var decryptedText = encryptionUtility.Decrypt(encryptedText, Key); // assert Assert.Equal(decryptedText, ExpectedResult); }
public static void SaveDatabaseDictionary(DatabaseDictionary dbDictionary, string path, string keyFile) { string connStr = dbDictionary.ConnectionString; if (connStr != null) { if (Utility.IsBase64Encoded(connStr)) { // connection string is not encrypted, encrypt it dbDictionary.ConnectionString = EncryptionUtility.Encrypt(connStr, keyFile); } } Utility.Write <DatabaseDictionary>(dbDictionary, path); }
private void InitSessionFactory(string path, string context) { try { lock (_lockObj) { string cfgPath = string.Format("{0}nh-configuration.{1}.xml", path, context); string mappingPath = string.Format("{0}nh-mapping.{1}.xml", path, context); if (File.Exists(cfgPath) && File.Exists(mappingPath)) { Configuration cfg = new Configuration(); cfg.Configure(cfgPath); string connStrProp = "connection.connection_string"; string connStr = cfg.Properties[connStrProp]; string keyFile = string.Format("{0}{1}.key", path, context); if (!Utility.IsBase64Encoded(connStr)) { // // connection string is not encrypted, encrypt and write it back // string encryptedConnStr = EncryptionUtility.Encrypt(connStr, keyFile); cfg.Properties[connStrProp] = encryptedConnStr; SaveConfiguration(cfg, cfgPath); // restore plain text connection string for creating session factory cfg.Properties[connStrProp] = connStr; } else { cfg.Properties[connStrProp] = EncryptionUtility.Decrypt(connStr, keyFile); } ISessionFactory sessionFactory = cfg.AddFile(mappingPath).BuildSessionFactory(); string factoryKey = context.ToLower(); _sessionFactories[factoryKey] = sessionFactory; } } } catch (Exception e) { _logger.Error("Error updating NHibernate session factory [" + context + "]. " + e); throw e; } }
private void SetOutput(string input, DisplayCertificate certificate) { if (input == null || certificate == null) { return; } try { Output = EncryptionUtility.Encrypt(input, certificate.Certificate); } catch (Exception ex) { Trace.TraceError($"Encryption failed: ({ex.GetType().Name}) {ex.Message}"); // TODO: Tell the user what went wrong } }
public void Save() { string json = saveGame.ToJson(); if (debug) { Debug.Log("saving json " + json); } if (encrypt) { json = EncryptionUtility.Encrypt(json); } File.WriteAllText(FilePath, json); }
public async Task <IActionResult> Index() { var permission = await _dbcontext.Permission.Select(q => new PermissionViewModel { Id = q.Id, ActionName = q.ActionName, ActionType = q.ActionType, AreaName = q.AreaName, ControllerName = q.ControllerName, ShowInMenu = q.ShowInMenu, Title = q.Title, Url = q.Url, EncryptedId = EncryptionUtility.Encrypt(q.Id.ToString()) }).ToListAsync(); //var permission = await _dbcontext.Permission.ToListAsync(); return(View(permission)); }
public IActionResult Authenticate([FromBody] LoginModels userParam) { try { var user = _userService.Authenticate(userParam.Email, EncryptionUtility.Encrypt(userParam.Password)); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } return(Ok(user)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public void Encrypt_Then_Decrypt_Result_Matches_Input() { var value = "This is some text that should be encrypted then decrypted and still come out the same."; var certificate = EncryptionUtility .FindCertificates(x => HasPrivateKey(x) && HasPublicKey(x)) .FirstOrDefault(); if (certificate == null) { Assert.Inconclusive("Unable to find a certificate suitable to preform the test."); } var encrypted = EncryptionUtility.Encrypt(value, certificate); var decrypted = EncryptionUtility.Decrypt(encrypted); Assert.AreEqual(value, decrypted); }
/// <summary> /// Gets the user information by username and password. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns></returns> public UserModel GetUserInfoByUsernameAndPassword(string username, string password) { using (var db = new SampleEntities()) { string encryptedPassword = EncryptionUtility.Encrypt(password, true); return(db.Users.Where(w => w.Username == username && w.Password == encryptedPassword).Select(s => new UserModel { Id = s.Id, FirstName = s.FirstName, MiddleName = s.MiddleName, LastName = s.LastName, Email = s.Email, Phone = s.Phone, Username = s.Username, UserTypeId = s.UserTypeId }).SingleOrDefault()); } }
public void Encrypt_With_No_Private_Key_Then_Decrypt_Throws_InvalidOperationException() { var value = "This is some text that should be encrypted then decrypted and still come out the same."; var certificate = EncryptionUtility .FindCertificates(x => !HasPrivateKey(x) && HasPublicKey(x)) // Make sure there is no other certificate with this public key and a private key as well .FirstOrDefault(x => !HasPrivateKey(EncryptionUtility.FindCertificateByPublicKey(x.GetPublicKey()))); if (certificate == null) { Assert.Inconclusive("Unable to find a certificate suitable to preform the test."); } var encrypted = EncryptionUtility.Encrypt(value, certificate); var decrypted = EncryptionUtility.Decrypt(encrypted); Assert.AreEqual(value, decrypted); }
public static void SendNotiifcationEmail(string emailBody, List <string> recepients) { try { string rootUrl = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"]; // Create a new Exchange service object ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); StringBuilder sbUserStatus = new StringBuilder(); string ExchangeServerEmail = ConfigurationManager.AppSettings["ExchangeServerEmailID"]; string ExchangeServerpwd = ConfigurationManager.AppSettings["ExchangeServerpwd"]; foreach (string toEmail in recepients) { string encryptedEmail = EncryptionUtility.Encrypt(toEmail); string url = string.Format(rootUrl + "Usersettings/Unsubscribe?validateToken={0}", encryptedEmail); emailBody = emailBody.Replace("{unsubribelink}", url); // Set user login credentials service.Credentials = new WebCredentials(ExchangeServerEmail, ExchangeServerpwd); try { //Set Office 365 Exchange Webserivce Url string serviceUrl = "https://outlook.office365.com/ews/exchange.asmx"; service.Url = new Uri(serviceUrl); EmailMessage emailMessage = new EmailMessage(service); emailMessage.Subject = "PnP TestAutomation daily summary report"; emailMessage.Body = new MessageBody(BodyType.HTML, emailBody); emailMessage.ToRecipients.Add(toEmail); //emailMessage.BccRecipients.Add(toEmail); emailMessage.Send(); } catch (AutodiscoverRemoteException exception) { Console.WriteLine("Erroe while sending the mails to user" + toEmail + exception.Message); throw; } } } catch (Exception ex) { Console.WriteLine("Erroe while sending the mails to users" + ex.Message); } }
/// <summary> /// Serializes a data contract /// </summary> /// <param name="t">The type of the object to serialize</param> /// <param name="obj">The object to serialize</param> /// <returns>The serialized version of the object</returns> public static string Serialize(Type t, object obj, string encryptionKey) { string xml; // check that the object is a data contract if ((t.GetCustomAttributes(typeof(DataContractAttribute), true).Any()) || (t.IsGenericType && typeof(IEnumerable).IsAssignableFrom(t) && t.GetGenericArguments().First().GetCustomAttributes(typeof(DataContractAttribute), true).Any())) { // create object to store xml StringBuilder objXml = new StringBuilder(); // create xml writer using (XmlWriter xmlWriter = XmlWriter.Create(objXml)) { // create data contract serializer for the contract type DataContractSerializer serializer = new DataContractSerializer(t); // write object to xml serializer.WriteObject(xmlWriter, obj); // flush the writer to ensure completion of xml writing xmlWriter.Flush(); // set xml xml = objXml.ToString(); } } else { xml = obj.ToString(); } // if an encryption key was provided, encrypt the serialized result before returning if (!string.IsNullOrEmpty(encryptionKey)) { xml = EncryptionUtility.Encrypt(encryptionKey, xml); } return(xml); }
/// <summary> /// Gets an encrypted token that will be used to identify an order. /// </summary> /// <param name="token">Parameters used to generate the token.</param> /// <returns></returns> public static string GenerateOrderToken(OrderToken token) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrWhiteSpace(token.OrderNumber)) { throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(token.OrderNumber)), nameof(token)); } if (string.IsNullOrWhiteSpace(token.Email)) { throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(token.Email)), nameof(token)); } var encryptor = new EncryptionUtility(); var rawToken = string.Join(TokenSeparator, token.OrderNumber, token.Email); var encryptedToken = encryptor.Encrypt(rawToken); return(encryptedToken); }
/// <summary> /// Gets an encrypted token that will be used to identify an order. /// </summary> /// <param name="token">Parameters used to generate the token.</param> /// <returns></returns> public static string GenerateOrderToken(OrderToken token) { if (token == null) { throw new ArgumentNullException("token"); } if (String.IsNullOrWhiteSpace(token.OrderNumber)) { throw new ArgumentException(ArgumentNullMessageFormatter.FormatErrorMessage("OrderNumber"), "token"); } if (String.IsNullOrWhiteSpace(token.Email)) { throw new ArgumentException(ArgumentNullMessageFormatter.FormatErrorMessage("Email"), "token"); } var encryptor = new EncryptionUtility(); var rawToken = String.Join(TokenSeparator, token.OrderNumber, token.Email); var encryptedToken = encryptor.Encrypt(rawToken); return(encryptedToken); }
public IActionResult AddUser([FromBody] UserViewModel model) { try { var data = Mapper.Map <UserProfile>(model); data.Password = EncryptionUtility.Encrypt(data.Password); var resp = _userService.Adduser(data); if (resp == false) { return(BadRequest(new { message = "Email already taken" })); } return(Ok("User Added Successfully! Kindly Proceed to login")); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
/// <summary> /// Initializes the customer identifier. /// </summary> private void InitializeCustomerId() { if (!_customerId.HasValue) { //First attempt, lazy load from cookie var dto = CookieAccessor.Read(); if (dto.EncryptedCustomerId != null) { _customerId = new Guid(EncryptionUtility.Decrypt(dto.EncryptedCustomerId)); } else { //Second attempt, create a new customerId _customerId = Guid.NewGuid(); _isGuest = true; //Store it in cookie for later dto.EncryptedCustomerId = EncryptionUtility.Encrypt(_customerId.ToString()); dto.IsGuest = _isGuest; CookieAccessor.Write(dto); } } }
/// <summary> /// Gets an encrypted token that will be used to identify an wish list. /// </summary> /// <param name="token">Parameters used to generate the token.</param> /// <returns></returns> public static string GenerateToken(SharedWishListToken token) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (token.CustomerId == Guid.Empty) { throw new ArgumentException(GetMessageOfEmpty(nameof(token.CustomerId)), nameof(token)); } if (string.IsNullOrWhiteSpace(token.Scope)) { throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(token.Scope)), nameof(token)); } var encryptor = new EncryptionUtility(); var rawToken = string.Join(TokenSeparator, token.CustomerId.ToString("N"), token.Scope); var encryptedToken = encryptor.Encrypt(rawToken); byte[] toEncodeAsBytes = System.Text.Encoding.ASCII.GetBytes(encryptedToken); return(Convert.ToBase64String(toEncodeAsBytes)); }
//[Bind(Include = "Id,UserId,ReviewId,Title,Body,DateCreated,StateId")] Article article public ActionResult Edit([Bind(Include = "Id,UserId,ReviewId,DateCreated,StateId,FileName,Title")] Article article, HttpPostedFileBase file) { if (ModelState.IsValid) { try { if (article.StateId == 1 || article.StateId == 3) // Unlocked states { EncryptionUtility utility = new EncryptionUtility(); SymmetricParameters parameters = utility.GenerateSymmetricParameters("123qwe", "ijbygcrz"); string userId = User.Identity.GetUserId(); // Public and private keys are generated during user registration, stored in UserKey table string PublicKey = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PublicKey; string PrivateKey = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PrivateKey; //Convert file into an array of bytes, results saved in memory MemoryStream ms = new MemoryStream(); file.InputStream.Position = 0; file.InputStream.CopyTo(ms); ms.Position = 0; //Signing Process string signature = utility.GenerateSignature(ms.ToArray(), PrivateKey); // Encryption Process string encryptedSK = utility.Encrypt(parameters.SecretKey, PublicKey); string encryptedIV = utility.Encrypt(parameters.IV, PublicKey); string encryptedFile = utility.Encrypt(ms.ToArray(), parameters); // Storage Process string filePath = Server.MapPath(@"\Files"); //File save location string absoluteFilePath = filePath + @"\" + article.FileName; // If same name of file present then delete that file first if (System.IO.File.Exists(absoluteFilePath)) { System.IO.File.Delete(absoluteFilePath); } //Build file data, Secret key and IV in file header utility.WriteToFile(absoluteFilePath, utility.FileMerge(encryptedSK, encryptedIV, encryptedFile)); // Database Process if (article.Review != null) { article.Review.Accepted = false; } article.StateId = 1; // Revert back to pending article.DateLastEdited = DateTime.Now; article.Signature = signature; db.Entry(article).State = EntityState.Modified; db.SaveChanges(); ViewBag.Message = "Upload & Encryption Successful"; return(RedirectToAction("Index")); } else { ViewBag.Message = "Only Pending or Finished articles can be updated."; } } catch { return(RedirectToAction("Missing")); } } return(View(article)); }
private string CreateConfiguration(Provider provider, string connectionString, String defaultSchema) { string driver = String.Empty; string dialect = String.Empty; try { string dbProvider = provider.ToString(); NHibernateProvider _NHibernateProvider = new NHibernateProvider(); driver = Convert.ToString(_NHibernateProvider.GetConnectionDriver(dbProvider)); dialect = Convert.ToString(_NHibernateProvider.GetDatabaseDialect(dbProvider)); StringBuilder configBuilder = new StringBuilder(); XmlTextWriter configWriter = new XmlTextWriter(new StringWriter(configBuilder)); configWriter.Formatting = Formatting.Indented; configWriter.WriteStartElement("configuration"); configWriter.WriteStartElement("hibernate-configuration", "urn:nhibernate-configuration-2.2"); configWriter.WriteStartElement("session-factory"); configWriter.WriteStartElement("property"); configWriter.WriteAttributeString("name", "connection.provider"); configWriter.WriteString("NHibernate.Connection.DriverConnectionProvider"); configWriter.WriteEndElement(); // end property element configWriter.WriteStartElement("property"); configWriter.WriteAttributeString("name", "connection.driver_class"); configWriter.WriteString(driver); configWriter.WriteEndElement(); // end property element configWriter.WriteStartElement("property"); configWriter.WriteAttributeString("name", "connection.connection_string"); string keyFile = string.Format("{0}{1}.{2}.key", _settings["AppDataPath"], _settings["ProjectName"], _settings["ApplicationName"]); configWriter.WriteString(EncryptionUtility.Encrypt(connectionString, keyFile)); configWriter.WriteEndElement(); // end property element configWriter.WriteStartElement("property"); configWriter.WriteAttributeString("name", "proxyfactory.factory_class"); configWriter.WriteString("NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"); configWriter.WriteEndElement(); // end property element configWriter.WriteStartElement("property"); configWriter.WriteAttributeString("name", "default_schema"); configWriter.WriteString(defaultSchema); configWriter.WriteEndElement(); // end property element configWriter.WriteStartElement("property"); configWriter.WriteAttributeString("name", "dialect"); configWriter.WriteString(dialect); configWriter.WriteEndElement(); // end property element configWriter.WriteStartElement("property"); configWriter.WriteAttributeString("name", "show_sql"); configWriter.WriteString("true"); configWriter.WriteEndElement(); // end property element configWriter.WriteStartElement("property"); configWriter.WriteAttributeString("name", "command_timeout"); configWriter.WriteString("0"); configWriter.WriteEndElement(); // end property element configWriter.WriteEndElement(); // end session-factory element configWriter.WriteEndElement(); // end hibernate-configuration element configWriter.WriteEndElement(); // end configuration element configWriter.Close(); return(configBuilder.ToString()); } catch (Exception ex) { throw ex; } }
private void btnEncrypt_Click(object sender, EventArgs e) { txtEncryptedContent.Text = EncryptionUtility.Encrypt(txtTextToEncrypt.Text, txtThumbPrint.Text); }