public void HashValueTest()
        {
            var hashVal = new HashValue();
            var result  = hashVal.GetHashValue("VSR");

            Assert.Equal(124, result);
        }
Example #2
0
 public override byte[] ToBytes()
 {
     return(TLUtils.Combine(
                TLUtils.SignatureToBytes(Signature),
                HashValue.ToBytes(),
                Sets.ToBytes()));
 }
Example #3
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("recruitment test credentials process request.");

            string      requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            Credentials cred        = JsonConvert.DeserializeObject <Credentials>(requestBody);

            if (cred == null || cred.password == null || cred.password.Length == 0)
            {
                return(new BadRequestResult());
            }

            try
            {
                HashValue hashValue = new HashValue();
                hashValue.hash_value = CreateMD5Hash(cred.password);
                return(new OkObjectResult(hashValue));
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.Message);
                return(new BadRequestResult());
            }
        }
Example #4
0
        /// <summary>
        /// </summary>
        /// <param name="Algo"></param>
        public byte[] ComputeLargeStreamHash(Stream Stream, RateTracker Tracker, ChecksumProgressEventHandler Callback)
        {
            // Buffer size optimized for reading massive files.
            byte[] buffer = MemoryPool.AllocBuffer(BufferSize);
            int    bytesRead;

            do
            {
                bytesRead = Stream.Read(buffer, 0, BufferSize);
                if (bytesRead > 0)
                {
                    HashCore(buffer, 0, bytesRead);

                    if (Callback != null)
                    {
                        Callback?.Invoke(bytesRead);
                    }

                    if (Tracker != null)
                    {
                        Tracker.Out(bytesRead);
                    }
                }
            } while (bytesRead > 0);

            HashValue = HashFinal();
            byte[] Tmp = (byte[])HashValue.Clone();
            Initialize();

            MemoryPool.ReleaseBuffer(buffer);
            return(Tmp);
        }
        public void HashValueEmptyStringTest()
        {
            var hashVal = new HashValue();
            var result  = hashVal.GetHashValue("");

            Assert.Equal(-1, result);
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var    iconBytes = Convert.FromBase64String(model.IconBase64);
                var    container = AzureStorageFactory.GetBlobContainer("werewolfkill", true);
                string blobName  = string.Format("icon/{0}.png", HashValue.md5(iconBytes));
                var    user      = new ApplicationUser(model.Username)
                {
                    //UserName = model.Username,
                    NickName  = string.IsNullOrEmpty(model.Nickname) ? model.Username : model.Nickname,
                    AvatarUrl = string.Format("{0}/{1}", container.EndpointUrl, blobName)
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await container.UploadBlob(blobName, iconBytes);

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #7
0
 public OngoingBlock(long index, INode node, HashValue previousHash, IReadOnlyList <Transaction> transactions)
 {
     Index        = index;
     Node         = node;
     PreviousHash = previousHash;
     Transactions = transactions;
 }
Example #8
0
        public RecruitmentTests()
        {
            // prepare mock httpclient
            var mockHttpMessageHandler = new Mock <HttpMessageHandler>();

            HashValue hashValue = new HashValue();

            hashValue.hash_value = "4ED9407630EB1000C0F6B63842DEFA7D";

            mockHttpMessageHandler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(hashValue))
            });

            var client = new HttpClient(mockHttpMessageHandler.Object);

            client.BaseAddress = new Uri("https://alternis.azurewebsites.net/api/CalcHash?code=5Fo6KFASKuXSHN5TwZOhlX9QoIk/bZn5mNANuhG7KQX4Rx5NaQat8g==");
            _httpClientFactoryMock.Setup(_ => _.CreateClient(It.IsAny <string>())).Returns(client);

            // prepare mock config
            _configMock.SetupGet(m => m[It.Is <string>(s => s == "functionUrl")]).Returns("https://alternis.azurewebsites.net/api/CalcHash");
            _configMock.SetupGet(m => m[It.Is <string>(s => s == "functionCode")]).Returns("5Fo6KFASKuXSHN5TwZOhlX9QoIk/bZn5mNANuhG7KQX4Rx5NaQat8g==");

            //
            _hashController = new HashController(_loggerMock.Object, _configMock.Object, _httpClientFactoryMock.Object);
        }
