public string GetPostUrl(string method, string body) { var bodyMD5 = HashUtil.MD5(body); var timeSpan = DateTime.Now.ToUnixTimestamp(); var rsa2Data = $"biz_content={bodyMD5}&method={method}&partner={_partner}×tamp={timeSpan}&version={_version}"; var signData = _rsa.SignData(rsa2Data.GetBytes(), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); string sign = signData.ToHexString(); return($"{Url}&method={method}×tamp={timeSpan}&sign={sign}"); }
public AssetTarget(Object o, FileInfo file, string assetPath) { this.asset = o; this.file = file; this.assetPath = assetPath; this.bundleShortName = file.Name.ToLower(); this.bundleName = HashUtil.Get(AssetBundleUtils.ConvertToABName(assetPath)) + ".ab"; this.bundleSavePath = Path.Combine(AssetBundleBuildPath.BundleSavePath, bundleName); _isFileChanged = true; _metaHash = "0"; }
public ChangePasswordViewModel() { this.RefreshCaptcha = new DelegateCommand(() => { ActionCaptchaId = Guid.NewGuid(); }); this.Ok = new DelegateCommand(() => { if (string.IsNullOrEmpty(OldPassword)) { VirtualRoot.Out.ShowWarn("未填写旧密码"); return; } if (RpcRoot.RpcUser.Password != HashUtil.Sha1(OldPassword)) { VirtualRoot.Out.ShowWarn("旧密码错误"); return; } if (string.IsNullOrEmpty(NewPassword)) { VirtualRoot.Out.ShowWarn("未填写新密码"); return; } if (string.IsNullOrEmpty(NewPasswordAgain)) { VirtualRoot.Out.ShowWarn("未填写重复密码"); return; } if (NewPassword != NewPasswordAgain) { VirtualRoot.Out.ShowWarn("两次输入的密码不一致"); return; } if (string.IsNullOrEmpty(ActionCaptcha)) { VirtualRoot.Out.ShowWarn("未填写验证码"); return; } RpcRoot.OfficialServer.UserService.ChangePasswordAsync(new ChangePasswordRequest { NewPassword = HashUtil.Sha1(NewPassword), ActionCaptcha = ActionCaptcha, ActionCaptchaId = ActionCaptchaId }, (response, e) => { if (!response.IsSuccess()) { VirtualRoot.Out.ShowError(response.ReadMessage(e), header: "修改密码失败", autoHideSeconds: 4); } else { VirtualRoot.Execute(new CloseWindowCommand(this.Id)); } }); }); }
/// <summary> /// 比较本地ab的cache.txt文件的文本与服务器的文本得出差异 /// 参数1:本地cache.txt文本 参数2:服务器cache.txt 文本 /// </summary> private void GetUpdateDownLoadAssetBundles(string localCacheFileText, string serverCacheFileText) { if (string.IsNullOrEmpty(serverCacheFileText)) { DebugManager.LogError("服务器 cache.txt 的文本存在空值!serverCacheFileText:" + serverCacheFileText); return; } if (serverCacheFileText.Equals(localCacheFileText)) { DebugManager.LogWarning("cache.txt 本地与服务器文本相同,不做比较,继续更新! localCacheFileText:" + localCacheFileText + "serverCacheFileText:" + serverCacheFileText); //return; } var serverCacheFileData = ResolveCacheFile(serverCacheFileText);//服务器cache.txt数据 //Dictionary<string, CacheFileDataModel> localCacheFileData = null; //if (localCacheFileText == null) //{ // localCacheFileData = new Dictionary<string, CacheFileDataModel>(); //} //else //{ // localCacheFileData = ResolveCacheFile(localCacheFileText);//本地cache.txt数据 //} if (waitDownloadAssetBundleList == null) { waitDownloadAssetBundleList = new List <AssetBundleDownloadModel>(); } //对比服务器与本地的数据 foreach (var v in serverCacheFileData) { var tempABData = AssetBundleDepFileManager.Instance.GetAssetBundleDataOfABFullName(v.Key); //dep.ll 文件中的ab信息 var tempFileUrl = ABDataConfig.localABFullName + tempABData.fullName; //源资源文件路径 //得到ab文件与ab依赖文件的哈希值组合 var tempFileHash = HashUtil.GetFileHash(tempFileUrl) + "|" + HashUtil.GetFileHash(tempFileUrl + ABDataConfig.assetBundleManifestFilePostfixName); if (v.Value.fileHash.Equals(tempFileHash)) { DebugManager.Log(tempABData.fullName + " " + v.Key + " 资源文件与依赖文件哈希值与服务器一致!不用更新!"); continue; } DebugManager.Log(tempABData.fullName + " " + v.Key + " 需要更新!添加到更新列表!"); waitDownloadAssetBundleList.Add(new AssetBundleDownloadModel { assetBundleFileName = tempABData.fullName, assetBundleManifestFileName = tempABData.fullName + ABDataConfig.assetBundleManifestFilePostfixName, assetBundleName = tempABData.debugName, }); } }
private async Task CheckLocalConfig(string agentName, CacheData cacheData) { string dataId = cacheData.DataId; string group = cacheData.Group; string tenant = cacheData.Tenant; var path = FileLocalConfigInfoProcessor.GetFailoverFile(agentName, dataId, group, tenant); if (!cacheData.IsUseLocalConfig && path.Exists) { string content = await FileLocalConfigInfoProcessor.GetFailoverAsync(agentName, dataId, group, tenant); string md5 = HashUtil.GetMd5(content); cacheData.SetUseLocalConfigInfo(true); cacheData.SetLocalConfigInfoVersion(path.LastWriteTimeUtc.ToTimestamp()); cacheData.SetContent(content); _logger?.LogWarning( "[{0}] [failover-change] failover file created. dataId={1}, group={2}, tenant={3}, md5={4}, content={5}", agentName, dataId, group, tenant, md5, ContentUtils.TruncateContent(content)); return; } // If use local config info, then it doesn't notify business listener and notify after getting from server. if (cacheData.IsUseLocalConfig && !path.Exists) { cacheData.SetUseLocalConfigInfo(false); _logger?.LogWarning( "[{0}] [failover-change] failover file deleted. dataId={1}, group={2}, tenant={3}", agentName, dataId, group, tenant); return; } // When it changed. if (cacheData.IsUseLocalConfig && path.Exists && cacheData.GetLocalConfigInfoVersion() != path.LastWriteTimeUtc.ToTimestamp()) { string content = await FileLocalConfigInfoProcessor.GetFailoverAsync(agentName, dataId, group, tenant); string md5 = HashUtil.GetMd5(content); cacheData.SetUseLocalConfigInfo(true); cacheData.SetLocalConfigInfoVersion(path.LastWriteTimeUtc.ToTimestamp()); cacheData.SetContent(content); _logger?.LogWarning( "[{0}] [failover-change] failover file created. dataId={1}, group={2}, tenant={3}, md5={4}, content={5}", agentName, dataId, group, tenant, md5, ContentUtils.TruncateContent(content)); } }
public void Validate_hash() { foreach (var algorithmType in this.algorithmTextAndHashes.Keys) { var textsAndHashes = this.algorithmTextAndHashes[algorithmType]; foreach (var keyValuePair in textsAndHashes) { byte[] bytes = Encoding.UTF8.GetBytes(keyValuePair.Key); Assert.AreEqual(keyValuePair.Value, HashUtil.ComputeHash(bytes, algorithmType)); } } }
private void ConstructRequestHeader(HttpMethod httpMethod, string method, string url, string body) { string timestamp = DateTime.Now.ToString(RESTConstants.TIMESTAMP_FORMAT, CultureInfo.InvariantCulture); httpMethod.AddRequestHeader(RESTConstants.HEADER_REQUEST_ID, (new Guid()).ToString()); if (requireClientSignature) { httpMethod.AddRequestHeader(RESTConstants.HEADER_CLIENT_ID, clientId); httpMethod.AddRequestHeader(RESTConstants.HEADER_TIMESTAMP, timestamp); httpMethod.AddRequestHeader(RESTConstants.HEADER_CLIENT_SIGNATURE, HashUtil.SHA1Sign(BuildSignMessage(method, url, body), clientKey, encoding)); } }
private void OpSha256(ParsedOpCode op) { if (!Options.EnableSha256) { OpNop(op); return; } var data = MainStack.Pop(); var hash = HashUtil.Sha256(data); MainStack.Push(hash); }
public HostedAdminRequest(string message, string secretWord, string merchantId, string endPointBase) { EndPointBase = endPointBase; Message = message; SecretWord = secretWord; MerchantId = merchantId; MessageBase64Encoded = Base64Util.EncodeBase64String(Message); Mac = HashUtil.CreateHash(MessageBase64Encoded + secretWord); MessageXmlDocument = new XmlDocument(); MessageXmlDocument.LoadXml(message); }
public LoginResponse LoginRequest(LoginRequest request) { var hasRegister = _userLoginRepository.FindByLogin(request.Login, HashUtil.HashPassword(request.Password)); if (hasRegister) { return(new LoginResponse(TokenUtil.GenerateTokenJWT())); } else { return(null); } }
public void Parameter_checks() { string text = null; var ane = Assert.Throws <ArgumentNullException>(delegate { HashUtil.ComputeHash(text); }); Assert.That(ane.Message, Contains.Substring("text"), "Test 1"); text = string.Empty; Assert.DoesNotThrow(delegate { HashUtil.ComputeHash(text); }, "Test 2"); text = " "; Assert.DoesNotThrow(delegate { HashUtil.ComputeHash(text); }, "Test 3"); }
public void HashUtilTest() { string[] values = new[] { "ntminer", "测试", "helloworld", "s d-," }; foreach (var value in values) { string v1 = HashUtil.EncDecInOne(value); Console.WriteLine(v1); Assert.AreEqual(value, HashUtil.EncDecInOne(v1)); } }
private ABTarget(UnityEngine.Object obj, FileInfo file, string assetPath) { this.asset = obj; this.fileInfo = file; this.assetPath = assetPath; this.bundleName = ConvertToABName() + ".ab"; this.bundleSavePath = Path.Combine(ABExportConst.PlatformBundleSavePath, bundleName); using (FileStream fs = new FileStream(assetPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { fileHash = HashUtil.Get(fs); fs.Close(); } }
public string GetSign(string password) { StringBuilder sb = new StringBuilder(); sb.Append(nameof(MessageId)).Append(MessageId) .Append(nameof(LoginName)).Append(LoginName) .Append(nameof(ClientId)).Append(ClientId) .Append(nameof(PropertyName)).Append(PropertyName) .Append(nameof(Value)).Append(Value) .Append(nameof(Timestamp)).Append(Timestamp.ToUlong()) .Append(nameof(IUser.Password)).Append(password); return(HashUtil.Sha1(sb.ToString())); }
public void Hash_does_not_matches_the_text() { // Arrange var message = "passw0rd"; var salt = SaltUtil.Create(); var hash = "blahblahblah"; // Act var match = HashUtil.Validate(message, salt, hash); // Assert Assert.False(match); }
public string CaclculateMachineHash(string salt) { if (string.IsNullOrEmpty(salt)) { throw new ArgumentException("salt"); } var serialString = SystemVolumeSerial.ToString("X8"); var hashBase = serialString + WindowsProductId + salt; return(HashUtil.GetSha1Hash(hashBase)); }
public void HashMatchesText() { // Arrange var message = "passw0rd"; var salt = SaltUtil.Create(); var hash = HashUtil.Create(message, salt); // Act var match = HashUtil.Validate(message, salt, hash); // Assert Assert.True(match); }
public static string GenerateBogus32BitPassword(string username) { byte[] sequence = new byte[32]; for (byte n = 0; n < sequence.Length; ++n) { sequence[n] = n; } String password = Convert.ToBase64String(sequence); byte[] salt = Encoding.UTF8.GetBytes(username); return(Convert.ToBase64String(HashUtil.Sha256Pbkdf2(password, salt, 5000, 32))); }
public void IsApplicationCreatorTestInvalidApplication() { ApplicationStorageView application = new ApplicationStorageView("username1"); string applicationId = _managerStorage.AddApplication(application); string invalidApplicationId = Guid.NewGuid().ToString(); SecurityCredentials sc = new SecurityCredentials("username1", HashUtil.GetHash("password1", HashType.MD5)); bool result = IsApplicationCreator(sc, invalidApplicationId); Assert.IsFalse(result); }
public void InsertOneEmployeeTest() { var salt = Guid.NewGuid().ToString(); var hashedPassword = HashUtil.Md5PasswordWithSalt("123456", salt); var item = new Employee() { Id = Guid.NewGuid(), Username = "******", Password = hashedPassword, Salt = salt, RealName = "张三", CreateTime = DateTime.Now }; _employeeRepository.InsertAsync(item).GetAwaiter().GetResult(); _uow.SaveChangesAsync().GetAwaiter().GetResult(); _uow.CommitAsync().GetAwaiter().GetResult(); }
private void BtnLogin_OnClick(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(Vm.ServerHost)) { Vm.ShowMessage("服务器地址不能为空"); return; } string passwordSha1 = HashUtil.Sha1(Vm.Password); NTMinerRegistry.SetControlCenterHost(Vm.ServerHost); var list = NTMinerRegistry.GetControlCenterHosts(); if (!list.Contains(Vm.ServerHost)) { list.Insert(0, Vm.ServerHost); } NTMinerRegistry.SetControlCenterHosts(list); if (Net.Util.IsInnerIp(Vm.ServerHost)) { SingleUser.LoginName = "localhost"; SingleUser.SetPasswordSha1("localhost"); this.Close(); return; } Server.ControlCenterService.LoginAsync(Vm.LoginName, passwordSha1, (response, exception) => { UIThread.Execute(() => { if (response == null) { Vm.ShowMessage("服务器忙"); return; } if (response.IsSuccess()) { SingleUser.LoginName = Vm.LoginName; SingleUser.SetPasswordSha1(passwordSha1); this.Close(); } else if (Vm.LoginName == "admin" && response.StateCode == 404) { Vm.IsPasswordAgainVisible = Visibility.Visible; Vm.ShowMessage(response.Description); this.PbPasswordAgain.Focus(); } else { Vm.IsPasswordAgainVisible = Visibility.Collapsed; Vm.ShowMessage(response.Description); } }); }); }
public string DecryptPrivateKey(string encryptJson, string passphrase) { KeystoreV3 keystoreV3 = JsonConvert.DeserializeObject <KeystoreV3>(encryptJson); byte[] ciphertext = ByteUtil.HexStringToByteArray(keystoreV3.Crypto.Ciphertext); byte[] iv = ByteUtil.HexStringToByteArray(keystoreV3.Crypto.Cipherparams.Iv); Kdfparams kp = keystoreV3.Crypto.Kdfparams; string kdf = keystoreV3.Crypto.Kdf; byte[] derivedKey; if (kdf == "pbkdf2") { PBKDF2Params pbkdf2Params = new PBKDF2Params(); pbkdf2Params.Salt = ByteUtil.ByteArrayToHexString(kp.Salt); pbkdf2Params.DkLen = 32; pbkdf2Params.Count = 262144; derivedKey = GetDerivedKey(Encoding.Default.GetBytes(passphrase), pbkdf2Params); } else { ScryptParams scryptParams = new ScryptParams(); scryptParams.Salt = ByteUtil.ByteArrayToHexString(kp.Salt); scryptParams.DkLen = 32; scryptParams.P = 1; scryptParams.R = 8; scryptParams.N = 8192; derivedKey = GetDerivedKey(Encoding.Default.GetBytes(passphrase), scryptParams); } string mac = ByteUtil.ByteArrayToHexString(HashUtil.GenerateMac(derivedKey, ciphertext)); if (mac.ToUpper() != keystoreV3.Crypto.Mac) { throw new Exception("Failed to decrypt."); } byte[] encryptKey = new byte[16]; Array.Copy(derivedKey, encryptKey, 16); //TODO 加密方法待完善 System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = encryptKey, Mode = CipherMode.CBC, Padding = System.Security.Cryptography.PaddingMode.None }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); byte[] ciphertextByte = cTransform.TransformFinalBlock(ciphertext, 0, ciphertext.Length); return(ByteUtil.ByteArrayToHexString(ciphertextByte)); }
public void Decode(string fileName) { using (BinaryReader reader = new BinaryReader(new FileStream(fileName, FileMode.Open))) { Header = WpgFileHeader.Load(reader); if (Header.Magic != "RPKG") { Console.WriteLine(String.Format("File Magic \"{0}\" does not match IS's \"RPKG\"", Header.Magic)); return; } reader.Seek(136, SeekOrigin.Begin); int AssetCount = reader.ReadInt32(); for (int i = 1; i < AssetCount + 1; i++) { reader.Seek(i * 140, SeekOrigin.Begin); string FileNameString = reader.ReadFixedString(128); int location = reader.ReadInt32(); int length = reader.ReadInt32(); string filetype = Path.GetExtension(FileNameString.Replace("-", "_")); if (filetype == ".msh" || filetype == ".dds" || filetype == ".fsb") { reader.Seek(location, SeekOrigin.Begin); Console.WriteLine("Exporting file : " + FileNameString); int blockSize = reader.ReadInt32(); int EncryptionNumber = reader.ReadInt16(); if (EncryptionNumber == -25480) { string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string output = path + "\\exported_files\\" + FileNameString; ScobUtil.CreateFilePath(path + "\\exported_files\\" + FileNameString); MemoryStream DecodedCodeStream = HashUtil.Decode(reader.ReadBytes(blockSize - 2), FileNameString); using (var outputStream = new FileStream(output, FileMode.Create)) { DecodedCodeStream.CopyTo(outputStream); if (filetype == ".msh") { outputStream.Close(); MshFile mshFile = new MshFile(); mshFile.Decode(output); File.Delete(output); } } } } } } }
public TMD(AppXMLInfo appInfo, FST fst, Ticket ticket) { groupID = appInfo.groupID; systemVersion = appInfo.osVersion; appType = appInfo.appType; titleVersion = appInfo.titleVersion; this.ticket = ticket; contents = fst.contents; contentCount = contents.GetContentCount(); contentInfo = new ContentInfo(contentCount) { SHA2Hash = HashUtil.HashSHA2(contents.GetAsData()) }; }
public ClientConnection(TcpClient client, Server server, IClientDataReceiver receiver = null, ILogger logger = null) { this.isConnected = false; this.client = client; this.stream = this.client.GetStream(); this.receiver = receiver; this.logger = logger; this.server = server; this.Id = HashUtil.HashMD5(GetIp() + GetPort()); InitilizeListenerThread(); }
public void Hash_of_two_different_messages_dont_match() { // Arrange var message1 = "passw0rd"; var message2 = "password"; var salt = SaltUtil.Create(); // Act var hash1 = HashUtil.Create(message1, salt); var hash2 = HashUtil.Create(message2, salt); // Assert Assert.AreNotEqual(hash1, hash2); }
/// <summary> /// Overrides the default hash code /// </summary> /// <returns>Unique int value for an object</returns> public override int GetHashCode() { int hashcode = 17; hashcode = HashUtil.SimpleObjectHashBuilderHelper(hashcode, base.GetHashCode()); hashcode = HashUtil.SimpleObjectHashBuilderHelper(hashcode, HostName); hashcode = HashUtil.SimpleObjectHashBuilderHelper(hashcode, Version); hashcode = HashUtil.SimpleObjectHashBuilderHelper(hashcode, MaxPlayers); hashcode = HashUtil.SimpleObjectHashBuilderHelper(hashcode, MaxPing); hashcode = HashUtil.SimpleObjectHashBuilderHelper(hashcode, MinPing); hashcode = HashUtil.SimpleObjectHashBuilderHelper(hashcode, Date); return(hashcode); }
public void ECSecurityService_VerifySignature_VerifiesGeneratedSignatureAgainstPublicKey() { const bool isCompressed = false; var messageHash = HashUtil.Blake256(_message); var signature = new ECSignature(_signature); var privateSecurityService = new ECPrivateSecurityService(_privateKey); var publicKeyBytes = privateSecurityService.GetPublicKey(isCompressed); var publicSecurityService = new ECPublicSecurityService(publicKeyBytes); var hasValidSignature = publicSecurityService.VerifySignature(messageHash, signature); Assert.True(hasValidSignature); }
/// <summary> /// Calculates the hash of a transaction to be signed. /// </summary> /// <param name="transaction"></param> /// <returns></returns> private byte[] CalculateTxHash(MsgTx transaction) { var wbuf = new List <byte>(32 * 2 + 4); wbuf.AddRange(BitConverter.GetBytes((uint)1)); var prefixHash = transaction.GetHash(TxSerializeType.NoWitness); var witnessHash = transaction.GetHash(TxSerializeType.WitnessSigning); wbuf.AddRange(prefixHash); wbuf.AddRange(witnessHash); return(HashUtil.Blake256(wbuf.ToArray())); }
/// <summary> /// Calculates the BLAKE256 hash of the current instance. Witness data is not serialized. /// </summary> /// <returns>The hash as a byte[] with length 32</returns> public byte[] GetHash(TxSerializeType serializationType = TxSerializeType.NoWitness) { byte[] bytes; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { Encode(bw, serializationType); bw.Flush(); bytes = ms.ToArray(); } return(HashUtil.Blake256(bytes)); }