private void Button1_Click(object sender, EventArgs e) { //Setup data varible var data = new dataJson(); //Setup json data.key = textBox1.Text; var JSON = JsonConvert.SerializeObject(data); //Setup keys for encryption var creds = EncryptProvider.CreateAesKey(); var key = creds.Key; var IV = creds.IV; //Encrypt data var encrypted = EncryptProvider.AESEncrypt(JSON, key, IV); //FInishing touches for encryption encrypted = key + "," + IV + "," + encrypted; //Write data to file File.WriteAllText(appDataPath + @"\data.json", encrypted); //Exit BypassQuit = true; this.Close(); }
public async Task <IActionResult> PutSiteOption(int id, SiteOption siteOption) { if (id != siteOption.Id) { return(BadRequest()); } _context.Entry(siteOption).State = EntityState.Modified; try { var aesKey = EncryptProvider.CreateAesKey(); var key = aesKey.Key; var iv = aesKey.IV; siteOption.SMTPPassword = $"{EncryptProvider.AESEncrypt(siteOption.SMTPPassword, key, iv)}.{key}.{iv}"; await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SiteOptionExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public IActionResult Authenticate([FromBody] OAuthModel login) { SmartHttpResult result = new SmartHttpResult(); try { var entity = DAL.SmartUser.GetEntityByName(login.UserName); if (entity != null) { var encrypted = EncryptProvider.AESEncrypt(login.PassWord, entity.Salt); if (entity.PassWord == encrypted) { //重新加密 var Saltkey = Guid.NewGuid().ToString("N"); var decrypted = EncryptProvider.AESEncrypt(login.PassWord, Saltkey); //替换密码与密钥 DAL.SmartUser.utlSmartUserByName(login.UserName, decrypted, Saltkey); var claims = new Claim[] { new Claim(ClaimTypes.Name, login.UserName), new Claim(ClaimTypes.Role, entity.Role) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var tokenModel = new JwtSecurityToken( setting.Issuer, setting.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(setting.TokenExpires), creds); var jwtToken = new JwtTokenModel(); jwtToken.Token = new JwtSecurityTokenHandler().WriteToken(tokenModel); var tokenUser = new TokenUserModel(); tokenUser.UserName = entity.UserName; tokenUser.Email = entity.Email; tokenUser.Phone = entity.Phone; tokenUser.Avatar = entity.Avatar; jwtToken.User = tokenUser; result.Set(true, jwtToken); return(new JsonResult(result)); } else { result.Set(false, "用户密码不正确!"); } } else { result.Set(false, "用户不存在!"); } } catch (Exception err) { result.Set(false, err.Message); } return(new JsonResult(result)); }
private void SaveFileAs_Executed(object sender, ExecutedRoutedEventArgs e) { Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); sfd.DefaultExt = "*.txt"; sfd.Filter = "文本文档|*.txt|黑 色 高 级 文 档|*.bad"; if (sfd.ShowDialog() == true) { var ctx = DataContext as FileContext; ctx.Path = sfd.FileName; ctx.Status = FcStatus.Saving; if (ctx.Path.EndsWith(".bad")) { ctx.isBADFile = true; CommandSetPassword.Execute(null, this); if (string.IsNullOrEmpty(ctx.Content)) { MessageBox.Show(this, "无法保存内容为空的 黑 色 高 级 文 档。"); return; } File.WriteAllText(ctx.Path, Base64ToFakeJapanese(EncryptProvider.AESEncrypt(ctx.Content, EncryptProvider.Md5(ctx.Password)))); } else { ctx.isBADFile = false; File.WriteAllText(ctx.Path, ctx.Content); } ctx.Status = FcStatus.Opened; } }
private void SaveFile_Executed(object sender, ExecutedRoutedEventArgs e) { var ctx = DataContext as FileContext; if (ctx.Path != string.Empty) { ctx.Status = FcStatus.Saving; if (ctx.isBADFile) { if (string.IsNullOrEmpty(ctx.Content)) { MessageBox.Show(this, "无法保存内容为空的 黑 色 高 级 文 档。"); return; } File.WriteAllText(ctx.Path, Base64ToFakeJapanese(EncryptProvider.AESEncrypt(ctx.Content, EncryptProvider.Md5(ctx.Password)))); } else { File.WriteAllText(ctx.Path, ctx.Content); } ctx.Status = FcStatus.Opened; } else { ApplicationCommands.SaveAs.Execute(null, this); } }
/// <summary> /// 数组加密 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static byte[] EncryptTo(this byte[] bytes) { if (bytes == null) { return(bytes); } return(EncryptProvider.AESEncrypt(bytes, AesKey, AesIv)); }
/// <summary> /// 字符串加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string EncryptTo(this string str) { if (string.IsNullOrWhiteSpace(str)) { return(str); } return(EncryptProvider.AESEncrypt(str, AesKey, AesIv)); }
public void Aes_Encrypt_ErrorKey_Fail_Test() { var aesKey = EncryptProvider.CreateAesKey(); var key = "1hyhuo"; var srcString = "test aes encrypt"; //Assert Assert.Throws <ArgumentOutOfRangeException>(() => EncryptProvider.AESEncrypt(srcString, key)); }
public IActionResult Index() { var key = "123456789012345678901234567890AA"; var iv = "1234567890ABCDEF"; string str = "Hi Crypt AES"; ViewBag.CryptCode = EncryptProvider.AESEncrypt(str, key, iv); return(View()); }
public override Task <IdentityResult> RedeemTwoFactorRecoveryCodeAsync(IdentityUser user, string code) { bool.TryParse(_configuration["TwoFactorAuthentication:EncryptionEnabled"], out bool encryptionEnabled); if (encryptionEnabled && !string.IsNullOrEmpty(code)) { code = EncryptProvider.AESEncrypt(code, _configuration["TwoFactorAuthentication:EncryptionKey"]); } return(base.RedeemTwoFactorRecoveryCodeAsync(user, code)); }
public void EncryptFileAES(string filepath) { var key = aesKey.Key; var iv = aesKey.IV; // TODO BACKUP MODE string contents = File.ReadAllText(filepath); string encrypted = EncryptProvider.AESEncrypt(contents, key, iv); File.WriteAllText(filepath, encrypted); }
/// <summary> /// عملیات رمز گذاری /// </summary> public static string AesEncrypt(this string text, string key) { if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException("لطفا مقدار کلید را وارد نمایید."); } string encrypt = EncryptProvider.AESEncrypt(text, key); return(encrypt); }
static void Main() { Console.WriteLine("Hello World!"); byte[] clearBytes = File.ReadAllBytes(@"C:\Users\Antonio\Pictures\image.jpg"); string encrypted = EncryptProvider.AESEncrypt("antonio", "7c529a69-2a26-4ed6-85da-16beef35db4a"); string decrypted = EncryptProvider.AESDecrypt(encrypted, "7c529a69-2a26-4ed6-85da-16beef35db4a"); Console.ReadLine(); //File.WriteAllBytes(@"C:\Users\Antonio\Pictures\image_dec.jpg", decryptedBytes); }
public static string AesEncrypt(this string text, string Key) { if (string.IsNullOrEmpty(Key) || string.IsNullOrWhiteSpace(Key)) { throw new ArgumentNullException("Key Cannot be null."); } string Encrypt = EncryptProvider.AESEncrypt(text, Key); return(Encrypt); }
public void Aes_Encrypt_With_ErrorKey_Fail_Test() { var aesKey = EncryptProvider.CreateAesKey(); var key = aesKey.Key; var iv = "ikojpoi"; //must be 16 bit var srcString = "test aes encrypt"; //Assert Assert.Throws <ArgumentOutOfRangeException>(() => EncryptProvider.AESEncrypt(srcString, key, iv)); }
/// <summary> /// aes加密 /// </summary> /// <param name="input">字符串</param> /// <param name="key">秘钥</param> /// <returns></returns> //public static string AesEncry(this string input, string key = null) //{ // if (key.IsNull()) key = EncryptContext.AesKey; // return EncryptProvider.AESEncrypt(input, key); //} /// <summary> /// AesEncry 加密 带偏移量 /// </summary> /// <param name="input">字符串</param> /// <param name="key">秘钥</param> /// <param name="iv">偏移量</param> /// <returns></returns> public static string AesEncry(this string input, string key = null, string iv = null) { if (key.IsNull()) { key = EncryptContext.AesKey; } if (iv.IsNull()) { iv = EncryptContext.AesIv; } return(EncryptProvider.AESEncrypt(input, key, iv)); }
protected override string CreateTwoFactorRecoveryCode() { var originalRecoveryCode = base.CreateTwoFactorRecoveryCode(); bool.TryParse(_configuration["TwoFactorAuthentication:EncryptionEnabled"], out bool encryptionEnabled); var encryptedRecoveryCode = encryptionEnabled ? EncryptProvider.AESEncrypt(originalRecoveryCode, _configuration["TwoFactorAuthentication:EncryptionKey"]) : originalRecoveryCode; return(encryptedRecoveryCode); }
public void Aes_Encryt_Success_Test() { var aesKey = EncryptProvider.CreateAesKey(); var key = aesKey.Key; var srcString = "test aes encrypt"; //Ack var result = EncryptProvider.AESEncrypt(srcString, key); //Assert Assert.NotEmpty(result); }
public void Aes_Encrypt_With_ErrorIV_Fail_Test() { var aesKey = EncryptProvider.CreateAesKey(); var key = "j1l23kj1j"; //must be 32 bit var iv = aesKey.IV; var srcString = "test aes encrypt"; //Assert Assert.Throws <ArgumentOutOfRangeException>(() => EncryptProvider.AESEncrypt(srcString, key, iv)); }
public override string GenerateNewAuthenticatorKey() { var originalAuthenticatorKey = base.GenerateNewAuthenticatorKey(); // var aesKey = EncryptProvider.CreateAesKey(); bool.TryParse(_configuration["TwoFactorAuthentication:EncryptionEnabled"], out bool encryptionEnabled); var encryptedKey = encryptionEnabled ? EncryptProvider.AESEncrypt(originalAuthenticatorKey, _configuration["TwoFactorAuthentication:EncryptionKey"]) : originalAuthenticatorKey; return(encryptedKey); }
private byte[] RealizarEncryptPorTipoCriptografia(byte[] pBytesFile, Criptografia pCriptografia, string pChave) { if (pCriptografia == Criptografia.Base64) { return(Convert.FromBase64String(EncryptProvider.Base64Encrypt(Convert.ToBase64String(pBytesFile)))); } else if (pCriptografia == Criptografia.DES) { return(EncryptProvider.DESEncrypt(pBytesFile, BuildKey(pChave, 24))); } else { return(Convert.FromBase64String(EncryptProvider.AESEncrypt(Convert.ToBase64String(pBytesFile), BuildKey(pChave, 32)))); } }
public void Aes_Decryt_Success_Test() { var aesKey = EncryptProvider.CreateAesKey(); var key = aesKey.Key; var srcString = "test aes encrypt"; //Ack var encrypted = EncryptProvider.AESEncrypt(srcString, key); var decrypted = EncryptProvider.AESDecrypt(encrypted, key); //Assert Assert.NotEmpty(encrypted); Assert.NotEmpty(decrypted); Assert.Equal(srcString, decrypted); }
public int Execute() { if (Data.AppSettings.Profile == null) { Data.AppSettings.Profile = new List <ProfileInfo>(); } var profileInfo = new ProfileInfo(); while (true) { Console.WriteLine("Enter User Profile Name (eg. Friedrich-dev)"); profileInfo.Name = Console.ReadLine(); if (Data.AppSettings.Profile.All(x => x.Name != profileInfo.Name)) { break; } Console.WriteLine("Profile name already exists, choose different one."); } Console.WriteLine("Enter oneomics username"); profileInfo.Username = Console.ReadLine(); string password1; while (true) { Console.WriteLine("Enter oneomics password"); password1 = PasswordHelper.GetPassword(); Console.WriteLine("Re-Enter oneomics password"); var password2 = PasswordHelper.GetPassword(); if (password1 == password2) { break; } Console.WriteLine("Passwords don't match"); } var encrypted = EncryptProvider.AESEncrypt(password1, Data.EncryptionKey); profileInfo.Password = encrypted; Data.AppSettings.Profile.Add(profileInfo); Data.Save(); Console.WriteLine($"Settings file updated: {Data.AppSettingsFileName}"); return(0); }
public static string AESEncrypt(string source, CryptAESKey key) { if (!string.IsNullOrEmpty(source) && key != null && string.IsNullOrEmpty(key.IV)) { //不带加密向量 var encrypted = EncryptProvider.AESEncrypt(source, key.Key); return(encrypted); } else if (!string.IsNullOrEmpty(source) && key != null) { //带加密向量 var encrypted = EncryptProvider.AESEncrypt(source, key.Key, key.IV); return(encrypted); } return(source); }
public static byte[] Encode(byte[] bytes, string password) { if (bytes.Length == 0) { MessageBox.Show("File size is zero"); return(null); } var sha = SHA256.Create(); var sb = new StringBuilder(); var keyBytes = sha.ComputeHash(Encoding.UTF8.GetBytes(password.ToCharArray())).ToList(); keyBytes.ForEach(x => sb.Append(x)); var key = new string(sb.ToString().Take(32).ToArray()); var iv = new string(sb.ToString().Take(16).ToArray()); var encryptedBytes = EncryptProvider.AESEncrypt(bytes, key, iv); return(encryptedBytes); }
public void Aes_File_Test() { var rootDir = Path.Combine(AppContext.BaseDirectory, "Assets"); if (!Directory.Exists(rootDir)) { Directory.CreateDirectory(rootDir); } var file = Path.Combine(rootDir, "AES_File_Test.txt"); if (!File.Exists(file)) { using (var fileStream = File.OpenWrite(file)) { var tempDatas = Encoding.UTF8.GetBytes("May be you shoud get all the buffer of file,and then decrypt by EncryptProvider."); fileStream.Write(tempDatas, 0, tempDatas.Length); } } var aesKey = EncryptProvider.CreateAesKey(); //encrypt var text = File.ReadAllText(file); var datas = File.ReadAllBytes(file); var encryptedDatas = EncryptProvider.AESEncrypt(datas, aesKey.Key, aesKey.IV); var encryptedFile = Path.Combine(rootDir, "AES_File_Test_Encrypted.txt"); using (var fileStream = File.OpenWrite(encryptedFile)) { fileStream.Write(encryptedDatas, 0, encryptedDatas.Length); } //decrypt var encryptedFileDatas = File.ReadAllBytes(encryptedFile); var decryptedDatas = EncryptProvider.AESDecrypt(encryptedFileDatas, aesKey.Key, aesKey.IV); var decryptedText = Encoding.UTF8.GetString(decryptedDatas); //assert Assert.NotNull(decryptedDatas); Assert.Equal(decryptedText, text); }
public async Task <IActionResult> LoginPost([FromBody] OAuthModel model) { var s = HttpContext.Authentication; //ViewData["ReturnUrl"] = "/"; if (ModelState.IsValid) { var entity = DAL.SmartUser.GetEntityByName(model.UserName); if (entity != null) { var encrypted = EncryptProvider.AESEncrypt(model.PassWord, entity.Salt); if (entity.PassWord == encrypted) { //重新加密 var Saltkey = Guid.NewGuid().ToString("N"); var decrypted = EncryptProvider.AESEncrypt(model.PassWord, Saltkey); //替换密码与密钥 DAL.SmartUser.utlSmartUserByName(model.UserName, decrypted, Saltkey); //创建用户身份标识 var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); claimsIdentity.AddClaims(new List <Claim>() { new Claim(ClaimTypes.Sid, model.UserName), new Claim(ClaimTypes.Name, model.UserName), new Claim(ClaimTypes.Role, "admin"), }); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); return(Redirect("/Home/Index")); } else { ModelState.AddModelError(string.Empty, "帐号或者密码错误。"); } } else { ModelState.AddModelError(string.Empty, "用户不存在。"); } } return(View(model)); }
private static void Method() { Console.WriteLine("Gratulacje!"); Console.WriteLine("Poprawnie wykonałeś zadanie."); var key = ConfigurationManager.AppSettings["key"]; var encrypted = EncryptProvider.AESEncrypt("DOTNET2020", key); var group = EncryptProvider.AESDecrypt(ConfigurationManager.AppSettings["group"], key); var password = EncryptProvider.AESDecrypt(ConfigurationManager.AppSettings["password"], key); Console.WriteLine(); Console.WriteLine($"Teraz dołącz do grupy: {group}"); Console.WriteLine($"podając hasło: {password}"); Console.WriteLine(); Console.WriteLine("Do zobaczenia na grupie!"); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("Test Client"); Console.WriteLine("Waiting for services to start...\nPress enter when ready."); Console.ReadLine(); authProducer = RabbitMqProducer.Create(StaticQueues.RequestAuth); authReceiver = RabbitMqReceiver.Create(APPLICATIONID, OnAuthReceived); var service = new Service { ApplicationId = APPLICATIONID, GroupId = GROUPID }; var json = JsonConvert.SerializeObject(service); var encrypt = EncryptProvider.AESEncrypt(json, KEY, IV); authProducer.SendMessage(encrypt); Console.WriteLine("Waiting for response."); }
public IActionResult Login([FromBody] LoginModel _user) { if (!ModelState.IsValid) { var errors = ModelState.Select(x => x.Value.Errors).Where(e => e.Count > 0).ToList(); return(BadRequest(errors)); } // Map the model to entity User userMapped = this._mapper.Map <User> (_user); // Validate user User userFound = this._context.Users.SingleOrDefault(u => u.Email == userMapped.Email); var key = this._config["PasswordKey"]; var passwordEncrypted = EncryptProvider.AESEncrypt(_user.Password, key); if (userFound == null || userFound.Password != passwordEncrypted) { return(BadRequest("Invalid user/password.")); } // Returning token return(Ok(this.GenerateToken(userFound))); }