Exemple #1
0
        public async Task <IActionResult> ValidateEmailAndSendCode(string emailAddress)
        {
            var user = await _userManager.FindByEmailAsync(emailAddress);

            if (user == null)
            {
                Random generator = new Random();
                string code      = generator.Next(0, 999999).ToString("D6");

                //var userInformation = new UserInformation() { Code = code, CodeSentOn = DateTime.UtcNow };
                var otp = new OneTimePassword()
                {
                    Key = emailAddress, Value = code, CreatedOn = DateTime.Now
                };
                await _context.OneTimePasswords.AddAsync(otp);

                await _context.SaveChangesAsync();

                string message = $"Your UPCLASS OTP is <h1>{code}</h1>. This code is valid for next 15 minutes only.";
                await _emailSender.SendEmailAsync(emailAddress, "UPCLASS OTP", message);

                return(new JsonResult(new { isExist = false, code }));
            }

            return(new JsonResult(new { isExist = true }));
        }
Exemple #2
0
        public async Task <IActionResult> ValidatePhoneForgotPassword(string phoneNumber)
        {
            var user = _context.Users.FirstOrDefault(x => x.PhoneNumber == phoneNumber);

            if (user != null)
            {
                Random generator = new Random();
                string code      = generator.Next(0, 999999).ToString("D6");

                var otp = new OneTimePassword()
                {
                    Key = phoneNumber, Value = code, CreatedOn = DateTime.Now
                };
                await _context.OneTimePasswords.AddAsync(otp);

                await _context.SaveChangesAsync();

                string message = $"Your UPCLASS OTP is {code}. This code is valid for next 15 minutes only.";
                _smsService.SendSMS(message, phoneNumber);

                return(new JsonResult(new { isExist = true, code }));
            }

            return(new JsonResult(new { isExist = false }));
        }
