/// <summary> /// Récupère les mots de passe d'un fichier /// </summary> /// <returns>les erreurs si il y en a</returns> public async Task <string> RecupFichier() { var erreur = Validate(); if (string.IsNullOrWhiteSpace(erreur)) { try { //lecture var buffer = (await FileIO.ReadBufferAsync(Fichier)).ToArray(); //déchiffrement var data = CryptUtils.AesDecryptByteArrayToString(buffer, CryptKey, CryptSalt); //deserialization var xsb = new XmlSerializer(typeof(ObservableCollection <MotDePasse>)); var rd = new StringReader(data); ListeMdpRecup = xsb.Deserialize(rd) as ObservableCollection <MotDePasse>; } catch { erreur += ResourceLoader.GetForCurrentView("Errors").GetString("erreurDechiffrementb"); } } return(erreur); }
public static void Signin(T user, DateTime?expires, HttpContext context) { if (SigningIn != null) { UserStatusEventArgs e = new UserStatusEventArgs(context, false); SigningIn(user, e); if (e.Cancel) { return; } } (user as UserBase <T>).IP = WebUtils.GetClientIP(context); HttpCookie hc = new HttpCookie("SInfo"); hc.Values.Add(".b", CryptUtils.EncryptDES((user as UserBase <T>).UserName)); hc.Values.Add(".a", CryptUtils.EncryptDES((user as UserBase <T>).Password)); if (expires != null) { hc.Values.Add(".c", expires.ToString()); hc.Expires = (DateTime)expires; } context.Response.Cookies.Set(hc); context.Session["Burst.Web.UserBase.Current"] = user; if (SignedIn != null) { SignedIn(user, new UserStatusEventArgs(context, false)); } }
/// <summary> /// Surchiffre le mot de passe utilisateur /// </summary> /// <param name="chaine">le mot de passe de l'utilisateur</param> /// <returns>le mot de passe surchiffré</returns> private static string ChiffrerMotDePasse(string chaine) { var intermed = CryptUtils.AesEncryptStringToString(chaine, MotDePasseASurchiffrement, SaltASurchiffrement); intermed = SuffixeSurchiffrement + intermed + PrefixeSurchiffrement; return(CryptUtils.AesEncryptStringToString(intermed, MotDePasseBSurchiffrement, SaltBSurchiffrement)); }
internal async Task SendPublicMessageAsync(PublicChatRoom chatRoom, string content) { if (_disposed) { throw new ObjectDisposedException(null); } if (!_publicRooms.Contains(chatRoom)) { throw new NotSupportedException("Enter ChatRoom first."); } try { var message = new Message { Content = content, Sender = _publicIdentity, TimeStamp = DateTimeOffset.Now.ToUnixTimeSeconds() }; var signedData = await CreateSignAndEncodeDataAsync(message); var encrypted = CryptUtils.AesEncryptByteArray(signedData, chatRoom.PreSharedKey); var chatRoomIdentifier = chatRoom.GetEncryptedIdentifier(); var packet = new PublicMessagePacket(encrypted, chatRoomIdentifier); await _networkHandler.SendPacketAsync(packet); } catch (Exception) when(_disposed) { } }
private async void HandleIncomingPublicMessageAsync(string json) { var packet = await JsonUtils.DeserializeAsync <PublicMessagePacket>(json); if (packet == null) { return; } var chatRoom = _publicRooms.FirstOrDefault(r => r.Equals(packet.ChatRoom)); if (chatRoom == null) { return; } var decrypted = CryptUtils.AesDecryptBytes(packet.Content, chatRoom.PreSharedKey); var signedJson = Config.DefaultEncoding.GetString(decrypted); var message = await GetAndVerifySignedDataAsync <Message>(signedJson); if (message?.Sender == null) { return; } OnKeepAliveReceived(message.Sender); chatRoom.OnPublicMessageReceived(new MessageReceivedEventArgs(message.Sender, message)); }
/// <summary> /// Exporte le fichier chiffré directement /// </summary> /// <returns>la liste des erreurs</returns> public async Task <string> ExporterKwi() { var retour = Validate(); if (string.IsNullOrWhiteSpace(retour)) { if (!StringUtils.GetExtension(Fichier.Name).Equals(FormatChoisi.Format)) { await Fichier.RenameAsync(Fichier.Name + "." + FormatChoisi.Format); } var xs = new XmlSerializer(typeof(Dossier)); using (var wr = new StringWriter()) { xs.Serialize(wr, SelectedDossier); var dataToSave = CryptUtils.AesEncryptStringToByteArray(wr.ToString(), MdpCypher, MdpCypher); await FileIO.WriteBytesAsync(Fichier, dataToSave); //anciennement pour exporter tout le fichier //await FileIO.WriteTextAsync(fichier, wr.ToString(), Windows.Storage.Streams.UnicodeEncoding.Utf8); } //await FileIO.WriteBytesAsync(fichier, await ContexteAppli.fichierPassword.lireByteArray()); } return(retour); }
internal async Task SendInviteAsync(string name, byte[] preSharedKey, UserIdentity receiver) { if (_disposed) { throw new ObjectDisposedException(null); } try { var invite = new Invite { Name = name, PreSharedKey = preSharedKey, Sender = _publicIdentity }; var signedData = await CreateSignAndEncodeDataAsync(invite); var publicKey = PemUtils.GetKeyFromPem(receiver.PublicKey); var aesKey = CryptUtils.GenrateAesKey(); var encryptedAesKey = CryptUtils.RsaEncryptWithPublic(aesKey, publicKey); var encryptedData = CryptUtils.AesEncryptByteArray(signedData, aesKey); var packet = new InvitePacket(encryptedData, encryptedAesKey); await _networkHandler.SendPacketAsync(packet); } catch (Exception) when(_disposed) { } }
public void Generate_Key_Pair() { var keyPair = CryptUtils.CreatePublicAndPrivateKeyPair(); "Public Key: {0}\n".Print(keyPair.PublicKey); "Private Key: {0}\n".Print(keyPair.PrivateKey); }
public override void Configure(Container container) { RequestConverters.Add((req, requestDto) => { var encRequest = requestDto as EncryptedMessage; if (encRequest == null) { return(null); } var requestType = Metadata.GetOperationType(encRequest.OperationName); var decryptedJson = CryptUtils.Decrypt(SecureConfig.PrivateKey, encRequest.EncryptedBody); var request = JsonSerializer.DeserializeFromString(decryptedJson, requestType); req.Items["_encrypt"] = encRequest; return(request); }); ResponseConverters.Add((req, response) => { if (!req.Items.ContainsKey("_encrypt")) { return(null); } var encResponse = CryptUtils.Encrypt(SecureConfig.PublicKey, response.ToJson()); return(new EncryptedMessageResponse { OperationName = response.GetType().Name, EncryptedBody = encResponse }); }); }
public ActionResult ChangePassword(Utilisateurs utilisateurs) { if (utilisateurs.MotDePasse != null && !CryptUtils.IsValidMotDePasse(utilisateurs.MotDePasse)) { ModelState.AddModelError("MotDePasse", "Le mot de passe doit contenir au moins une majuscule, une minuscule, un chiffre et un caractère spécial"); } if (ModelState.IsValid) { var user = Db.Utilisateurs.Find(utilisateurs.Id); if (user != null) { user.MotDePasse = CryptUtils.GenerateHashPassword(utilisateurs.MotDePasse); Db.Entry(user).State = EntityState.Modified; Db.SaveChanges(); } else { ModelState.AddModelError("MotDePasse", "Cet utilisateur est introuvable"); } return(RedirectToAction("Index")); } return(View(utilisateurs)); }
public ActionResult ChangeProfile(FormChangeUser u) { User user = (User)Session[KeysUtils.SessionUser()]; if (!user.email.Trim().Equals(u.email) && Models.User.EmailExists(u.email)) { ModelState.AddModelError("EmailExists", "Email already exists"); } else { if (u.password == null || u.password.Trim().Equals("")) { u.password = ((User)(Session[KeysUtils.SessionUser()])).password; } else { user.password = CryptUtils.Hash(u.password); } user.email = u.email; user.first_name = u.firstName; user.last_name = u.lastName; user.saveChanges(); Session[KeysUtils.SessionUser()] = user; ViewBag.Status = true; ViewBag.Message = "Changed profile successfully"; } return(View(u)); }
/// <summary> /// lit le fichier , le déchiffre à partir du mot de passe fournit et le désérialize /// </summary> /// <param name="passwordTmp">le mot de passe pour tenter le déchiffrement</param> /// <param name="fullLoad">Indique si c'est un chargement complet ou légé</param> /// <returns>true si ok</returns> public static async Task <bool> Load(string passwordTmp, bool fullLoad) { try { //lecture var inFile = await Fichier.LireByteArray(); //dechiffrement var xmlIn = CryptUtils.AesDecryptByteArrayToString(inFile, passwordTmp, passwordTmp); //deserialize var xsb = new XmlSerializer(typeof(Dossier)); var rd = new StringReader(xmlIn); ContexteAppli.DossierMere = xsb.Deserialize(rd) as Dossier; if (fullLoad) { RemiseEnPlaceParent(ContexteAppli.DossierMere); RemiseEnPlaceIcone(ContexteAppli.DossierMere); } Password = passwordTmp; return(true); } catch (Exception) { return(false); } }
public static Image LoadImage(string imageName, string decode) { Image res = null; try { Stream imageStream; if (decode.ToLower() == CryptUtils.EncDec.BASE64) { imageStream = CryptUtils.Decode(imageName, decode); } else { imageStream = ResourcesUtils.GetEmbeddedResourceStream(null, imageName); } if (imageStream != null) { res = Image.FromStream(imageStream); } } #if DEBUG catch (Exception e) #else catch (Exception) #endif { #if DEBUG Logger.GetLogger().Error($"error while loading the image {imageName}: {e}"); #endif } return(res); }
/// <summary> /// Lance le chiffrement ou le déchiffrement du fichier /// </summary> /// <returns>les erreurs</returns> public async Task <string> Valider() { var retour = await Validate(); if (string.IsNullOrWhiteSpace(retour)) { try { var buffer = await FileIO.ReadBufferAsync(FileInput); switch (Mode) { case ChiffrerDechiffrerEnum.Chiffrer: var cypherByte = CryptUtils.AesEncryptByteArrayToByteArray(buffer.ToArray(), Password, Password); await FileIO.WriteBytesAsync(FileOutput, cypherByte); break; case ChiffrerDechiffrerEnum.Dechiffrer: var cypherByteB = CryptUtils.AesDecryptByteArrayToByteArray(buffer.ToArray(), Password, Password); await FileIO.WriteBytesAsync(FileOutput, cypherByteB); break; } } catch { retour += ResourceLoader.GetForCurrentView("Errors").GetString("erreurDechiffrement") + "\r\n"; } } return(retour); }
private DokuAuthUser _UserAdd(DokuAuthUser user) { DokuAuthUser userexist = this._userList.SingleOrDefault(o => o.Login.Equals(user.Login)); if (userexist == null) { if ( (string.IsNullOrWhiteSpace(user.Password)) && (string.IsNullOrWhiteSpace(user.PasswdHash)) ) { return(default(DokuAuthUser)); } user.PasswdHash = ((string.IsNullOrWhiteSpace(user.PasswdHash)) ? CryptUtils.Crypt(user.Password) : user.Password); user.Group = ((string.IsNullOrWhiteSpace(user.Group)) ? ((string.IsNullOrWhiteSpace(this._group)) ? groupDefault : this._group) : user.Group ); this._userList.Add(user); userexist = user; } else { userexist.Name = user.Name; userexist.Email = user.Email; userexist.Group = ((string.IsNullOrWhiteSpace(user.Group)) ? userexist.Group : user.Group); userexist.PasswdHash = ((string.IsNullOrWhiteSpace(user.PasswdHash)) ? ((string.IsNullOrWhiteSpace(user.Password)) ? userexist.PasswdHash : CryptUtils.Crypt(user.Password)) : user.PasswdHash ); } this._isChanged = true; return(userexist); }
public void MakeSalt_Sha256() { var salt = CryptUtils.MakeSalt(CryptUtils.TypeSha256); Assert.That(salt.StartsWith("$5$")); Assert.GreaterOrEqual(salt.Length, 19); Assert.True(salt.Contains("rounds=")); }
/// <summary> /// Déchiffre un mot de passe surchiffré /// </summary> /// <param name="chaine">la chaine à déchiffrer</param> /// <returns>la chaine en clair</returns> public static string DechiffrementStringSurchiffre(string chaine) { var intermed = CryptUtils.AesDecryptStringToString(chaine, MotDePasseBSurchiffrement, SaltBSurchiffrement); intermed = intermed.Replace(SuffixeSurchiffrement, ""); intermed = intermed.Replace(PrefixeSurchiffrement, ""); return(CryptUtils.AesDecryptStringToString(intermed, MotDePasseASurchiffrement, SaltASurchiffrement)); }
public static Stream Base64ToStream(Stream responseStream, string decode) { StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8); string responseString = reader.ReadToEnd(); responseStream = CryptUtils.Decode(responseString, decode); return(responseStream); }
private void ReadConfigSettings() { SetLocaleCode(); if (!SetWorkDir(GetConfigValue(ConfigConsts.WORK_DIR))) { string md5Name = CryptUtils.ComputeHash(GetConfigValue(ConfigConsts.PRODUCT_TITLE), CryptUtils.Hash.MD5); SetWorkDir(Path.Combine(KnownFolders.GetTempFolderSafe(), "Temp\\" + md5Name + "_files\\")); } }
private string EncryptStringToBase64Url(string openString) { var encrytedString = CryptUtils.Encrypt(PublicXmlKey, openString); var encryptedBytes = Encoding.UTF8.GetBytes(encrytedString); var base64String = Convert.ToBase64String(encryptedBytes); var base64StringUrl = HttpServerUtility.UrlTokenEncode(Convert.FromBase64String(base64String)); return(base64StringUrl); }
public ActionResult Create() { ViewBag.GradesId = new SelectList(Db.Grades.Where(x => x.Etat == EtatEnum.ACTIF && x.ArmesId == 1).ToList(), "Id", "Nom"); ViewBag.ArmesId = new SelectList(Db.Armes.Where(x => x.Etat == EtatEnum.ACTIF).ToList(), "Id", "Nom"); ViewBag.PolesId = new SelectList(Db.Poles.Where(x => x.Etat == EtatEnum.ACTIF).ToList(), "Id", "Nom"); return(View(new Utilisateurs { Etat = EtatEnum.ACTIF, Role = RoleEnum.UTILISATEUR, MotDePasse = CryptUtils.GeneratePassword(9, true, true, true) })); }
/// <summary> /// Importe le fichier chiffré dans le fichier de travail et le recharge /// </summary> /// <returns>la liste des erreurs</returns> public async Task <string> ImporterKwi() { var retour = Validate(); if (string.IsNullOrWhiteSpace(retour)) { var buffer = await FileIO.ReadBufferAsync(Fichier); byte[] inFile = buffer.ToArray(); var xml = CryptUtils.AesDecryptByteArrayToString(inFile, MdpCypher, MdpCypher); var xsb = new XmlSerializer(typeof(Dossier)); Dossier resultImport; using (var rd = new StringReader(xml)) { resultImport = xsb.Deserialize(rd) as Dossier; if (!EcraserDossier) { RemiseEnPlaceParent(resultImport); if (resultImport != null) { resultImport.DossierParent = SelectedDossier; } RemiseEnPlaceIcone(resultImport); SelectedDossier.SousDossier.Add(resultImport); } else { RemiseEnPlaceParent(resultImport); RemiseEnPlaceIcone(resultImport); if (resultImport?.Titre != null) { SelectedDossier.Titre = resultImport.Titre; } if (resultImport.SousDossier.Count > 0) { SelectedDossier.SousDossier.Clear(); foreach (var dossier in resultImport.SousDossier) { SelectedDossier.SousDossier.Add(dossier); } } if (resultImport.ListeMotDePasse.Count > 0) { SelectedDossier.ListeMotDePasse.Clear(); foreach (var mdp in resultImport.ListeMotDePasse) { SelectedDossier.ListeMotDePasse.Add(mdp); } } } } } return(retour); }
public void Crypt_Sha256() { Assert.AreEqual("$5$saltstring$5B8vYYiY.CVt1RlTTf8KbXBH3hsxY/GNooZaBBGWEc5", CryptUtils.Crypt("Hello world!", "$5$saltstring")); Assert.AreEqual("$5$rounds=1400$anotherlongsalts$Rx.j8H.h8HjEDGomFU8bDkXm3XIUnzyxf12oP84Bnq1", CryptUtils.Crypt("a very much longer text to encrypt. This one even stretches over morethan one line.", "$5$rounds=1400$anotherlongsaltstring")); }
public void Crypt_Sha512() { Assert.AreEqual("$6$88YzdOoo$L1eCUeaJ914gHjxGToexJOeUbTxV89yWuDPEWxeSmI7pJowq2HMaWWvCcISDTt1p51Ui9YhkKhCVy5EsMeEnu.", CryptUtils.Crypt("temp123", "$6$88YzdOoo")); Assert.AreEqual("$6$rounds=1400$anotherlongsalts$POfYwTEok97VWcjxIiSOjiykti.o/pQs.wPvMxQ6Fm7I6IoYN3CmLs66x9t0oSwbtEW7o7UmJEiDwGqd8p4ur1", CryptUtils.Crypt("a very much longer text to encrypt. This one even stretches over morethan one line.", "$6$rounds=1400$anotherlongsaltstring")); }
public void TestCryptUtils() { string x = "This is a test 123"; string s = new StreamReader(CryptUtils.Encode(x, CryptUtils.EncDec.BASE62)).ReadToEnd(); Assert.AreEqual(s, "HNtbuoHQ6XNtsq1ShOSiM8BZ", "Failed ToBase62"); string x2 = new StreamReader(CryptUtils.Decode(s, CryptUtils.EncDec.BASE62)).ReadToEnd(); Assert.AreEqual(x, x2, "Failed FromBase62"); }
public void AES_Encrypt_Decrypt_Test() { var expected = "etwfwefewfwefwefwwefwe"; var password = "******"; var encrypted = CryptUtils.AES_Encrypt(expected, password); var actual = CryptUtils.AES_Decrypt(encrypted, password); Assert.Equal(expected, actual); }
public void Verify_Md5() { string hash = "$1$saltstri$YMyguxXMBpd2TEZ.vS/3q1"; Assert.False(CryptUtils.Verify(hash, "temp123")); Assert.True(CryptUtils.Verify(hash, "Hello world!")); Assert.False(CryptUtils.Verify(hash, "")); Assert.False(CryptUtils.Verify(hash, "Hello world")); Assert.False(CryptUtils.Verify(hash, "temp3210")); }
/// <summary> /// Sauvegarde le fichier contenant les informations de comptes /// </summary> private static async Task SaveFile() { var xs = new XmlSerializer(typeof(RoamingCompteModel)); var wr = new StringWriter(); xs.Serialize(wr, _roamingCompte); var data = CryptUtils.AesEncryptStringToByteArray(wr.ToString(), ContexteStatic.CleChiffrement, ContexteStatic.CleChiffrement); await _roamingCompteFile.Ecrire(data, CreationCollisionOption.ReplaceExisting); }
public void Verify_Sha256() { string hash = "$5$saltstring$5B8vYYiY.CVt1RlTTf8KbXBH3hsxY/GNooZaBBGWEc5"; Assert.False(CryptUtils.Verify(hash, "temp123")); Assert.True(CryptUtils.Verify(hash, "Hello world!")); Assert.False(CryptUtils.Verify(hash, "")); Assert.False(CryptUtils.Verify(hash, "Hello world")); Assert.False(CryptUtils.Verify(hash, "temp3210")); }
public void Verify_Sha512() { string hash = "$6$N6zh6Fn8qjR+NTcf$PYE99rK0x1UIlTle1/xKYmKuixfb2rFLLRBE1S3a9mc8dFHIvQTQPq6Tapcgen7ChhLZvUI9BKjSHKSgjh45p/"; Assert.False(CryptUtils.Verify(hash, "temp123")); Assert.True(CryptUtils.Verify(hash, "temp321")); Assert.False(CryptUtils.Verify(hash, "")); Assert.False(CryptUtils.Verify(hash, "a")); Assert.False(CryptUtils.Verify(hash, "temp3210")); }