public void HashAndValidateTest() { IHasher hasher = new Hasher(); const string unhashed = "44************23"; string hashed = hasher.Hash(unhashed); Assert.IsTrue(hasher.Verify(hashed, unhashed)); }
public void CalculateMd5Etag_FileInfo_HashedString() { //Arrange var retryableFileOpener = MockRepository.GenerateMock<IRetryableFileOpener>(); var text = "This is a test"; var md5HashOfText = "zhFORQHS9OLc6j4XtUbzOQ=="; //Hash value of bytes var byteArray = Encoding.ASCII.GetBytes(text); var stream = new MemoryStream(byteArray); var fileName = "test.txt"; var fileInfo = new FileInfo(fileName); var fileStream = MockRepository.GenerateMock<FileStream>(); retryableFileOpener.Expect(x => x.OpenFileStream(fileInfo, 5, FileMode.Open, FileAccess.Read, FileShare.Read)).Return(fileStream); Func<byte[], int, int, int> read = stream.Read; fileStream.Stub(x => x.Read(null, 0, 0)).IgnoreArguments().Do(read); //Act var hasher = new Hasher(retryableFileOpener); var md5Hash = hasher.CalculateMd5Etag(fileInfo); //Assert Assert.AreEqual(md5HashOfText, md5Hash); }
private CrusherManager() { var crusherConfiguration = CurrentCrusherConfiguration.Current; _hashQueryStringKeyName = crusherConfiguration.QuerystringKeyName; _cssGroups = crusherConfiguration.CssGroups; _jsGroups = crusherConfiguration.JsGroups; var retryableFileOpener = new RetryableFileOpener(); var hasher = new Hasher(retryableFileOpener); var retryableFileWriter = new RetryableFileWriter(BufferSize, _encoding, retryableFileOpener, hasher); _pathProvider = new PathProvider(); var cssAssetsFileHasher = new CssAssetsFileHasher(_hashQueryStringKeyName, hasher, _pathProvider); var cssPathRewriter = new CssPathRewriter(cssAssetsFileHasher, _pathProvider); var cacheManager = new HttpCacheManager(); var jsSpriteMetaDataFileInfo = new FileInfo("js.metadata"); var jsMetaData = new SingleFileMetaData(jsSpriteMetaDataFileInfo, retryableFileOpener, retryableFileWriter); var cssSpriteMetaDataFileInfo = new FileInfo("css.metadata"); var cssMetaData = new SingleFileMetaData(cssSpriteMetaDataFileInfo, retryableFileOpener, retryableFileWriter); _cssCrusher = new CssCrusher(cacheManager, _pathProvider, retryableFileOpener, retryableFileWriter, cssPathRewriter, cssMetaData, crusherConfiguration.WatchAssets); _jsCrusher = new JsCrusher(cacheManager, _pathProvider, retryableFileOpener, retryableFileWriter, jsMetaData); InitManager(); }
public void HashTest() { const string unhashed = "Hello"; IHasher hasher = new Hasher(); string firstHashed = hasher.Hash(unhashed), secondHashed = hasher.Hash(unhashed); Assert.AreNotEqual(firstHashed, secondHashed); Assert.IsTrue(hasher.Verify(firstHashed, unhashed)); Assert.IsTrue(hasher.Verify(secondHashed, unhashed)); }
public void FromFile_EmptyFile_Md5() { var hasher = new Hasher(); var hash1 = hasher.FromFile(TempFile, HashType.Md5); var hash2 = hasher.FromFile(TempFile, new MD5CryptoServiceProvider()); Assert.IsTrue(hash1 == "d41d8cd98f00b204e9800998ecf8427e"); Assert.IsTrue(hash2 == "d41d8cd98f00b204e9800998ecf8427e"); }
public void FromFile_EmptyFile_Sha256() { var hasher = new Hasher(); var hash1 = hasher.FromFile(TempFile, HashType.Sha256); var hash2 = hasher.FromFile(TempFile, new SHA256CryptoServiceProvider()); Assert.IsTrue(hash1 == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); Assert.IsTrue(hash2 == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); }
public void FromFile_EmptyFile_Sha1() { var hasher = new Hasher(); var hash1 = hasher.FromFile(TempFile, HashType.Sha1); var hash2 = hasher.FromFile(TempFile, new SHA1CryptoServiceProvider()); Assert.IsTrue(hash1 == "da39a3ee5e6b4b0d3255bfef95601890afd80709"); Assert.IsTrue(hash2 == "da39a3ee5e6b4b0d3255bfef95601890afd80709"); }
private CssSpriteManager() { var retryableFileOpener = new RetryableFileOpener(); var hasher = new Hasher(retryableFileOpener); var retryableFileWriter = new RetryableFileWriter(BufferSize, retryableFileOpener, hasher); _pathProvider = new PathProvider(); _cssSpriteCreator = new CssSpriteCreator(retryableFileOpener, hasher, retryableFileWriter); InitManager(); }
private CrusherManager() { var retryableFileOpener = new RetryableFileOpener(); var hasher = new Hasher(retryableFileOpener); var retryableFileWriter = new RetryableFileWriter(BufferSize, retryableFileOpener, hasher); _pathProvider = new PathProvider(); var cssAssetsFileHasher = new CssAssetsFileHasher(_hashQueryStringKeyName, hasher, _pathProvider); var cssPathRewriter = new CssPathRewriter(cssAssetsFileHasher, _pathProvider); _cssCrusher = new CssCrusher(retryableFileOpener, retryableFileWriter, cssPathRewriter, _pathProvider); _jsCrusher = new JsCrusher(retryableFileOpener, retryableFileWriter, _pathProvider); InitManager(); }
private CssSpriteManager() { var retryableFileOpener = new RetryableFileOpener(); var hasher = new Hasher(retryableFileOpener); var retryableFileWriter = new RetryableFileWriter(BufferSize, _encoding, retryableFileOpener, hasher); var cacheManager = new HttpCacheManager(); _pathProvider = new PathProvider(); var cssSpriteMetaDataFileInfo = new FileInfo("cssSprite.metadata"); _cssSpriteMetaData = new SingleFileMetaData(cssSpriteMetaDataFileInfo, retryableFileOpener, retryableFileWriter); _cssSpriteCreator = new CssSpriteCreator(cacheManager, retryableFileOpener, _pathProvider, retryableFileWriter, _cssSpriteMetaData); InitManager(); }
public void FileNameHashTest(string filename) { var result = new Hasher().GetHash(filename); var result2 = new Hasher().GetHash(filename); var result3 = new Hasher().GetHash(filename+'\0'); Console.WriteLine(result); // первое требование - хэш должен быть Assert.False(string.IsNullOrWhiteSpace(result)); // второе требование - хэш должен иметь фиксированный размер Assert.AreEqual(Const.MaxHashSize,result.Length); // третье требование - хэш должен быть совместим с файловой системой Assert.True(result.All(char.IsLetterOrDigit)); // четвертое требование - хэш должен быть воспроизводимым Assert.AreEqual(result,result2); // пятое требование - хэш должен уникальным Assert.AreNotEqual(result, result3); }
public void CalculateMd5Etag_Stream_HashedString() { //Arrange var retryableFileOpener = MockRepository.GenerateMock<IRetryableFileOpener>(); var text = "This is a test"; var md5HashOfText = "zhFORQHS9OLc6j4XtUbzOQ=="; //Hash value of bytes var byteArray = Encoding.ASCII.GetBytes(text); var stream = new MemoryStream(byteArray); //Act var hasher = new Hasher(retryableFileOpener); var md5Hash = hasher.CalculateMd5Etag(stream); //Assert Assert.AreEqual(md5HashOfText, md5Hash); }
public void Checksum01(string url_or_path, Hasher type, string hash) { Uri uri; if (url_or_path.StartsWith(".")) { var path = url_or_path; uri = new Uri(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase), path); } else { var url = url_or_path; uri = new Uri(url); } var h = uri.Checksum(type); Console.WriteLine(h); Assert.AreEqual(hash, h); }
/// <summary> /// Calculate checksum / hash (sha1 or md5) for uri (url or local file). /// <para> /// hash: sha1 20 bytes, md5 hash 16 bytes /// </para> /// </summary> /// <param name="uri">uri (url or local file).</param> /// <param name="type">Hasher.sha1 or Hasher.md5.</param> /// <returns>hash</returns> /// <remarks>http://hash.online-convert.com/</remarks> public static string Checksum(this Uri uri, Hasher type = Hasher.sha1) { uri.ThrowIfArgumentNull(nameof(uri)); switch (type) { case Hasher.sha1: using (var hasher = new SHA1CryptoServiceProvider()) { return Checksum(hasher, uri); } case Hasher.md5: using (var hasher = MD5.Create()) { return Checksum(hasher, uri); } default: throw new ArgumentOutOfRangeException("Unknown hash algorithm type."); } }
private CrusherManager() { var crusherConfiguration = CurrentCrusherConfiguration.Current; _hashQueryStringKeyName = crusherConfiguration.QuerystringKeyName; _cssGroups = crusherConfiguration.CssGroups; _jsGroups = crusherConfiguration.JsGroups; var retryableFileOpener = new RetryableFileOpener(); var hasher = new Hasher(retryableFileOpener); var retryableFileWriter = new RetryableFileWriter(BufferSize, retryableFileOpener, hasher); _pathProvider = new PathProvider(); var cssAssetsFileHasher = new CssAssetsFileHasher(_hashQueryStringKeyName, hasher, _pathProvider); var cssPathRewriter = new CssPathRewriter(cssAssetsFileHasher, _pathProvider); _cacheManager = new HttpCacheManager(); _cssCrusher = new CssCrusher(_cacheManager, _pathProvider, retryableFileOpener, retryableFileWriter, cssPathRewriter); _jsCrusher = new JsCrusher(_cacheManager, _pathProvider, retryableFileOpener, retryableFileWriter); InitManager(); }
public void ConsistentBasicHash() { var hasher = new Hasher(); var hasher2 = new Hasher(); Assert.DoesNotThrow(() => { hasher. Combine(1). Combine(2). Combine(8). Combine(null as string). Combine(9). Combine(7). Combine("hello"). Combine("HELLO"); hasher2. Combine(1). Combine(2). Combine(8). Combine(null as string). Combine(9). Combine(7). Combine("hello"). Combine("HELLO"); }); Assert.Equal(hasher.Hash(), hasher2.Hash()); hasher = new Hasher(); hasher2 = new Hasher(); Assert.DoesNotThrow(() => { hasher. Combine(1). Combine(2); hasher2. Combine(2). Combine(1); }); Assert.NotEqual(hasher.Hash(), hasher2.Hash()); }
public void BasicHash() { int hash = 0; int oldHash = 0; var hasher = new Hasher(); oldHash = hasher.Hash(); Assert.DoesNotThrow(() => hasher.Combine(5)); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); oldHash = hash; Assert.DoesNotThrow(() => hasher.Combine(5)); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); oldHash = hash; Assert.DoesNotThrow(() => hasher.Combine(null as string)); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); }
public void ComparerHash() { int hash = 0; int oldHash = 0; var hasher = new Hasher(); oldHash = hasher.Hash(); Assert.DoesNotThrow(() => hasher.Combine(null as string, StringComparer.InvariantCultureIgnoreCase)); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); oldHash = hash; Assert.DoesNotThrow(() => hasher.Combine(null as string, StringComparer.InvariantCultureIgnoreCase)); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); oldHash = hash; Assert.DoesNotThrow(() => hasher.Combine("hello", StringComparer.InvariantCultureIgnoreCase)); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); }
public Key(string name) { Name = name; _hashCode = Hasher.Hash(name); }
public void ConsistentComparerHash() { var hasher = new Hasher(); var hasher2 = new Hasher(); Assert.DoesNotThrow(() => { hasher. Combine(null as string, StringComparer.InvariantCultureIgnoreCase). Combine("hello", StringComparer.InvariantCultureIgnoreCase). Combine("HELLO", StringComparer.InvariantCultureIgnoreCase); hasher2. Combine(null as string, StringComparer.InvariantCultureIgnoreCase). Combine("hello", StringComparer.InvariantCultureIgnoreCase). Combine("hello", StringComparer.InvariantCultureIgnoreCase); }); Assert.Equal(hasher.Hash(), hasher2.Hash()); hasher = new Hasher(); hasher2 = new Hasher(); Assert.DoesNotThrow(() => { hasher. Combine("hello", StringComparer.InvariantCultureIgnoreCase). Combine(null as string, StringComparer.InvariantCultureIgnoreCase). Combine("HELLO", StringComparer.InvariantCultureIgnoreCase); hasher2. Combine(null as string, StringComparer.InvariantCultureIgnoreCase). Combine("hello", StringComparer.InvariantCultureIgnoreCase). Combine("hello", StringComparer.InvariantCultureIgnoreCase); }); Assert.NotEqual(hasher.Hash(), hasher2.Hash()); }
public void Submit(RetainedGizmos gizmos, Hasher hasher) { SubmitLines(gizmos, hasher.Hash); SubmitMeshes(gizmos, hasher.Hash); }
/** Schedules the meshes for the specified hash to be drawn. * \returns False if there is no cached mesh for this hash, you may want to * submit one in that case. The draw command will be issued regardless of the return value. */ public bool Draw(Hasher hasher) { usedHashes.Add(hasher.Hash); return(HasCachedMesh(hasher)); }
// POST: api/Empleados public HttpResponseMessage Post([FromBody] Empleados value) { if (this.Request.Headers.Authorization != null) { if (TokenManager.ValidateToken(this.Request.Headers.Authorization.Parameter)) { if (value.Usuario != null && value.Contrasenia != null) { HashSalt hashSalt = Hasher.GenerateSaltedHash(32, value.Contrasenia); value.Contrasenia = hashSalt.Hash; value.Contrasenia_Salt = hashSalt.Salt; dbAlmacen.Empleados.Add(value); dbAlmacen.SaveChanges(); value.Contrasenia = null; value.Contrasenia_Salt = null; return(Request.CreateResponse(HttpStatusCode.OK, new ReturnMessageJson( "success", "11", value, "User saved succesfully." ))); } else { value.Usuario = null; value.Contrasenia = null; dbAlmacen.Empleados.Add(value); dbAlmacen.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, new ReturnMessageJson( "success", "11", value, "User saved succesfully." ))); } } else { return(Request.CreateResponse(HttpStatusCode.NotFound, new ReturnMessageJson( "fail", "-1", null, "Not authorized." ))); } } else { return(Request.CreateResponse(HttpStatusCode.NotFound, new ReturnMessageJson( "fail", "-1", null, "Not authorized." ))); } }
/// <summary> /// 编译文件 /// </summary> /// <param name="path">脚本ID</param> /// <param name="forceCompile">是否强制重新编译</param> /// <returns>发生变化的文件列表</returns> public static IEnumerable <string> CompileAsset(string path, bool forceCompile = false) { if (!Application.isEditor) { throw new NotSupportedException($"Cannot compile {path}: static file compiler can only run in editor mode"); } if (!path.EndsWith(".vns")) { throw new NotSupportedException($"Cannot compile {path}: file name extension must be .vns"); } var option = ScriptInformation.CreateInformationFromAsset(path); if (option == null) { throw new NullReferenceException($"Cannot compile {path}: target outside of source folder or target is not acceptable script/binary"); } var changedFiles = new List <string>(); var source = File.ReadAllText(path, Encoding.UTF8).UnifyLineBreak(); if (!option.hash.HasValue) { option.hash = Hasher.Crc32(Encoding.UTF8.GetBytes(source)); } var identifier = new CodeIdentifier { Id = option.id, Hash = option.hash.Value }; // 编译文件 if (!forceCompile) { if (option.recordedHash.HasValue && option.recordedHash.Value == identifier.Hash) { return(new string[] { }); // 如果源代码内容没有变化则直接跳过编译 } } var(content, defaultTranslation) = CompileCode(source, identifier); var binaryFile = option.BinaryAssetPath(); File.WriteAllBytes(binaryFile, content); option.recordedHash = option.hash = identifier.Hash; changedFiles.Add(binaryFile); // 处理其他翻译 foreach (var(language, _) in option.Translations) { var languageFile = option.LanguageAssetPath(language); if (File.Exists(languageFile)) { var existedTranslation = new ScriptTranslation(File.ReadAllText(languageFile)); if (!existedTranslation.MergeWith(defaultTranslation)) { continue; } existedTranslation.SaveToAsset(languageFile); changedFiles.Add(languageFile); } else { // 如果翻译不存在,以默认翻译为蓝本新建翻译文件 defaultTranslation.SaveToAsset(languageFile); changedFiles.Add(languageFile); } } CompileConfiguration.Save(); return(changedFiles); }
public CompressingBlockAction(Hasher.Hasher hasher) { this.hasher = hasher; }
// PUT: api/Empleados/5 public HttpResponseMessage Put(int id, [FromBody] Empleados value) { if (this.Request.Headers.Authorization != null) { if (TokenManager.ValidateToken(this.Request.Headers.Authorization.Parameter)) { Empleados empleadoToModify = dbAlmacen.Empleados.Find(id); if (value.Contrasenia != null) { empleadoToModify.Nombre = value.Nombre; empleadoToModify.DPI = value.DPI; empleadoToModify.Cantidad_Hijos = value.Cantidad_Hijos; empleadoToModify.Salario_Base = value.Salario_Base; empleadoToModify.Fecha_Nacimiento = value.Fecha_Nacimiento; empleadoToModify.Bono_Decreto = value.Bono_Decreto; empleadoToModify.Email = value.Email; empleadoToModify.Usuario = value.Usuario; HashSalt hashSalt = Hasher.GenerateSaltedHash(32, value.Contrasenia); empleadoToModify.Contrasenia = hashSalt.Hash; empleadoToModify.Contrasenia_Salt = hashSalt.Salt; dbAlmacen.Entry(empleadoToModify).State = EntityState.Modified; dbAlmacen.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, new ReturnMessageJson( "success", "13", empleadoToModify, "User modified succesfully." ))); } else { empleadoToModify.Nombre = value.Nombre; empleadoToModify.DPI = value.DPI; empleadoToModify.Cantidad_Hijos = value.Cantidad_Hijos; empleadoToModify.Salario_Base = value.Salario_Base; empleadoToModify.Fecha_Nacimiento = value.Fecha_Nacimiento; empleadoToModify.Bono_Decreto = value.Bono_Decreto; empleadoToModify.Email = value.Email; empleadoToModify.Usuario = value.Usuario; dbAlmacen.Entry(empleadoToModify).State = EntityState.Modified; dbAlmacen.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, new ReturnMessageJson( "success", "13", empleadoToModify, "User modified succesfully." ))); } } else { return(Request.CreateResponse(HttpStatusCode.NotFound, new ReturnMessageJson( "fail", "-1", null, "Not authorized." ))); } } else { return(Request.CreateResponse(HttpStatusCode.NotFound, new ReturnMessageJson( "fail", "-1", null, "Not authorized." ))); } }
public void change_password() { var author = new Author() { Email = "*****@*****.**", HashedPassword = Hasher.GetMd5Hash("mzblog") }; _db.Insert(DBTableNames.Authors, author); new ChangePasswordCommandInvoker(_db) .Execute(new ChangePasswordCommand() { AuthorId = author.Id, OldPassword = "******", NewPassword = "******", NewPasswordConfirm = "pswtest" }) .Success.Should().BeTrue(); _db.SelectKey <Author>(DBTableNames.Authors, author.Id).HashedPassword.Should().BeEquivalentTo(Hasher.GetMd5Hash("pswtest")); }
protected async Task <PhishingToken> ValidateAsync(LoginDetails loginDetails) { AddLoginHeaders(); HttpClient.AddRequestHeader(NonStandardHttpHeaders.NucleusId, LoginResponse.Persona.NucUserId); HttpClient.AddRequestHeader(NonStandardHttpHeaders.SessionId, LoginResponse.AuthData.Sid); var validateResponseMessage = await HttpClient.GetAsync(String.Format(Resources.ValidateQuestion, DateTime.Now.ToUnixTime())); validateResponseMessage = await HttpClient.PostAsync(String.Format(Resources.ValidateAnswer, Hasher.Hash(loginDetails.SecretAnswer)), new FormUrlEncodedContent( new[] { new KeyValuePair <string, string>("answer", Hasher.Hash(loginDetails.SecretAnswer)) })); var phishingToken = await DeserializeAsync <PhishingToken>(validateResponseMessage); var validateResponseMessageContent = await validateResponseMessage.Content.ReadAsStringAsync(); if (phishingToken.Code != "200" || phishingToken.Token == null) { throw new Exception($"Unable to get Phishing Token {LoginDetails?.AppVersion}."); } return(phishingToken); }
internal static string GetLookupKey(string connectionString, string identifier) { string key = Hasher.GetFnvHash32AsString(connectionString) + "$" + identifier; return(key); }
private static string Hash(Hasher hasher, FileInfo info) { using (var stream = info.OpenRead()) return(hasher.ComputeHashS(stream).ToLowerInvariant()); }
protected void ViewInfo(object sender, EventArgs e) { Random intt = new Random(); Response.Redirect("Information?security=" + Hasher.SILICON64(intt.Next(0, 10).ToString()) + Hasher.SILICON64(intt.Next(11, 20).ToString()) + "&reference=" + "22" + "&type?=_SECURITY_CHECK"); }
/// <summary> /// Returns the salted version of a user password. /// </summary> /// <param name="name">Name of the user.</param> /// <param name="pass">Hash of the user's password (without salt).</param> /// <returns></returns> public static string GetSaltedHash(string name, string pass) { pass = string.Concat(name, pass); return(Hasher.CreatePasswordHash(pass)); }
protected void GridWithHeld_SelectedIndexChanged(object sender, EventArgs e) { try { connect.Open(); string id = GridWithHeld.SelectedRow.Cells[0].Text.ToString(); string qerr = "select usn1 from userdetails where ID=" + id; MySqlCommand SqlProcess2 = new MySqlCommand(qerr, connect); MySqlDataReader reader = SqlProcess2.ExecuteReader(); reader.Read(); Session["DeletionID"] = id; string email = reader[0].ToString() + "@bmsit.in"; Session["DeletionEmail"] = email.ToLower(); reader.Close(); connect.Close(); Random intt = new Random(); Response.Redirect("~/ConfirmDelete?security=" + Hasher.SILICON64(intt.Next(0, 10).ToString()) + Hasher.SILICON64(intt.Next(11, 20).ToString()) + "&reference=" + "22" + "&type?=_SECURITY_CHECK"); } catch (MySqlException Err) { RookErrorHandler("Unhandeled Error!", Err.Message); } catch (Exception Ex) { RookErrorHandler("Unhandeled Error!", Ex.Message); } }
private string SmsLoginUrl(AccountLinkControl accountLinkControl) { if (!StudioSmsNotificationSettings.IsVisibleSettings || !StudioSmsNotificationSettings.Enable) { return(string.Empty); } UserInfo user; if (string.IsNullOrEmpty(HashId)) { user = CoreContext.UserManager.GetUsers(TenantProvider.CurrentTenantID, Login, Hasher.Base64Hash(Password, HashAlg.SHA256)); } else { Guid userId; TryByHashId(accountLinkControl, HashId, out userId); user = CoreContext.UserManager.GetUsers(userId); } if (Constants.LostUser.Equals(user)) { throw new InvalidCredentialException(); } return(Studio.Confirm.SmsConfirmUrl(user)); }
public IEnumerable <Tenant> GetTenants(string login, string passwordHash) { if (string.IsNullOrEmpty(login)) { throw new ArgumentNullException("login"); } IQueryable <TenantUserSecurity> query() => TenantsQuery() .Where(r => r.Status == TenantStatus.Active) .Join(TenantDbContext.Users, r => r.Id, r => r.Tenant, (tenant, user) => new { tenant, user }) .Join(TenantDbContext.UserSecurity, r => r.user.Id, r => r.UserId, (tenantUser, security) => new TenantUserSecurity { DbTenant = tenantUser.tenant, User = tenantUser.user, UserSecurity = security }) .Where(r => r.User.Status == EmployeeStatus.Active) .Where(r => r.DbTenant.Status == TenantStatus.Active) .Where(r => r.User.Removed == false); if (passwordHash == null) { var q = query() .Where(r => login.Contains('@') ? r.User.Email == login : r.User.Id.ToString() == login); return(q.Select(FromTenantUserToTenant).ToList()); } if (Guid.TryParse(login, out var userId)) { var pwdHash = GetPasswordHash(userId, passwordHash); var oldHash = Hasher.Base64Hash(passwordHash, HashAlg.SHA256); var q = query() .Where(r => r.User.Id == userId) .Where(r => r.UserSecurity.PwdHash == pwdHash || r.UserSecurity.PwdHash == oldHash) //todo: remove old scheme ; return(q.Select(FromTenantUserToTenant).ToList()); } else { var oldHash = Hasher.Base64Hash(passwordHash, HashAlg.SHA256); var q = query() .Where(r => r.UserSecurity.PwdHash == oldHash); if (login.Contains('@')) { q = q.Where(r => r.User.Email == login); } else if (Guid.TryParse(login, out var uId)) { q = q.Where(r => r.User.Id == uId); } //old password var result = q.Select(FromTenantUserToTenant).ToList(); var usersQuery = TenantDbContext.Users .Where(r => r.Email == login) .Where(r => r.Status == EmployeeStatus.Active) .Where(r => !r.Removed) .Select(r => r.Id) .ToList(); var passwordHashs = usersQuery.Select(r => GetPasswordHash(r, passwordHash)).ToList(); q = query() .Where(r => passwordHashs.Any(p => r.UserSecurity.PwdHash == p)); //new password result = result.Concat(q.Select(FromTenantUserToTenant)).ToList(); result.Distinct(); return(result); } }
/** True if there already is a mesh with the specified hash */ public bool HasCachedMesh(Hasher hasher) { return(existingHashes.Contains(hasher.Hash)); }
public void TestHasher() { var data = new byte[240]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)i; } var seen32 = new HashSet <uint>(); var seen64 = new HashSet <ulong>(); var hasher = Hasher.Create(); for (int len = 1; len < data.Length; len++) { hasher.Reset(); hasher.Add(data.AsSpan(0, len)); var h32 = hasher.Finalize32(); Assert.IsFalse(seen32.Contains(h32)); hasher.Reset(); hasher.Add(data.AsSpan(0, len)); var h64 = hasher.Finalize64(); Assert.IsFalse(seen64.Contains(h64)); } { hasher.Reset(); hasher.Add("abc"); var one = hasher.Finalize64(); hasher.Reset(); hasher.AddLower("AbC"); var two = hasher.Finalize64(); Assert.AreEqual(one, two); } { hasher.Reset(); hasher.Add((byte)1); hasher.Add((byte)2); var one = hasher.Finalize64(); hasher.Reset(); hasher.Add((byte)2); hasher.Add((byte)1); var two = hasher.Finalize64(); Assert.AreNotEqual(one, two); } { var hashes = new HashSet <ulong>(); foreach (var word in s_words) { var h = HashUtil.FNV1a(word); var added = hashes.Add(h); Assert.IsTrue(added); } } { var hashes = new HashSet <ulong>(); foreach (var word in s_words) { var h = HashUtil.Hash32(word); var added = hashes.Add(h); Assert.IsTrue(added); } } { var hashes = new HashSet <ulong>(); foreach (var word in s_words) { var h = HashUtil.Hash64(word); var added = hashes.Add(h); Assert.IsTrue(added); } } { var hashes = new HashSet <ulong>(); foreach (var word in s_words) { var bytes = System.Text.Encoding.UTF8.GetBytes(word); var h = HashUtil.FNV1a64(bytes); var added = hashes.Add(h); Assert.IsTrue(added); } } }
public IEnumerable <Tenant> GetTenants(string login, string passwordHash) { if (string.IsNullOrEmpty(login)) { throw new ArgumentNullException("login"); } if (passwordHash == null) { var q = TenantsQuery(Exp.Empty) .InnerJoin("core_user u", Exp.EqColumns("t.id", "u.tenant")) .InnerJoin("core_usersecurity s", Exp.EqColumns("u.id", "s.userid")) .Where("t.status", (int)TenantStatus.Active) .Where(login.Contains('@') ? "u.email" : "u.id", login) .Where("u.status", EmployeeStatus.Active) .Where("u.removed", false); return(ExecList(q).ConvertAll(ToTenant)); } Guid userId; if (Guid.TryParse(login, out userId)) { var q = TenantsQuery(Exp.Empty) .InnerJoin("core_user u", Exp.EqColumns("t.id", "u.tenant")) .InnerJoin("core_usersecurity s", Exp.EqColumns("u.id", "s.userid")) .Where("t.status", (int)TenantStatus.Active) .Where("u.id", userId) .Where("u.status", EmployeeStatus.Active) .Where("u.removed", false) .Where(Exp.Or( Exp.Eq("s.pwdhash", GetPasswordHash(userId, passwordHash)), Exp.Eq("s.pwdhash", Hasher.Base64Hash(passwordHash, HashAlg.SHA256)) //todo: remove old scheme )); return(ExecList(q).ConvertAll(ToTenant)); } else { var q = TenantsQuery(Exp.Empty) .InnerJoin("core_user u", Exp.EqColumns("t.id", "u.tenant")) .InnerJoin("core_usersecurity s", Exp.EqColumns("u.id", "s.userid")) .Where("t.status", (int)TenantStatus.Active) .Where(login.Contains('@') ? "u.email" : "u.id", login) .Where("u.status", EmployeeStatus.Active) .Where("u.removed", false) .Where("s.pwdhash", Hasher.Base64Hash(passwordHash, HashAlg.SHA256)); //old password var result = ExecList(q).ConvertAll(ToTenant); var usersQuery = new SqlQuery("core_user u") .Select("u.id") .Where("u.email", login) .Where("u.status", EmployeeStatus.Active) .Where("u.removed", false); var passwordHashs = ExecList(usersQuery).ConvertAll(r => GetPasswordHash(new Guid((string)r[0]), passwordHash) ); q = TenantsQuery(Exp.Empty) .InnerJoin("core_usersecurity s", Exp.EqColumns("t.id", "s.tenant")) .Where(Exp.In("s.pwdhash", passwordHashs)); //new password result = result.Concat(ExecList(q).ConvertAll(ToTenant)).ToList(); result.Distinct(); return(result); } }
public override Stream OpenFile(string name) => OpenFile(Hasher.ComputeHash(name));
public async Task <string> GetHash(string name) { var bytes = await GetConfiguration(name); return(Hasher.CreateHash(bytes)); }
/// <summary> /// /// </summary> /// <returns></returns> public byte[] ToHash() { return(Hasher.Hash(ToStream()).HexToByte()); }
public void ConsistentEnumerableHash() { var hasher = new Hasher(); var hasher2 = new Hasher(); Assert.DoesNotThrow(() => { hasher. Combine(new List<int>() { 1, 2, 3, 4, 5 }). Combine(null). Combine(8). Combine(new List<int>() { 5, 4, 3, 2, 1 }); hasher2. Combine(new List<int>() { 1, 2, 3, 4, 5 }). Combine(null). Combine(8). Combine(new List<int>() { 5, 4, 3, 2, 1 }); }); Assert.Equal(hasher.Hash(), hasher2.Hash()); hasher = new Hasher(); hasher2 = new Hasher(); Assert.DoesNotThrow(() => { hasher. Combine(new int[] { 5, 4, 3, 2, 1 }). Combine(8). Combine(null). Combine(new int[] { 1, 2, 3, 4, 5 }); hasher2. Combine(new int[] { 1, 2, 3, 4, 5 }). Combine(null). Combine(8). Combine(new int[] { 5, 4, 3, 2, 1 }); }); Assert.NotEqual(hasher.Hash(), hasher2.Hash()); // This test may be a bit confusing // In order for these two value-equality things to compare inconsistent, the type must be factored in because they are otherwise identical. // It's not clear that accounting for this case is worthwhile when the hash codes are almost strictly used to determine loose equality. // That is, it's only a problem if the same thing comes up with a different hashcode, which is why consistency is something we're testing for in general. // Different things coming up with the same hashcode is expected and that's why it falls back to full equality, where the type will be taken into consideration. hasher = new Hasher(); hasher2 = new Hasher(); Assert.DoesNotThrow(() => { hasher. Combine(new int[] { 5, 4, 3, 2, 1 }). Combine(8). Combine(null). Combine(new int[] { 1, 2, 3, 4, 5 }); hasher2. Combine(new List<int>() { 5, 4, 3, 2, 1 }). Combine(8). Combine(null). Combine(new List<int>() { 1, 2, 3, 4, 5 }); }); Assert.Equal(hasher.Hash(), hasher2.Hash()); }
static void Main(string[] args) { byte[] testbytes = {(byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'\n'}; Dictionary<HashType,string> hashes = new Dictionary<HashType,string>(); hashes.Add(HashType.CRC32, "261dafe6"); hashes.Add(HashType.MD4, "b1a45cdad19cb02482323fac9cea9b9f"); hashes.Add(HashType.MD5, "d577273ff885c3f84dadb8578bb41399"); hashes.Add(HashType.SHA1, "2672275fe0c456fb671e4f417fb2f9892c7573ba"); hashes.Add(HashType.SHA224, "ea2fa9708c96b4acb281be31fa98827addc5017305b7a038a3fca413"); hashes.Add(HashType.SHA256, "f33ae3bc9a22cd7564990a794789954409977013966fb1a8f43c35776b833a95"); hashes.Add(HashType.SHA384, "4e1cbb008acaa65ba788e3f150f7a8689c8fca289a57a65ef65b28f11ba61e59c3f4ddf069ca9521a9ac0e02eade4dae"); hashes.Add(HashType.SHA512, "f2dc0119c9dac46f49d3b7d0be1f61adf7619b770ff076fb11a2f61ff3fcba6b68d224588c4983670da31b33b4efabd448e38a2fda508622cc33ff8304ddf49c"); hashes.Add(HashType.TIGER, "6a31f8b7b80bab8b45263f56b5f609f93daf47d0a086bda5"); hashes.Add(HashType.TTH, "dctamcmte5tqwam5afghps2xpx3yeozwj2odzcq"); //hashes.Add(HashType.BTIH, "d4344cf79b89e4732c6241e730ac3f945d7a774c"); hashes.Add(HashType.AICH, "ezzcox7ayrlpwzy6j5ax7mxzrewhk452"); hashes.Add(HashType.ED2K, "b1a45cdad19cb02482323fac9cea9b9f"); hashes.Add(HashType.WHIRLPOOL, "0e8ce019c9d5185d2103a4ff015ec92587da9b22e77ad34f2eddbba9705b3602bc6ede67f5b5e4dd225e7762208ea54895b26c39fc550914d6eca9604b724d11"); hashes.Add(HashType.GOST, "0aaaf17200323d024437837d6f6f6384a4a108474cff03cd349ac12776713f5f"); hashes.Add(HashType.GOST_CRYPTOPRO, "2ed45a995ffdd7a2e5d9ab212c91cec5c65448e6a0840749a00f326ccb0c936d"); hashes.Add(HashType.RIPEMD160, "ead888178685c5d3a0400befba9188e4da3d5144"); hashes.Add(HashType.HAS160, "c7589afd23462e76703b1f7a031010eec70180d4"); hashes.Add(HashType.SNEFRU128, "d559a2b62f6f44111324f85208723707"); hashes.Add(HashType.SNEFRU256, "1b59927d85a9349a87796620fe2ff401a06a7ba48794498ebab978efc3a68912"); hashes.Add(HashType.EDONR256, "c3d2bbfd63f7461a806f756bf4efeb224036331a9c1d867d251e9e480b18e6fb"); hashes.Add(HashType.EDONR512, "a040056378fbd1f9a528677defd141c964fab9c429003fecf2eadfc20c8980cf2e083a1b4e74d5369af3cc0537bcf9b386fedf3613c9ee6c44f54f11bcf3feae"); hashes.Add(HashType.SHA3_224, "85c4da0ecd8a48e3037b386bd8eda3fda126da3718e5915a7a278852"); hashes.Add(HashType.SHA3_256, "2cdf0ba4e0e4030458a78d501aeacc7a7ae41828a426f131e6cfc970b2c9da07"); hashes.Add(HashType.SHA3_384, "f3b149af9526580999ad5a114c1ee143840fe1b6d76d7a8c26a3fab38b0e8c70c989aed2c858903f5c4b66400de50874"); hashes.Add(HashType.SHA3_512, "5edfdeca660f19975c192e8e24ef6deb8f76f334e6e3fa11dc4d7bfcd7dbfa760fc9a9fb205e4b2f92a427208dcfe6c03c26e02bfb143e0c2d8eefc645f4d076"); Console.WriteLine("\nTests: hashes for message"); int errcount1 = 0; foreach (HashType t in hashes.Keys) { string mustbe = hashes[t]; string got = Hasher.GetHashForMsg(testbytes, t); if (!got.Equals(mustbe)) { Console.WriteLine("Test for {0} failed: expected '{1}', got '{2}'\n", t, mustbe, got); errcount1++; } } Console.WriteLine("{0} tests / {1} failed\n", hashes.Count, errcount1); Console.WriteLine("\nTests: hashes for file"); int errcount2 = 0; foreach (HashType t in hashes.Keys) { string mustbe = hashes[t]; string got = Hasher.GetHashForFile("12345.txt", t); if (!got.Equals(mustbe)) { Console.WriteLine("Test for {0} failed: expected '{1}', got '{2}'\n", t, mustbe, got); errcount2++; } } Console.WriteLine("{0} tests / {1} failed\n", hashes.Count, errcount2); Console.WriteLine("\nTests: magnet links"); int errcount3 = 0; { // magnet by static method string mustbe = "magnet:?xl=6&dn=12345.txt&xt=urn:crc32:261dafe6&xt=urn:md5:d577273ff885c3f84dadb8578bb41399"; string got = Hasher.GetMagnetFor("12345.txt", (uint)HashType.CRC32 | (uint)HashType.MD5); if (!got.Equals(mustbe)) { Console.WriteLine("Magnet by static method test failed: expected '{0}', got '{1}'\n", mustbe, got); errcount3++; } // magnet with null argument Hasher hasher = new Hasher((uint)HashType.CRC32 | (uint)HashType.MD5); hasher.UpdateFile("12345.txt").Finish(); mustbe = "magnet:?xl=6&xt=urn:crc32:261dafe6"; got = hasher.GetMagnet(null, (uint)HashType.CRC32 | (uint)HashType.AICH); if (!got.Equals(mustbe)) { Console.WriteLine("Magnet with null argument test failed: expected '{0}', got '{1}'\n", mustbe, got); errcount3++; } } Console.WriteLine("{0} tests / {1} failed\n", 2, errcount3); System.Environment.ExitCode = errcount1 + errcount2 + errcount3; }
public void EnumerableHash() { int hash = 0; int oldHash = 0; var hasher = new Hasher(); oldHash = hasher.Hash(); Assert.DoesNotThrow(() => hasher.Combine(new int[] { })); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); oldHash = hash; Assert.DoesNotThrow(() => hasher.Combine(null as int[])); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); oldHash = hash; Assert.DoesNotThrow(() => hasher.Combine(null as int[])); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); oldHash = hash; Assert.DoesNotThrow(() => hasher.Combine(new List<int>() { 1, 2, 3, 4 })); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); oldHash = hash; Assert.DoesNotThrow(() => hasher.Combine(new int[] { 1, 2, 3, 4 })); Assert.DoesNotThrow(() => hash = hasher.Hash()); Assert.NotEqual(oldHash, hash); }
static void Main(string[] args) { byte[] testbytes = {(byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'\n'}; Dictionary<HashType,string> hashes = new Dictionary<HashType,string>(); hashes.Add(HashType.CRC32, "261dafe6"); hashes.Add(HashType.MD4, "b1a45cdad19cb02482323fac9cea9b9f"); hashes.Add(HashType.MD5, "d577273ff885c3f84dadb8578bb41399"); hashes.Add(HashType.SHA1, "2672275fe0c456fb671e4f417fb2f9892c7573ba"); hashes.Add(HashType.SHA224, "ea2fa9708c96b4acb281be31fa98827addc5017305b7a038a3fca413"); hashes.Add(HashType.SHA256, "f33ae3bc9a22cd7564990a794789954409977013966fb1a8f43c35776b833a95"); hashes.Add(HashType.SHA384, "4e1cbb008acaa65ba788e3f150f7a8689c8fca289a57a65ef65b28f11ba61e59c3f4ddf069ca9521a9ac0e02eade4dae"); hashes.Add(HashType.SHA512, "f2dc0119c9dac46f49d3b7d0be1f61adf7619b770ff076fb11a2f61ff3fcba6b68d224588c4983670da31b33b4efabd448e38a2fda508622cc33ff8304ddf49c"); hashes.Add(HashType.TIGER, "6a31f8b7b80bab8b45263f56b5f609f93daf47d0a086bda5"); hashes.Add(HashType.TTH, "dctamcmte5tqwam5afghps2xpx3yeozwj2odzcq"); //hashes.Add(HashType.BTIH, "d4344cf79b89e4732c6241e730ac3f945d7a774c"); hashes.Add(HashType.AICH, "ezzcox7ayrlpwzy6j5ax7mxzrewhk452"); hashes.Add(HashType.ED2K, "b1a45cdad19cb02482323fac9cea9b9f"); hashes.Add(HashType.WHIRLPOOL, "0e8ce019c9d5185d2103a4ff015ec92587da9b22e77ad34f2eddbba9705b3602bc6ede67f5b5e4dd225e7762208ea54895b26c39fc550914d6eca9604b724d11"); hashes.Add(HashType.GOST, "0aaaf17200323d024437837d6f6f6384a4a108474cff03cd349ac12776713f5f"); hashes.Add(HashType.GOST_CRYPTOPRO, "2ed45a995ffdd7a2e5d9ab212c91cec5c65448e6a0840749a00f326ccb0c936d"); hashes.Add(HashType.RIPEMD160, "ead888178685c5d3a0400befba9188e4da3d5144"); hashes.Add(HashType.HAS160, "c7589afd23462e76703b1f7a031010eec70180d4"); hashes.Add(HashType.SNEFRU128, "d559a2b62f6f44111324f85208723707"); hashes.Add(HashType.SNEFRU256, "1b59927d85a9349a87796620fe2ff401a06a7ba48794498ebab978efc3a68912"); hashes.Add(HashType.EDONR256, "c3d2bbfd63f7461a806f756bf4efeb224036331a9c1d867d251e9e480b18e6fb"); hashes.Add(HashType.EDONR512, "a040056378fbd1f9a528677defd141c964fab9c429003fecf2eadfc20c8980cf2e083a1b4e74d5369af3cc0537bcf9b386fedf3613c9ee6c44f54f11bcf3feae"); hashes.Add(HashType.SHA3_224, "952f55abd73d0efd9656982f65c4dc837a6a129de02464b85d04cb18"); hashes.Add(HashType.SHA3_256, "f627c8f9355399ef45e1a6b6e5a9e6a3abcb3e1b6255603357bffa9f2211ba7e"); hashes.Add(HashType.SHA3_384, "0529075e85bcdc06da94cbc83c53b7402c5032440210a1a24d9ccca481ddbd6c1309ae0ef23741f13352a4f3382dee51"); hashes.Add(HashType.SHA3_512, "fdd7e7b9655f4f0ef89056e864a2d2dce3602404480281c88455e3a98f728aa08b3f116e6b434200a035e0780d9237ca367c976c5506f7c6f367e6b65447d97c"); Console.WriteLine("\nTests: hashes for message"); int errcount1 = 0; foreach (HashType t in hashes.Keys) { string mustbe = hashes[t]; string got = Hasher.GetHashForMsg(testbytes, t); if (!got.Equals(mustbe)) { Console.WriteLine("Test for {0} failed: expected '{1}', got '{2}'\n", t, mustbe, got); errcount1++; } } Console.WriteLine("{0} tests / {1} failed\n", hashes.Count, errcount1); Console.WriteLine("\nTests: hashes for file"); int errcount2 = 0; foreach (HashType t in hashes.Keys) { string mustbe = hashes[t]; string got = Hasher.GetHashForFile("12345.txt", t); if (!got.Equals(mustbe)) { Console.WriteLine("Test for {0} failed: expected '{1}', got '{2}'\n", t, mustbe, got); errcount2++; } } Console.WriteLine("{0} tests / {1} failed\n", hashes.Count, errcount2); Console.WriteLine("\nTests: magnet links"); int errcount3 = 0; { // magnet by static method string mustbe = "magnet:?xl=6&dn=12345.txt&xt=urn:crc32:261dafe6&xt=urn:md5:d577273ff885c3f84dadb8578bb41399"; string got = Hasher.GetMagnetFor("12345.txt", (uint)HashType.CRC32 | (uint)HashType.MD5); if (!got.Equals(mustbe)) { Console.WriteLine("Magnet by static method test failed: expected '{0}', got '{1}'\n", mustbe, got); errcount3++; } // magnet with null argument Hasher hasher = new Hasher((uint)HashType.CRC32 | (uint)HashType.MD5); hasher.UpdateFile("12345.txt").Finish(); mustbe = "magnet:?xl=6&xt=urn:crc32:261dafe6"; got = hasher.GetMagnet(null, (uint)HashType.CRC32 | (uint)HashType.AICH); if (!got.Equals(mustbe)) { Console.WriteLine("Magnet with null argument test failed: expected '{0}', got '{1}'\n", mustbe, got); errcount3++; } } Console.WriteLine("{0} tests / {1} failed\n", 2, errcount3); System.Environment.ExitCode = errcount1 + errcount2 + errcount3; }
public void CRUDUser() { var user1 = new UserInfo { UserName = "******", FirstName = "first name", LastName = "last name", BirthDate = new DateTime(2011, 01, 01, 7, 8, 9), Sex = true, Department = "department", Email = "*****@*****.**", Location = "location", Notes = "notes", Status = EmployeeStatus.Active, Title = "title", WorkFromDate = new DateTime(2011, 01, 01, 7, 8, 9), TerminatedDate = new DateTime(2011, 01, 01, 7, 8, 9), CultureName = "de-DE", }; user1.ContactsFromString("contacts"); user1 = Service.SaveUser(Tenant, user1); CompareUsers(user1, Service.GetUser(Tenant, user1.ID)); var user2 = new UserInfo { UserName = "******", FirstName = "first name", LastName = "last name", }; user2 = Service.SaveUser(Tenant, user2); user2 = Service.SaveUser(Tenant, user2); CompareUsers(user2, Service.GetUser(Tenant, user2.ID)); var duplicateUsername = false; var user3 = new UserInfo { UserName = "******", FirstName = "first name", LastName = "last name", }; var user4 = new UserInfo { UserName = "******", FirstName = "first name", LastName = "last name", }; try { user3 = Service.SaveUser(Tenant, user3); user4 = Service.SaveUser(Tenant, user4); } catch (ArgumentOutOfRangeException) { duplicateUsername = true; } Assert.IsTrue(duplicateUsername); Service.RemoveUser(Tenant, user3.ID, false); user4 = Service.SaveUser(Tenant, user4); Service.RemoveUser(Tenant, user3.ID, true); Service.RemoveUser(Tenant, user4.ID, true); var users = Service.GetUsers(Tenant, new DateTime(1900, 1, 1)).Values; CollectionAssert.AreEquivalent(new[] { user1, user2 }, users); Service.RemoveUser(Tenant, user2.ID, true); Service.SetUserPhoto(Tenant, user1.ID, null); CollectionAssert.IsEmpty(Service.GetUserPhoto(Tenant, user1.ID)); Service.SetUserPhoto(Tenant, user1.ID, new byte[0]); CollectionAssert.IsEmpty(Service.GetUserPhoto(Tenant, user1.ID)); Service.SetUserPhoto(Tenant, user1.ID, new byte[] { 1, 2, 3 }); CollectionAssert.AreEquivalent(new byte[] { 1, 2, 3 }, Service.GetUserPhoto(Tenant, user1.ID)); var password = "******"; Service.SetUserPassword(Tenant, user1.ID, password); Assert.AreEqual(password, Service.GetUserPassword(Tenant, user1.ID)); CompareUsers(user1, Service.GetUser(Tenant, user1.Email, Hasher.Base64Hash(password, HashAlg.SHA256))); Service.RemoveUser(Tenant, user1.ID); Assert.IsTrue(Service.GetUser(Tenant, user1.ID).Removed); Service.RemoveUser(Tenant, user1.ID, true); CollectionAssert.IsEmpty(Service.GetUserPhoto(Tenant, user1.ID)); Assert.IsNull(Service.GetUserPassword(Tenant, user1.ID)); }
/// <summary> /// 重新扫描项目并更新目标脚本的信息 /// </summary> /// <param name="option">目标脚本信息</param> /// <param name="save">是否扫描完成后自动保存</param> public static void RescanScriptInformation(ScriptInformation option, bool save = true) { var source = option.SourceAssetPath(); if (!string.IsNullOrEmpty(source)) { if (File.Exists(source)) { option.hash = Hasher.Crc32(Encoding.UTF8.GetBytes(File.ReadAllText(source, Encoding.UTF8).UnifyLineBreak())); } else { option.hash = null; } } var binary = option.BinaryAssetPath(); if (!string.IsNullOrEmpty(binary)) { if (File.Exists(source)) { var stream = new FileStream(binary, FileMode.Open); var hash = ScriptInformation.ReadBinaryHash(stream); stream.Close(); option.recordedHash = hash; } else { option.recordedHash = null; } } var detectedLanguage = new List <string>(); foreach (var language in Directory.GetDirectories($"Assets/{CompileConfiguration.Content.TranslationFolder}").Select(Path.GetFileName)) { if (File.Exists($"Assets/{CompileConfiguration.Content.TranslationFolder}/{language}/{option.id}.txt")) { if (!option.Translations.ContainsKey(language)) { option.Translations.Add(language, null); } detectedLanguage.Add(language); } else { if (option.Translations.ContainsKey(language)) { option.Translations.Remove(language); } } } var needRemove = new List <string>(); foreach (var(key, _) in option.Translations) { if (!detectedLanguage.Contains(key)) { needRemove.Add(key); } } foreach (var key in needRemove) { option.Translations.Remove(key); } if (!option.HasSource() && !option.HasBinary()) { CompileConfiguration.Content.Scripts.Remove(option.id); } if (save) { CompileConfiguration.Save(); } }
private static void RunHash(HashType hashtype) { Console.WriteLine("Hash type: " + hashtype.ToString()); //Random r = new Random(); DateTime starttime = DateTime.Now; //ConcurrentBag<String> SmallBag = new ConcurrentBag<String>(); //ConcurrentBag<String> MediumBag = new ConcurrentBag<String>(); //ConcurrentBag<String> LargeBag = new ConcurrentBag<String>(); //ConcurrentBag<String> GiantBag = new ConcurrentBag<String>(); Hasher hasher = new Hasher(); #region slow also //ConcurrentBag<Int32> smallarrdisty = new ConcurrentBag<Int32>(); //ConcurrentBag<Int32> mediumarrdisty = new ConcurrentBag<Int32>(); //ConcurrentBag<Int32> largearrdisty = new ConcurrentBag<Int32>(); //ConcurrentBag<Int32> giantarrdisty = new ConcurrentBag<Int32>(); //Int32 smallarraycollisions = 0; //Int32 mediumarraycollisions = 0; //Int32 largearraycollisions = 0; //Int32 giantarraycollisions = 0; //IEnumerable<Hash> smallhash = null; //IEnumerable<Hash> mediumhash = null; //IEnumerable<Hash> largehash = null; //IEnumerable<Hash> gianthash = null; //Parallel.Invoke( // () => smallhash = hasher.Hash(SmallBag, hashtype), // () => mediumhash = hasher.Hash(MediumBag, hashtype), // () => largehash = hasher.Hash(LargeBag, hashtype), // () => gianthash = hasher.Hash(GiantBag, hashtype) // ); //Parallel.Invoke(() => // Parallel.ForEach(smallhash, h => // { // if (smallarrdisty.Contains(h.HashCode)) // smallarraycollisions++; // else // smallarrdisty.Add(h.HashCode); // }), () => // Parallel.ForEach(mediumhash, h => // { // if (mediumarrdisty.Contains(h.HashCode)) // mediumarraycollisions++; // else // mediumarrdisty.Add(h.HashCode); // }), () => // Parallel.ForEach(largehash, h => // { // if (largearrdisty.Contains(h.HashCode)) // largearraycollisions++; // else // largearrdisty.Add(h.HashCode); // }), () => // Parallel.ForEach(gianthash, h => // { // if (giantarrdisty.Contains(h.HashCode)) // giantarraycollisions++; // else // giantarrdisty.Add(h.HashCode); // })); ////() => ////{ //// hasher.Hash(MediumBag, hashtype).Map(h => //// { //// if (mediumarrdisty.Contains(h.HashCode)) //// mediumarraycollisions++; //// else //// mediumarrdisty.Add(h.HashCode); //// }); ////}, () => ////{ //// hasher.Hash(LargeBag, hashtype).Map(h => //// { //// if (largearrdisty.Contains(h.HashCode)) //// largearraycollisions++; //// else //// largearrdisty.Add(h.HashCode); //// }); ////}, () => ////{ //// hasher.Hash(GiantBag, hashtype).Map(h => //// { //// if (giantarrdisty.Contains(h.HashCode)) //// giantarraycollisions++; //// else //// giantarrdisty.Add(h.HashCode); //// }); ////}); #endregion #region slow way //List<Int32> smallarrdisty = new List<Int32>(SmallArray.Length); //Int32 smallarraycollisions = 0; //hasher.Hash(SmallArray, hashtype).Map(h => // { // if (smallarrdisty.Contains(h.HashCode)) // smallarraycollisions++; // else // smallarrdisty.Add(h.HashCode); // }); //List<Int32> mediumarrdisty = new List<Int32>(MediumArray.Length); //Int32 mediumarraycollisions = 0; //hasher.Hash(MediumArray, hashtype).AsParallel().Map(h => // { // if (mediumarrdisty.Contains(h.HashCode)) // mediumarraycollisions++; // else // mediumarrdisty.Add(h.HashCode); // }); //List<Int32> largearrdisty = new List<Int32>(LargeArray.Length); //Int32 largearraycollisions = 0; //hasher.Hash(LargeArray, hashtype).AsParallel().Map(h => // { // if (largearrdisty.Contains(h.HashCode)) // largearraycollisions++; // else // largearrdisty.Add(h.HashCode); // }); //List<Int32> superarrdisty = new List<Int32>(SuperArray.Length); //Int32 superarraycollisions = 0; //hasher.Hash(SuperArray, hashtype).AsParallel().Map(h => // { // if (superarrdisty.Contains(h.HashCode)) // superarraycollisions++; // else // superarrdisty.Add(h.HashCode); // }); #endregion #region best way //ConcurrentDictionary<Int32, Int32> smallarraydistribution = new ConcurrentDictionary<int, int>(20, 5500); //ConcurrentDictionary<Int32, Int32> mediumarraydistribution = new ConcurrentDictionary<int, int>(20, 60000); //ConcurrentDictionary<Int32, Int32> largearraydistribution = new ConcurrentDictionary<int, int>(20, 500000); //ConcurrentDictionary<Int32, Int32> superarraydistribution = new ConcurrentDictionary<int, int>(20, 20000000); Dictionary<Int32, Int32> smallarraydistribution = new Dictionary<Int32, Int32>(5500); Dictionary<Int32, Int32> mediumarraydistribution = new Dictionary<Int32, Int32>(60000); Dictionary<Int32, Int32> largearraydistribution = new Dictionary<Int32, Int32>(500000); Dictionary<Int32, Int32> superarraydistribution = new Dictionary<Int32, Int32>(20000000); IEnumerable<Hash> smallhash = null; IEnumerable<Hash> mediumhash = null; IEnumerable<Hash> largehash = null; IEnumerable<Hash> superhash = null; DateTime starthash = DateTime.Now; Parallel.Invoke( () => smallhash = hasher.Hash(SmallArray, hashtype), () => mediumhash = hasher.Hash(MediumArray, hashtype), () => largehash = hasher.Hash(LargeArray, hashtype), () => superhash = hasher.Hash(SuperArray, hashtype) ); DateTime endhash = DateTime.Now; DateTime startdist = DateTime.Now; #region seems threads get too swamped //Parallel.ForEach(smallhash, h => // { // if (smallarraydistribution.ContainsKey(h.HashCode)) // smallarraydistribution[h.HashCode] += 1; // else // smallarraydistribution.TryAdd(h.HashCode, 1); // }); //Parallel.ForEach(mediumhash, h => // { // if (mediumarraydistribution.ContainsKey(h.HashCode)) // mediumarraydistribution[h.HashCode] += 1; // else // mediumarraydistribution.TryAdd(h.HashCode, 1); // }); //Parallel.ForEach(largehash, h => // { // if (largearraydistribution.ContainsKey(h.HashCode)) // largearraydistribution[h.HashCode] += 1; // else // largearraydistribution.TryAdd(h.HashCode, 1); // }); //Parallel.ForEach(superhash, h => // { // if (superarraydistribution.ContainsKey(h.HashCode)) // { // Int32 old = superarraydistribution[h.HashCode]; // if(!superarraydistribution.TryUpdate(h.HashCode, old + 1, old)) // Console.WriteLine("Super Distribution failed to update: " + h.HashCode); // } // else // if (!superarraydistribution.TryAdd(h.HashCode, 1)) // Console.WriteLine("Super Distribution failed to add: " + h.HashCode); // }); #endregion smallarraydistribution = smallhash.Select<Int32, Int32, Hash>((h, d) => { if (d.ContainsKey(h.HashCode)) d[h.HashCode] += 1; else d.Add(h.HashCode, 1); }); mediumarraydistribution = mediumhash.Select<Int32, Int32, Hash>((h, d) => { if (d.ContainsKey(h.HashCode)) d[h.HashCode] += 1; else d.Add(h.HashCode, 1); }); largearraydistribution = largehash.Select<Int32, Int32, Hash>((h, d) => { if (d.ContainsKey(h.HashCode)) d[h.HashCode] += 1; else d.Add(h.HashCode, 1); }); superarraydistribution = superhash.Select<Int32, Int32, Hash>((h, d) => { if (d.ContainsKey(h.HashCode)) d[h.HashCode] += 1; else d.Add(h.HashCode, 1); }); DateTime enddist = DateTime.Now; Int32 smalltotalcollisions = 0, mediumtotalcollisions = 0, largetotalcollisions= 0, supertotalcollisions = 0; Int32 smallcollisions = smallarraydistribution.Count(d =>{ if (d.Value > 1) { smalltotalcollisions += d.Value; return true; } else return false; }); Int32 mediumcollisions = mediumarraydistribution.Count(d => { if (d.Value > 1) { mediumtotalcollisions += d.Value; return true; } else return false; }); Int32 largecollisions = largearraydistribution.Count(d => { if (d.Value > 1) { largetotalcollisions += d.Value; return true; } else return false; }); Int32 supercollisions = superarraydistribution.Count(d => { if (d.Value > 1) { supertotalcollisions += d.Value; return true; } else return false; }); #endregion Console.WriteLine("Small Array Collisions: " + smallcollisions); Console.WriteLine("Small Array Total Collisions: " + smalltotalcollisions); Console.WriteLine("Medium Array Collisions: " + mediumcollisions); Console.WriteLine("Medium Array Total Collisions: " + mediumtotalcollisions); Console.WriteLine("Large Array Collisions: " + largecollisions); Console.WriteLine("Large Array Total Collisions: " + largetotalcollisions); Console.WriteLine("Super Array Collisions: " + supercollisions); Console.WriteLine("Super Array Total Collisions: " + supertotalcollisions); Console.WriteLine("Total Timer: " + (DateTime.Now - starttime).TotalSeconds); Console.WriteLine("Hash Timer: " + (endhash - starthash).TotalSeconds); Console.WriteLine("Distribution Timer: " + (enddist - startdist).TotalSeconds); Console.WriteLine(); }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using BtsMsiLib.Utilities; using Microsoft.Deployment.Compression.Cab; using Microsoft.Deployment.WindowsInstaller; namespace BtsMsiLib.Msi { //TODO: User better variable names in general public static class MsiDatabaseExtensions { public static void UpdateSummaryInfo(this Database db) { // TODO: Correct values needs to be set using (SummaryInfo summaryInfo = db.SummaryInfo) { summaryInfo.Title = "A"; summaryInfo.Author = "B"; summaryInfo.Subject = "C"; summaryInfo.Comments = "D"; summaryInfo.Keywords = "BizTalk, deployment, application, " + "sdfsdWfsdf"; summaryInfo.RevisionNumber = Guid.NewGuid().ToString("B").ToUpperInvariant(); summaryInfo.CreatingApp = typeof(MsiDatabaseExtensions).Assembly.FullName; summaryInfo.CreateTime = DateTime.Now; summaryInfo.Persist(); } } public static void UpdateSummaryInfo(this Database db, BtsMsiLib.Model.BtsApplication btsApp) { using (SummaryInfo summaryInfo = db.SummaryInfo) { summaryInfo.Title = btsApp.Name; summaryInfo.Author = btsApp.Authors; summaryInfo.Subject = btsApp.Subject; summaryInfo.Comments = btsApp.Description; summaryInfo.Keywords = btsApp.Keywords; summaryInfo.RevisionNumber = Guid.NewGuid().ToString("B").ToUpperInvariant(); summaryInfo.CreatingApp = typeof(MsiDatabaseExtensions).Assembly.FullName; summaryInfo.CreateTime = DateTime.Now; summaryInfo.Persist(); } } public static void UpdateUpgradeTable(this Database db, Guid upgradeCode) { using (View view = db.OpenView("SELECT * FROM `Upgrade`", new object[0])) { view.Execute(); using (Record record = view.Fetch()) { record[1] = upgradeCode.ToString("B").ToUpperInvariant(); view.Replace(record); } db.Commit(); } } public static void UpdateProperties(this Database db, IDictionary<string, object> properties) { using (View view = db.OpenView("SELECT * FROM `Property`", new object[0])) { view.Execute(); foreach (string index in properties.Keys) { using (var record = new Record(2)) { record[1] = index; record[2] = properties[index]; view.Assign(record); } } db.Commit(); } } public static void UpdateFileContent(this Database db, string folder, string adfFile, int resourceCount) { using (View view1 = db.OpenView("SELECT * FROM `File` WHERE `FileName` = 'APPLIC~1.ADF|ApplicationDefinition.adf'", new object[0])) { view1.Execute(); using (Record record1 = view1.Fetch()) { string path2_1 = (string)record1[1]; Guid guid = Guid.NewGuid(); string path2_2 = "_" + guid.ToString("N").ToUpperInvariant(); string str1 = "C_" + path2_2; string mediaStream = ExtractMediaStream(db); File.Delete(Path.Combine(mediaStream, path2_1)); File.Copy(adfFile, Path.Combine(mediaStream, path2_2)); using (View view2 = db.OpenView("SELECT * FROM `Component` WHERE `KeyPath` = '{0}'", new object[] { path2_1 })) { view2.Execute(); using (Record record2 = view2.Fetch()) { record2[1] = str1; record2[2] = guid.ToString("B").ToUpperInvariant(); record2[6] = path2_2; record2[3] = "ADFDIR"; view2.Replace(record2); } } using (View view2 = db.OpenView("SELECT * FROM `FeatureComponents` WHERE `Component_` = '{0}'", new object[] { "C_" + path2_1 })) { view2.Execute(); using (Record record2 = view2.Fetch()) { record2[2] = str1; view2.Assign(record2); } } record1[1] = path2_2; record1[2] = str1; record1[4] = FileHelper.FileSize(adfFile); view1.Replace(record1); var num = (int)db.ExecuteScalar("SELECT `LastSequence` FROM `Media` WHERE `DiskId` = {0}", new object[] { 1 }); for (int index = 0; index < resourceCount; ++index) { string cabFileName = string.Format(CultureInfo.InvariantCulture, "ITEM~{0}.CAB", new object[]{index}); string cabFilePath = Path.Combine(folder, cabFileName); record1[1] = "_" + Guid.NewGuid().ToString("N").ToUpperInvariant(); record1[3] = string.Format(CultureInfo.InvariantCulture, "{0}|{1}", new object[] { cabFileName, cabFileName }); record1[4] = FileHelper.FileSize(cabFilePath); record1[8] = ++num; view1.Assign(record1); File.Copy(cabFilePath, Path.Combine(mediaStream, (string)record1[1])); } UpdateMediaCab(db, mediaStream, num); } } } private static string ExtractMediaStream(Database db) { string tempFileName = Path.GetTempFileName(); string tempFolder = FileHelper.GetTempFolder(tempFileName); string cabTempFileName = Path.ChangeExtension(tempFileName, ".cab"); var cabFileName = (string)db.ExecuteScalar("SELECT `Cabinet` FROM `Media` WHERE `DiskId` = {0}", new object[] { 1 }); using (View view = db.OpenView("SELECT `Name`, `Data` FROM `_Streams` WHERE `Name` = '{0}'", new object[] { cabFileName.Substring(1) })) { view.Execute(); Record record = view.Fetch(); if (record == null) throw new InstallerException("Stream not found: " + cabFileName); using (record) record.GetStream("Data", cabTempFileName); } var cabinetInfo = new CabInfo(cabTempFileName); cabinetInfo.Unpack(tempFolder); cabinetInfo.Delete(); return tempFolder; } private static void UpdateMediaCab(Database msiDb, string folderToPack, int lastSequence) { string tempFileName = Path.GetTempFileName(); if (File.Exists(tempFileName)) File.Delete(tempFileName); string cabFileName = Path.ChangeExtension(tempFileName, ".cab"); new CabInfo(cabFileName).Pack(folderToPack); Directory.Delete(folderToPack, true); var list = new List<string>(); using (View view = msiDb.OpenView("SELECT `File` FROM `File`", new object[0])) { view.Execute(); Record record; while ((record = view.Fetch()) != null) { using (record) list.Add((string)record[1]); } list.Sort(); } using (View view = msiDb.OpenView("SELECT `File`, `Sequence` FROM `File`", new object[0])) { view.Execute(); for (Record record = view.Fetch(); record != null; record = view.Fetch()) { using (record) { record[2] = list.IndexOf((string)record[1]) + 1; view.Update(record); } } } string cabinet; using (View view = msiDb.OpenView("SELECT `LastSequence`, `Cabinet` FROM `Media` WHERE `DiskId` = {0}", new object[] { 1 })) { view.Execute(); Record record = view.Fetch(); if (record == null) throw new InstallerException("Media for DiskID=1 is not found: "); using (record) { cabinet = (string)record[2]; record[1] = lastSequence; view.Update(record); } } using (View view = msiDb.OpenView("SELECT `Name`, `Data` FROM `_Streams` WHERE `Name` = '{0}'", new object[] { cabinet.Substring(1) })) { view.Execute(); Record record = view.Fetch(); using (record) { record.SetStream("Data", cabFileName); view.Update(record); } } } public static void MakeCustomModifications(this Database db, Guid productCode, string applicationName) { string productCodeUpper = productCode.ToString("B").ToUpperInvariant(); string shortProductCode = productCodeUpper.Substring(1, productCodeUpper.Length - 2); using (View view = db.OpenView("SELECT * FROM `Directory`", new object[0])) { view.Execute(); using (var record = new Record(3)) { record[1] = "ADFDIR"; record[2] = "TARGETDIR"; record[3] = shortProductCode; view.Assign(record); } db.Commit(); } using (View view = db.OpenView("SELECT * FROM `ControlCondition`", new object[0])) { view.Execute(); using (var record = new Record(4)) { record[1] = "FolderForm"; record[2] = "DiskCostButton"; record[3] = "Hide"; record[4] = "1=1"; view.Assign(record); } db.Commit(); } Guid applicationGuid = Hasher.HashApplicationName(applicationName); string applicationCompId = "C__" + applicationGuid.ToString("N").ToUpperInvariant(); string msiCompId; using (View view = db.OpenView("SELECT * FROM `File` WHERE `FileName` = 'APPLIC~1.ADF|ApplicationDefinition.adf'", new object[0])) { view.Execute(); using (Record record = view.Fetch()) msiCompId = record[2].ToString(); db.Commit(); } CustomModifyRegistry(db, applicationCompId, msiCompId); CustomModifyComponent(db, applicationGuid, applicationCompId); CustomModifyFeatureComponents(db, applicationCompId, msiCompId); CustomModifyCustomAction(db); ModifySecureCustomProperties(db); AddErrorTableEntry(db); } private static void CustomModifyRegistry(Database msiDb, string applicationCompId, string msiCompId) { using (View view = msiDb.OpenView("SELECT * FROM `Registry` WHERE `Key` = 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\[ProductName]\\[ProductCode]'", new object[0])) { view.Execute(); using (Record record = view.Fetch()) { record[6] = msiCompId; view.Replace(record); } } using (View view = msiDb.OpenView("SELECT * FROM `Registry` WHERE `Key` = 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\[ProductName]' AND `Name` = '*'", new object[0])) { view.Execute(); using (Record record = view.Fetch()) { record[6] = applicationCompId; view.Replace(record); } } CustomModifyRegistryEntry(msiDb, applicationCompId, "NoModify"); ModifyReadmeRegistryEntry(msiDb, applicationCompId); CustomModifyRegistryEntry(msiDb, applicationCompId, "URLInfoAbout"); CustomModifyRegistryEntry(msiDb, applicationCompId, "Contact"); CustomModifyRegistryEntry(msiDb, applicationCompId, "Uninstallstring"); CustomModifyRegistryEntry(msiDb, applicationCompId, "NoRepair"); CustomModifyRegistryEntry(msiDb, applicationCompId, "DisplayName"); msiDb.Commit(); } private static void CustomModifyComponent(Database msiDb, Guid applicationGuid, string applicationCompId) { using (View view = msiDb.OpenView("SELECT * FROM `Component` WHERE `Directory_` = 'TARGETDIR' AND `Attributes` = 4", new object[0])) { view.Execute(); using (Record record = view.Fetch()) { record[1] = applicationCompId; record[2] = applicationGuid.ToString("B").ToUpperInvariant(); view.Replace(record); } while (true) { using (Record record = view.Fetch()) { if (record != null) view.Delete(record); else break; } } msiDb.Commit(); } } private static void CustomModifyFeatureComponents(Database msiDb, string applicationCompId, string msiCompId) { using (View view = msiDb.OpenView("SELECT * FROM `FeatureComponents`", new object[0])) { view.Execute(); while (true) { using (Record record = view.Fetch()) { if (record != null) view.Delete(record); else break; } } const string featureName = "DefaultFeature"; using (var record = new Record(2)) { record[1] = featureName; record[2] = applicationCompId; view.Assign(record); } using (var record = new Record(2)) { record[1] = featureName; record[2] = msiCompId; view.Assign(record); } msiDb.Commit(); } } private static void CustomModifyCustomAction(Database msiDb) { using (View view = msiDb.OpenView("SELECT * FROM `CustomAction` WHERE `Source` = 'InstallUtil'", new object[0])) { view.Execute(); while (true) { using (Record record = view.Fetch()) { if (record != null) { record.SetInteger(2, record.GetInteger(2) | 2048); view.Replace(record); } else break; } } msiDb.Commit(); } } private static void ModifySecureCustomProperties(Database msiDb) { using (View view = msiDb.OpenView("SELECT * FROM `Property` WHERE `Property` = 'SecureCustomProperties'", new object[0])) { view.Execute(); using (Record record = view.Fetch()) { record[2] = "NEWERPRODUCTFOUND;BTSVERSION;BTSPATH;BTSPRODUCTNAME"; view.Replace(record); } msiDb.Commit(); } } private static void AddErrorTableEntry(Database msiDb) { using (View view = msiDb.OpenView("SELECT * FROM `Error`", new object[0])) { view.Execute(); using (var record = new Record(2)) { record[1] = 1001; record[2] = "Error [1]: [2]"; view.Assign(record); } msiDb.Commit(); } } private static void CustomModifyRegistryEntry(Database msiDb, string compId, string name) { using (View view = msiDb.OpenView("SELECT * FROM `Registry` WHERE `Name` = '{0}'", new object[] { name })) { view.Execute(); using (Record record = view.Fetch()) { record[6] = compId; view.Replace(record); } } } private static void ModifyReadmeRegistryEntry(Database msiDb, string compId) { using (View view = msiDb.OpenView("SELECT * FROM `Registry` WHERE `Name` = '{0}'", new object[] { "Readme" })) { view.Execute(); using (Record record = view.Fetch()) { record[6] = compId; record[5] = "file://[TARGETDIR]Readme.htm"; view.Replace(record); } } } } }
/// <summary> /// Loads this profile from disk. If loading fails this will default to a new profile with the fall-back character /// class. /// </summary> /// <exception cref="ArgumentException">Profile name is invalid.</exception> public void Load(string name) { if (InvalidCharPattern.IsMatch(name)) { throw new ArgumentException(@"Invalid profile name, contains invalid character.", "name"); } // Figure out the path, check if it's valid. Reset(); Name = name; var profilePath = GetFullProfilePath(); if (!File.Exists(profilePath)) { throw new ArgumentException(@"Invalid profile name, no such file.", "name"); } try { // Load the file contents, which are encrypted and compressed. var encrypted = File.ReadAllBytes(profilePath); var compressed = Crypto.Decrypt(encrypted); var plain = SimpleCompression.Decompress(compressed); // Now we have the plain data, handle it as a packet to read our // data from it. using (var packet = new Packet(plain, false)) { // Get file header. if (!CheckHeader(packet.ReadByteArray())) { Logger.Error("Failed loading profile, invalid header, using default."); return; } // Get the hash the data had when writing. var hash = packet.ReadInt32(); // Get the player class. var playerClass = (PlayerClassType)packet.ReadByte(); // And the actual data. var data = packet.ReadPacketizable <Packet>(); // Check if the hash matches. var hasher = new Hasher(); hasher.Write((byte)playerClass); if (data != null) { hasher.Write(data); } if (hasher.Value == hash) { // All is well, keep the data, drop our old data, if any. PlayerClass = playerClass; _data = data; } } } catch (Exception ex) { Logger.ErrorException("Failed loading profile, using default.", ex); } }
/// <summary>Stores the profile to disk, under the specified profile name.</summary> public void Save() { // Get our plain data and hash it. var hasher = new Hasher(); hasher.Write((byte)PlayerClass); if (_data != null) { hasher.Write(_data); } // Write it to a packet, compress it, encrypt it and save it. using (var packet = new Packet()) { // Put our hash and plain data. packet.Write(Header); packet.Write(hasher.Value); packet.Write((byte)PlayerClass); packet.Write(_data); // Compress and encrypt, then save. var compressed = SimpleCompression.Compress(packet.GetBuffer(), packet.Length); var encrypted = Crypto.Encrypt(compressed); var profilePath = GetFullProfilePath(); try { var path = Path.GetDirectoryName(profilePath); if (path != null) { Directory.CreateDirectory(path); } // Make a backup if there's a save already. if (File.Exists(profilePath)) { var backupPath = profilePath + ".bak"; try { if (File.Exists(backupPath)) { File.Delete(backupPath); } File.Move(profilePath, backupPath); } catch (Exception ex) { Logger.WarnException("Failed backing-up saved profile.", ex); } } try { File.WriteAllBytes(profilePath, encrypted); #if DEBUG if (_data != null) { File.WriteAllBytes(profilePath + ".raw", (byte[])_data); } #endif } catch (Exception ex) { Logger.ErrorException("Failed saving profile.", ex); // If we have a backup, try to restore it. var backupPath = profilePath + ".bak"; if (File.Exists(backupPath)) { try { if (File.Exists(profilePath)) { File.Delete(profilePath); } File.Copy(backupPath, profilePath); } catch (Exception ex2) { Logger.WarnException("Failed restoring backed-up profile.", ex2); } } } } catch (Exception ex) { Logger.ErrorException("Failed saving.", ex); } } }
public int GetFileDataIdByName(string name) => GetFileDataIdByHash(Hasher.ComputeHash(name));
public string GetPlainStorageKey(Hasher hasher, string prefix) { return(GetStorageKey(hasher, Encoding.ASCII.GetBytes(prefix), prefix.Length)); }
/// <summary> /// Создает хэшированную директорию для записи файлов /// </summary> protected HashedDirectoryBase(string targetDirectoryName, bool compress = true, int hashsize = Const.MaxHashSize) { _rootDirectory = targetDirectoryName; _compress = compress; _hasher = new Hasher(hashsize); }
public override void LoadListFile(string path, BackgroundWorkerEx worker = null) { if (LoadPreHashedListFile("listfile.bin", path, worker)) { return; } using (var _ = new PerfCounter("WowRootHandler::LoadListFile()")) { worker?.ReportProgress(0, "Loading \"listfile\"..."); if (!File.Exists(path)) { Logger.WriteLine("WowRootHandler: list file missing!"); return; } Logger.WriteLine("WowRootHandler: loading file names..."); Dictionary <string, Dictionary <ulong, string> > dirData = new Dictionary <string, Dictionary <ulong, string> >(StringComparer.OrdinalIgnoreCase); dirData[""] = new Dictionary <ulong, string>(); using (var fs = new FileStream("listfile.bin", FileMode.Create)) using (var bw = new BinaryWriter(fs)) using (var fs2 = File.Open(path, FileMode.Open)) using (var sr = new StreamReader(fs2)) { string file; while ((file = sr.ReadLine()) != null) { ulong fileHash = Hasher.ComputeHash(file); // skip invalid names if (!RootData.ContainsKey(fileHash)) { Logger.WriteLine("Invalid file name: {0}", file); continue; } CASCFile.FileNames[fileHash] = file; int dirSepIndex = file.LastIndexOf('\\'); if (dirSepIndex >= 0) { string key = file.Substring(0, dirSepIndex); if (!dirData.ContainsKey(key)) { dirData[key] = new Dictionary <ulong, string>(); } dirData[key][fileHash] = file.Substring(dirSepIndex + 1); } else { dirData[""][fileHash] = file; } worker?.ReportProgress((int)(sr.BaseStream.Position / (float)sr.BaseStream.Length * 100)); } bw.Write(dirData.Count); // count of dirs foreach (var dir in dirData) { bw.Write(dir.Key); // dir name Logger.WriteLine(dir.Key); bw.Write(dirData[dir.Key].Count); // count of files in dir foreach (var fh in dirData[dir.Key]) { bw.Write(fh.Key); // file name hash bw.Write(fh.Value); // file name (without dir name) } } Logger.WriteLine("WowRootHandler: loaded {0} valid file names", CASCFile.FileNames.Count); } File.SetLastWriteTime("listfile.bin", File.GetLastWriteTime(path)); } }
public HashedExpression(Expression expression) { this.expression = expression; this.hashCode = Hasher.ComputeHash(expression); }
public HashProvider() { this.hasher = new Hasher(); }