Esempio n. 1
0
        public void Base32()
        {
            byte[] testData     = { 0x41, 0x42, 0x43, 0x44 };
            string expectedData = "IFBEGRA=";

            CollectionAssert.AreEqual(expectedData, Base32Encoder.Encode(testData));
        }
Esempio n. 2
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());
        }
Esempio n. 3
0
        public IdentityResult ResetAuthenticatorKeyAsync(ApplicationUser user)
        {
            try
            {
                var usertoken = Context.UserTokens.SingleOrDefault(ut => ut.UserId == user.Id);

                if (usertoken != null)
                {
                    Context.UserTokens.Remove(Context.UserTokens.SingleOrDefault(ut => ut.UserId == user.Id));
                }

                byte[] authenticatorKey  = KeyGeneration.GenerateRandomKey(20);
                var    identityUserToken = new IdentityUserToken();
                identityUserToken.UserId        = user.Id;
                identityUserToken.LoginProvider = "AspNetUserStore";
                identityUserToken.Name          = "AuthenticatorKey";
                identityUserToken.Value         = Base32Encoder.Encode(authenticatorKey);


                Context.UserTokens.Add(identityUserToken);
                Context.SaveChanges();

                return(IdentityResult.Success);
            }
            catch (Exception exception)
            {
                return(new IdentityResult(exception.ToString()));
            }
        }
Esempio n. 4
0
        public async Task GetTwoFactorAsync(User user, Enums.TwoFactorProvider provider)
        {
            if (user.TwoFactorEnabled && user.TwoFactorProvider.HasValue && user.TwoFactorProvider.Value == provider)
            {
                switch (provider)
                {
                case Enums.TwoFactorProvider.Authenticator:
                    if (!string.IsNullOrWhiteSpace(user.AuthenticatorKey))
                    {
                        return;
                    }
                    break;

                default:
                    throw new ArgumentException(nameof(provider));
                }
            }

            user.TwoFactorProvider = provider;
            // Reset authenticator key.
            user.AuthenticatorKey = null;

            switch (provider)
            {
            case Enums.TwoFactorProvider.Authenticator:
                var key = KeyGeneration.GenerateRandomKey(20);
                user.AuthenticatorKey = Base32Encoder.Encode(key);
                break;

            default:
                throw new ArgumentException(nameof(provider));
            }

            await SaveUserAsync(user);
        }
        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);
        }
Esempio n. 6
0
 private string GenerateBarcodeUrl(byte[] secretKey)
 {
     return(string.Format("otpauth://totp/{0}?secret={1}&issuer={2}",
                          HttpUtility.UrlEncode(User.Name),
                          Base32Encoder.Encode(secretKey),
                          HttpUtility.UrlEncode(AppName)
                          ));
 }
Esempio n. 7
0
        public void encoding(string input, string expectedResult)
        {
            var arrayInput = Encoding.ASCII.GetBytes(input);

            var result = Base32Encoder.Encode(arrayInput, true);

            Assert.Equal(result, expectedResult);
        }
Esempio n. 8
0
        public string GenerateCodeUrl(User user)
        {
            var key = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha512);

            var barcodeUrl = $"{KeyUrl.GetTotpUrl(key, user.UserName, 30, OtpHashMode.Sha512)}&issuer=TOTPSharp";

            user.TotpKey = Base32Encoder.Encode(key).Replace("=", string.Empty);

            return(barcodeUrl);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            var preSecret = "1234567890";

            //for (int i = 0; i < 10; i++)
            //{
            //    Console.WriteLine(HashedOneTimePassword.GeneratePassword(preSecret, i));
            //}

            //long[] seconds = new long[] { 59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000 };

            //foreach (var second in seconds)
            //{
            //    Console.WriteLine(TimeBasedOneTimePassword.GetPassword(preSecret, TimeBasedOneTimePassword.UNIX_EPOCH + TimeSpan.FromSeconds(second), TimeBasedOneTimePassword.UNIX_EPOCH, 30, 8));
            //}

            var enc = new Base32Encoder();

            while (true)
            {

                // feed this into GA to create a new Application
                string secret = enc.Encode(Encoding.ASCII.GetBytes(preSecret));

                Console.WriteLine(secret);

                //this will get the preSecret key back ...
                var preSecretBack = Encoding.UTF8.GetString ( enc.Decode(secret));
                Console.WriteLine(preSecretBack);

                // this would be a VALID password right now
                Console.WriteLine("Valid pw: " + TimeBasedOneTimePassword.GetPassword(preSecret));

                Console.WriteLine("Enter your password: "******"")
                {
                    break;
                }

                // this will check the entered password (possibly from GA) ...

                if (TimeBasedOneTimePassword.IsValid(preSecret, password))
                {
                    Console.WriteLine("Success!");
                }
                else
                {
                    Console.WriteLine("ERROR!");
                }
            }

            return;
        }
