public static string GenerateTokenString(Jwt jwt, string key) { return(string.Format(tokenTemplate, Cryptographer.Base64Encode(JsonConvert.SerializeObject(jwt.Header)), Cryptographer.Base64Encode(JsonConvert.SerializeObject(jwt.Payload)), GenerateSignature(jwt, key))); }
public static Jwt DecodeTokenString(string str) { string[] arr = str.Split('.'); return(new Jwt(JsonConvert.DeserializeObject <Header>(Cryptographer.Base64Decode(arr[0])), JsonConvert.DeserializeObject <Payload>(Cryptographer.Base64Decode(arr[1])), arr[2])); }
/// <summary> /// Encrypt a sample text using the default symmetric provider. /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private void encryptButton_Click(object sender, System.EventArgs e) { if (this.inputForm != null) { this.inputForm.Title = Resources.EncryptTitleMessage; this.inputForm.InstructionsText = Resources.EncryptInstructionsMessage; if (this.inputForm.ShowDialog() == DialogResult.OK) { try { this.Cursor = Cursors.WaitCursor; string valueToEncrypt = this.inputForm.Input; this.encryptedContentsBase64 = Cryptographer.EncryptSymmetric(symmProvider, this.inputForm.Input); this.DisplayResults(string.Format(Resources.Culture, Resources.OriginalTextMessage, this.inputForm.Input)); this.DisplayResults(string.Format(Resources.EncryptedTextMessage, this.encryptedContentsBase64)); } catch (Exception ex) { ProcessUnhandledException(ex); } finally { this.decryptButton.Enabled = true; this.Cursor = Cursors.Default; } } } }
/// <summary> /// Decrypts a set of bytes and displayed the decrypted contents. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void decryptButton_Click(object sender, System.EventArgs e) { if (this.encryptedContentsBase64 != null) { try { this.Cursor = Cursors.WaitCursor; // Descrypt and display value string readableString = Cryptographer.DecryptSymmetric(symmProvider, this.encryptedContentsBase64); this.DisplayResults(string.Format(Resources.Culture, Resources.DecryptedTextMessage, readableString)); } catch (Exception ex) { ProcessUnhandledException(ex); } finally { this.Cursor = Cursors.Default; } } else { this.DisplayResults(Resources.DecryptErrorMessage); } }
public void Send(string data) { try { if (!string.IsNullOrEmpty(data)) { var socket = new Socket(_ip.AddressFamily, SocketType.Dgram, ProtocolType.Udp); socket.Bind(_ipEP); var des = GetDES(socket); var encryptedData = Cryptographer.SymmetricEncrypt(data, des); //отправляем данные socket.SendTo(encryptedData, _ipEP); socket.Shutdown(SocketShutdown.Both); socket.Close(); socket.Dispose(); } } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } }
private DESCryptoServiceProvider GetDES(Socket socket) { var buffer = new byte[1024]; // Принимаем RSA public var sizeRSA = socket.Receive(buffer); var publicKeyJsonByte = new byte[sizeRSA]; Array.Copy(buffer, 0, publicKeyJsonByte, 0, sizeRSA); var publicKeyJson = Encoding.UTF8.GetString(publicKeyJsonByte); var publicKey = JsonConvert.DeserializeObject <RSAPublicKeyParameters>(publicKeyJson); var publicKeyParameters = publicKey.GetRSAParameters(); var des = Cryptographer.GetDES(); var iv = Cryptographer.RSAEncrypt(des.IV, publicKeyParameters); var key = Cryptographer.RSAEncrypt(des.Key, publicKeyParameters); var encrypdedDes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new DESParameters(iv, key))); //отправляем ключ socket.Send(encrypdedDes); return(des); }
private List <ViewUserModel> DecodeData(List <UserApp> list) { List <ViewUserModel> user_list = new List <ViewUserModel>(); for (int i = 0; i < list.Count(); i++) { Cryptographer cryptographer = new Cryptographer().Create(list[i].Upassword); string firstName = cryptographer.Decode(list[i].FirstName); string lastName = cryptographer.Decode(list[i].LastName); long count_task = _context.BoardTasks.Where(b => b.IdOwner == list[i].Id).Count(); ViewUserModel userView = new ViewUserModel() { Id = list[i].Id, Name = firstName.First().ToString().ToUpper() + String.Join("", firstName.Skip(1)), LastName = lastName.First().ToString().ToUpper() + String.Join("", firstName.Skip(1)), DateRegister = list[i].DateApp, CountTask = count_task, Image = list[i].ImagePath }; user_list.Add(userView); } return(user_list); }
private void btnChangeEmailSettings_Click(object sender, EventArgs e) { string str; ConfigData data = LoadConfig(out str); SiteSettings masterSettings = SettingsManager.GetMasterSettings(false); if (string.IsNullOrEmpty(str) || (data == null)) { masterSettings.EmailSender = string.Empty; masterSettings.EmailSettings = string.Empty; } else { if (!data.IsValid) { string msg = ""; foreach (string str3 in data.ErrorMsgs) { msg = msg + Formatter.FormatErrorMessage(str3); } ShowMsg(msg, false); return; } masterSettings.EmailSender = str; masterSettings.EmailSettings = Cryptographer.Encrypt(data.SettingsXml); } SettingsManager.Save(masterSettings); Page.Response.Redirect(Globals.GetAdminAbsolutePath("tools/SendMessageTemplets.aspx")); }
protected void btnOK_Click(object sender, EventArgs e) { if ((txtTopkey.Text.Trim().Length != 0) && (txtTopkey.Text.Trim().Length != 8)) { ShowMsg("淘宝Appkey不能为空,为8位数字ID", false); } else if ((txtTopSecret.Text.Trim().Length != 0) && (txtTopSecret.Text.Trim().Length != 0x20)) { ShowMsg("淘宝AppSecret不能为空,为32位字符", false); } else { SiteSettings masterSettings = SettingsManager.GetSiteSettings(HiContext.Current.User.UserId);// SettingsManager.GetMasterSettings(false); if (!string.IsNullOrEmpty(txtTopkey.Text.Trim())) { masterSettings.Topkey = Cryptographer.Encrypt(txtTopkey.Text.Trim()); } if (!string.IsNullOrEmpty(txtTopSecret.Text.Trim())) { masterSettings.TopSecret = Cryptographer.Encrypt(txtTopSecret.Text.Trim()); } SettingsManager.Save(masterSettings); ShowMsg("成功保存了淘宝同步设置", true); } }
bool ReEncryptKey(string oldPassword, string newPassword) { HttpContext context = HiContext.Current.Context; XmlDocument document = new XmlDocument(); string filename = context.Request.MapPath(Globals.ApplicationPath + "/config/key.config"); string str2 = context.Request.MapPath(Globals.ApplicationPath + "/config/key.config.bak"); try { document.Load(filename); } catch { document.Load(str2); } if (int.Parse(document.SelectSingleNode("Settings/Token").InnerText) == this.UserId) { XmlNode node = document.SelectSingleNode("Settings/Key"); byte[] plaintext = Cryptographer.DecryptWithPassword(Convert.FromBase64String(node.InnerText), oldPassword); node.InnerText = Convert.ToBase64String(Cryptographer.EncryptWithPassword(plaintext, newPassword)); document.Save(filename); document.Save(str2); } return(true); }
public void Send(string data) { try { if (!string.IsNullOrEmpty(data)) { Socket socket = new Socket(_ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(_remoteEP); var des = GetDes(socket); var encryptedData = Cryptographer.SymmetricEncrypt(data, des); socket.Send(encryptedData); socket.Shutdown(SocketShutdown.Both); socket.Close(); socket.Dispose(); } } catch (ArgumentNullException error) { Console.WriteLine("ОШИБКА аргументов : {0}", error.ToString()); } catch (SocketException error) { Console.WriteLine("ОШИБКА сокетов: : {0}", error.ToString()); } catch (Exception error) { Console.WriteLine("ОШИБКА: {0}", error.ToString()); } }
public void GetPasswordAndGetCodPasswordTest() { string strActual = Cryptographer.GetPassword(strIn); string strFinish = Cryptographer.GetCodPassword(strActual); StringAssert.Contains(strFinish, strIn, "Проверка методов закончена"); }
/// <summary> /// 从加密文件中读取连接字符串 /// </summary> public static void LoadConnectionStrings() { // <connectionStrings configSource="connections.config"></connectionStrings> AMS.Profile.IProfile profile = new AMS.Profile.Xml(IOHelper.GetDataDirectory() + "\\Dbs.dat"); string skey = profile.GetValue("ConnectionStringSetting", "Key", string.Empty); if (!string.IsNullOrEmpty(skey)) { string cryptedConnectionStrings = profile.GetValue("ConnectionStringSetting", "ConnectionString", string.Empty); if (!string.IsNullOrEmpty(cryptedConnectionStrings)) { string connectionStrings = Cryptographer.DecryptSymmetric(cryptedConnectionStrings, skey); if (!string.IsNullOrEmpty(connectionStrings)) { string tempConfigFileName = IOHelper.GetDataDirectory() + "\\temp.config"; System.IO.File.WriteAllText(tempConfigFileName, connectionStrings, Encoding.UTF8); ExeConfigurationFileMap configMap = new ExeConfigurationFileMap { ExeConfigFilename = tempConfigFileName }; Configuration externalConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); foreach (ConnectionStringSettings i in externalConfig.ConnectionStrings.ConnectionStrings) { SystemHelper.ChangeConnectionString(i.Name, i.ConnectionString, i.ProviderName); } System.IO.File.Delete(tempConfigFileName); } } } }
internal string EncodePassword(string pass) { byte[] bIn = Encoding.UTF8.GetBytes(pass); byte[] bRet = Cryptographer.EncryptSymmetric("Custom Symmetric Cryptography Provider", bIn); return(Convert.ToBase64String(bRet)); //return Cryptographer.EncryptSymmetric("RijndaelManaged", pass); }
public void KeyValidation(string membercode, string password, DateTime loginDate, string key) { if (!Cryptographer.GenerateSignature(membercode + password + loginDate.ToString("yyyy-MM-ddTHH:mm")).Equals(key)) { throw new InvalidKeyException(membercode, password, loginDate, key); } }
static void ConvertOldPasswordFormat() { int processed = 0; var toBeUpdated = new List <IUser>(); foreach (var user in DataFacade.GetData <IUser>()) { if (string.IsNullOrEmpty(user.EncryptedPassword) || !string.IsNullOrEmpty(user.PasswordHashSalt)) { continue; } string password = Cryptographer.Decrypt(user.EncryptedPassword); var salt = UserFormLoginManager.GenerateHashSalt(); user.PasswordHashSalt = Convert.ToBase64String(salt); user.EncryptedPassword = UserFormLoginManager.GeneratePasswordHash(password, salt); toBeUpdated.Add(user); processed++; } if (toBeUpdated.Any()) { DataFacade.Update(toBeUpdated); } if (processed > 0) { Log.LogInformation(LogTitle, "User passwords converted to a new format: " + processed); } }
public bool CoincidePassword(Usuario usuario, string password) { var cryptographer = new Cryptographer(); var passwordHash = cryptographer.GetHash(password); return(passwordHash.Equals(usuario.Password)); }
public User ValidateUser(string username, string password) { User user = null; try { if (string.IsNullOrWhiteSpace(password)) { return(null); } user = GetUserByEmail(username); if (user == null) { return(null); } string hash = new Cryptographer().HashPassword(password, user.Salt); if (user.Password == hash) { return(user); } } catch (Exception e) { return(null); } return(null); }
protected void Page_Load(object sender, EventArgs e) { if (!int.TryParse(Page.Request.QueryString["modeId"], out modeId)) { base.GotoResourceNotFound(); } else { btnUpdate.Click += new EventHandler(btnUpdate_Click); if (!Page.IsPostBack) { PaymentModeInfo paymentMode = SubsiteSalesHelper.GetPaymentMode(modeId); if (paymentMode == null) { base.GotoResourceNotFound(); } else { Globals.EntityCoding(paymentMode, false); txtSelectedName.Value = paymentMode.Gateway.ToLower(); ConfigData data = new ConfigData(Cryptographer.Decrypt(paymentMode.Settings)); txtConfigData.Value = data.SettingsXml; txtName.Text = paymentMode.Name; fcContent.Text = paymentMode.Description; txtCharge.Text = paymentMode.Charge.ToString("F", CultureInfo.InvariantCulture); chkIsPercent.Checked = paymentMode.IsPercent; radiIsUseInpour.SelectedValue = paymentMode.IsUseInpour; } } } }
public override bool IsValid(object value) { if (value != null) { SocialNetworkDbContext dbContext = new SocialNetworkDbContext(); LoginAndPasswordDto loginAndPasswordDto = (LoginAndPasswordDto)value; string login = loginAndPasswordDto.Login; string password = Cryptographer.Hash(loginAndPasswordDto.Password); if (dbContext.Users.Select(u => u.Login).Contains(login)) { string actualPassword = dbContext.Users.Where(u => u.Login == login).First().Password; if (actualPassword == password) { return(true); } else { ErrorMessage = "Wrong password"; return(false); } } else { ErrorMessage = "Wrong login"; return(false); } } return(false); }
/// <summary> /// Creates the HTTP Authorization header in hawk scheme. /// </summary> internal async Task CreateClientAuthorizationInternalAsync(IRequestMessage request, DateTime utcNow) { var credential = options.CredentialsCallback(); this.artifacts = new ArtifactsContainer() { Id = credential.Id, Timestamp = utcNow.AddSeconds(HawkClient.CompensatorySeconds).ToUnixTime(), Nonce = NonceGenerator.Generate() }; if (options.NormalizationCallback != null) { this.artifacts.ApplicationSpecificData = options.NormalizationCallback(request); } var normalizedRequest = new NormalizedRequest(request, this.artifacts, options.HostNameSource); this.crypto = new Cryptographer(normalizedRequest, this.artifacts, credential); // Sign the request bool includePayloadHash = options.RequestPayloadHashabilityCallback != null && options.RequestPayloadHashabilityCallback(request); string payload = includePayloadHash ? await request.ReadBodyAsStringAsync() : null; crypto.Sign(payload, request.ContentType); request.Authorization = new AuthenticationHeaderValue(HawkConstants.Scheme, this.artifacts.ToAuthorizationHeaderParameter()); }
protected void Page_Load(object sender, EventArgs e) { openIdType = base.Request.QueryString["t"]; if (string.IsNullOrEmpty(openIdType) || (openIdType.Trim().Length == 0)) { base.GotoResourceNotFound(); } PluginItem pluginItem = OpenIdPlugins.Instance().GetPluginItem(openIdType); if (pluginItem == null) { base.GotoResourceNotFound(); } if (!Page.IsPostBack) { txtName.Text = pluginItem.DisplayName; lblDisplayName.Text = pluginItem.DisplayName; txtSelectedName.Value = openIdType; OpenIdSettingsInfo openIdSettings = OpenIdHelper.GetOpenIdSettings(openIdType); if (openIdSettings != null) { ConfigData data = new ConfigData(Cryptographer.Decrypt(openIdSettings.Settings)); txtConfigData.Value = data.SettingsXml; txtName.Text = openIdSettings.Name; fcContent.Text = openIdSettings.Description; } } }
/// <summary> /// Creates the HTTP Authorization header in hawk scheme. /// </summary> internal async Task CreateClientAuthorizationInternalAsync(HttpRequestMessage request, DateTime utcNow) { var credential = credentialFunc(); this.artifacts = new ArtifactsContainer() { Id = credential.Id, Timestamp = utcNow.AddSeconds(HawkClient.CompensatorySeconds).ToUnixTime(), Nonce = NonceGenerator.Generate() }; if (!String.IsNullOrWhiteSpace(this.ApplicationSpecificData)) { this.artifacts.ApplicationSpecificData = this.ApplicationSpecificData; } var normalizedRequest = new NormalizedRequest(request, this.artifacts); this.crypto = new Cryptographer(normalizedRequest, this.artifacts, credential); // Sign the request await crypto.SignAsync(request.Content); request.Headers.Authorization = new AuthenticationHeaderValue( HawkConstants.Scheme, this.artifacts.ToAuthorizationHeaderParameter()); }
private DESCryptoServiceProvider GetDes(Socket socket) { var rsa = Cryptographer.GetRSA(); var publicKey = rsa.ExportParameters(false); var privateKey = rsa.ExportParameters(true); var rsaBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new RsaPublicKeyParameters(publicKey))); socket.Send(rsaBytes); var buffer = new byte[1024]; int sizeDES = socket.Receive(buffer); var encryptedDES = new byte[sizeDES]; Array.Copy(buffer, 0, encryptedDES, 0, sizeDES); var encryptedDESstr = Encoding.UTF8.GetString(encryptedDES); var encrypdedDesParams = JsonConvert.DeserializeObject <DesParameters>(encryptedDESstr); var desIV = Cryptographer.RSADecrypt(encrypdedDesParams.IV, privateKey); var desKey = Cryptographer.RSADecrypt(encrypdedDesParams.Key, privateKey); DESCryptoServiceProvider des = Cryptographer.GetDES(desIV, desKey); return(des); }
internal string GetSecurityHash() { return(Cryptographer.CreateHashCode(this.GetElectronicSeal(), _request.UID) .Substring(0, 8) .ToUpperInvariant()); }
private static void Main(string[] args) { Cryptographer c = new Cryptographer("aaaaaaaa"); byte[] vs = Encoding.Unicode.GetBytes("'sÙ%šM6›>‚êUÝãÄ›ýÿ%šM6›>‚êýÿãÄ›"); printeByte(vs); var r = c.Encrypt(vs); Console.WriteLine(); printeByte(r); Console.WriteLine(); printeByte(c.Decrypt(r)); //var handle = GetConsoleWindow(); //FixExeptions(); //load(); //loadConfig(); //if (!startconsol) // ShowWindow(handle, SW_HIDE); //if (exe != "" && name != "") //{ // start(); //} //while (startconsol) // Consol(); Console.WriteLine("Press any Key to exit..."); //if (!startconsol) Console.ReadKey(); }
public void DA_Cifrado_UpdUser(Usuario u) { try { using (SqlConnection conexion = new SqlConnection(conexionString)) { SqlCommand cmd = new SqlCommand("GAP_USUARIO_UPDATE", conexion); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id_Usuario", u.Id_Usuario); cmd.Parameters.AddWithValue("@Id_Regional", u.Id_Regional); cmd.Parameters.AddWithValue("@Id_Rol", u.Id_Rol); cmd.Parameters.AddWithValue("@Id_Categoria", u.Id_Categoria); cmd.Parameters.AddWithValue("@Cargo", u.Cargo); string Encrip = string.Empty; Encrip = Cryptographer.CreateHash(hashProvider, u.Clave); cmd.Parameters.AddWithValue("@Clave", Encrip); cmd.Parameters.AddWithValue("@Estado", u.Estado); conexion.Open(); cmd.ExecuteNonQuery(); conexion.Close(); } } catch (Exception err) { throw (new Exception(err.ToString() + "-" + err.Source.ToString() + "-" + err.Message.ToString())); } }
protected override string AuthenticateToken(UsernameToken token) { LoginUserStatus invalidCredentials = LoginUserStatus.InvalidCredentials; try { SiteManager user = Users.GetUser(0, token.Identity.Name, false, false) as SiteManager; if ((user != null) && user.IsAdministrator) { HiContext current = HiContext.Current; user.Password = Cryptographer.Decrypt(token.Password); invalidCredentials = Users.ValidateUser(user); } else { invalidCredentials = LoginUserStatus.InvalidCredentials; } } catch { invalidCredentials = LoginUserStatus.InvalidCredentials; } if (invalidCredentials == LoginUserStatus.Success) { return(token.Password); } return(Cryptographer.CreateHash(token.Password)); }
public void CreateAndCompareHashBytes() { byte[] hash = Cryptographer.CreateHash(hashInstance, plainTextBytes); bool result = Cryptographer.CompareHash(hashInstance, plainTextBytes, hash); Assert.IsTrue(result); }
private void btnSaveSMSSettings_Click(object sender, EventArgs e) { string str; ConfigData data = LoadConfig(out str); SiteSettings siteSettings = SettingsManager.GetSiteSettings(HiContext.Current.User.UserId); if (string.IsNullOrEmpty(str) || (data == null)) { siteSettings.SMSSender = string.Empty; siteSettings.SMSSettings = string.Empty; } else { if (!data.IsValid) { string msg = ""; foreach (string str3 in data.ErrorMsgs) { msg = msg + Formatter.FormatErrorMessage(str3); } ShowMsg(msg, false); return; } siteSettings.SMSSender = str; siteSettings.SMSSettings = Cryptographer.Encrypt(data.SettingsXml); } SettingsManager.Save(siteSettings); Page.Response.Redirect(Globals.ApplicationPath + "/Shopadmin/tools/MySendMessageTemplets.aspx"); }
// ... private string Encrypt(string item) { Console.WriteLine($">>>>>Encrypting '{ item }'."); Cryptographer cryptographer = new Cryptographer(); string itemEncrypted = cryptographer.Encrypt(item); Console.WriteLine($"<<<<<Finished encrypting '{ itemEncrypted }'."); return itemEncrypted; }
/// <summary> /// Returns true if the server response HMAC cannot be validated, indicating possible tampering. /// </summary> private async Task<bool> IsResponseTamperedAsync(ArtifactsContainer artifacts, Cryptographer crypto, HttpResponseMessage response) { if (response.Headers.Contains(HawkConstants.ServerAuthorizationHeaderName)) { string header = response.Headers.GetValues(HawkConstants.ServerAuthorizationHeaderName).FirstOrDefault(); if (!String.IsNullOrWhiteSpace(header) && header.Substring(0, HawkConstants.Scheme.Length).ToLower() == HawkConstants.Scheme) { ArtifactsContainer serverAuthorizationArtifacts; if (ArtifactsContainer.TryParse(header.Substring(HawkConstants.Scheme.Length + " ".Length), out serverAuthorizationArtifacts)) { // To validate response, ext, hash, and mac in the request artifacts must be // replaced with the ones from the server. artifacts.ApplicationSpecificData = serverAuthorizationArtifacts.ApplicationSpecificData; artifacts.PayloadHash = serverAuthorizationArtifacts.PayloadHash; artifacts.Mac = serverAuthorizationArtifacts.Mac; bool isValid = await crypto.IsSignatureValidAsync(response.Content); if(isValid) this.WebApiSpecificData = serverAuthorizationArtifacts.ApplicationSpecificData; return !isValid; } } } return true; // Missing header means possible tampered response (to err on the side of caution). }
/// <summary> /// Creates the HTTP Authorization header in hawk scheme. /// </summary> internal async Task CreateClientAuthorizationInternalAsync(HttpRequestMessage request, DateTime utcNow) { var credential = credentialFunc(); this.artifacts = new ArtifactsContainer() { Id = credential.Id, Timestamp = utcNow.AddSeconds(HawkClient.CompensatorySeconds).ToUnixTime(), Nonce = NonceGenerator.Generate() }; if (!String.IsNullOrWhiteSpace(this.ApplicationSpecificData)) this.artifacts.ApplicationSpecificData = this.ApplicationSpecificData; var normalizedRequest = new NormalizedRequest(request, this.artifacts); this.crypto = new Cryptographer(normalizedRequest, this.artifacts, credential); // Sign the request await crypto.SignAsync(request.Content); request.Headers.Authorization = new AuthenticationHeaderValue( HawkConstants.Scheme, this.artifacts.ToAuthorizationHeaderParameter()); }