Example #1
0
        public void ValidateQueryStringFields_SingleFalse()
        {
            NameValueCollection collection = new NameValueCollection();

            collection.Add("key", "value");
            Assert.IsFalse(KeyUrl.ValidateQueryStringFields(collection, "true"));
        }
Example #2
0
        public string GenerateBarcodeUrl(string secretKey, string emailOrMobile, int otpStep = OtpStep, OtpHashMode otpHashMode = OtpHashMode, int otpSize = OtpSize)
        {
            string barcodeUrl =
                $"{KeyUrl.GetTotpUrl(Base32Encoding.Standard.ToBytes(secretKey), emailOrMobile, otpStep, otpHashMode, otpSize)}&issuer=gico.vn";

            return(HttpUtility.UrlEncode(barcodeUrl));
        }
Example #3
0
        public async Task <IActionResult> GoogleTokenAsync(string code, string provider, bool rememberMe, string returnUrl = null)
        {
            // Require that the user has already logged in via username/password or external login
            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

            if (user == null)
            {
                return(View("Error"));
            }

            string message = "Verificación de 2 pasos con Google Authorization";

            byte[] secretKey  = KeyGeneration.GenerateRandomKey(20);
            string userId     = user.Id;
            string barcodeUrl = KeyUrl.GetTotpUrl(secretKey, userId) + "&issuer=AjeGroupCore";


            var model = new GoogleAuthenticatorViewModel
            {
                SecretKey  = Convert.ToBase64String(secretKey),
                BarcodeUrl = WebUtility.UrlEncode(barcodeUrl),
                Provider   = provider,
                RememberMe = rememberMe,
                ReturnUrl  = returnUrl,
                Code       = code
            };


            ViewData["Message"] = message;

            return(View(model));
        }
        public async Task <ActionResult> EnableGoogleAuthenticator(string provider, string returnUrl, bool rememberMe)
        {
            var CurrentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>().FindById(
                System.Web.HttpContext.Current.User.Identity.GetUserId());

            byte[] secretKey = KeyGeneration.GenerateRandomKey(20);
            //string userName = User.Identity.GetUserName();
            var    userss     = Session["userId"];
            var    userName   = db.Users.Where(c => c.Id.Equals(userss.ToString())).Select(d => d.Email).First();
            string sessionID  = HttpContext.Session.SessionID;
            string barcodeUrl = KeyUrl.GetTotpUrl(secretKey, userName) + "&issuer=MySuperApplication";

            var secret  = Base32Encoder.Encode(secretKey);
            var barcode = HttpUtility.UrlEncode(barcodeUrl);
            var ff      = Base32Encoder.Encode(secretKey);



            var model = new VerifyCodeViewModel
            {
                SecretKey  = Base32Encoder.Encode(secretKey),
                BarcodeUrl = HttpUtility.UrlEncode(barcodeUrl)
            };

            //ViewBag.Status = model;

            return(View(new VerifyCodeViewModel {
                Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe, SecretKey = secret, BarcodeUrl = barcode
            }));
            //return View(model);
        }