Esempio n. 10
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));
        }
Esempio n. 11
0
 public static string GenerateOtpKey()
 {
     try
     {
         var secretKey = KeyGeneration.GenerateRandomKey(20);
         return(Base32Encoder.Encode(secretKey));
     }
     catch (Exception)
     {
         return(string.Empty);
     }
 }
        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;
            }
        }
Esempio n. 13
0
        public static OperationResult TokensCreateNew(TokenTypeBaseParams tkTypeBaseParams, string masterKey, string vendorSerialNumber, string dataEntropy, out TokenCryptoData tokenCryptoData)
        {
            OperationResult result;

            try
            {
                byte[] data;
                byte[] data2;
                long   movingFactor;
                if (OperationResult.Error == HOTPCryptoData.Generate(masterKey, null, tkTypeBaseParams, out data, out data2, out movingFactor))
                {
                    tokenCryptoData = new TokenCryptoData(null, null, default(CryptoData), default(TokenTypeBaseParams));
                    result          = OperationResult.Error;
                }
                else
                {
                    TokenCryptoData tokenCryptoData2 = new TokenCryptoData(null, vendorSerialNumber, new CryptoData(movingFactor, BaseFunctions.HexEncoder(data), BaseFunctions.HexEncoder(data2), ""), tkTypeBaseParams);
                    tokenCryptoData2.ResetMovingFactor(HOTPCipherInitialize.createSequenceNumber());

                    /*--------------------------*/
                    byte[]        tokenSeed = tokenCryptoData2.GetTokenSeed(masterKey);
                    string        x         = Encoding.ASCII.GetString(tokenSeed);
                    Base32Encoder enc       = new Base32Encoder();
                    string        y         = enc.Encode(tokenSeed);


                    /*--------------------------*/


                    if (tkTypeBaseParams.MovingFactorType == TokenMovingFactorType.TransactionAuthenticationNumber)
                    {
                        string value;
                        if (OperationResult.Error == TokensBaseFunctions.tokenTANMatrixIntegrityCheck(tokenCryptoData2, tokenCryptoData2.GetTokenSeed(masterKey), (dataEntropy == null || dataEntropy.Length < 1) ? new byte[0] : BaseFunctions.convertStringToByteArray(dataEntropy), out value))
                        {
                            tokenCryptoData = new TokenCryptoData(null, null, default(CryptoData), default(TokenTypeBaseParams));
                            result          = OperationResult.Error;
                            return(result);
                        }
                        tokenCryptoData2.ResetSupportCryptoData(value);
                    }
                    tokenCryptoData = tokenCryptoData2;
                    result          = OperationResult.Success;
                }
            }
            catch
            {
                LOGGER.Write(LOGGER.LogCategory.ERROR, "SF.Expand.SAF.Core::TokensCreateNew[]", null);
                tokenCryptoData = new TokenCryptoData(null, null, default(CryptoData), default(TokenTypeBaseParams));
                result          = OperationResult.Error;
            }
            return(result);
        }
Esempio n. 14
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);
        }
        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));
        }
Esempio n. 16
0
        public void FromTotpUrl_DigitsEight()
        {
            var url = string.Format("otpauth://totp/user?secret={0}&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(30, totp.GetTimeStep(), "Step size doesn't match");
            Assert.AreEqual(OtpHashMode.Sha1, 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));
        }
        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));
        }
        private static string Secret()
        {
            string secret = "";

            byte[] buffer = new byte[9];
            using (RandomNumberGenerator rng = RNGCryptoServiceProvider.Create())
            {
                rng.GetBytes(buffer);
            }

            secret = Convert.ToBase64String(buffer).Substring(0, 10).Replace('/', '0').Replace('+', '1');
            var enc = Base32Encoder.Encode(Encoding.ASCII.GetBytes(secret));

            return(enc);
        }