Example #9
0
        public new byte[] ComputeHash(Stream stream)
        {
            size           = stream.Length;
            totalBytesRead = 0;

            isHashing = true;

            // Default the buffer size to 4K.
            byte[] buffer = new byte[4096];
            int    bytesRead;

            do
            {
                bytesRead = stream.Read(buffer, 0, 4096);
                if (bytesRead > 0)
                {
                    HashCore(buffer, 0, bytesRead);
                }
            } while (bytesRead > 0 && isHashing);

            if (!isHashing)
            {
                Initialize();
                return(null);
            }

            HashValue = HashFinal();
            byte[] Tmp = (byte[])HashValue.Clone();
            Initialize();

            return(Tmp);
        }
Example #10
0
        public bool Contains(Field item)
        {
            switch (fieldType)
            {
            case FieldType.Object:
                return(HashValue.ContainsValue(item));

            case FieldType.Array:
                return(ListValue.Contains(item));

            case FieldType.String:
                switch (item.fieldType)
                {
                case FieldType.Integer:
                case FieldType.Float:
                case FieldType.String:
                    return(StringValue.Contains((string)item));

                default:
                    return(false);
                }

            default:
                return(false);
            }
        }
Example #11
0
 public Transaction(IUser user, HashValue previous, HashValue signature, UserMessage message)
 {
     User      = user;
     Previous  = previous;
     Signature = signature;
     Message   = message;
 }
Example #12
0
 public byte[] ComputeHash(byte[] buffer, int offset, int count)
 {
     Initialize();
     HashCore(buffer, offset, count);
     HashValue = HashFinal();
     return((byte[])HashValue.Clone());
 }
Example #13
0
        public UserRole(string userId, string roleName)
        {
            string roleId = HashValue.md5(roleName);

            PartitionKey = UserId = userId;
            RowKey       = RoleName = roleName;
            RoleId       = roleId;
        }
Example #14
0
        public void CreateFromToStringResult()
        {
            var hash   = new HashValue(new byte[] { 0x99, 0xE9, 0xD8, 0x51, 0x37, 0xDB, 0x46, 0xEF });
            var str    = hash.ToString();
            var result = new HashValue(str);

            result.Should().BeEquivalentTo(hash);
        }
Example #15
0
 IEnumerator <KeyValuePair <string, Field> > IEnumerable <KeyValuePair <string, Field> > .GetEnumerator()
 {
     if (fieldType == FieldType.Object)
     {
         return(HashValue.GetEnumerator());
     }
     return(Enumerable.Empty <KeyValuePair <string, Field> >().GetEnumerator());
 }
Example #16
0
        public static FlowToken Deserialize(string serialziedFlowToken, bool includeHashValue)
        {
            if (string.IsNullOrEmpty(serialziedFlowToken))
            {
                throw new ArgumentNullException("serialziedFlowToken");
            }

            Dictionary <string, string> dic = StringConversionServices.ParseKeyValueCollection(serialziedFlowToken);

            if ((dic.ContainsKey("flowTokenType") == false) ||
                (dic.ContainsKey("flowToken") == false) ||
                ((includeHashValue) && (dic.ContainsKey("flowTokenHash") == false)))
            {
                throw new ArgumentException("The serialziedFlowToken is not a serialized flowToken", "serialziedFlowToken");
            }

            string flowTokenTypeString = StringConversionServices.DeserializeValueString(dic["flowTokenType"]);
            string flowTokenString     = StringConversionServices.DeserializeValueString(dic["flowToken"]);

            if (includeHashValue)
            {
                string flowTokenHash = StringConversionServices.DeserializeValueString(dic["flowTokenHash"]);

                HashValue hashValue = HashValue.Deserialize(flowTokenHash);
                if (HashSigner.ValidateSignedHash(flowTokenString, hashValue) == false)
                {
                    throw new SecurityException("Serialized flow token is tampered");
                }
            }

            Type flowType = TypeManager.GetType(flowTokenTypeString);

            MethodInfo methodInfo = flowType.GetMethod("Deserialize", BindingFlags.Public | BindingFlags.Static);

            if (methodInfo == null || !(typeof(FlowToken).IsAssignableFrom(methodInfo.ReturnType)))
            {
                throw new InvalidOperationException(string.Format("The flow token {0} is missing a public static Deserialize method taking a string as parameter and returning an {1}", flowType, typeof(FlowToken)));
            }


            FlowToken flowToken;

            try
            {
                flowToken = (FlowToken)methodInfo.Invoke(null, new object[] { flowTokenString });
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(string.Format("The flow token {0} is missing a public static Deserialize method taking a string as parameter and returning an {1}", flowType, typeof(FlowToken)), ex);
            }

            if (flowToken == null)
            {
                throw new InvalidOperationException(string.Format("public static Deserialize method taking a string as parameter and returning an {1} on the flow token {0} did not return an object", flowType, typeof(FlowToken)));
            }

            return(flowToken);
        }