Example #5
0
        public async Task <ActionResult> Generate()
        {
            string input = null;

            // If not data came in, then return
            if (this.Request.Body == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is null", HttpStatusCode.Conflict)));
            }

            // Read the input claims from the request body
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                input = await reader.ReadToEndAsync();
            }

            // Check input content value
            if (string.IsNullOrEmpty(input))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is empty", HttpStatusCode.Conflict)));
            }

            // Convert the input string into InputClaimsModel object
            InputClaimsModel inputClaims = InputClaimsModel.Parse(input);

            if (inputClaims == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Can not deserialize input claims", HttpStatusCode.Conflict)));
            }

            try
            {
                // Define the URL for the QR code. When user scan this URL, it opens one of the
                // authentication apps running on the mobile device
                byte[] secretKey = KeyGeneration.GenerateRandomKey(20);

                string TOTPUrl = KeyUrl.GetTotpUrl(secretKey, $"{AppSettings.TOTPAccountPrefix}:{inputClaims.userName}",
                                                   AppSettings.TOTPTimestep);

                TOTPUrl = $"{TOTPUrl}&issuer={AppSettings.TOTPIssuer.Replace(" ", "%20")}";

                // Generate QR code for the above URL
                var              qrCodeGenerator = new QRCodeGenerator();
                QRCodeData       qrCodeData      = qrCodeGenerator.CreateQrCode(TOTPUrl, QRCodeGenerator.ECCLevel.L);
                BitmapByteQRCode qrCode          = new BitmapByteQRCode(qrCodeData);
                byte[]           qrCodeBitmap    = qrCode.GetGraphic(4);

                B2CResponseModel output = new B2CResponseModel(string.Empty, HttpStatusCode.OK)
                {
                    qrCodeBitmap = Convert.ToBase64String(qrCodeBitmap),
                    secretKey    = this.EncryptAndBase64(Convert.ToBase64String(secretKey))
                };

                return(Ok(output));
            }
            catch (Exception ex)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel($"General error (REST API): {ex.Message}", HttpStatusCode.Conflict)));
            }
        }
Example #6
0
        // GET: Auth
        public ActionResult TwoStepVerif()
        {
            byte[] secretKey = KeyGeneration.GenerateRandomKey(20);
            string userId    = "dummy";
            string qrcodeUrl = KeyUrl.GetTotpUrl(secretKey, userId) + "&issuer=MyOnlineMemo";

            var encoder = new QRCodeEncoder();

            encoder.QRCodeEncodeMode   = QRCodeEncoder.ENCODE_MODE.BYTE;
            encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            var qrImage = encoder.Encode(qrcodeUrl);

            string qrcodeString = "";

            using (var ms = new MemoryStream())
            {
                qrImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                qrcodeString = Convert.ToBase64String(ms.GetBuffer());
            }
            //Test
            Session["secretKey"] = Base32Encoder.Encode(secretKey);

            // この認証キーをユーザーごとに保存しておく
            ViewData["secretKey"] = Base32Encoder.Encode(secretKey);
            ViewData["url"]       = string.Format("data:{0};base64,{1}", "image/png", qrcodeString);
            return(View());
        }
        /// <summary>
        /// 获取认证器二维码url
        /// </summary>
        /// <param name="secretKey"></param>
        /// <param name="userName"></param>
        /// <param name="appName"></param>
        /// <returns></returns>
        public static string GetAuthenticatorUrl(string secretKey, string userName, string appName)
        {
            var barcodeUrl     = string.Empty;
            var secretKeyBytes = GetSecretKeyBytes(secretKey);

            barcodeUrl = $"{KeyUrl.GetTotpUrl(secretKeyBytes, userName)}&issuer={appName}";

            return(barcodeUrl);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var secretKeyBytes = KeyGeneration.GenerateRandomKey(20);
                SharedKey = Base32Encoder.Encode(secretKeyBytes);

                var encodedIssuer = HttpUtility.UrlEncode("GlobomanticsFramework");
                SharedKeyField.Value = SharedKey;
                AuthenticatorUri     = KeyUrl.GetTotpUrl(secretKeyBytes, User.Identity.Name) + "&issuer=" + encodedIssuer;
            }
        }
Example #9
0
        public ActionResult EnableTotp()
        {
            var name       = this.User.Identity.GetUserName();
            var key        = KeyGeneration.GenerateRandomKey(20);
            var barcodeUrl = KeyUrl.GetTotpUrl(key, name) + "&issuer=AspNetTotp";

            var model = new EnableTotpViewModel {
                Key = Base32Encoder.Encode(key), TotpUrl = barcodeUrl
            };

            return(this.View(model));
        }
        public ActionResult EnableGoogleAuthenticator()
        {
            var secretKey  = KeyGeneration.GenerateRandomKey(20);
            var userName   = User.Identity.GetUserName();
            var barcodeUrl = KeyUrl.GetTotpUrl(secretKey, userName) + "&issuer=ServerMonitor";
            var model      = new GoogleAuthenticatorViewModel
            {
                SecretKey  = Base32Encoder.Encode(secretKey),
                BarcodeUrl = HttpUtility.UrlEncode(barcodeUrl)
            };

            return(View(model));
        }