Esempio n. 20
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());
 }
Esempio n. 21
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));
        }
Esempio n. 22
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));
        }
Esempio n. 23
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());
        }
Esempio n. 24
0
        public async Task <ActionResult> EnableTwoFactorAuthentication()
        {
            await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);

            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user != null)
            {
                user.IsSinchAuthEnabled = true;
                byte[] secretKey = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha512);
                user.SinchAuthSecretKey = Base32Encoder.Encode(secretKey);
                await UserManager.UpdateAsync(user);

                await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
            }
            return(RedirectToAction("Index", "Manage"));
        }
Esempio n. 25
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());
 }
Esempio n. 26
0
        public async Task <ActionResult> EnableGoogleAuthenticator(GoogleAuthenticatorViewModel model)
        {
            if (ModelState.IsValid)
            {
                byte[] key = Session["GoogleAuthKey"] as byte[];
                if (_GoogleAuthenticatorService.ValidatCode(key, model.Code))
                {
                    var appUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());

                    appUser.IsGoogleAuthenticatorEnabled = true;
                    appUser.GoogleAuthenticatorSecretKey = Base32Encoder.Encode(key);
                    Session.Remove("GoogleAuthKey");
                    await UserManager.UpdateAsync(appUser);
                }
            }

            return(RedirectToAction("Index"));
        }
Esempio n. 27
0
        public static string CacheBreakerFor(string assetRef)
        {
            var filenameAndPath = assetRef;

            if (assetRef.Contains("~"))
            {
                filenameAndPath = System.Web.Hosting.HostingEnvironment.MapPath(assetRef);
            }

            return(_CacheBreakerForFile.GetOrAdd(filenameAndPath, (fileName) =>
            {
                // Calculate a hash of the file.
                using (var hasher = new SHA256Managed())
                    using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 16384))
                    {
                        var hash = hasher.ComputeHash(fs);
                        return Base32Encoder.Encode(hash).ToLower();
                    }
            }));
        }
Esempio n. 28
0
        public ActionResult Enable()
        {
            if (User == null)
            {
                ModelState.AddModelError("not-authenticated", "you are not logged in");
                return(View());
            }

            if (User.TotpSecret != null)
            {
                ModelState.AddModelError("already-enabled", "Google Authenticator is already enabled");
                return(View());
            }

            var secretKey = KeyGeneration.GenerateRandomKey();

            ViewBag.SecretKey  = Base32Encoder.Encode(secretKey);
            ViewBag.BarcodeUrl = GenerateBarcodeUrl(secretKey);;

            return(View());
        }
