public void FunkyPasswords() { Crypto c = new Crypto(); { const string source = "antonida"; string s = c.Encrypt(source); Assert.AreNotEqual(source, s); Assert.AreEqual(source, c.Decrypt(s)); } { const string source = "привет мир"; string s = c.Encrypt(source); Assert.AreNotEqual(source, s); Assert.AreEqual(source, c.Decrypt(s)); } { const string source = @">rL`Fpbgr>_1j^?];cK5U>/!fm;&736puCLZeql=b-,-}rOdeR"; string s = c.Encrypt(source); Assert.AreNotEqual(source, s); Assert.AreEqual(source, c.Decrypt(s)); } { for (int i = 0; i < 1000; i++) { string source = RandomString(Math.Min(i + 1, 50)); string s = c.Encrypt(source); Assert.AreNotEqual(source, s); Assert.AreEqual(source, c.Decrypt(s)); } } }
public JsonResult Login(string system, string username, string password) { if (!this.model.IsLoginRequired(system)) { return(this.Json(new { isSuccess = true })); } try { if (this.model.Login(system, username, password)) { var cookie = this.HttpContext.Request.Cookies.Get("sqleditor"); var userKey = cookie != null ? cookie.Value : string.Empty; var connString = this.model.GetUserConnectionString(system, username, password).ConnectionString; var cryptoConnString = Crypto.Encrypt(connString, KeyProvider.GetUserSpecificSecretKey(userKey)); this.Session.Add(system, cryptoConnString); return(this.Json(new { isSuccess = true })); } } catch (Exception ex) { return(this.Json(new { isSuccess = false, message = ex.Message })); } return(this.Json(new { isSuccess = false })); }
public void Throw_An_Exception_For_Incorrect_Salt() { const string plaintext = "this is another sensitive string"; string ciphertext = Crypto.Encrypt(plaintext, "apple"); string shouldntWork = Crypto.Decrypt(ciphertext, "orange"); }
//[ValidateAntiForgeryToken] public ActionResult Index(LoginViewModel lvm) { if (ModelState.IsValid) { string gelenkullaniciadi = lvm.KullaniciAdi; string gelensifre = lvm.Sifre; if (lvm.KullaniciAdi == System.Configuration.ConfigurationManager.AppSettings["KullaniciAdi"].ToString() && lvm.Sifre == System.Configuration.ConfigurationManager.AppSettings["Sifre"].ToString()) { //Giriş Yapılacak HttpCookie myCookie = new HttpCookie(System.Configuration.ConfigurationManager.AppSettings["key"].ToString()); myCookie["User"] = Crypto.Encrypt(lvm.KullaniciAdi.ToString(), "a61", true); myCookie["pass"] = Crypto.Encrypt(lvm.Sifre.ToString(), "a61", true); myCookie.Expires = DateTime.Now.AddMinutes(5); Response.Cookies.Add(myCookie); Response.Redirect("~/AdminUI/Home"); } else { ViewBag.ErrorText = "Hatalı İşlem Şifre Yanlış"; } } ViewBag.Path = "/areas/admin/content"; return(View()); }
public bool login(string userId, string password) { Database db = SecuritySettings.GetDb(); DbConnection conn = db.CreateConnection(); try { // if (conn.State == ConnectionState.Closed) conn.Open(); DbCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = @"select [user_id],[password],[display_name],[group_id] from xsys_user_account where [user_id]=@UserId" + @" or bind_email=@UserId" + @" or bind_mobile=@UserId"; SqlParameter pr = new SqlParameter(); pr.ParameterName = "@UserId"; pr.Value = userId; cmd.Parameters.Add(pr); DbDataReader reader = cmd.ExecuteReader(); try { if (!reader.HasRows) { throw new XUserException("用户或口令错误"); } while (reader.Read()) { object p = reader["password"]; object u = reader["user_id"]; object n = reader["display_name"]; object g = reader["group_id"]; if (p.ToString().Equals(Crypto.Encrypt(password))) { userContext.Id = u.ToString(); userContext.Name = n.ToString(); if (String.IsNullOrEmpty(userContext.Name)) { userContext.Name = userContext.Id; } userContext.GroupId = g.ToString(); isLogin = true; return(true); } } } finally { reader.Close(); } throw new XUserException("用户或口令错误"); } finally { conn.Close(); } throw new XUserException("用户或口令错误"); }
public override void Execute(string[] args) { if (args.Length < 2) { throw new ArgumentNullException("Requires voucher redemption OTC and Password"); } if (!Guid.TryParse(args[0], out Guid redemptionId)) { throw new ArgumentException("Requires voucher redemption OTC as GUID"); } var rnd = new Random(); var publicRegistryKey = KeyManager.LoadKeyFromPem <AsymmetricCipherKeyPair>("registry.pem").Public; byte[] sessionKey = new byte[256 / 8]; rnd.NextBytes(sessionKey); var request = CreateJsonRequest("voucher/redeem", new VoucherRedeemPayload { Payload = Crypto.Encrypt(new VoucherRedeemPayload.Content { Otc = redemptionId, Password = args[1], SessionKey = sessionKey.ToBase64() }, publicRegistryKey) }); var response = PerformRequest <VoucherRedeemResponse>(request); var responseContent = Crypto.Decrypt <VoucherRedeemResponse.Content>(response.Payload, sessionKey); Console.WriteLine("Vouchers redeemed"); foreach (var v in responseContent.Vouchers) { Console.WriteLine("V #{0} aim {1}", v.Id, v.Aim); Console.WriteLine(" @ {2} in {0},{1}", v.Latitude, v.Longitude, v.Timestamp); } }
public unsafe void Send(byte[] packet) { SendSync.WaitOne(); if (Crypto != null) { var iv = Crypto.SetRandomIV(); var size = BitConverter.ToInt32(packet, 0); var header = packet.AsSpan().Slice(0, sizeof(MsgHeader)); var data = packet.AsSpan().Slice(sizeof(MsgHeader), size - sizeof(MsgHeader)); var encryptedData = Crypto.Encrypt(data.ToArray()); BitConverter.GetBytes(encryptedData.Length + sizeof(MsgHeader)).CopyTo(header); iv.CopyTo(header.Slice(sizeof(MsgHeader) - 16, 16)); var newPacket = new byte[encryptedData.Length + sizeof(MsgHeader)]; header.CopyTo(newPacket); encryptedData.CopyTo(newPacket.AsSpan().Slice(sizeof(MsgHeader))); SendQueue.Add(SendArgs, newPacket, newPacket.Length); } else { SendQueue.Add(SendArgs, packet, BitConverter.ToInt32(packet, 0)); } }
public void TestEncrypt() { Assert.AreEqual("1233skjv", Crypto.Encrypt("1233skjv", "мама")); //сообщение не должно измениться, если оно состоит не из букв русского алфавита Assert.AreEqual(null, Crypto.Encrypt("мама", "скорпион")); //должно вернуться null, если длина ключа больше длины сообщения Assert.AreEqual(null, Crypto.Encrypt("мама", "sк0r")); //должно вернуться null, если в ключе есть символ(-ы) не из русского алфавита Assert.AreEqual("бщцфаирщри", Crypto.Encrypt("поздравляю", "скорпион")); }
public Asset Create(Asset t) { using (var ctx = new CADBContext()) { var cryptoSave = new Crypto(); t.Password = cryptoSave.Encrypt(t.Password); t.CustomerId = t.Customer.Id; t.TypeId = t.Type.Id; if (t.Manufacturer != null) { t.ManufacturerId = t.Manufacturer.Id; ctx.Entry(t.Manufacturer).State = EntityState.Unchanged; } ctx.Entry(t.Customer).State = EntityState.Unchanged; ctx.Entry(t.Type).State = EntityState.Unchanged; Asset a = ctx.Assets.Add(t); ctx.SaveChanges(); return(a); } }
/// <summary> /// Run the application. /// </summary> public override BoolMessageItem Execute() { // 1. Encrypt using default provider. ( Symmetric TripleDes ) string plainText = "www.knowledgedrink.com"; string encrypted = Crypto.Encrypt(plainText); string decrypted = Crypto.Decrypt(encrypted); Console.WriteLine("===================================================="); Console.WriteLine("CRYPTOGRAPHY "); Console.WriteLine("Encrypted : " + plainText + " to " + encrypted); Console.WriteLine("Decrypted : " + encrypted + " to " + decrypted); Console.WriteLine(Environment.NewLine); // 2. Use non-static encryption provider. ICrypto crypto = new CryptoHash("commonlib.net", new MD5CryptoServiceProvider()); string hashed = crypto.Encrypt("my baby - 2002 honda accord ex coupe"); Console.WriteLine(hashed); // 3. Change the crypto provider on the static helper. ICrypto crypto2 = new CryptoSym("new key", new TripleDESCryptoServiceProvider()); Crypto.Init(crypto2); string encryptedWithNewKey = Crypto.Encrypt("www.knowledgedrink.com"); Console.WriteLine(string.Format("Encrypted text : using old key - {0}, using new key - {1}", encrypted, encryptedWithNewKey)); return(BoolMessageItem.True); }
public bool Add(string name, string connectionstring) { if (String.IsNullOrEmpty(_root)) { return(false); } DirectoryInfo di = new DirectoryInfo(_root); if (!di.Exists) { di.Create(); } if (!String.IsNullOrEmpty(_encKey)) { byte[] bytes = Crypto.Encrypt(_encoding.GetBytes(connectionstring), _encKey); connectionstring = Convert.ToBase64String(bytes); } StreamWriter sw = new StreamWriter(di.FullName + @"/" + ReplaceSlash(name) + ".con", false, _encoding); sw.Write(connectionstring); sw.Close(); return(true); }
public UsuarioLogin Acessar(string login, string senha, string ip) { var senhaCrypt = Crypto.Encrypt(senha, Crypto.Key256, 256); var usuario = _db.Database.SqlQuery <UsuarioLogin>("SP_AdministradorLogin @dsLogin , @dsSenha , @dsIP", new SqlParameter("dsLogin", login) , new SqlParameter("dsSenha", senhaCrypt) , new SqlParameter("dsIP", ip)).FirstOrDefault(); if (usuario != null && usuario.idAdministrador > 0) { FormsAuthentication.SetAuthCookie("loginUsuarioAdmin", false); Geral.criaCookie(new UsuarioLogin { idAdministrador = usuario.idAdministrador , dsEmail = usuario.dsEmail , dsLogin = usuario.dsLogin , dsNome = usuario.dsNome, idTipo = usuario.idTipo, dsTipo = usuario.dsTipo, dsSenha = usuario.dsSenha }); Geral.CriaCookiePermissao(usuario.dsTipo); } return(usuario); }
public static ConnectionStrings Protect(this ConnectionStrings file, string key) { try { file.is_protected = "true"; file.MaderoAuthConnection = Crypto.Encrypt(file.MaderoAuthConnection.IsNull() ? string.Empty : file.MaderoAuthConnection, key); file.MaderoConnection = Crypto.Encrypt(file.MaderoConnection.IsNull() ? string.Empty : file.MaderoConnection, key); file.MaderoExpressConnection = Crypto.Encrypt(file.MaderoExpressConnection.IsNull() ? string.Empty : file.MaderoExpressConnection, key); file.MelsConnection = Crypto.Encrypt(file.MelsConnection.IsNull() ? string.Empty : file.MelsConnection, key); file.MongoDBConnection = Crypto.Encrypt(file.MongoDBConnection.IsNull() ? string.Empty : file.MongoDBConnection, key); file.NotificacoesConnection = Crypto.Encrypt(file.NotificacoesConnection.IsNull() ? string.Empty : file.NotificacoesConnection, key); file.PessoasConnection = Crypto.Encrypt(file.PessoasConnection.IsNull() ? string.Empty : file.PessoasConnection, key); file.RetiradaConnection = Crypto.Encrypt(file.RetiradaConnection.IsNull() ? string.Empty : file.RetiradaConnection, key); file.TeknisaAuthConnection = Crypto.Encrypt(file.TeknisaAuthConnection.IsNull() ? string.Empty : file.TeknisaAuthConnection, key); var json = JsonConvert.SerializeObject(file); System.IO.File.WriteAllText(@"connections_strings.json", json); return(file); } catch (Exception ex) { throw new Exception($"{ex.Message}-{ex.StackTrace}"); } }
public static User QueryAuth(AuthenticateModel model) { using (var connection = DataBase.GetConnection()) { //string password = hasher.HashPassword(model.Password); string password = Crypto.Encrypt(model.Password); connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = REQ_POST_AUTH; command.Parameters.AddWithValue($"@{FIELD_PSEUDO}", model.Username); command.Parameters.AddWithValue($"@{FIELD_HASHPWD}", password); SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { return(new User(reader)); } else { return(null); } } }
public bool Update(Asset t) { using (var ctx = new CADBContext()) { var cryptoSave = new Crypto(); t.Password = cryptoSave.Encrypt(t.Password); t.CustomerId = t.Customer.Id; t.TypeId = t.Type.Id; ctx.Assets.Attach(t); ctx.Entry(t).State = EntityState.Modified; try { ctx.SaveChanges(t.Id); } catch (DbUpdateConcurrencyException) { if (!AssetExists(t.Id, ctx)) { return(false); } else { throw; } } return(true); } }
/// <summary> /// Encrypt all properties that marked with the [Encrypt] attribute. /// This method encrypt only the properties of the calling model object /// </summary> /// <typeparam name="T">Pass the type parameter of the Model</typeparam> /// <remarks>TODO:The type Parameter does not need to pass. Should be able to remove it</remarks> public virtual void EncryptRecords <T>() where T : IBaseObject { PropertyInfo[] allEntityProperties = this.GetType().GetProperties(); foreach (PropertyInfo prop in allEntityProperties) { object[] attrs = prop.GetCustomAttributes(true); foreach (object attr in attrs) { EncryptedAttribute authAttr = attr as EncryptedAttribute; if (authAttr != null) { object propName = prop.GetValue(this, null); bool doEncrypt = authAttr.DoEncrypt; if (doEncrypt) { if (prop.PropertyType == typeof(string)) { prop.SetValue(this, Crypto.Encrypt(propName.ToString()), null); } } } } } }
public void TestNewCryptoObjectWithSaltError() { var c1 = new Crypto(); var target = "Bart is the biatch."; var crypted = c1.Encrypt(target); Assert.AreNotEqual <string>(target, crypted, "Should be different strings"); var salt = Crypto.StringToBytes(c1.SystemSalt); salt[0] = (byte)~salt[0]; var key = Crypto.StringToBytes(c1.Key); var iv = Crypto.StringToBytes(c1.IV); var c2 = new Crypto(key, iv, salt); var actual = c2.Decrypt(crypted); Assert.IsNull(actual, "Should be NULL with a bad Salt."); salt[0] = (byte)~salt[0]; var c3 = new Crypto(key, iv, salt); actual = c3.Decrypt(crypted); Assert.AreEqual <string>(target, actual, "Should be equal again"); }
public static void Write(string path, string secret) { string jsonString = JsonConvert.SerializeObject(dataDic); string encryptedText = Crypto.Encrypt(jsonString, secret); File.WriteAllText(path, encryptedText); }
public async Task <(Usuario usuario, string messageReturning)> UpdateUser(Usuario usuario) { var user = (await CustomFind(x => x.IdUsuario == usuario.IdUsuario)).First(); if (user == null) { throw new Exception("Usuario não encontrado"); } if (!string.IsNullOrEmpty(usuario.Senha)) { user.Senha = Crypto.Encrypt(usuario.Senha, Crypto.Key256, 256); } user.Nome = usuario.Nome; user.Sobrenome = usuario.Sobrenome; user.Email = usuario.Email; user.Login = usuario.Login; user.DataAtualizacao = usuario.DataAtualizacao; user.DataCadastro = usuario.DataCadastro; user.Ativo = usuario.Ativo; return(usuario, "Usuario atualizado com sucesso!"); }
private void btnLogin_Click(object sender, EventArgs e) { lbErrorPasswd.Visible = false; if (!validator.Validate()) { return; } string login = tfUser.EditValue.ToString(); string passwd = tfPassword.EditValue.ToString(); user s = user.SingleOrDefault("WHERE login=@0 AND password=@1", tfUser.EditValue, Crypto.Encrypt(tfPassword.Text)); if (s != null) { s.last_acess = user.Now(); s.Save(); Singleton.setCurrentUser(s); this.DialogResult = DialogResult.OK; this.Close(); } else { lbErrorPasswd.Visible = true; tfPassword.EditValue = ""; tfUser.SelectAll(); tfUser.Focus(); return; } }
private static void initUsers(FileDriveContext context) { // If there are no users, init users data if (context.Users.Any()) { return; } var users = new User[] { new User { Name = "Admin", UserType = ENUMUserType.Admin, Password = Crypto.Encrypt("password", "Admin") }, new User { Name = "ShStav", UserType = ENUMUserType.Normal, Password = Crypto.Encrypt("password", "ShStav") }, new User { Name = "ZeKoren", UserType = ENUMUserType.Normal, Password = Crypto.Encrypt("password", "ZeKoren") }, new User { Name = "DuDonald", UserType = ENUMUserType.Normal, Password = Crypto.Encrypt("password", "DuDonald") } }; foreach (User user in users) { context.Users.Add(user); } context.SaveChanges(); }
public void WriteXml(XmlWriter writer) { writer.WriteStartElement("dictionary"); writer.WriteAttributeString("encrypt", encrypt.ToString()); foreach (string key in Keys) { object value = this[key]; writer.WriteStartElement("item"); writer.WriteElementString("key", key); using (MemoryStream ms = new MemoryStream()) using (StreamReader sr = new StreamReader(ms)) { NetDataContractSerializer ser = new NetDataContractSerializer(); ser.Serialize(ms, value); ms.Seek(0, SeekOrigin.Begin); writer.WriteElementString("value", encrypt ? Crypto.Encrypt(sr.ReadToEnd(), EncryptionKey) : sr.ReadToEnd()); } writer.WriteEndElement(); } writer.WriteEndElement(); }
public void TestsUserAccounts_User_Request_Password_Reset() { var USRM1 = db.Users.Where(u => u.Email == "*****@*****.**").FirstOrDefault(); var model = new UserResetPasswordModel(); // Fail wrong security key model.Email = USRM1.Email; model.SecurityKey = Crypto.Encrypt("rubbish"); model.NewPassword = "******";; model.ConfirmPassword = "******"; var response = service.ResetPassword(model); Assert.IsFalse(response.IsOK); //pass model.GenerateSecurityKey(); model.Email = ""; response = service.ResetPassword(model); Assert.IsTrue(response.IsOK); Assert.AreEqual(model.Email, USRM1.Email); db = new Repository(this.TContext); // save took place var user = db.Users.Where(u => u.Email == model.Email).FirstOrDefault(); Assert.IsNotNull(user); Assert.IsTrue(user.Password == Crypto.Hash(model.NewPassword, user.Salt)); }
public object Post([FromBody] object ciphertext, [FromServices] AccessManager accessManager) { dynamic json = JsonConvert.DeserializeObject(ciphertext.ToString()); string msg = json.ciphertext; byte[] crypt = Convert.FromBase64String(msg); byte[] keybytes = Encoding.UTF8.GetBytes("8080808080808080"); byte[] iv = Encoding.UTF8.GetBytes("8080808080808080"); // Decrypt var decripted = Crypto.Decrypt(crypt, keybytes, iv); //Enviar para o login User user = JsonConvert.DeserializeObject <User>(decripted); object obj = Login(user, accessManager); string output = JsonConvert.SerializeObject(obj); // Encrypt byte[] encrypted = Crypto.Encrypt(output, keybytes, iv); return(new { Message = encrypted }); }
/// <summary> /// Get the random encoded text. /// </summary> /// <returns></returns> public string GetRandomTextEncoded() { string text = GetRandomText(); string encoded = Crypto.Encrypt(text); return(encoded); }
public void TestsUserAccounts_Security_Encrypt_Decrypt() { var code = Crypto.Encrypt("rubbish"); var dec = Crypto.Decrypt(code); Assert.IsTrue("rubbish" == dec); }
public bool AddUser(string name, string password, string confirmPassword) { if (name == null || password == null) { throw new InvalidParametersException(); } if (password != confirmPassword) { throw new PasswordNotMatchingException(); } User user = this.unitOfWork.UserRepository.GetUser(name, Crypto.Encrypt(password, name)); bool isUniqueName = user == null; bool isValidPassword = validatePassword(password); if (!isUniqueName) { throw new UserNameExistsException(); } if (!isValidPassword) { throw new InvalidPasswordException(); } this.unitOfWork.UserRepository.AddUser(name, Crypto.Encrypt(password, name)); this.unitOfWork.Save(); return(true); }
public IActionResult Post([FromBody][Required] LoginVM login) { try { IActionResult response = Unauthorized(); if (!ModelState.IsValid) { return(BadRequest(new ResponseVM("User name or password must be enterd."))); } Crypto crypto = new Crypto(CryptoTypes.encTypeTripleDES); login.Password = crypto.Encrypt(login.Password); var user = _token.AuthenticateUser(login); if (user != null) { var tokenString = _token.GenerateJSONWebToken(user); response = Ok(new ResponseVM(hasError: false, data: new { token = tokenString })); } else { return(NotFound(new ResponseVM("User not found"))); } return(response); } catch (Exception ex) { _logger.LogError("Invalid user object sent from client.Exception:" + ex.Message ?? ""); return(StatusCode(500, new ResponseVM("Internal server error"))); } }
public ServiceResponse UserSignUp(RegistrationModel userModel) { ServiceResponse response = new ServiceResponse(); var emailExistModel = GetEntity <UserTable>(new List <SearchValueData> { new SearchValueData { Name = "Email", Value = userModel.Email, IsEqual = true } }); if (emailExistModel != null) { response = Common.GenerateResponse(Resource.UserAlreadyExists); return(response); } UserTable dbUserTable = new UserTable(); dbUserTable.FirstName = userModel.FirstName; dbUserTable.LastName = userModel.LastName; dbUserTable.Email = userModel.Email; dbUserTable.Password = Crypto.Encrypt(userModel.Password); SaveEntity <UserTable>(dbUserTable); response = Common.GenerateResponse(Resource.RegistrationProcessCompleted); return(response); }
private string GenerateHeader(string password) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; string plainheader = new string(Enumerable.Repeat(chars, 256).Select(s => s[random.Next(s.Length)]).ToArray()); return(Crypto.Encrypt(plainheader, EnhancePassword(password))); }
/// <summary> /// Handles the TextChanged event of the TextMessage control. /// Handles the CheckBoxBase64_CheckedChanged control /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void TextMessage_TextChanged(object sender, EventArgs e) { if (StegEncode == null) { return; } if (StegEncode.PixelLoaded) { string text = TextMessage.Text; if (CheckBoxBase64.Checked) { text = Converter.AsciiToBase64(text); } if (CheckBoxAes.Checked) { text = Crypto.Encrypt(text, "filler"); if (text == null) { return; } } int characters = (Constants.MessageLength * 8) + text.Length; LblCharacterCount.Text = String.Format("Characters: {0}/{1}", characters, StegEncode.MaxCharacters); } }
public void UseCustomKey() { const string S = "WqJCvfqa6JKiSXFm6t9MSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="; Crypto c = new Crypto("my secret key"); string s = c.Encrypt("hello world"); Assert.AreNotEqual("hello world", s); Assert.AreEqual("hello world", c.Decrypt(s)); Assert.AreEqual("hello world", c.Decrypt(S)); }
public void TestEncryptionAES() { var c = new Crypto(); string userKey = "4b236698-ebbb-4d3d-9513-961c5603d431"; string keySalt = "0000000001"; string text = "hello"; string cypher = c.Encrypt(text, userKey, keySalt); Console.WriteLine(cypher); string textdec = c.Decrypt(cypher, userKey, keySalt); Assert.AreEqual(text, textdec); }
public static string Encrypt(string string_to_encrypt) { //I noticed a lot of this unable to encrypt message in the logs, I figured it would be best to silence this if (String.IsNullOrEmpty(string_to_encrypt)) return ""; try { Crypto c = new Crypto(Crypto.CryptoTypes.encTypeTripleDES); return c.Encrypt(string_to_encrypt); } catch (Exception ex) { LogHelper.logError("CryptoUtils.cs", "Unable to encrypt " + string_to_encrypt + " " + ex.Message + " " + ex.StackTrace); return ""; } }
public void UseDefaultKey() { Crypto c = new Crypto(); string s = c.Encrypt("hello world"); Assert.AreNotEqual("hello world", s); Assert.AreEqual("hello world", c.Decrypt(s)); }
public void EmptyString() { Crypto c = new Crypto(); string s = c.Encrypt(""); Assert.AreEqual("", s); Assert.AreEqual("", c.Decrypt(s)); }
public static string FastMicroEncrypt(string src) { Crypto c = new Crypto(CryptoTypes.encTypeTripleDES); c.mCompactCompatible = true; return c.Encrypt(src); }
public static string FastEncrypt(string src) { Crypto c = new Crypto(CryptoTypes.encTypeTripleDES); return c.Encrypt(src); }
public Password(string text) { Crypto = new Crypto (Crypto.CryptoTypes.encTypeTripleDES); SecurePwd = Crypto.Encrypt (text); }
public virtual string Encrypt(string Source, bool includeSession) { Crypto CheckCrypto = new Crypto(Crypto.Providers.DES); return CheckCrypto.Encrypt(Source, includeSession); }
public string AESEncryption(string plain, string key, bool fips) //Encryption for Settings.DAT { Crypto superSecret = new Crypto(new AesEngine(), _encoding); superSecret.SetPadding(_padding); return superSecret.Encrypt(plain, key); }
// The URLEncryptionKey is specified in the web.config. The rightmost three characters of the current // Session Id are concatenated with the URLEncryptionKey to provide added protection. You can change // this to anything you like by changing this function for the application. // This function is private and not overridable because each page cannot have its own key - it must // be common across the entire application. public virtual string Encrypt(string Source) { Crypto CheckCrypto = new Crypto(Crypto.Providers.DES); return(CheckCrypto.Encrypt(Source)); }
/// <summary> /// Return the encrypted value of the string passed in. /// </summary> /// <param name="str">The string to encrypt</param> /// <returns>The encrypted value of the string.</returns> public static string EncryptData(string str) { if (str == null) return string.Empty; Crypto CheckCrypto = new Crypto(); return CheckCrypto.Encrypt(str, false); }
public static void Main(string[] args) { string serverHost; int serverPort; int httpPort; int payloadSize; int uint16Size = 2; int uint32Size = 4; int packetSize; uint cmdId = 1; uint seq = 100; uint stopSymbol = 1550998638; byte[] msg; byte[] packet; Console.WriteLine("Enter server host name:"); serverHost = Console.ReadLine(); Console.WriteLine("Enter HTTP server port:"); httpPort = int.Parse(Console.ReadLine()); var request = (HttpWebRequest)WebRequest.Create("http://" + serverHost + ":" + httpPort + "/auth"); var postData = "thing1=hello"; postData += "&thing2=world"; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; var hstream = request.GetRequestStream(); hstream.Write(data, 0, data.Length); var response = (HttpWebResponse)request.GetResponse(); var authRes = new StreamReader(response.GetResponseStream()).ReadToEnd(); Console.WriteLine("Auth response:{0}", authRes); JSONNode auth = JSON.Parse(authRes); Console.WriteLine("Session ID is {0}", auth["sessionId"]); Console.WriteLine( "Cipher Key, Nonce, and MacKey:{0}, {1}, {2}", auth["cipherData"]["base64"]["cipherKey"], auth["cipherData"]["base64"]["cipherNonce"], auth["cipherData"]["base64"]["macKey"] ); Console.WriteLine("Enter TCP server port number:"); serverPort = int.Parse(Console.ReadLine()); TcpClient client = new TcpClient(serverHost, serverPort); NetworkStream stream = client.GetStream(); msg = Encoding.UTF8.GetBytes("{ \"message\":\"Hello\"}"); // prepare encryption Guid sid = new Guid(auth["sessionId"]); byte[] cipherKey = System.Convert.FromBase64String(auth["cipherData"]["base64"]["cipherKey"]); byte[] cipherNonce = System.Convert.FromBase64String(auth["cipherData"]["base64"]["cipherNonce"]); byte[] macKey = System.Convert.FromBase64String(auth["cipherData"]["base64"]["macKey"]); var crypto = new Crypto(sid, cipherKey, cipherNonce, macKey); // encrypt msg = crypto.Encrypt(msg); // create gracenode RPC command packet payloadSize = IPAddress.HostToNetworkOrder(msg.Length); byte[] payloadSizeBytes = BitConverter.GetBytes(payloadSize); packetSize = uint32Size + (uint16Size * 2) + msg.Length + uint32Size; packet = new byte[packetSize]; Console.WriteLine("payload size is {0}", msg.Length); Console.WriteLine("packet size is {0}", packetSize); // RPC protocol version 0 packet[0] = 0x0; // add payload size at the offset of 0: payload size if utin32 4 bytes Buffer.BlockCopy(payloadSizeBytes, 0, packet, 0, uint32Size); // add command ID at the offset of 4: command ID is uint16 2 bytes byte[] cmd = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)cmdId)); Buffer.BlockCopy(cmd, 0, packet, 4, uint16Size); // add seq at the offset of 6: seq is uint16 2 bytes byte[] seqBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)seq)); Buffer.BlockCopy(seqBytes, 0, packet, 6, uint16Size); // add payload at the offset of 8 Buffer.BlockCopy(msg, 0, packet, 8, msg.Length); // add magic stop symbol: magic stop symbol is uint 32 4 bytes int stop = IPAddress.HostToNetworkOrder(Convert.ToInt32(stopSymbol)); byte[] stopBytes = BitConverter.GetBytes(stop); Buffer.BlockCopy(stopBytes, 0, packet, msg.Length + 8, uint32Size); Console.WriteLine("Sending command packet: {0}", packet.Length); // send command packet to server stream.Write(packet, 0, packet.Length); // receive the response back from server // read in chunk of 2KB byte[] res = new byte[2048]; int bytesRead = 0; bytesRead = stream.Read(res, 0, res.Length); while (bytesRead > 0) { // read payload size byte[] psizeBytes = new byte[uint32Size]; Buffer.BlockCopy(res, 0, psizeBytes, 0, uint32Size); // big endian Array.Reverse(psizeBytes); uint psize = BitConverter.ToUInt32(psizeBytes, 0); Console.WriteLine("Reply payload size is {0}", psize); // read reply flag byte[] flagBytes = new byte[4]; Buffer.BlockCopy(res, 4, flagBytes, 0, 1); int replyFlag = BitConverter.ToInt32(flagBytes, 0); Console.WriteLine("Reply flag is {0}", replyFlag); // read reply status byte[] statusBytes = new byte[4]; Buffer.BlockCopy(res, 5, statusBytes, 0, 1); int status = BitConverter.ToInt32(statusBytes, 0); Console.WriteLine("Replay status is {0}", status); // read seq byte[] rseqBytes = new byte[uint16Size]; Buffer.BlockCopy(res, 6, rseqBytes, 0, uint16Size); // big endian Array.Reverse(rseqBytes); uint rseq = BitConverter.ToUInt16(rseqBytes, 0); Console.WriteLine("Reply seq is {0}", rseq); // read payload byte[] payloadBytes = new byte[psize]; Buffer.BlockCopy(res, 8, payloadBytes, 0, Convert.ToInt32(psize)); //string payload = Encoding.UTF8.GetString(payloadBytes, 0, payloadBytes.Length); Console.WriteLine("Reply payload is {0}", Encoding.UTF8.GetString(crypto.Decrypt(payloadBytes))); // read magic stop symbol byte[] sbytes = new byte[uint32Size]; Buffer.BlockCopy(res, 8 + Convert.ToInt32(psize), sbytes, 0, uint32Size); // big endian Array.Reverse(sbytes); uint mstop = BitConverter.ToUInt32(sbytes, 0); Console.WriteLine("Magic stop symbol is {0}. must be the same as {1}", mstop, stopSymbol); if (mstop == stopSymbol) { Console.WriteLine("End of replay packet"); break; } bytesRead = stream.Read(res, 0, res.Length); } Console.WriteLine("Done and close connection"); // close the connection //stream.Close(); }
/// <summary> /// Return the decrypted value of the string passed in. /// </summary> /// <param name="str">The string to decrypt</param> /// <returns>The decrypted value of the string.</returns> public static string DecryptData(string str) { if (str == null) return string.Empty; Crypto CheckCrypto = new Crypto(); string result = CheckCrypto.Decrypt(str, false); if (result == str || result == null || result == "") result = CheckCrypto.Encrypt(str, true); return result; }
static void Main(string[] args) { string serverIp; int httpPort; int serverPort; const string STOP = "stop"; Console.WriteLine("Enter server IP address:"); serverIp = Console.ReadLine(); Console.WriteLine("Enter HTTP port number:"); httpPort = int.Parse(Console.ReadLine()); Console.WriteLine("Connection to {0}:{1}", serverIp, httpPort); var request = (HttpWebRequest)WebRequest.Create("http://" + serverIp + ":" + httpPort + "/auth"); var postData = "thing1=hello"; postData += "&thing2=world"; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; var stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); var response = (HttpWebResponse)request.GetResponse(); var authRes = new StreamReader(response.GetResponseStream()).ReadToEnd(); Console.WriteLine("Auth response:{0}", authRes); JSONNode auth = JSON.Parse(authRes); Console.WriteLine("Session ID is {0}", auth["sessionId"]); Console.WriteLine( "Cipher Key, Nonce, and MacKey:{0}, {1}, {2}", auth["cipherData"]["base64"]["cipherKey"], auth["cipherData"]["base64"]["cipherNonce"], auth["cipherData"]["base64"]["macKey"] ); Console.WriteLine("Enter UDP server port number:"); serverPort = int.Parse(Console.ReadLine()); Console.WriteLine("Connection to {0}:{1}", serverIp, serverPort); int myPort = 54061; // connect to UDP server and send message UdpClient client = new UdpClient(myPort); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(serverIp), serverPort); client.Connect(endPoint); Console.WriteLine("Prepare encryption"); // prepare encryption Guid sid = new Guid(auth["sessionId"]); byte[] cipherKey = System.Convert.FromBase64String(auth["cipherData"]["base64"]["cipherKey"]); byte[] cipherNonce = System.Convert.FromBase64String(auth["cipherData"]["base64"]["cipherNonce"]); byte[] macKey = System.Convert.FromBase64String(auth["cipherData"]["base64"]["macKey"]); var crypto = new Crypto(sid, cipherKey, cipherNonce, macKey); byte[] packet = Encoding.ASCII.GetBytes("{\"command\":1,\"payload\":\"Hello\"}"); var epacket = crypto.Encrypt(packet); client.Send(epacket, epacket.Length); Console.WriteLine("UDP message sent: size is {0}", epacket.Length); Console.WriteLine("Waiting for server message..."); byte[] recData = client.Receive(ref endPoint); Console.WriteLine("Try decrypting..."); var dpack = crypto.Decrypt(recData); Console.WriteLine("message from server: {0}", Encoding.UTF8.GetString(dpack)); }
private void EncryptButton_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(KeyBox.Text)) { MessageBox.Show("You must enter a key!"); } else { var crypto = new Crypto(KeyBox.Text); OutputBox.Text = crypto.Encrypt(InputBox.Text); } }
private void EncryptFileButton_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(KeyBoxFile.Text) || string.IsNullOrWhiteSpace(FilePathBox.Text)) { MessageBox.Show("You must enter a key!"); } else { ResultsTextBox.AppendText("Encrypting...\n"); var crypto = new Crypto(KeyBoxFile.Text); string fileContents; using (StreamReader sr = new StreamReader(FilePathBox.Text)) { fileContents = sr.ReadToEnd(); } using ( StreamWriter sw = new StreamWriter(Path.Combine(Path.GetDirectoryName(FilePathBox.Text), Path.GetFileNameWithoutExtension(FilePathBox.Text) + "Encrypted" + ".txt"))) { sw.Write(crypto.Encrypt(fileContents)); sw.Write(Hasher.GenerateBase64Hash(MD5.Create(), fileContents)); } ResultsTextBox.AppendText("Encryption complete.\n"); } }
protected void btnSubmit_Click(object sender, EventArgs e) { Crypto crypto = new Crypto(true); string plaintextToken = DateTime.Now.Ticks.ToString(); plaintextToken += " " + tbTerritories.Text; string encryptedToken = Server.UrlEncode(crypto.Encrypt(plaintextToken)); link.HRef = tbUrl.Text + "?token=" + encryptedToken; //Response.Redirect(tbUrl.Text + "?token=" + encryptedToken); }