Example #11
0
        public async Task <GoogleAuthConfirmationModel> GetSecret(string userName)
        {
            var secretKey  = KeyGeneration.GenerateRandomKey(20);
            var barcodeUrl = KeyUrl.GetTotpUrl(secretKey, userName) + $"&issuer={issuerName}";

            var model = new GoogleAuthConfirmationModel
            {
                Barcode   = QrCodeImageGeneratorUrlPrefix + HttpUtility.UrlEncode(barcodeUrl),
                SecretKey = Base32Encoder.Encode(secretKey)
            };

            return(model);
        }
Example #12
0
        public void FromTotpUrl_Sha512AndStepSizeFifteenDigitsEight()
        {
            var url = string.Format("otpauth://totp/user/?secret={0}&algorithm=Sha512&period=15&digits=8", Base32Encoder.Encode(OtpCalculationTests.RfcTestKey));
            var otp = KeyUrl.FromUrl(url);

            Assert.IsTrue(otp is Totp);
            var totp = (Totp)otp;

            CollectionAssert.AreEqual(OtpCalculationTests.RfcTestKey, totp.GetKey(), "Key's don't match");
            Assert.AreEqual(8, totp.GetDigitLength(), "Digits don't match");
            Assert.AreEqual(15, totp.GetTimeStep(), "Step size doesn't match");
            Assert.AreEqual(OtpHashMode.Sha512, totp.GetHashMode(), "Hash mode doesn't match");
        }
Example #13
0
        public void FromTotpUrl_Sha256()
        {
            var url = string.Format("otpauth://totp/user?secret={0}&algorithm=Sha256", Base32Encoder.Encode(OtpCalculationTests.RfcTestKey));
            var otp = KeyUrl.FromUrl(url);

            Assert.IsTrue(otp is Totp);
            var totp = (Totp)otp;

            CollectionAssert.AreEqual(OtpCalculationTests.RfcTestKey, totp.GetKey(), "Key's don't match");
            Assert.AreEqual(6, totp.GetDigitLength(), "Digits don't match");
            Assert.AreEqual(30, totp.GetTimeStep(), "Step size doesn't match");
            Assert.AreEqual(OtpHashMode.Sha256, totp.GetHashMode(), "Hash mode doesn't match");
        }
        public ActionResult EnableGoogleAuthenticator()
        {
            byte[] secretKey  = KeyGeneration.GenerateRandomKey(20);
            string userName   = User.Identity.GetUserName();
            string barcodeUrl = KeyUrl.GetTotpUrl(secretKey, userName) + "&issuer=MySuperApplication";

            var model = new GoogleAuthenticatorViewModel
            {
                SecretKey  = Base32Encoder.Encode(secretKey),
                BarcodeUrl = HttpUtility.UrlEncode(barcodeUrl)
            };

            return(View(model));
        }
        private void ResetTotp()
        {
            this.totp = new Totp(rfcKey, this.stepSize, totpSize: this.digits);
            var name = this.textBoxKeyLabel.Text;

            if (string.IsNullOrWhiteSpace(name))
            {
                name = "*****@*****.**";
            }

            string url = KeyUrl.GetTotpUrl(rfcKey, name, step: this.stepSize, totpSize: this.digits);

            this.pictureBox1.ImageLocation = string.Format("http://qrcode.kaywa.com/img.php?s=4&d={0}", HttpUtility.UrlEncode(url));
        }