Example #17
0
 public Block(long index, INode node, string rnd, HashValue previousBlock, HashValue signature, IReadOnlyList <Transaction> transactions)
 {
     Index         = index;
     Node          = node;
     Rnd           = rnd;
     PreviousBlock = previousBlock;
     Signature     = signature;
     Transactions  = transactions;
 }
        public override HashValue ComputeHash(long offset, long length)
        {
            HashValue retval;

            if (length == 0)
            {
                return(new HashValue(this.Algorithm.ComputeHash(new byte[0]), this.ServiceType.AlgorithmName, offset, 0L));
            }

            if (offset == 0 && length == -1 && ServiceType.AlgorithmType != null)
            {
                var retvaln = GetHashFromCache(this.OperatingNode, this.ServiceType.AlgorithmName);

                if (retvaln != null)
                {
                    return(retvaln.Value);
                }
            }

            var stream = this.OperatingNode.GetContent().GetInputStream();

            if (!(offset == 0 && length == -1 && !stream.CanSeek))
            {
                stream = new PartialStream(stream, offset, length);

                if (length <= 0)
                {
                    stream = new BufferedStream(stream, 128 * 1024);
                }
                else
                {
                    stream = new BufferedStream(stream, Math.Min(128 * 1024, (int)length));
                }
            }

            var meteringStream = new MeteringStream(stream);

            using (meteringStream)
            {
                retval = new HashValue(this.Algorithm.ComputeHash(meteringStream), this.ServiceType.AlgorithmName, offset, Convert.ToInt64(meteringStream.ReadMeter.Value));
            }

            if (offset == 0 && length == -1 && ServiceType.AlgorithmType != null)
            {
                try
                {
                    //	SaveHashToCache(this.OperatingNode, this.ServiceType.AlgorithmName, retval);
                }
                catch (IOException)
                {
                    // TODO: Log
                }
            }

            return(retval);
        }
Example #19
0
        public override void ToStream(Stream output)
        {
            output.Write(TLUtils.SignatureToBytes(Signature));
            HashValue.ToStream(output);
            Sets.ToStream(output);

            Packs.ToStream(output);
            Documents.ToStream(output);
            MessagesStickerSets.ToStream(output);
        }
Example #20
0
        private byte[] CaptureHashCodeAndReinitialize()
        {
            HashValue = HashFinal();

            // Clone the hash value prior to invoking Initialize in case the user-defined Initialize
            // manipulates the array.
            byte[] tmp = (byte[])HashValue.Clone();
            Initialize();
            return(tmp);
        }
        public void HashValue_BitLength_IsSameAsConstructorValue()
        {
            var validBitLengths = Enumerable.Range(1, 16);

            foreach (var validBitLength in validBitLengths)
            {
                var hashValue = new HashValue(new byte[2], validBitLength);

                Assert.Equal(validBitLength, hashValue.BitLength);
            }
        }
        public HashValue Sign(IUser user, HashValue previousHash, UserMessage message)
        {
            using (var stream = _streamFactory.Create())
            {
                stream.Write("Client {0} after {1} ask for ", user, previousHash);
                _messageStreamWriter.Write(stream, message);

                var hash = _hashProvider.GetHashOfStream(stream);
                return(hash);
            }
        }
		public virtual HashValue ComputeHash(HashValue inputResult, long outputOffset, long outputLength)
		{
			var service = (IHashingService)this.OperatingNode.GetService((HashingServiceType)this.ServiceType.Clone(inputResult.AlgorithmName));
			var result = service.ComputeHash(inputResult.Offset, inputResult.Length);

			if (result.Equals(inputResult))
			{
				return inputResult;
			}

			return ComputeHash(outputOffset, outputLength);
		}