Esempio n. 29
0
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(HashedOneTimePassword.GeneratePassword("12345678901234567890", i));
            }

            long[] seconds = new long[] { 59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000 };

            foreach (var second in seconds)
            {
                Console.WriteLine(TimeBasedOneTimePassword.GetPassword("12345678901234567890", TimeBasedOneTimePassword.UNIX_EPOCH + TimeSpan.FromSeconds(second), TimeBasedOneTimePassword.UNIX_EPOCH, 30, 8));
            }

            Base32Encoder enc = new Base32Encoder();

            string secret = enc.Encode(Encoding.ASCII.GetBytes("1234567890"));

            Console.WriteLine(secret);

            Console.WriteLine("Enter your password: "******"1234567890", password))
            {
                Console.WriteLine("Success!");
            }
            else
            {
                Console.WriteLine("ERROR!");
            }

            return;

            while (true)
            {
                Console.WriteLine(TimeBasedOneTimePassword.GetPassword("1234567890"));
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
            }
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(HashedOneTimePassword.GeneratePassword("12345678901234567890", i));
            }

            long[] seconds = new long[] { 59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000 };

            foreach (var second in seconds)
            {
                Console.WriteLine(TimeBasedOneTimePassword.GetPassword("12345678901234567890", TimeBasedOneTimePassword.UNIX_EPOCH + TimeSpan.FromSeconds(second), TimeBasedOneTimePassword.UNIX_EPOCH, 30, 8));
            }

            Base32Encoder enc = new Base32Encoder();

            string secret = enc.Encode(Encoding.ASCII.GetBytes("1234567890"));

            Console.WriteLine(secret);

            Console.WriteLine("Enter your password: "******"1234567890", password))
            {
                Console.WriteLine("Success!");
            }
            else
            {
                Console.WriteLine("ERROR!");
            }

            return;

            while (true)
            {
                Console.WriteLine(TimeBasedOneTimePassword.GetPassword("1234567890"));
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Generate a handshake packet for the current keys
        /// </summary>
        public Packet Handshake(byte csid, bool isReply = false)
        {
            Packet inner     = new Packet();
            Packet keyPacket = new Packet();

            foreach (var csItem in Local.CipherSets)
            {
                if (csItem.Value.CSID == csid)
                {
                    keyPacket.Body = csItem.Value.Keys.PublicKey;
                }
                else
                {
                    keyPacket.Head.Add(csItem.Value.CSID.ToString(), Base32Encoder.Encode(csItem.Value.Keys.PublicKey));
                }
            }
            if (isReply)
            {
                inner.Head.Add("at", OutAt);
            }
            else
            {
                inner.Head.Add("at", NextAt());
            }
            inner.Head.Add("csid", csid.ToString("x2"));
            keyPacket.Encode();
            inner.Body = keyPacket.FullPacket;
            inner.Encode();

            Packet outer = Local.CipherSets[csid].MessageEncrypt(remoteInfo, inner);

            outer.HeadBytes     = new byte[1];
            outer.HeadLength    = 1;
            outer.HeadBytes [0] = csid;
            outer.Encode();

            return(outer);
        }
Esempio n. 32
0
        private void InitiailizeOtp()
        {
            otpEnrollmentKey = new byte[20];
            using (var randomNumberGenerator = RandomNumberGenerator.Create())
                randomNumberGenerator.GetBytes(otpEnrollmentKey);


            var encodedKey    = Base32Encoder.Encode(otpEnrollmentKey);
            var enrollmentUrl = String.Format("otpauth://totp/{0}?secret={1}&issuer=Altus", userName.Name, encodedKey);

            var qrEncoder = new QRCodeEncoder
            {
                QRCodeBackgroundColor = System.Drawing.Color.Transparent,
                QRCodeEncodeMode      = QRCodeEncoder.ENCODE_MODE.BYTE,
                QRCodeErrorCorrect    = QRCodeEncoder.ERROR_CORRECTION.H,
                QRCodeForegroundColor = System.Drawing.Color.Black
            };

            qrCode = qrEncoder.Encode(enrollmentUrl);

            OtpImage.Source = Imaging.CreateBitmapSourceFromHBitmap(qrCode.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
                                                                    BitmapSizeOptions.FromEmptyOptions());
        }
Esempio n. 33
0
        private string convertToBase32(byte[] input)
        {
            string output;

            Base32Encoder base32 = new Base32Encoder();

            output = base32.Encode(input);

            return output;

        }
Esempio n. 34
0
File: Base32.cs Progetto: NDWX/PugFX
        /*
        static string GetString( byte data)
        {
            string result = string.Empty;

            switch( data)
            {
                case 0:
                    result = "A";
                    break;

                case 1:
                    result = "B";
                    break;

                case 2:
                    result = "C";
                    break;

                case 3:
                    result = "D";
                    break;

                case 4:
                    result = "E";
                    break;

                case 5:
                    result = "F";
                    break;

                case 6:
                    result = "G";
                    break;

                case 7:
                    result = "H";
                    break;

                case 8:
                    result = "I";
                    break;

                case 9:
                    result = "J";
                    break;

                case 10:
                    result = "K";
                    break;

                case 11:
                    result = "L";
                    break;

                case 12:
                    result = "M";
                    break;

                case 13:
                    result = "N";
                    break;

                case 14:
                    result = "O";
                    break;

                case 15:
                    result = "P";
                    break;

                case 16:
                    result = "Q";
                    break;

                case 17:
                    result = "R";
                    break;

                case 18:
                    result = "S";
                    break;

                case 19:
                    result = "T";
                    break;

                case 20:
                    result = "U";
                    break;

                case 21:
                    result = "V";
                    break;

                case 22:
                    result = "W";
                    break;

                case 23:
                    result = "X";
                    break;

                case 24:
                    result = "Y";
                    break;

                case 25:
                    result = "Z";
                    break;

                case 26:
                    result = "2";
                    break;

                case 27:
                    result = "3";
                    break;

                case 28:
                    result = "4";
                    break;

                case 29:
                    result = "5";
                    break;

                case 30:
                    result = "6";
                    break;

                case 31:
                    result = "7";
                    break;
            }

            return result;
        }

        static byte[] Expand(byte[] data)
        {
            byte[] result = new byte[] {0, 0, 0, 0, 0, 0, 0, 0};

            for (int idx = 0; idx < data.Length; idx++)
            {
                result[idx] = data[idx];
            }

            return result;
        }

        static string GetString(byte[] data)
        {
            StringBuilder result = new StringBuilder();

            // 5, 3+2, 5, 1+4, 4 + 1, 5, 2+3, 5

            int base32StringLength = (int)Math.Ceiling((double)((data.Length * 8) / 5));

            UInt64 dataNumber = BitConverter.ToUInt64(Expand(data), 0);

            byte character;

            character = BitConverter.GetBytes(dataNumber & 31)[0];

            result.Append(GetString(character));

            for (int idx = 1; idx < base32StringLength; idx++)
            {
                dataNumber = dataNumber >> 5;

                character = BitConverter.GetBytes(dataNumber & 31)[0];

                result.Append(GetString(character));
            }

            return result.ToString().Pad('=', 8);
        }

        public static string From(byte[] data)
        {
            StringBuilder result = new StringBuilder();

            byte[] dataSegment;

            int oddLength = data.Length % 5;
            int wordsLength = data.Length  - oddLength;

            int remainingDataLength = wordsLength;;

            for (int idx = 0; idx < wordsLength; idx += 5)
            {
                dataSegment = new byte[5];

                Array.Copy(data, idx, dataSegment, 0, 5 );

                result.Append(GetString(dataSegment));
            }

            if (oddLength > 0)
            {
                dataSegment = new byte[oddLength];

                Array.Copy(data, wordsLength, dataSegment, 0, oddLength);
                result.Append(GetString(dataSegment));
            }

            return result.ToString();
        }

        static byte ValueOf(char character)
        {
            byte value = 0;

            switch( character)
            {
                case 'A':
                    value = 0;
                    break;

                case 'B':
                    value = 1;
                    break;

                case 'C':
                    value = 2;
                    break;

                case 'D':
                    value = 3;
                    break;

                case 'E':
                    value = 4;
                    break;

                case 'F':
                    value = 5;
                    break;

                case 'G':
                    value = 6;
                    break;

                case 'H':
                    value = 7;
                    break;

                case 'I':
                    value = 8;
                    break;

                case 'J':
                    value = 9;
                    break;

                case 'K':
                    value = 10;
                    break;

                case 'L':
                    value = 11;
                    break;

                case 'M':
                    value = 12;
                    break;

                case 'N':
                    value = 13;
                    break;

                case 'O':
                    value = 14;
                    break;

                case 'P':
                    value = 15;
                    break;

                case 'Q':
                    value = 16;
                    break;

                case 'R':
                    value = 17;
                    break;

                case 'S':
                    value = 18;
                    break;

                case 'T':
                    value = 19;
                    break;

                case 'U':
                    value = 20;
                    break;

                case 'V':
                    value = 21;
                    break;

                case 'W':
                    value = 22;
                    break;

                case 'X':
                    value = 23;
                    break;

                case 'Y':
                    value = 24;
                    break;

                case 'Z':
                    value = 25;
                    break;

                case '2':
                    value = 26;
                    break;

                case '3':
                    value = 27;
                    break;

                case '4':
                    value = 28;
                    break;

                case '5':
                    value = 29;
                    break;

                case '6':
                    value = 30;
                    break;

                case '7':
                    value = 31;
                    break;

                default:
                    throw new ArgumentException(string.Format("'{0}' is not valid Base 32 character.", character));
            }

            return value;
        }

        static byte[] GetData(string word)
        {
            int firstPaddingPosition = word.IndexOf('=');
            int wordLength = firstPaddingPosition > 0? firstPaddingPosition : word.Length;

            int resultLength = (int)Math.Ceiling((double)(( wordLength * 5) / 8));

            UInt64 dataNumber = 0;

            dataNumber = ValueOf(word[0]);

            for (int idx = 1; idx < wordLength; idx++)
            {
                dataNumber = dataNumber << 5;
                dataNumber |= word[idx];
            }

            byte[] result = new byte[resultLength];

            byte[] dataNumberBytes = BitConverter.GetBytes(dataNumber);

            Array.Copy(dataNumberBytes, 0, result, 0, result.Length);

            return result;
        }

        public static byte[] GetBytes(string base32String)
        {
            List<byte> result = new List<byte>();

            for (int idx = 0; idx < base32String.Length; idx += 8)
            {
                result.AddRange(GetData(base32String.Substring(idx, 8)));
            }

            return result.ToArray();
        }

        */
        //[ThreadStatic]
        //static Base32Encoder _encoder = new Base32Encoder();
        public static string From(byte[] data)
        {
            Base32Encoder _encoder = new Base32Encoder();

            string result = string.Empty;

            try
            {
                result = _encoder.Encode(data);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return result;
        }
        public static OperationResult loadTokenKeyInformation(string tokenID, out string tokenKey)
        {
            OperationResult result = OperationResult.Error;
            tokenKey = null;
            TokenCryptoData tokenCryptoData2 = new TokensDAO().loadTokenCryptoData(tokenID);

            string masterKey = SF.Expand.SAF.Configuration.SAFConfiguration.readMasterKey();
            byte[] tokenSeed = tokenCryptoData2.GetTokenSeed(masterKey);
            if (tokenSeed != null)
            {
                Base32Encoder enc = new Base32Encoder();
                tokenKey = enc.Encode(tokenSeed);
                result = OperationResult.Success;
            }

            return result;
        }
		public static OperationResult TokensCreateNew(TokenTypeBaseParams tkTypeBaseParams, string masterKey, string vendorSerialNumber, string dataEntropy, out TokenCryptoData tokenCryptoData)
		{
			OperationResult result;
			try
			{
				byte[] data;
				byte[] data2;
				long movingFactor;
				if (OperationResult.Error == HOTPCryptoData.Generate(masterKey, null, tkTypeBaseParams, out data, out data2, out movingFactor))
				{
					tokenCryptoData = new TokenCryptoData(null, null, default(CryptoData), default(TokenTypeBaseParams));
					result = OperationResult.Error;
				}
				else
				{
					TokenCryptoData tokenCryptoData2 = new TokenCryptoData(null, vendorSerialNumber, new CryptoData(movingFactor, BaseFunctions.HexEncoder(data), BaseFunctions.HexEncoder(data2), ""), tkTypeBaseParams);
					tokenCryptoData2.ResetMovingFactor(HOTPCipherInitialize.createSequenceNumber());

                    /*--------------------------*/
                    byte[] tokenSeed = tokenCryptoData2.GetTokenSeed(masterKey);
                    string x = Encoding.ASCII.GetString(tokenSeed);
                    Base32Encoder enc = new Base32Encoder();
                    string y = enc.Encode(tokenSeed);


                    /*--------------------------*/


					if (tkTypeBaseParams.MovingFactorType == TokenMovingFactorType.TransactionAuthenticationNumber)
					{
						string value;
						if (OperationResult.Error == TokensBaseFunctions.tokenTANMatrixIntegrityCheck(tokenCryptoData2, tokenCryptoData2.GetTokenSeed(masterKey), (dataEntropy == null || dataEntropy.Length < 1) ? new byte[0] : BaseFunctions.convertStringToByteArray(dataEntropy), out value))
						{
							tokenCryptoData = new TokenCryptoData(null, null, default(CryptoData), default(TokenTypeBaseParams));
							result = OperationResult.Error;
							return result;
						}
						tokenCryptoData2.ResetSupportCryptoData(value);
					}
					tokenCryptoData = tokenCryptoData2;
					result = OperationResult.Success;
				}
			}
			catch
			{
				LOGGER.Write(LOGGER.LogCategory.ERROR, "SF.Expand.SAF.Core::TokensCreateNew[]", null);
				tokenCryptoData = new TokenCryptoData(null, null, default(CryptoData), default(TokenTypeBaseParams));
				result = OperationResult.Error;
			}
			return result;
		}