Example #16
0
 public static GoogleTwoFactorData GetGoogleTwoFactorData(string userName)
 {
     try
     {
         var    secretKey  = KeyGeneration.GenerateRandomKey(20);
         string barcodeUrl = string.Format("{0}&issuer={1}", KeyUrl.GetTotpUrl(secretKey, userName), Issuer);
         return(new GoogleTwoFactorData
         {
             PrivateKey = Base32Encoder.Encode(secretKey),
             PublicKey = HttpUtility.UrlEncode(barcodeUrl)
         });
     }
     catch { }
     return(new GoogleTwoFactorData());
 }
        public async Task <ActionResult> EnableGoogleAuthenticator(string returnUrl, string userName)
        {
            byte[] secretKey  = KeyGeneration.GenerateRandomKey(20);
            string barcodeUrl = KeyUrl.GetTotpUrl(secretKey, userName) + "&issuer=" + Properties.Settings.Default.ApplicationName;

            var model = new GoogleAuthenticatorViewModel
            {
                SecretKey  = Base32Encoder.Encode(secretKey),
                BarcodeUrl = HttpUtility.UrlEncode(barcodeUrl)
            };

            TempData["returnAction"] = returnUrl;
            TempData["userName"]     = userName;
            return(View(model));
        }
Example #18
0
        public ActionResult EnableGoogleAuthenticator()
        {
            byte[] secretKey     = KeyGeneration.GenerateRandomKey(20);
            string userName      = User.Identity.GetUserName();
            string issuer        = "CMS Xây dựng Minh Thanh";
            string issuerEncoded = HttpUtility.UrlEncode(issuer);
            string barcodeUrl    = KeyUrl.GetTotpUrl(secretKey, userName) + "&issuer=" + issuerEncoded;

            var model = new GoogleAuthenticatorViewModel
            {
                SecretKey  = Base32Encoder.Encode(secretKey),
                BarcodeUrl = barcodeUrl
            };

            return(View(model));
        }
Example #19
0
        void SetupTotp()
        {
            if (this.CustomData != null && this.CustomData.Exists(PassXYZLib.PxDefs.PxCustomDataOtpUrl))
            {
                var rawUrl = this.CustomData.Get(PassXYZLib.PxDefs.PxCustomDataOtpUrl);
                var otp    = KeyUrl.FromUrl(rawUrl);
                if (otp is Totp totp)
                {
                    var url = new Uri(rawUrl);
                    m_TotpDescription = url.LocalPath.Substring(1);

                    Totp  = totp;
                    Token = totp.ComputeTotp();
                }
            }
        }
Example #20
0
        public ActionResult EnableGoogleAuthenticator()
        {
            byte[] secretKey     = KeyGeneration.GenerateRandomKey(20);
            string userName      = User.Identity.GetUserName();
            string issuer        = "Hệ thống quản lý đơn hàng thương mại điện tử - Bưu điện Hải Phòng";
            string issuerEncoded = HttpUtility.UrlEncode(issuer);
            string barcodeUrl    = KeyUrl.GetTotpUrl(secretKey, userName) + "&issuer=" + issuerEncoded;

            var model = new GoogleAuthenticatorViewModel
            {
                SecretKey  = Base32Encoder.Encode(secretKey),
                BarcodeUrl = barcodeUrl
            };

            return(View(model));
        }
Example #21
0
        public ActionResult AuthKey(int id)
        {
            var ctx = new DataAccess.SirCoNominaDataContext();
            var emp = ctx.Empleados.Where(i => i.idempleado == id).Single();

            byte[] secretKey  = KeyGeneration.GenerateRandomKey(20);
            var    issuer     = "ZapateriaTorreon";
            string barcodeUrl = KeyUrl.GetTotpUrl(secretKey, $"{emp.idempleado}") + $"&issuer={issuer}";

            //barcodeUrl = HttpUtility.UrlDecode(barcodeUrl);

            ViewBag.id         = id;
            ViewBag.SecretKey  = Base32Encoder.Encode(secretKey);
            ViewBag.BarcodeUrl = barcodeUrl;
            //ViewBag.issuer = issuer;
            return(View());
        }
Example #22
0
 public static GoogleTwoFactorData GetGoogleTwoFactorData(string userName)
 {
     try
     {
         var secretKey  = KeyGeneration.GenerateRandomKey(20);
         var barcodeUrl = $"{KeyUrl.GetTotpUrl(secretKey, userName)}&issuer={Issuer}";
         return(new GoogleTwoFactorData
         {
             PrivateKey = Base32Encoder.Encode(secretKey),
             PublicKey = HttpUtility.UrlEncode(barcodeUrl)
         });
     }
     catch (Exception ex)
     {
         Log.Exception("[GetGoogleTwoFactorData] Authentication Set Up Failed", ex);
     }
     return(new GoogleTwoFactorData());
 }