Exemple #3
0
        public void TOTP_Validate6_SHA256()
        {
            var o = new OneTimePassword(ASCIIEncoding.ASCII.GetBytes("12345678901234567890123456789012"))
            {
                Algorithm = OneTimePasswordAlgorithm.Sha256,
                Digits    = 6
            };

            Assert.True(o.IsCodeValid(119246, new DateTimeOffset(1970, 01, 01, 01, 00, 59, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(084774, new DateTimeOffset(2005, 03, 18, 02, 58, 29, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(062674, new DateTimeOffset(2005, 03, 18, 02, 58, 31, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(819424, new DateTimeOffset(2009, 02, 14, 00, 31, 30, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(698825, new DateTimeOffset(2033, 05, 18, 04, 33, 20, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(737706, new DateTimeOffset(2603, 10, 11, 12, 33, 20, TimeSpan.FromHours(1))));

            Assert.True(o.IsCodeValid(119246, new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(084774, new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(062674, new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(819424, new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(698825, new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(737706, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));

            Assert.True(o.IsCodeValid(119246, new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(084774, new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(062674, new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(819424, new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(698825, new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(737706, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc).ToLocalTime()));
        }
Exemple #4
0
        public void TOTP_Validate6_SHA512()
        {
            var o = new OneTimePassword(ASCIIEncoding.ASCII.GetBytes("1234567890123456789012345678901234567890123456789012345678901234"))
            {
                Algorithm = OneTimePasswordAlgorithm.Sha512,
                Digits    = 6
            };

            Assert.True(o.IsCodeValid(693936, new DateTimeOffset(1970, 01, 01, 01, 00, 59, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(091201, new DateTimeOffset(2005, 03, 18, 02, 58, 29, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(943326, new DateTimeOffset(2005, 03, 18, 02, 58, 31, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(441116, new DateTimeOffset(2009, 02, 14, 00, 31, 30, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(618901, new DateTimeOffset(2033, 05, 18, 04, 33, 20, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(863826, new DateTimeOffset(2603, 10, 11, 12, 33, 20, TimeSpan.FromHours(1))));

            Assert.True(o.IsCodeValid(693936, new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(091201, new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(943326, new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(441116, new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(618901, new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(863826, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));

            Assert.True(o.IsCodeValid(693936, new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(091201, new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(943326, new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(441116, new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(618901, new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(863826, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc).ToLocalTime()));
        }
Exemple #5
0
        public void TOTP_Generate_SHA512()
        {
            var o = new OneTimePassword(ASCIIEncoding.ASCII.GetBytes("1234567890123456789012345678901234567890123456789012345678901234"))
            {
                Algorithm = OneTimePasswordAlgorithm.Sha512,
                Digits    = 8
            };

            Assert.Equal(90693936, o.GetCode(new DateTimeOffset(1970, 01, 01, 01, 00, 59, TimeSpan.FromHours(1))));
            Assert.Equal(25091201, o.GetCode(new DateTimeOffset(2005, 03, 18, 02, 58, 29, TimeSpan.FromHours(1))));
            Assert.Equal(99943326, o.GetCode(new DateTimeOffset(2005, 03, 18, 02, 58, 31, TimeSpan.FromHours(1))));
            Assert.Equal(93441116, o.GetCode(new DateTimeOffset(2009, 02, 14, 00, 31, 30, TimeSpan.FromHours(1))));
            Assert.Equal(38618901, o.GetCode(new DateTimeOffset(2033, 05, 18, 04, 33, 20, TimeSpan.FromHours(1))));
            Assert.Equal(47863826, o.GetCode(new DateTimeOffset(2603, 10, 11, 12, 33, 20, TimeSpan.FromHours(1))));

            Assert.Equal(90693936, o.GetCode(new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc)));
            Assert.Equal(25091201, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc)));
            Assert.Equal(99943326, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc)));
            Assert.Equal(93441116, o.GetCode(new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.Equal(38618901, o.GetCode(new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc)));
            Assert.Equal(47863826, o.GetCode(new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));

            Assert.Equal(90693936, o.GetCode(new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(25091201, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(99943326, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(93441116, o.GetCode(new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(38618901, o.GetCode(new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(47863826, o.GetCode(new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc).ToLocalTime()));

            Assert.Equal(o.GetCode(), o.GetCode(DateTime.UtcNow));
            Assert.Equal(o.GetCode(), o.GetCode(DateTime.Now));
        }
Exemple #6
0
        public void TOTP_Validate6_SHA1()
        {
            var o = new OneTimePassword(ASCIIEncoding.ASCII.GetBytes("12345678901234567890"))
            {
                Digits = 6
            };

            Assert.True(o.IsCodeValid(287082, new DateTimeOffset(1970, 01, 01, 01, 00, 59, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(081804, new DateTimeOffset(2005, 03, 18, 02, 58, 29, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(050471, new DateTimeOffset(2005, 03, 18, 02, 58, 31, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(005924, new DateTimeOffset(2009, 02, 14, 00, 31, 30, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(279037, new DateTimeOffset(2033, 05, 18, 04, 33, 20, TimeSpan.FromHours(1))));
            Assert.True(o.IsCodeValid(353130, new DateTimeOffset(2603, 10, 11, 12, 33, 20, TimeSpan.FromHours(1))));

            Assert.True(o.IsCodeValid(287082, new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(081804, new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(050471, new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(005924, new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(279037, new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc)));
            Assert.True(o.IsCodeValid(353130, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));

            Assert.True(o.IsCodeValid(287082, new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(081804, new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(050471, new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(005924, new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(279037, new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc).ToLocalTime()));
            Assert.True(o.IsCodeValid(353130, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc).ToLocalTime()));
        }
Exemple #7
0
        public void TOTP_Generate_SHA256()
        {
            var o = new OneTimePassword(ASCIIEncoding.ASCII.GetBytes("12345678901234567890123456789012"))
            {
                Algorithm = OneTimePasswordAlgorithm.Sha256,
                Digits    = 8
            };

            Assert.Equal(46119246, o.GetCode(new DateTimeOffset(1970, 01, 01, 01, 00, 59, TimeSpan.FromHours(1))));
            Assert.Equal(68084774, o.GetCode(new DateTimeOffset(2005, 03, 18, 02, 58, 29, TimeSpan.FromHours(1))));
            Assert.Equal(67062674, o.GetCode(new DateTimeOffset(2005, 03, 18, 02, 58, 31, TimeSpan.FromHours(1))));
            Assert.Equal(91819424, o.GetCode(new DateTimeOffset(2009, 02, 14, 00, 31, 30, TimeSpan.FromHours(1))));
            Assert.Equal(90698825, o.GetCode(new DateTimeOffset(2033, 05, 18, 04, 33, 20, TimeSpan.FromHours(1))));
            Assert.Equal(77737706, o.GetCode(new DateTimeOffset(2603, 10, 11, 12, 33, 20, TimeSpan.FromHours(1))));

            Assert.Equal(46119246, o.GetCode(new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc)));
            Assert.Equal(68084774, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc)));
            Assert.Equal(67062674, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc)));
            Assert.Equal(91819424, o.GetCode(new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.Equal(90698825, o.GetCode(new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc)));
            Assert.Equal(77737706, o.GetCode(new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));

            Assert.Equal(46119246, o.GetCode(new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(68084774, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(67062674, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(91819424, o.GetCode(new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(90698825, o.GetCode(new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(77737706, o.GetCode(new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc).ToLocalTime()));

            Assert.Equal(o.GetCode(), o.GetCode(DateTime.UtcNow));
            Assert.Equal(o.GetCode(), o.GetCode(DateTime.Now));
        }
Exemple #8
0
        public void TOTP_Generate_SHA1()
        {
            var o = new OneTimePassword(ASCIIEncoding.ASCII.GetBytes("12345678901234567890"))
            {
                Digits = 8
            };

            Assert.Equal(94287082, o.GetCode(new DateTimeOffset(1970, 01, 01, 01, 00, 59, TimeSpan.FromHours(1))));
            Assert.Equal(07081804, o.GetCode(new DateTimeOffset(2005, 03, 18, 02, 58, 29, TimeSpan.FromHours(1))));
            Assert.Equal(14050471, o.GetCode(new DateTimeOffset(2005, 03, 18, 02, 58, 31, TimeSpan.FromHours(1))));
            Assert.Equal(89005924, o.GetCode(new DateTimeOffset(2009, 02, 14, 00, 31, 30, TimeSpan.FromHours(1))));
            Assert.Equal(69279037, o.GetCode(new DateTimeOffset(2033, 05, 18, 04, 33, 20, TimeSpan.FromHours(1))));
            Assert.Equal(65353130, o.GetCode(new DateTimeOffset(2603, 10, 11, 12, 33, 20, TimeSpan.FromHours(1))));

            Assert.Equal(94287082, o.GetCode(new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc)));
            Assert.Equal(07081804, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc)));
            Assert.Equal(14050471, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc)));
            Assert.Equal(89005924, o.GetCode(new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.Equal(69279037, o.GetCode(new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc)));
            Assert.Equal(65353130, o.GetCode(new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));

            Assert.Equal(94287082, o.GetCode(new DateTime(1970, 01, 01, 00, 00, 59, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(07081804, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 29, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(14050471, o.GetCode(new DateTime(2005, 03, 18, 01, 58, 31, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(89005924, o.GetCode(new DateTime(2009, 02, 13, 23, 31, 30, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(69279037, o.GetCode(new DateTime(2033, 05, 18, 03, 33, 20, DateTimeKind.Utc).ToLocalTime()));
            Assert.Equal(65353130, o.GetCode(new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc).ToLocalTime()));

            Assert.Equal(o.GetCode(), o.GetCode(DateTime.UtcNow));
            Assert.Equal(o.GetCode(), o.GetCode(DateTime.Now));
        }
        public async Task <IActionResult> GenerateEmailOneTimePassword([FromBody] EmailViewModel model)
        {
            string id   = User.FindFirst("id").Value;
            User   user = await UserManager.FindByIdAsync(id);

            if (user == null)
            {
                return(Unauthorized());
            }

            // TODO: Use inbuild tokens
            OneTimePassword password = await Auth.GenerateOneTimePassword(user, OnePasswordType.Email);

            var pvm = Mapper.Map <OneTimePasswordViewModel>(password);

            string body = model.Body;

            try
            {
                string code = Encoding.ASCII.ToBase64(password.Code);
                body = string.Format(body, code);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "An error occured while formatting input body.\n{0}", body);
                return(BadRequest("The format of the email body is invalid."));
            }

            await EmailService.SendEmailAsync(user.Email.ToLower(), model.Subject, body);

            return(Ok(pvm));
        }
Exemple #10
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     foreach (Control control in pnl.Controls)
     {
         if (control.Tag is Record record)
         {
             if (record.RecordType == RecordType.TwoFactorKey)
             {
                 var buffer = new byte[1024];
                 try {
                     OneTimePassword.FromBase32(control.Text, buffer, out var bytesLength);
                     var bytes = new byte[bytesLength];
                     try {
                         Buffer.BlockCopy(buffer, 0, bytes, 0, bytes.Length);
                         record.SetBytes(bytes);
                     } finally {
                         Array.Clear(bytes, 0, bytes.Length);
                     }
                 } catch (FormatException) {
                     Medo.MessageBox.ShowWarning(this, string.Format("2-factor key {0} is not a valid base-32 string.", control.Text));
                 } finally {
                     Array.Clear(buffer, 0, buffer.Length);
                 }
             }
             else
             {
                 if (!string.Equals(record.Text, control.Text, StringComparison.Ordinal))
                 {
                     record.Text = control.Text;
                 }
             }
         }
     }
 }
Exemple #11
0
        /// <summary>
        /// Service method to Verify user for now via email.
        /// Note: If a user is not verified such a one cannot create a wallet.
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task <(UserView user, string message)> VerifyUserEmail(OneTimePassword otp)
        {
            var userExists = await _userrepo.FirstOrDefault(r => r.Username == otp.Username);

            if (userExists == null)
            {
                return(user : null, message : @$ "PLease Create an account with us. {otp.Username} doesn't exist");
            }

            if (userExists.OTP == otp.Otp)
            {
                userExists.IsEmailConfirm = true;
                userExists.OTP            = string.Empty;
                await _userrepo.Update(userExists);

                var returnView = new UserView
                {
                    Username   = userExists.Username,
                    Email      = userExists.Email,
                    IsVerified = true,
                    Message    = $"{userExists.Username}, your account verified."
                };


                return(user : returnView, message : "User verified successfully.");
            }

            return(user : null, message : "User verification unsuccessful.");
        }
Exemple #12
0
        private IEnumerable <AutotypeToken> GetProcessedTokens(Record record, IEnumerable <AutotypeToken> tokens, AutotypeToken suffixToken = null)
        {
            var tokenList = new List <AutotypeToken>(AutotypeToken.GetAutotypeTokens(tokens, this.Entry));

            if (suffixToken != null)
            {
                tokenList.Add(suffixToken);
            }

            var processedTokens = new List <AutotypeToken>();

            foreach (var token in tokenList)
            {
                if ((token.Kind == AutotypeTokenKind.Command) && token.Content.Equals("TwoFactorCode", StringComparison.Ordinal))
                {
                    var bytes = (record != null) ? record.GetBytes() : this.Entry.TwoFactorKey;
                    var key   = OneTimePassword.ToBase32(bytes, bytes.Length, SecretFormatFlags.Spacing | SecretFormatFlags.Padding);
                    processedTokens.AddRange(AutotypeToken.GetAutotypeTokensFromText(Helpers.GetTwoFactorCode(key)));
                }
                else
                {
                    processedTokens.Add(token);
                }
            }

            return(processedTokens.AsReadOnly());
        }
Exemple #13
0
        public void HOTP_Generate_SHA1()
        {
            var o = new OneTimePassword(ASCIIEncoding.ASCII.GetBytes("12345678901234567890"))
            {
                Digits = 8, TimeStep = 0
            };

            o.Counter = 0x0000000000000001;
            Assert.Equal(94287082, o.GetCode());

            o.Counter = 0x00000000023523EC;
            Assert.Equal(07081804, o.GetCode());

            o.Counter = 0x00000000023523ED;
            Assert.Equal(14050471, o.GetCode());

            o.Counter = 0x000000000273EF07;
            Assert.Equal(89005924, o.GetCode());

            o.Counter = 0x0000000003F940AA;
            Assert.Equal(69279037, o.GetCode());

            o.Counter = 0x0000000027BC86AA;
            Assert.Equal(65353130, o.GetCode());
        }
        public string GenerateOtp()
        {
            var otp     = new OneTimePassword(SecretKey);
            var otpCode = otp.GetCode().ToString("000000");

            return(otpCode);
        }
Exemple #15
0
        public OneTimePassword New(string type, AppUser user)
        {
            var otp = new OneTimePassword
            {
                ApplicationId = user.ApplicationId,
                UserName      = user.UserName,
                OTP           = GenerateOTP().ToString(),
                Type          = type,
                ValidDays     = _appSettings.OtpValidDays
            };

            var list = _context.OneTimePassword.Where(t => t.UserName == user.UserName && t.DelFlag == false);

            if (list != null)
            {
                foreach (var item in list)
                {
                    item.DelFlag = true;
                    _context.OneTimePassword.Update(item);
                }
            }
            _context.OneTimePassword.Add(otp);
            _context.SaveChanges();

            return(otp);
        }
Exemple #16
0
        private bool AuthenticateWithOneTimePassword(Userprofile profile, string password)
        {
            if (password.Length > 8 || password != Regex.Replace(password, @"[^0-9]", ""))
            {
                return(false);
            }

            bool authenticated = false;
            var  secret        = Base32.Decode(profile.SecretKey);

            for (int i = 0; !authenticated && i < 3; i++)
            {
                var passw = OneTimePassword.Get(secret, i);
                authenticated = (passw == password);

                if (!authenticated && i != -i)
                {
                    passw         = OneTimePassword.Get(secret, -i);
                    authenticated = (passw == password);
                }
            }

            if (authenticated)
            {
                TokenList.UseToken($"otp/{profile.Username}/{password}");
            }

            return(authenticated);
        }
Exemple #17
0
        public void HOTP_Validate_SHA1()
        {
            var o = new OneTimePassword(ASCIIEncoding.ASCII.GetBytes("12345678901234567890"))
            {
                Digits = 8, TimeStep = 0
            };

            o.Counter = 0x0000000000000001;
            Assert.Equal(true, o.IsCodeValid(94287082));
            Assert.Equal(true, o.IsCodeValid(94287082));
            Assert.Equal(false, o.IsCodeValid(94287082));

            o.Counter = 0x00000000023523EC;
            Assert.Equal(true, o.IsCodeValid("0708 1804"));

            o.Counter = 0x00000000023523ED;
            Assert.Equal(true, o.IsCodeValid(14050471));

            o.Counter = 0x000000000273EF07;
            Assert.Equal(true, o.IsCodeValid(89005924));

            o.Counter = 0x0000000003F940AA;
            Assert.Equal(true, o.IsCodeValid(69279037));

            o.Counter = 0x0000000027BC86AA;
            Assert.Equal(true, o.IsCodeValid(65353130));
        }
Exemple #18
0
        public void DbxGetKeyCommandTest020()
        {
            using (var stream1 = new MemoryStream())
                using (var channel1 = new ServiceChannel())
                    using (var channel2 = new ServiceChannel())
                    {
                        channel1.SetWriteStream(stream1, canDispose: false);

                        Context ctx = new Context();
                        ctx.ClientIP = IPAddress.None;
                        ctx.Channel  = channel1;

                        ctx.Query = new QueryMessage {
                            Command = "dbx-GetKey"
                        };
                        ctx.Query.Params["username"] = "******";
                        ctx.Query.Params["uuid"]     = "safevault";
                        ctx.Query.Params["password"] = OneTimePassword.Get(Base32.Decode("12345678"), 0);

                        Command.Process(ctx);

                        stream1.Position = 0;
                        channel2.SetReadStream(stream1, canDispose: false);

                        Assert.Catch <SecureChannelException>(() => channel2.ReadObject <ResponseMessage>());
                    }
        }
Exemple #19
0
        public void DbxGetKeyCommandTest010()
        {
            using (var stream1 = new MemoryStream())
                using (var channel1 = new ServiceChannel())
                    using (var channel2 = new ServiceChannel())
                    {
                        channel1.SetWriteStream(stream1, canDispose: false);

                        Context ctx = new Context();
                        ctx.ClientIP = IPAddress.None;
                        ctx.Channel  = channel1;

                        ctx.Query = new QueryMessage {
                            Command = "dbx-GetKey"
                        };
                        ctx.Query.Params["username"] = "******";
                        ctx.Query.Params["uuid"]     = "safevault";
                        ctx.Query.Params["password"] = OneTimePassword.Get(Base32.Decode("12345678"), 0);

                        Command.Process(ctx);

                        stream1.Position = 0;
                        channel2.SetReadStream(stream1, canDispose: false);
                        channel2.CipherLib["rsa-private"] = RsaCipher
                                                            .LoadFromPEM($"{_location}/data/client/test-user/cer.pem", $"{_location}/data/client/test-user/cer.pem.key");

                        var response = channel2.ReadObject <ResponseMessage>();
                        Assert.AreEqual(200, response.StatusCode);
                        var data = response.Header["data"];

                        Assert.AreEqual("1234567801234567890abcdefghiklmnopqvwxyz12345678012345678901234567890=", data);
                    }
        }
Exemple #20
0
        public async Task <bool> GenerateOTP(User user)
        {
            await UserDataContext.Entry(user).Reference(u => u.OneTimePassword).LoadAsync();

            if (user.OneTimePassword != null && !user.OneTimePassword.IsExpired)
            {
                return(true);
            }

            await ClearOneTimePasswords(user);

            OneTimePassword password = new OneTimePassword(user);
            await UserDataContext.OneTimePasswords.AddAsync(password);

            await UserDataContext.SaveChangesAsync();

            password.Code = Generator.ComputeHOTP(password.Id);
            UserDataContext.Update(password);
            await UserDataContext.SaveChangesAsync();

            string message = $"Your NYSC One Time Password is {password.Code}."
                             + " Keep this password should be kept private and should not be shared with anyone.";
            await SMS.SendMessage(user.FormattedPhoneNumber, message);

            return(true);
        }
        public string VerifyOtp(Data data)
        {
            var otp     = new OneTimePassword(SecretKey);
            var isValid = otp.IsCodeValid(data.OtpCode);

            return(isValid ? "The code you supplied is valid" : "The code you supplied is invalid");
        }
Exemple #22
0
        internal ApiResult SendOneTimePIN(string username, string MethodOfSending)
        {
            ApiResult apiResult = new ApiResult();

            try
            {
                //Thread.Sleep(new TimeSpan(0, 1, 0));
                if (string.IsNullOrEmpty(username))
                {
                    apiResult.StatusCode = Globals.FAILURE_STATUS_CODE;
                    apiResult.StatusDesc = $"Please Supply a Username";
                    return(apiResult);
                }
                if (!Globals.AcceptableMethodsOfSendingOTP.Contains(MethodOfSending.ToUpper()))
                {
                    apiResult.StatusCode = Globals.FAILURE_STATUS_CODE;
                    apiResult.StatusDesc = $"Please Specify how you want to recieve the OTP";
                    return(apiResult);
                }

                SystemUser[] systemUsers = SystemUser.QueryWithStoredProc("GetSystemUserByID", username);

                if (systemUsers.Count() <= 0)
                {
                    apiResult.StatusCode = Globals.FAILURE_STATUS_CODE;
                    apiResult.StatusDesc = $"User with Username [{username}] doesnt exist";
                    return(apiResult);
                }

                SystemUser user = systemUsers[0];

                OneTimePassword oneTimePassword = new OneTimePassword();
                oneTimePassword.CompanyCode = user.CompanyCode;
                oneTimePassword.Password    = "******";
                oneTimePassword.ValidityDurationInSeconds = 5 * 60;
                oneTimePassword.Username = user.Username;
                oneTimePassword.Save();


                ApiResult sendResult = MethodOfSending.ToUpper() == "PHONE" ? NotificationsHandler.SendOneTimePINByPhone(user.PhoneNumber, oneTimePassword.Password) : NotificationsHandler.SendOneTimePINByEmail(user.Email, oneTimePassword.Password);


                if (sendResult.StatusCode != Globals.SUCCESS_STATUS_CODE)
                {
                    apiResult.StatusCode = Globals.FAILURE_STATUS_CODE;
                    apiResult.StatusDesc = "Send One Time PIN failed: " + sendResult.StatusDesc;
                    return(apiResult);
                }

                apiResult.StatusCode = Globals.SUCCESS_STATUS_CODE;
                apiResult.StatusDesc = $"Successfully Sent One time Password by {MethodOfSending} to {sendResult.PegPayID}. Its Valid for {oneTimePassword.ValidityDurationInSeconds / 60} minute(s)";
                return(apiResult);
            }
            catch (Exception ex)
            {
                apiResult = HandleException(nameof(SendOneTimePIN), $"{username}, Error:{ex.Message}", ex);
            }
            return(apiResult);
        }
Exemple #23
0
        public IActionResult Index()
        {
            var model = new BankViewModel();

            model.QrValue = OneTimePassword.Phrase();
            HttpContext.Session.SetString("Phrase", model.QrValue);
            return(View(model));
        }
Exemple #24
0
 public void Parameter_Algorithm_OutOfRange()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => {
         var o = new OneTimePassword {
             Algorithm = (OneTimePasswordAlgorithm)3
         };
     });
 }
Exemple #25
0
 public void Parameter_Counter_WrongMode()
 {
     Assert.Throws <NotSupportedException>(() => {
         var o = new OneTimePassword {
             Counter = 11
         };
     });
 }
Exemple #26
0
 public void Parameter_Digits_TooLong()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => {
         var o = new OneTimePassword {
             Digits = 10
         };
     });
 }
Exemple #27
0
        public void Parameter_Digits()
        {
            var o = new OneTimePassword {
                Digits = 4
            };

            o.Digits = 9;
        }
Exemple #28
0
        public void MyTestMethod()
        {
            var secret = OneTimePassword.CreateSharedSecret();

            Debug.WriteLine(OneTimePassword.SharedSecretToString(secret));

            Debug.WriteLine(OneTimePassword.TimeBasedPassword(secret));
        }
Exemple #29
0
        public void Basic()
        {
            var o1 = new OneTimePassword();
            var o2 = new OneTimePassword();

            Assert.Equal(20, o1.GetSecret().Length);
            Assert.NotEqual(BitConverter.ToString(o1.GetSecret()), BitConverter.ToString(o2.GetSecret()));
        }
Exemple #30
0
        public void Parameter_Algorithm()
        {
            var o = new OneTimePassword {
                Algorithm = OneTimePasswordAlgorithm.Sha1
            };

            o.Algorithm = OneTimePasswordAlgorithm.Sha256;
            o.Algorithm = OneTimePasswordAlgorithm.Sha512;
        }