Example #24
0
        public bool IsSatisfy(HashValue hash, string factor)
        {
            var hashValue = hash.Value;

            //align size
            if (factor.Length < hashValue.Length)
            {
                factor = "00000000000000".Substring(0, hashValue.Length - factor.Length) + factor;
            }

            return(hashValue.CompareTo(factor) <= 0);
        }
Example #25
0
        public virtual HashValue ComputeHash(HashValue inputResult, long outputOffset, long outputLength)
        {
            var service = (IHashingService)this.OperatingNode.GetService((HashingServiceType)this.ServiceType.Clone(inputResult.AlgorithmName));
            var result  = service.ComputeHash(inputResult.Offset, inputResult.Length);

            if (result.Equals(inputResult))
            {
                return(inputResult);
            }

            return(ComputeHash(outputOffset, outputLength));
        }
Example #26
0
        public byte[] ComputeHash(Stream inputStream)
        {
            Initialize();
            int count;

            byte[] buffer = new byte[4096];
            while (0 < (count = inputStream.Read(buffer, 0, 4096)))
            {
                HashCore(buffer, 0, count);
            }
            HashValue = HashFinal();
            return((byte[])HashValue.Clone());
        }
        public void HashValue_AsBitArray_ExpectedValues()
        {
            var hashValue = new HashValue(new byte[] { 173 }, 8);
            var bitArray  = hashValue.AsBitArray();

            Assert.True(bitArray[0]);
            Assert.False(bitArray[1]);
            Assert.True(bitArray[2]);
            Assert.True(bitArray[3]);
            Assert.False(bitArray[4]);
            Assert.True(bitArray[5]);
            Assert.False(bitArray[6]);
            Assert.True(bitArray[7]);
        }
        public async Task <ActionResult> ChangeIcon(ChangeIconViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var    iconBytes = Convert.FromBase64String(model.IconBase64);
            var    container = AzureStorageFactory.GetBlobContainer("werewolfkill", true);
            string blobName  = string.Format("icon/{0}.png", HashValue.md5(iconBytes));
            await container.UploadBlob(blobName, iconBytes);

            ViewData["Message"] = "Success";
            return(PartialView());
        }
Example #29
0
        public async Task ComputeHashAsync(byte[] expected, byte[] data)
        {
            //Arrange
            var expectedV = new HashValue(expected);
            var stream    = new MemoryStream(data);
            var hash      = new XXHash64();

            //Act
            var result = await hash.ComputeHashAsync(stream, CancellationToken.None);

            //Assert
            Assert.Equal(expectedV, result);
            Assert.Equal <byte>(expectedV.Value, result.Value);
        }
        public void HashValue_AsHexString_ExpectedValue()
        {
            var hashValue = new HashValue(new byte[] { 173, 0, 255 }, 24);

            Assert.Equal(
                "ad00ff",
                hashValue.AsHexString());

            Assert.Equal(
                "ad00ff",
                hashValue.AsHexString(false));

            Assert.Equal(
                "AD00FF",
                hashValue.AsHexString(true));
        }
Example #31
0
        public override void ToStream(Stream output)
        {
            output.Write(TLUtils.SignatureToBytes(Signature));
            HashValue.ToStream(output);
            Packs.ToStream(output);

            Sets.ToStream(output);
            Documents.ToStream(output);
            ShowStickersTab.NullableToStream(output);
            RecentlyUsed.NullableToStream(output);
            Date.NullableToStream(output);
            CustomFlags.ToStream(output);
            ToStream(output, RecentStickers, CustomFlags, (int)AllStickersCustomFlags.RecentStickers);
            ToStream(output, FavedStickers, CustomFlags, (int)AllStickersCustomFlags.FavedStickers);
            ToStream(output, _showStickersByEmoji, CustomFlags, (int)AllStickersCustomFlags.ShowStickersByEmoji);
        }
Example #32
0
        /// <exclude />
        public static bool ValidateSignedHash(string content, HashValue hashValue)
        {
            HashValue newHashValue = GetSignedHash(content);

            return newHashValue.Equals(hashValue);
        }
		public virtual HashValue ComputeHash(HashValue inputResult)
		{
			return ComputeHash(inputResult, 0, -1);
		}