protected void SaveClick(object sender, EventArgs e) { if (OldPassword.Text.Length <= 0) { Script.alertMsg("请输入原密码", this.Page); return; } if (NewPassword.Text.Length <= 0) { Script.alertMsg("请输入新密码", this.Page); return; } Encrypter encrypt = new Encrypter(); IList<QueryModel> qmlist = new List<QueryModel>(); qmlist.Add(MakeUtil.getQueryModel("UserID", "'", SqlWhere.WhereOperator.Equal, UserID.Value)); qmlist.Add(MakeUtil.getQueryModel("UserPassword", "'", SqlWhere.WhereOperator.Equal, encrypt.EncryptString(OldPassword.Text))); UsersModel um = bllUE.getModel(qmlist); if (um.Evenid <= 0) { Script.alertMsg("原密码错误", this.Page); return; } um.UserPassword = encrypt.EncryptString(NewPassword.Text); bllUE.update(um); Script.alertMsg("修改成功", this.Page); }
public void Connect() { Encrypter encrypter = new Encrypter("64bit"); String keyword = encrypter.Decrypt("QnV0IHlvdSBkb24ndCByZWFsbHkgbWVhbiBpdA=="); // Check if crypter is changed Assert.AreEqual(true, encrypter.SetCrypter("AES")); this.connection = encrypter.Decrypt ("Sf+ulELX4tNuvsQtUG2EZWPJDPhm8obnrSyEm7F5mtg/eziYSjoIZndeCHk8iZOhvAuMNJBxiiatrRHTt2LVFv/vJNoo8yCHkOO7TwUWv3+l8+Wpis4TSsEvc8zHgEPIucH/OQ2tyYlMboyoFH26dZLZ2Y+Kevfu79VfqLBcKGE=", keyword); }
/*public ISessionFactory Session { get { session = fluentCfg.BuildSessionFactory(); return session; } }*/ public DatabaseConfiguration() { Encrypter encrypter = new Encrypter("64bit"); string keyword = encrypter.Decrypt("QnV0IHlvdSBkb24ndCByZWFsbHkgbWVhbiBpdA=="); encrypter.SetCrypter("AES"); this.connectionString = encrypter.Decrypt("Sf+ulELX4tNuvsQtUG2EZWPJDPhm8obnrSyEm7F5mtg/eziYSjoIZndeCHk8iZOhvAuMNJBxiiatrRHTt2LVFv/vJNoo8yCHkOO7TwUWv3+l8+Wpis4TSsEvc8zHgEPIucH/OQ2tyYlMboyoFH26dZLZ2Y+Kevfu79VfqLBcKGE=", keyword); fluentCfg = Fluently.Configure().Database(PostgreSQLConfiguration.Standard.ConnectionString(this.connectionString)).Mappings(m => { m.HbmMappings.AddFromAssemblyOf<Users>(); m.HbmMappings.AddFromAssemblyOf<Contacts>(); }); var config = fluentCfg.BuildSessionFactory(); }
public void TestCryptImport([Values("rsa")] String keyType, [Values("pem", "der")] String fileFormat) { using ( var keyset = ImportedKeySet.Import.X509Certificate(KeyPurpose.Encrypt, Util.TestDataPath(TEST_DATA, keyType + "-crypt-crt." + fileFormat))) using (var encrypter = new Encrypter(keyset)) using (var crypter = new Crypter(Util.TestDataPath(TEST_DATA, "rsa-crypt"))) { var ciphertext = encrypter.Encrypt(input); var plaintext = crypter.Decrypt(ciphertext); Expect(plaintext, Is.EqualTo(input)); } }
public void TestCryptImport( [Values("rsa")] string keyType, [Values("pem", "der")] string format) { using (var keystream = HelperOpenPkcsStream(keyType, format, "crypt")) using ( var keyset = ImportedKeySet.Import.PkcsKey(KeyPurpose.DecryptAndEncrypt, keystream, () => "pass" /* hard coding for test only!!!!*/)) using (var crypter = new Crypter(keyset)) using (var encrypter = new Encrypter(Util.TestDataPath(TEST_DATA, "rsa-crypt"))) { var ciphertext = encrypter.Encrypt(input); var plaintext = crypter.Decrypt(ciphertext); Expect(plaintext, Is.EqualTo(input)); } }
public bool Login(AuthModel authModel, out string msgError) { msgError = string.Empty; try { if (string.IsNullOrEmpty(authModel.Login)) { msgError = "Usuário não informado!"; return(false); } authModel.Login = authModel.Login.ToUpper(); User user = userBusiness.Get.FirstOrDefault(u => u.login == authModel.Login); if (user == null) { msgError = "Usuário não cadastrado!"; return(false); } if (!user.senha.Equals(Encrypter.EncryptPass(authModel.Password))) { msgError = "Senha incorreta!"; return(false); } authModel.sID = user.sID; authModel.Nome = user.nome; } catch (Exception ex) { msgError = ex.Message; if (ex.InnerException != null) { msgError += " - " + ex.InnerException.Message; if (ex.InnerException.InnerException != null) { msgError += " - " + ex.InnerException.InnerException.Message; } } return(false); } // Gerar o ticket e armazena como cookie GenerateAndStoreTicket(authModel); return(true); }
public ActionResult DoiMatKhau(string Password) { matkhausesion ds = (matkhausesion)Session["matkhau_Session"]; TaiKhoan tk = new TaiKhoan(); tk.UserName = ds.tentaikhoan; tk.MatKhau = Encrypter.MD5Hash(Password); tk.Remember = true; if (db.Update(tk)) { return(Json(new { success = true, ms = "Thêm thành công" }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { success = false, ms = "Thêm khong thành công" }, JsonRequestBehavior.AllowGet)); } }
public static string JSONSerialize <T>(T serializeObject, string encrytPass) where T : class { JsonSerializerSettings jsSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; string result = JsonConvert.SerializeObject(serializeObject, jsSettings); if (!string.IsNullOrEmpty(encrytPass)) { result = Encrypter.Encrypt(result, encrytPass); } return(result); }
public void UploadFilePacketEncrypt(int fileUploadID, string uploadFileName, string contentBase64, int userId) { string requestUri = string.Format("fileCopyer/encrypted"); UploadPacketRequest uploadPacketReq = new UploadPacketRequest(); uploadPacketReq.FileName = uploadFileName; uploadPacketReq.Base64Content = contentBase64; uploadPacketReq.FileUploadID = fileUploadID; uploadPacketReq.UserId = userId; var request = Encrypter.Encrypt <UploadPacketRequest>(uploadPacketReq); var response = client.PostAsJsonAsync(requestUri, request).Result; response.EnsureSuccessStatusCode(); // Throw on error code. var meeting = response.Content.ReadAsAsync <bool>().Result; }
public void CreateUser() { var e = new Encrypter(); var u = new User() { Email = "*****@*****.**" }; var password = "******"; //u.MasterPassword = e.HashPassword(password); using (var db = new Database()) { db.Users.Add(u); db.SaveChanges(); } }
public void Test1() { DummyConnecter c = new DummyConnecter(); DummyRawServer rs = new DummyRawServer(); IEncrypter e = new Encrypter(c, rs, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 500, DummySchedule, 30, new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, 40); DummySingleSocket c1 = new DummySingleSocket(); e.MakeExternalConnection(c1); byte[] temp = c1.Pop(); int i; for (i = 0; i < 68; i++) { Assert.AreEqual(handshakeMessage[i], temp[i]); } }
public async Task <IActionResult> Details(string Token, string Password) { if (Token == null) { return(NotFound()); } if (string.IsNullOrEmpty(Password)) { return(RedirectToAction("Details", new { id = Encrypter.Decrypt(Token), haspassworderror = true })); } var user = await _userManager.CheckPasswordAsync(_context.Users.FirstOrDefault(i => i.UserName == User.Identity.Name), Password); if (!user) { return(RedirectToAction("Details", new { id = Encrypter.Decrypt(Token), haspassworderror = true })); } var ordre = _context.Ordre.FirstOrDefault(i => i.Orderid == Encrypter.Decrypt(Token)); ordre.Status = "Payment Reshived"; _context.Ordre.Update(ordre); string body = @"<br/>Du vil modtage dine vare inde for få hverdage<br/><table><thead><tr><th>Pris</th><th>Productnavn</th></tr></thead><tbody>"; foreach (var product in _context.OrderProduct.Where(i => i.OrderId == Encrypter.Decrypt(Token))) { var products = _context.Product.FirstOrDefault(i => i.Id == product.ProductId); products.NoOfItems--; if (products.NoOfItems < 0) { ModelState.AddModelError("Email", "Der gik noget galt under ordren. prøv veligst igen, og vis det statid ikke virker så kontakt venligst en administator"); RedirectToAction("Details", new { id = Encrypter.Decrypt(Token) }); } _context.Update(products); body = body + @"<tr><td>" + products.Price + @" DKK  </td><td>" + products.Name + @"</td></tr>"; } body = body + "</tbody></table><br/><br>Total pris: " + ordre.Price + "DKK"; _context.SaveChanges(); EmailSender.SendEmail("Kvitering for køb", body, "Kvitering", ordre.Email); return(RedirectToAction("Confirmation")); }
static void Main(string[] args) { Console.WriteLine("Type yout full name : "); string Name = Console.ReadLine(); BinaryConverter binaryConverter = new BinaryConverter(); string binaryValue = binaryConverter.ConvertTo(Name); Console.WriteLine($"\n{Name} as Binary: {binaryValue}"); Console.WriteLine("\nCopy and Paste your Binary full name here : "); string binvalue = Console.ReadLine(); Console.WriteLine($"\n{binvalue} from Binary to ASCII: {binaryConverter.ConvertBinaryToString(binaryValue)}"); HexadecimalConverter hexadecimalConverter = new HexadecimalConverter(); string hexadecimalValue = hexadecimalConverter.ConvertTo(Name); Console.WriteLine($"\n{Name} as Hexadecimal: {hexadecimalValue}"); Console.WriteLine($"\n{Name} from Hexadecimal to ASCII: {hexadecimalConverter.ConveryFromHexToASCII(hexadecimalValue)}"); string nameBase64Encoded = StringToBase64(Name); Console.WriteLine($"\n{Name} as Base64: {nameBase64Encoded}"); string nameBase64Decoded = Base64ToString(nameBase64Encoded); Console.WriteLine($"\n{Name} from Base64 to ASCII: {nameBase64Decoded}"); int[] cipher = new[] { 1, 1, 2, 3, 5, 8, 13 }; //Fibonacci Sequence string cipherasString = String.Join(",", cipher.Select(x => x.ToString())); //FOr display int encryptionDepth = 20; Encrypter encrypter = new Encrypter(Name, cipher, encryptionDepth); //Deep Encrytion string nameDeepEncryptWithCipher = Encrypter.DeepEncryptWithCipher(Name, cipher, encryptionDepth); Console.WriteLine($"\nDeep Encrypted {encryptionDepth} times using the cipher {{{cipherasString}}} {nameDeepEncryptWithCipher}"); string nameDeepDecryptWithCipher = Encrypter.DeepDecryptWithCipher(nameDeepEncryptWithCipher, cipher, encryptionDepth); Console.WriteLine($"\nDeep Decrypted {encryptionDepth} times using the cipher {{{cipherasString}}} {nameDeepDecryptWithCipher}"); }
public ActionResult Login(LoginModel model) { if (ModelState.IsValid) { var dao = new UserDao(); var result = dao.Login(model.nv_tendangnhap, Encrypter.MD5Hash(model.nv_matkhau), true); if (result == 1) { var user = dao.GetByID(model.nv_tendangnhap); var nvSession = new UserLogin(); nvSession.nv_tendangnhap = user.nv_tendangnhap; nvSession.nv_id = user.nv_id; nvSession.cv_id = user.chucvu.cv_id; var listCredential = dao.GetListCredential(model.nv_tendangnhap); Session.Add(CommonConstants.SESSION_CREDENTIALS, listCredential); Session.Add(CommonConstants.NV_SESSION, nvSession); Session.Add( CommonConstants.NV_ID, nvSession.nv_id); return(RedirectToAction("Index", "Home")); } else if (result == -1) { ModelState.AddModelError("", "Tài khoản đã bị khóa"); } else if (result == 0) { ModelState.AddModelError("", "Tài khoản không tồn tại"); } else if (result == -2) { ModelState.AddModelError("", "Mật khẩu không đúng"); } else if (result == -3) { ModelState.AddModelError("", "Tài khoản không có quyền đăng nhập"); } else { ModelState.AddModelError("", "Đăng nhập không thành công"); } } return(View("Index")); }
public static void Main(string[] args) { Console.WriteLine("Wann4 play a G4m3?"); PathUtil pathUtil = new PathUtil(); #if DEBUG Console.WriteLine("Starting spread in paths:"); foreach (string path in pathUtil.Start) { Console.WriteLine("\t" + path); } #endif Spider spider; Encrypter encrypter = new Encrypter(); spider = new Spider(pathUtil, encrypter); spider.Spread(); }
public void AuthWithWrongPassword() { // Arrange var password = "******"; var passwordHash = Encrypter.EncryptString(password, KEY); var client = new Client(Guid.NewGuid(), 1, new Role { Name = "Admin", RoleId = 1 }, passwordHash, "Wall Disney"); var authParameters = new AuthParameters(client.Login, "253532"); var mockClientRepository = new Mock <IClientRepository>(); mockClientRepository.Setup(repo => repo.GetByLogin(It.IsAny <string>())).Returns(client); var authService = new AuthService(mockClientRepository.Object); // Act Assert.Throws <WrongPasswordException>(() => authService.Auth(authParameters)); }
public void TestDecrypt() { const string text = "Sample text to hide"; var image = ColoredBitmap.CreateBitmap(100, 100); var usage = new ChannelUsage(2); var picture = new Encrypter(new Picture(image)); picture.InsertText(text, usage); var endImage = picture.GetPictureData().GetImage(); endImage.Save("image.png", ImageFormat.Png); var resText = Interface.Decrypt(endImage, usage, 0); Assert.AreEqual(text, resText); }
public void Encrypt_abc_cde() { #region Подготавливаем исходные данные для тестирования var input_str = "abc"; var key = 1; var expected_result = "bcd"; #endregion #region Тестируем целевой объект var actual_result = Encrypter.Encrypt(input_str, key); #endregion #region Проверяем результаты теста Assert.AreEqual(expected_result, actual_result, "Ошибка кодирования строки"); #endregion }
private void btnSignUp_Click(object sender, EventArgs e) { textUsername = ""; textPassword = ""; textConfirmPassoword = ""; comboType = ""; textUsername = txtUsername.Text; textPassword = txtPassword.Text; textConfirmPassoword = txtConfirmPassword.Text; comboType = cboType.Text; //First Validate our form data validateForm(); //if form validation is not ok then dont execute further lines of code if (!isFormValidationOk) { return; } //to check if username is already registered in our database if (checkIfUserAlreadyExist()) { errorProvider1.SetError(txtUsername, null); errorProvider1.SetError(txtUsername, "User Already Registered,Please Enter New Username"); txtUsername.Focus(); return; } Encrypter encrypter = new Encrypter(); //getting md5 hashed code to conPass String conPass = encrypter.MD5Hash(txtPassword.Text); try { dbConn.executeQuery("INSERT INTO userdetails (userid, username, password, type, status) VALUES " + "(NULL, '" + textUsername + "','" + conPass + "', '" + comboType.ToLower() + "','active');"); MessageBox.Show("A New ADMIN has been Registered"); txtConfirmPassword.Clear(); txtPassword.Clear(); txtUsername.Clear(); } catch (Exception ex) { MessageBox.Show("" + ex.StackTrace); } }
static public string GetStringEncrypted(string key, string defaultValue) { try { string encryptedString = Encrypter.Decrypt(PlayerPrefs.GetString(key, ""), PASS_PHRASE); if (encryptedString.StartsWith(ECRYPTED_PREFIX)) { return(encryptedString.Remove(0, ECRYPTED_PREFIX.Length)); } else { return(defaultValue); } } catch { return(defaultValue); } }
public async Task <ResetPasswordResponseModel> ResetPassword(ResetPasswordModel model) { if (!await resetPasswordPolicy.IsValid(model)) { throw new PolicyViolationException(resetPasswordPolicy.PolicyViolations); } var passwordModel = new PasswordModel() { Password = model.Password }; if (!await passwordPolicy.IsValid(passwordModel)) { throw new PolicyViolationException(passwordPolicy.PolicyViolations); } var user = await dbContext .Users .Where(n => n.UserId == model.UserId) .FirstAsync(); var resetRequest = await dbContext .PasswordResetRequests .Where(n => n.UserId == user.UserId) .OrderByDescending(n => n.DateTimeIn) .FirstOrDefaultAsync(); resetRequest.IsActive = false; resetRequest.PasswordResetTime = DateTime.Now; IEncrypter encrypter = new Encrypter(); user.PasswordHash = encrypter.GenerateHash(model.Password, user.Salt); user.LockoutExpiryDate = null; user.FailedLoginAttempts = 0; user.ResetPasswordOnNextLogin = false; await dbContext.SaveChangesAsync(); return(new ResetPasswordResponseModel() { Username = user.Username }); }
public XmlDocument Post(datos Datos) { var fechaVencimiento = DateTime.Today.Date.AddDays(1000); var pswEncriptado = Encrypter.Encrypt(Datos.contrasena, Datos.usuario.ToUpper()); DocumentoEntrada entrada = new DocumentoEntrada { Usuario = Datos.usuario, Origen = "Login Usuario", Transaccion = 100004, Operacion = 9 }; entrada.agregaElemento("SgUsuId", Datos.usuario); entrada.agregaElemento("SgUsuClaveAcceso", pswEncriptado); entrada.agregaElemento("SgUsuFechaVencimiento", fechaVencimiento); DocumentoSalida respuesta = PeticionCatalogo(entrada.Documento); if (respuesta.Resultado == "1") { return(respuesta.Documento); } else { string msnError = ""; XmlDocument xmErrores = new XmlDocument(); XmlDocument xmError = new XmlDocument(); xmErrores.LoadXml(respuesta.Errores.InnerXml); XmlNodeList elemList = xmErrores.GetElementsByTagName("Descripcion"); for (int i = 0; i < elemList.Count; i++) { msnError += elemList[i].InnerXml; } xmError.LoadXml("<Salida><Resultado>0</Resultado><Error>" + msnError + "</Error></Salida>"); return(xmError); //var errores = respuesta.Errores; //return respuesta.Documento; } }
public virtual string RenderBody() { velocityContext.Put("account", AccountCard); velocityContext.Put("header", renderHeader.ToString()); velocityContext.Put("buffer", renderBuffer.ToString()); velocityContext.Put("footer", renderFooter.ToString()); // 系统名称 velocityContext.Put("systemName", KernelConfigurationView.Instance.SystemName); // 系统状态 velocityContext.Put("systemStatus", KernelConfigurationView.Instance.SystemStatus); // 版本 velocityContext.Put("version", KernelConfigurationView.Instance.Version); // 默认域名 velocityContext.Put("domain", KernelConfigurationView.Instance.Domain); // 身份标识名称 velocityContext.Put("identityName", KernelContext.Current.AuthenticationManagement.IdentityName); // 页面加载次数 velocityContext.Put("reloadCount", this.reloadCount); // 给Session对象赋值,固定取得SessionID HttpContext.Current.Session["__session__ticket__"] = this.initializedTime; // 会话标识 velocityContext.Put("session", HttpContext.Current.Session.SessionID); // 时间间隔 velocityContext.Put("timeSpan", DateHelper.GetTimeSpan(this.initializedTime)); // ------------------------------------------------------- // 生成签名 // ------------------------------------------------------- velocityContext.Put("clientId", KernelConfigurationView.Instance.ApplicationClientId); // 时间戳 velocityContext.Put("timestamp", DateHelper.GetTimestamp()); // 随机数 velocityContext.Put("nonce", DigitalNumberContext.Generate("Key_Nonce")); // 签名 velocityContext.Put("clientSignature", Encrypter.EncryptSHA1(Encrypter.SortAndConcat( KernelConfigurationView.Instance.ApplicationClientSecret, velocityContext.Get("timestamp").ToString(), velocityContext.Get("nonce").ToString()))); return(VelocityManager.Instance.Merge(velocityContext, RenderBodyTemplatePath)); }
private bool IsValid(string name, string pass) { //假的,可以直接登录,不要密码 //return true; //加密登录,很吊的。客户这边还是输入自己的密码,我后台这里加了密和数据库里已经加密的比较,(算法一样的,所以一样的东西加密出来的一定会一样),正确就密码正确。 string md5Pass = Encrypter.GetMD5(pass); object record = SqlHelper.GetScaler("exec loginpwd '" + name + "','" + md5Pass + "'"); if (record != null) { return(true); } else { return(false); } }
public static void saveFile(List <User> userDatabase) { try { FileStream fs = File.OpenWrite("userdatabase.txt"); Encrypter e = new Encrypter(key); for (int i = 0; i < userDatabase.Count; i++) { AddText(fs, e.start(userDatabase[i].ToString())); AddText(fs, "\n"); } fs.Close(); } catch (Exception e) { Console.Out.WriteLine(e); } }
public XConnection() { Encrypter encrypter = new Encrypter("64bit"); String keyword = encrypter.Decrypt("QnV0IHlvdSBkb24ndCByZWFsbHkgbWVhbiBpdA=="); if (encrypter.SetCrypter("AES")) { String connection = encrypter.Decrypt ("Sf+ulELX4tNuvsQtUG2EZWPJDPhm8obnrSyEm7F5mtg/eziYSjoIZndeCHk8iZOhvAuMNJBxiiatrRHTt2LVFv/vJNoo8yCHkOO7TwUWv3+l8+Wpis4TSsEvc8zHgEPIucH/OQ2tyYlMboyoFH26dZLZ2Y+Kevfu79VfqLBcKGE=", keyword); _Connection = new NpgsqlConnection(connection); } else { throw new XConnectionException(); } }
private DeploymentMappings Read(Stream deployerConfiguration) { if (!string.IsNullOrEmpty(_signingKeyFile)) { if (!Encrypter.VerifyXml(deployerConfiguration, _signingKeyFile)) { TraceHelper.TraceWarning(TraceSwitches.TfsDeployer, "Verification Failed for the deployment mapping using key file {0}", Properties.Settings.Default.KeyFile); return(null); } deployerConfiguration.Seek(0, SeekOrigin.Begin); TraceHelper.TraceInformation(TraceSwitches.TfsDeployer, "Verification Succeeded for the deployment mapping"); } using (var reader = new StreamReader(deployerConfiguration)) { return((DeploymentMappings)DeploymentMappingsSerializer.Deserialize(reader)); } }
private void OnRead(IAsyncResult ar) { int count = this._stream.EndRead(ar); this.totalBuffer += Encrypter.Decrypt(this._buffer.SubArray(0, count), "password123"); string eof = $"<{Tag.EOF.ToString()}>"; while (this.totalBuffer.Contains(eof)) { string packet = this.totalBuffer.Substring(0, this.totalBuffer.IndexOf(eof) + eof.Length); this.totalBuffer = this.totalBuffer.Substring(packet.IndexOf(eof) + eof.Length); this.HandlePacket(packet); } this._stream.BeginRead(this._buffer, 0, this._buffer.Length, new AsyncCallback(this.OnRead), null); }
public MainViewModel(INavigation navigation) { Navigation = navigation; encrypter = new Encrypter(); if (Preferences.ContainsKey("symbol_table")) { encrypter.SetSymbolTable(Preferences.Get("symbol_table", "Unicode")); } else { Preferences.Set("symbol_table", "Unicode"); } if (Preferences.ContainsKey("use_preset_key")) { if (Preferences.Get("use_preset_key", false)) { if (Preferences.ContainsKey("preset_key")) { SetPresetKey(Preferences.Get("preset_key", "")); } else { Preferences.Set("preset_key", ""); } } else { SetPresetKey(""); } } else { Preferences.Set("preset_key", ""); } EncryptCommand = new Command(Encrypt); DecryptCommand = new Command(Decrypt); SettingsCommand = new Command(OpenSettings); ShareCommand = new Command(ShareMessage); HideKey = Preferences.Get("hide_key", false); }
private async void SubmitButton_Click(object sender, RoutedEventArgs e) { // Initialize Client-Side-Encryption (with the public key from Adyen CA) string publicKey = "YourPublicKey"; Encrypter cse = new Encrypter(publicKey); // Create card object Card card = new Card(); card.CardNumber = CardNumber.Text; card.HolderName = HolderName.Text; card.ExpirationMonth = ExpirationMonth.Text; card.ExpirationYear = ExpirationYear.Text; card.CVC = CVC.Text; // Apply Client-Side-Encryption to the card data string encryptedCard = cse.Encrypt(card.ToString()); Debug.WriteLine(encryptedCard); // Send payment request with encrypted card data (using HTTP Post) var httpClientHandler = new HttpClientHandler(); httpClientHandler.Credentials = new NetworkCredential("YourWSUser", "YourWSPassword"); var httpClient = new HttpClient(httpClientHandler); var values = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("action", "Payment.authorise"), new KeyValuePair <string, string>("paymentRequest.merchantAccount", "YourMerchantAccount"), new KeyValuePair <string, string>("paymentRequest.reference", "TEST-PAYMENT-WindowsPhone-" + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")), new KeyValuePair <string, string>("paymentRequest.amount.currency", "EUR"), new KeyValuePair <string, string>("paymentRequest.amount.value", "1000"), new KeyValuePair <string, string>("paymentRequest.additionalData.card.encrypted.json", encryptedCard), }; HttpResponseMessage response = await httpClient.PostAsync("https://pal-test.adyen.com/pal/adapter/httppost", new FormUrlEncodedContent(values)); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); // Show payment result MessageBox.Show(responseString, "Payment result", MessageBoxButton.OK); }
/// <summary> /// RSA加签验签测试 /// </summary> public static void TestSign() { string originalData = "文章不错,这是我的签名:奥巴马!"; Console.WriteLine("签名数为:{0}", originalData); KeyValuePair <string, string> keyPair = Encrypter.CreateRSAKey(); string privateKey = keyPair.Value; string publicKey = keyPair.Key; //1、生成签名,通过摘要算法 string signedData = Encrypter.HashAndSignString(originalData, privateKey); Console.WriteLine("数字签名:{0}", signedData); //2、验证签名 bool verify = Encrypter.VerifySigned(originalData, signedData, publicKey); Console.WriteLine("签名验证结果:{0}", verify); }
private void btnRegister_Click(object sender, EventArgs e) { //Place all selected Specialism into an array - specialismList int noOfSpecialisms = chkListSpecialisms.CheckedItems.Count; string[] specialismList = new string[noOfSpecialisms]; int i = 0; foreach (var item in chkListSpecialisms.CheckedItems) { if (i < noOfSpecialisms) { specialismList[i] = item.ToString(); } i++; } btnRegister.Enabled = false; User newUser = new User(); newUser.Firstname = txtFirstname.Text.Trim().ToLower(); newUser.Surname = txtSurname.Text.Trim().ToLower(); newUser.Username = txtUsername.Text.Trim().ToLower(); newUser.Password = Encrypter.Encrypt(txtPassword.Text); newUser.SpecialismList = specialismList; Registration registration = new Registration(); registration.Register(newUser); MessageBox.Show( " You have been registered successfully." + "\r You can now login with your Username and Password.", "Welcome To MRIC Peer Review", MessageBoxButtons.OK, MessageBoxIcon.Information ); this.Close(); thread = new Thread(openLoginForm); thread.SetApartmentState(ApartmentState.STA); thread.Start(); }
public static SiteUser Login(string email, string password) { string MD5Password = Encrypter.CalculateMD5Hash(password); SiteUser user = BaseObject.GetFirst <SiteUser>("Email ='" + email + "' AND Password = '******'"); //"' AND Type = 30"); if (user == null) { if (email == "test" && password == "test") { SiteUser siteUser = new SiteUser(); siteUser.Name = "test gebruiker"; siteUser.Email = email; user = siteUser; } } return(user); }
/// <summary></summary> /// <param name="applicationId"></param> /// <returns></returns> public static string CreateSecurityToken(string applicationId) { ApplicationInfo param = AppsContext.Instance.ApplicationService.FindOne(applicationId); // 时间戳 var timestamp = DateHelper.GetTimestamp(); // 随机数 var nonce = DigitalNumberContext.Generate("Key_Nonce"); // 签名 var clientSignature = Encrypter.EncryptSHA1(Encrypter.SortAndConcat( param.ApplicationSecret, timestamp.ToString(), nonce.ToString())); return("{\"clientId\":\"" + param.Id + "\"," + "\"clientSignature\":\"" + clientSignature + "\"," + "\"timestamp\":\"" + timestamp + "\"," + "\"nonce\":\"" + nonce + "\"}"); }
public static SecondarySoundBuffer LoadSound(string FileName) { if (isFromResource) { FileName = FileName.Split('.')[0]; } if (!File.Exists(FileName)) { throw (new ArgumentException("The sound " + FileName + " could not be found.")); } SoundBufferDescription BufferDesc = new SoundBufferDescription(); //enable volume changes on all buffers created with this function. BufferDesc.Flags = SharpDX.DirectSound.BufferFlags.ControlVolume | SharpDX.DirectSound.BufferFlags.ControlFrequency //| SharpDX.DirectSound.BufferFlags.StickyFocus | SharpDX.DirectSound.BufferFlags.ControlPan; //load wave file into DirectSound buffer SecondarySoundBuffer theBuffer = null; if (!isFromResource) { AudioFile wFile = new AudioFile(new FileStream(FileName, FileMode.Open)); byte[] final = wFile.getRawWaveData(); BufferDesc.Format = wFile.format(); BufferDesc.BufferBytes = final.Length; theBuffer = new SecondarySoundBuffer(objDS, BufferDesc); theBuffer.Write(final, 0, LockFlags.EntireBuffer); wFile.close(); } else { byte[] data = Encrypter.getData(FileName, pass); AudioFile wFile = new AudioFile(data); byte[] final = wFile.getRawWaveData(); BufferDesc.Format = wFile.format(); BufferDesc.BufferBytes = final.Length; theBuffer = new SecondarySoundBuffer(objDS, BufferDesc); theBuffer.Write(final, 0, LockFlags.EntireBuffer); wFile.close(); } return(theBuffer); }
public static string[] Encrypter(string textToEncrypt, PathProvider p) { WebBase64 sessionMaterial; WebBase64 cipherText; string[] data; string path = p.GetPublicPath(); using (var encrypter = new Encrypter(path)) using (var sessionCrypter = new SessionCrypter(encrypter)) { sessionMaterial = sessionCrypter.SessionMaterial; cipherText = sessionCrypter.Encrypt(textToEncrypt); data = new string[] { sessionMaterial.ToString(), cipherText.ToString() }; //data.Add("sessionmaterial", sessionMaterial); //data.Add("data", cipherText); } return data; }
public ActionResult Create(User user) { if (ModelState.IsValid) { var dao = new UserDao(); user.Password = Encrypter.MD5Hash(user.Password); long id = dao.Insert(user); if (id > 0) { return(RedirectToAction("Index", "User")); } else { ModelState.AddModelError("", "Thêm User không thành công !!!"); } } //View mac dinh la Create.cshtml return(View("Index")); }
public void Encrypt_Decrypt() { var key = "1234567887654321"; Encrypter encrypter = new Encrypter(key); var data = @"GET http://offline.dev.wingontravel.com/Ticket/Booking/SearchFare HTTP/1.1 Accept: text/html, application/xhtml+xml, */* Referer: http://offline1.dev.wingontravel.com/RightsManagement/Default.aspx Accept-Language: zh-CN User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko Accept-Encoding: gzip, deflate Host: offline.dev.wingontravel.com Connection: Keep-Alive Cookie: _ga=GA1.2.1208780554.1452854271; app_pop=1; WINGON_TRACKING_CID=03635888155583694324; FIRST_DISCOUNT_ABS=1; token=00XK5jOIs7cNgdWotUrmGIpL+A0l/59NOwAu5RTN7YhTwaYcQRNFgzW9PUphv6UC7CUk2WEpdKVpZY8F4FkM24gYcMspthIUPZOa90KvzaA="; var dataBytes = Encoding.UTF8.GetBytes(data); var alfterDataBytes = encrypter.Encrypt(dataBytes); var decryptedDataBytes = encrypter.Decrypt(alfterDataBytes); Assert.AreEqual(data, Encoding.UTF8.GetString(decryptedDataBytes)); }
public void Connect() { Console.WriteLine(); TestHelper.log("Decrypting keyword"); Encrypter encrypter = new Encrypter("64bit"); String keyword = encrypter.Decrypt("QnV0IHlvdSBkb24ndCByZWFsbHkgbWVhbiBpdA=="); TestHelper.done(); TestHelper.log("Decrypting connection parameters"); Assert.AreEqual(true, encrypter.SetCrypter("AES")); TestHelper.done(); TestHelper.log("Connection decritpion"); try { this.connection = encrypter.Decrypt ("Sf+ulELX4tNuvsQtUG2EZWPJDPhm8obnrSyEm7F5mtg/eziYSjoIZndeCHk8iZOhvAuMNJBxiiatrRHTt2LVFv/vJNoo8yCHkOO7TwUWv3+l8+Wpis4TSsEvc8zHgEPIucH/OQ2tyYlMboyoFH26dZLZ2Y+Kevfu79VfqLBcKGE=", keyword); TestHelper.done(); } catch (Exception e) { TestHelper.error(e.Message); } TestHelper.log("Connection test"); try { NpgsqlConnection _Connection = new NpgsqlConnection(connection); Assert.IsNotNull(_Connection); TestHelper.done(); } catch (Exception e) { TestHelper.error(e.Message); } }
public void Setup() { publicKeyEncrypter = new Encrypter(Util.TestDataPath(TEST_DATA, "rsa.public")); privateKeyDecrypter = new Crypter(Util.TestDataPath(TEST_DATA, "rsa")); }
public void TestRsaCryptWithPublicKey() { using (var encrypter = new Encrypter(Util.TestDataPath(TEST_DATA, "rsa.public"))) { var cipher = encrypter.Encrypt(input); var subPath = Util.TestDataPath(TEST_DATA, "rsa"); using (var crypter = new Crypter(subPath)) { var decrypt = crypter.Decrypt(cipher); Expect(decrypt, Is.EqualTo(input)); } } }
public void TestIncompatibility() { var encrypter = new Encrypter(oaepReader); var ciphertext = encrypter.Encrypt(input); var crypter = new Crypter(pkcsReader); Expect(() => crypter.Decrypt(ciphertext), Throws.TypeOf<InvalidCryptoDataException>()); }
/// <summary> /// Initializes a new instance of the <see cref="EncryptedKeySetWriter"/> class. /// </summary> /// <param name="writer">The writer.</param> /// <param name="encrypter">The encrypter.</param> public EncryptedKeySetWriter(IKeySetWriter writer, Encrypter encrypter) { _encrypter = encrypter; _writer = writer; }
private SessionCrypter HelperSessionCrypter(Encrypter encrypter, string unoffical) { if (String.IsNullOrWhiteSpace(unoffical)) { return new SessionCrypter(encrypter); } else { return new SessionCrypter(encrypter, symmetricKeyType: UnofficialKeyType.AesAead, keyPacker: new BsonSessionKeyPacker()); } }
protected void Page_Load(object sender, EventArgs e) { //声明加密程序 Encrypter encrypt = new Encrypter(); //Action string Action = MakeUtil.getStringFromRequestByName(Request, "Action", -1); if (Action == "Login") { string result = ""; string userid = MakeUtil.getStringFromRequestByName(Request, "UserID", -1); string userpwd = MakeUtil.getStringFromRequestByName(Request, "UserPWD", -1); string companypwd = MakeUtil.getStringFromRequestByName(Request, "CompanyPwd", -1); string[] FieldNames = MakeUtil.getStringFromRequestByName(Request, "FieldNames", -1).Split('|'); string guid = MakeUtil.getStringFromRequestByName(Request, "Guid", -1); Dictionary<string, LoginState> LoginStateDic = (Dictionary<string, LoginState>)Application["LoginState"]; bool newLS = true; LoginState ls = null; // 检测重复登录 if (result.Length == 0) { if (LoginStateDic.Keys.Contains(userid)) { newLS = false; ls = LoginStateDic[userid]; if (guid != ls.SerialID) { // 已有用户登录该账号 result = "error|该用户已登录"; } } } if (result.Length == 0) { IList<QueryModel> qmlist = new List<QueryModel>(); qmlist.Add(MakeUtil.getQueryModel("UserID", "'", SqlWhere.WhereOperator.Equal, userid)); qmlist.Add(MakeUtil.getQueryModel("UserPassword", "'", SqlWhere.WhereOperator.Equal, encrypt.EncryptString(userpwd))); try { UsersModel um = bllUE.getModel(qmlist); if (um.UserID == "" || !um.Login) { result = "error|操作用户账号错误或操作用户密码错误"; } else { if (newLS) { ls = new LoginState(); } ls.SerialID = guid; ls.LoginName = userid; ls.LastTime = DateTime.Now; ls.IP = MakeUtil.GetClientIP(); ls.MAC = MakeUtil.GetClientMAC(ls.IP); string[] tempMac = ls.MAC.Split('|'); if (tempMac.Length > 1 && tempMac[0] != "error") { result = string.Format("error|对不起您的MAC地址不在允许的范围之内"); } else { //验证MAC地址 if (checkMAC(um, ls.MAC)) { if (newLS) { LoginStateDic[userid] = ls; } Application["LoginState"] = LoginStateDic; List<string> ModulesList = new List<string>(); ModulesList.AddRange(new string[] { "Base", "System", "Sale" }); foreach (string str in FieldNames) { switch (str) { case "UserId": result += um.UserID + "|"; break; case "UserName": result += um.UserName + "|"; break; case "Power": result += getAllPower(um, ModulesList.ToArray()) + "|"; break; case "PartsPower": result += getPartsPower(um) + "|"; break; case "DepartmentNo": result += um.DepartmentNo + "|"; break; case "Modules": result += string.Join(",", ModulesList.ToArray()) + "|"; break; } } if (result.Length > 0) { result = result.Substring(0, result.Length - 1); } } else { result = string.Format("error|对不起您的MAC地址为{0},不在允许的范围之内", ls.MAC); } } } } catch (Make.Exp.MakeException mEx) { result = "error|" + mEx.Message; } } WriteBack(result); } else if (Action == "UpdateLS") { string userid = MakeUtil.getStringFromRequestByName(Request, "UserID", -1); string guid = MakeUtil.getStringFromRequestByName(Request, "Guid", -1); Dictionary<string, LoginState> LoginStateDic = (Dictionary<string, LoginState>)Application["LoginState"]; { LoginState ls = LoginStateDic[userid]; if (ls.SerialID == guid) { ls.LastTime = DateTime.Now; Application["LoginState"] = LoginStateDic; } } } else if (Action == "Exit") { string userid = MakeUtil.getStringFromRequestByName(Request, "UserID", -1); string guid = MakeUtil.getStringFromRequestByName(Request, "Guid", -1); Dictionary<string, LoginState> LoginStateDic = (Dictionary<string, LoginState>)Application["LoginState"]; if (LoginStateDic.Keys.Contains(userid)) { LoginState ls = LoginStateDic[userid]; if (ls.SerialID == guid) { LoginStateDic.Remove(userid); Application["LoginState"] = LoginStateDic; } } } }
public void TestPkcsEncryption() { var ciphertext = new Encrypter(pkcsReader).Encrypt(input); var plaintext = new Crypter(pkcsReader).Decrypt(ciphertext); Expect(plaintext, Is.EqualTo(input)); }