Example #23
0
        protected void OtpEnableButton_Click(object sender, EventArgs e)
        {
            var userName = this.User.Identity.GetUserName();

            // Generate OTP secret and store in hidden field
            var secret = KeyGeneration.GenerateRandomKey(20);

            this.HiddenSecret.Value = Base32.Base32Encoder.Encode(secret);
            this.LiteralSecret.Text = PrettyFormatSecret(this.HiddenSecret.Value);

            // Generate QR code to setup authenticator app
            var setupUrl = KeyUrl.GetTotpUrl(secret, "OTP Demo/" + userName) + "&issuer=ASP.NET%20Identity%20OTP%20demo";
            var qrUrl    = "https://chart.googleapis.com/chart?cht=qr&chs=250x250&chld=L|0&chl=" + HttpUtility.UrlEncode(setupUrl);

            this.QrImage.ImageUrl = qrUrl;

            // Show form to enable
            this.MultiViewOtp.SetActiveView(this.ViewOtpSetup);
        }
Example #24
0
        private void GenerateOTP()
        {
            // Reseting data
            this.timer.Stop();
            this.OTP.Otp = "";
            this.OTP.RemainingSeconds = 0;
            this.IsValid = false;

            // Validating input
            if (string.IsNullOrWhiteSpace(this.OTPRequest.SecretKey))
            {
                this.totp = null;
                return;
            }

            if (this.OTPRequest.Step <= 0)
            {
                this.OTPRequest.Size = 30;
            }

            if (this.OTPRequest.Step <= 4)
            {
                this.OTPRequest.Size = 6;
            }

            byte[] rfcKey = UTF8Encoding.ASCII.GetBytes(this.OTPRequest.SecretKey);

            // Generating TOTP
            this.totp = new Totp(rfcKey, this.OTPRequest.Step,
                                 OtpHashMode.Sha1, this.OTPRequest.Size);

            // Generate shared key (QR)
            string url = KeyUrl.GetTotpUrl(rfcKey, this.OTPRequest.SiteId, this.OTPRequest.Step, OtpHashMode.Sha1, this.OTPRequest.Size);

            this.LoadQr(url);

            // Updating TOTP data
            this.UpdateOTPInfo();
            this.timer.Start();
        }
Example #25
0
        public async Task <ActionResult> Generate([FromBody] TOTPInputModel inputClaims)
        {
            if (inputClaims == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new TOTPB2CResponse("Can not deserialize input claims", HttpStatusCode.Conflict)));
            }

            try
            {
                // Define the URL for the QR code. When user scan this URL, it opens one of the
                // authentication apps running on the mobile device
                var secretKey = KeyGeneration.GenerateRandomKey(20);

                var TOTPUrl = KeyUrl.GetTotpUrl(secretKey, $"{_settings.AccountPrefix}:{inputClaims.userName}",
                                                _settings.Timestep);

                TOTPUrl = $"{TOTPUrl}&issuer={_settings.Issuer.Replace(" ", "%20")}";

                // Generate QR code for the above URL
                var qrCodeGenerator = new QRCodeGenerator();
                var qrCodeData      = qrCodeGenerator.CreateQrCode(TOTPUrl, QRCodeGenerator.ECCLevel.L);
                var qrCode          = new BitmapByteQRCode(qrCodeData);
                var qrCodeBitmap    = qrCode.GetGraphic(4);

                var output = new TOTPB2CResponse(string.Empty, HttpStatusCode.OK)
                {
                    qrCodeBitmap = Convert.ToBase64String(qrCodeBitmap), secretKey = EncryptAndBase64(Convert.ToBase64String(secretKey))
                };

                return(Ok(output));
            }
            catch (Exception ex)
            {
                return(StatusCode((int)HttpStatusCode.Conflict,
                                  new TOTPB2CResponse($"General error (REST API): {ex.Message} - {ex.StackTrace}", HttpStatusCode.Conflict)));
            }
        }
