Example #1
0
        private bool TryGenerateNumber(int offset, out int number, long?value = null)
        {
            number = 0;

            var         bufflen   = 8 + this.Settings.Additional.Length;
            Span <byte> challenge = stackalloc byte[bufflen];

            if (value == null)
            {
                if (!this.Settings.TryGetChallengeInput(challenge, out bufflen, offset))
                {
                    return(false);
                }
            }
            else
            {
                if (!this.Settings.TryGetChallengeInput(value.Value, challenge, out bufflen))
                {
                    return(false);
                }
            }

            using var hmac = HmacProviderSelector.FromId(this.Settings.Algorithm);
            Span <byte> buff = stackalloc byte[hmac.OutputSize];

            if (!hmac.TryCompute(this.Settings.Secret.AsSpan(), challenge, buff, out bufflen))
            {
                return(false);
            }

            var transformer = CodeTransformerSelector.FromId(CodeTransformer.Rfc4226);

            if (!transformer.TryTransform(buff.Slice(0, bufflen), out number))
            {
                return(false);
            }

            return(true);
        }
Example #2
0
        private int GenerateNumber(int offset = 0, long?value = null)
        {
            var         bufflen   = 8 + this.Settings.Additional.Length;
            Span <byte> challenge = stackalloc byte[bufflen];

            if (value == null)
            {
                if (!this.Settings.TryGetChallengeInput(challenge, out bufflen, offset))
                {
                    throw new Exception("Failed to generate challenge.");
                }
            }
            else
            {
                if (!this.Settings.TryGetChallengeInput(value.Value, challenge, out bufflen))
                {
                    throw new Exception("Failed to generate challenge.");
                }
            }

            using var hmac = HmacProviderSelector.FromId(this.Settings.Algorithm);
            Span <byte> buff = stackalloc byte[hmac.OutputSize];

            if (!hmac.TryCompute(this.Settings.Secret.AsSpan(), challenge, buff, out bufflen))
            {
                throw new Exception("Failed to compute HMAC.");
            }

            var transformer = CodeTransformerSelector.FromId(CodeTransformer.Rfc4226);

            if (!transformer.TryTransform(buff.Slice(0, bufflen), out var number))
            {
                throw new Exception("Failed to transform HMAC.");
            }

            return(number);
        }