Example #26
0
 public void TotpUrl_DigitsTen()
 {
     new Action(() => KeyUrl.GetTotpUrl(OtpCalculationTests.RfcTestKey, "user", totpSize: 10))
     .ShouldThrow <ArgumentException>()
     .WithMessage("size must be 6 or 8");
 }
        public async Task <OperationDataResult <GoogleAuthenticatorModel> > GetGoogleAuthenticator(LoginModel loginModel)
        {
            // try to sign in with user credentials
            var user = await _userManager.FindByNameAsync(loginModel.Username);

            if (user == null)
            {
                return(new OperationDataResult <GoogleAuthenticatorModel>(false,
                                                                          _localizationService.GetString("UserNameOrPasswordIncorrect")));
            }

            var signInResult =
                await _signInManager.CheckPasswordSignInAsync(user, loginModel.Password, true);

            if (!signInResult.Succeeded)
            {
                if (signInResult.IsLockedOut)
                {
                    return(new OperationDataResult <GoogleAuthenticatorModel>(false,
                                                                              "Locked Out. Please, try again after 10 min"));
                }

                // Credentials are invalid, or account doesn't exist
                return(new OperationDataResult <GoogleAuthenticatorModel>(false,
                                                                          _localizationService.GetString("UserNameOrPasswordIncorrect")));
            }

            // check if two factor is enabled
            var isTwoFactorAuthForced = _appSettings.Value.IsTwoFactorForced;

            if (!user.TwoFactorEnabled && !isTwoFactorAuthForced)
            {
                return(new OperationDataResult <GoogleAuthenticatorModel>(true));
            }

            // generate PSK and barcode
            if (!string.IsNullOrEmpty(user.GoogleAuthenticatorSecretKey) && user.IsGoogleAuthenticatorEnabled)
            {
                return(new OperationDataResult <GoogleAuthenticatorModel>(true, new GoogleAuthenticatorModel()));
            }

            var psk        = KeyGeneration.GenerateRandomKey(20);
            var barcodeUrl = KeyUrl.GetTotpUrl(psk, user.UserName) + "&issuer=EformApplication";
            var model      = new GoogleAuthenticatorModel
            {
                PSK        = Base32.ToBase32String(psk),
                BarcodeUrl = HttpUtility.UrlEncode(barcodeUrl)
            };

            // write PSK to the user entity
            user.GoogleAuthenticatorSecretKey = model.PSK;
            var updateResult = _userManager.UpdateAsync(user).Result;

            if (!updateResult.Succeeded)
            {
                return(new OperationDataResult <GoogleAuthenticatorModel>(false,
                                                                          _localizationService.GetString("ErrorWhileUpdatingPSK")));
            }

            // return
            return(new OperationDataResult <GoogleAuthenticatorModel>(true, model));
        }
Example #28
0
        public void TotpUrl_Sha512AndStepSizeFifteenDigitsEight()
        {
            var url = KeyUrl.GetTotpUrl(OtpCalculationTests.RfcTestKey, "user", step: 15, mode: OtpHashMode.Sha512, totpSize: 8);

            Assert.AreEqual(string.Format("otpauth://totp/user?secret={0}&digits=8&algorithm=Sha512&period=15", Base32Encoder.Encode(OtpCalculationTests.RfcTestKey)), url);
        }
Example #29
0
 public void TotpUrl_NullUser()
 {
     new Action(() => KeyUrl.GetTotpUrl(OtpCalculationTests.RfcTestKey, null))
     .ShouldThrow <ArgumentNullException>()
     .WithMessage("Value cannot be null.\r\nParameter name: user");
 }
Example #30
0
 public void TotpUrl_NullKey()
 {
     new Action(() => KeyUrl.GetTotpUrl(null, "user"))
     .ShouldThrow <ArgumentNullException>()
     .WithMessage("Value cannot be null.\r\nParameter name: key");
 }