Esempio n. 1
0
        [Test] public void Base32()
        {
            {
                var data = new byte[] { 0xff };
                var enc  = Base32Encoding.ToString(data);
                var dec  = Base32Encoding.ToBytes(enc);
                Assert.Equal(enc.Length, Base32Encoding.EncodedLength(data.Length));
                Assert.Equal(dec.Length, Base32Encoding.DecodedLength(enc));
                Assert.Equal(0, Array_.Compare(data, 0, data.Length, dec, 0, dec.Length));
            }
            {
                var data = new byte[256];
                for (int i = 0; i != data.Length; ++i)
                {
                    data[i] = (byte)i;
                }
                var enc = Base32Encoding.ToString(data);
                var dec = Base32Encoding.ToBytes(enc);
                Assert.Equal(enc.Length, Base32Encoding.EncodedLength(data.Length));
                Assert.Equal(dec.Length, Base32Encoding.DecodedLength(enc));
                Assert.Equal(0, Array_.Compare(data, 0, data.Length, dec, 0, dec.Length));
            }
            var rand = new Random(42);

            for (int i = 0; i != 100; ++i)
            {
                var data = new byte[rand.Next(16000)];
                rand.NextBytes(data);
                var enc = Base32Encoding.ToString(data);
                var dec = Base32Encoding.ToBytes(enc);
                Assert.Equal(enc.Length, Base32Encoding.EncodedLength(data.Length));
                Assert.Equal(dec.Length, Base32Encoding.DecodedLength(enc));
                Assert.Equal(0, Array_.Compare(data, 0, data.Length, dec, 0, dec.Length));
            }
        }
        public string GenerateSecretKey()
        {
            var key          = KeyGeneration.GenerateRandomKey(_SecretKeyLength);
            var base32String = Base32Encoding.ToString(key);

            return(base32String.Replace("=", ""));
        }
        public async Task Handle_GivenCodeDoesVerify_ExpectSuccessfulResultAndEnrollAttempted()
        {
            var user = new Mock <IUser>();

            user.Setup(x => x.AuthenticatorApps).Returns(() => new List <AuthenticatorApp>());
            var userRepository = new Mock <IUserRepository>();
            var unitOfWork     = new Mock <IUnitOfWork>();

            unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => true);
            userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object);
            userRepository.Setup(x => x.Find(It.IsAny <Guid>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(() => Maybe.From(user.Object));

            var clock = new Mock <IClock>();
            var currentAuthenticatedUserProvider = new Mock <ICurrentAuthenticatedUserProvider>();

            currentAuthenticatedUserProvider.Setup(x => x.CurrentAuthenticatedUser)
            .Returns(Maybe.From(new AuthenticatedUser(TestVariables.UserId, "email-address", "first-name", "last-name") as ISystemUser));

            var commandHandler = new EnrollAuthenticatorAppCommandHandler(userRepository.Object, clock.Object,
                                                                          currentAuthenticatedUserProvider.Object);

            var key = KeyGeneration.GenerateRandomKey();
            var keyAsBase32String = Base32Encoding.ToString(key);
            var totp = new Totp(key);
            var code = totp.ComputeTotp();

            var cmd    = new EnrollAuthenticatorAppCommand(keyAsBase32String, code);
            var result = await commandHandler.Handle(cmd, CancellationToken.None);

            Assert.True(result.IsSuccess);
            user.Verify(
                x => x.EnrollAuthenticatorApp(It.IsAny <Guid>(), It.IsAny <string>(), It.IsAny <DateTime>()),
                Times.Once);
        }
        public async Task Handle_GivenSavingFails_ExpectFailedResult()
        {
            var user = new Mock <IUser>();

            user.Setup(x => x.AuthenticatorApps).Returns(() => new List <AuthenticatorApp>());
            var userRepository = new Mock <IUserRepository>();
            var unitOfWork     = new Mock <IUnitOfWork>();

            unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => false);
            userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object);
            userRepository.Setup(x => x.Find(It.IsAny <Guid>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(() => Maybe.From(user.Object));

            var clock = new Mock <IClock>();
            var currentAuthenticatedUserProvider = new Mock <ICurrentAuthenticatedUserProvider>();

            currentAuthenticatedUserProvider.Setup(x => x.CurrentAuthenticatedUser)
            .Returns(Maybe.From(new AuthenticatedUser(TestVariables.UserId, "email-address", "first-name", "last-name") as ISystemUser));

            var commandHandler = new EnrollAuthenticatorAppCommandHandler(userRepository.Object, clock.Object,
                                                                          currentAuthenticatedUserProvider.Object);

            var key = KeyGeneration.GenerateRandomKey();
            var keyAsBase32String = Base32Encoding.ToString(key);
            var totp = new Totp(key);
            var code = totp.ComputeTotp();

            var cmd    = new EnrollAuthenticatorAppCommand(keyAsBase32String, code);
            var result = await commandHandler.Handle(cmd, CancellationToken.None);

            Assert.True(result.IsFailure);
            Assert.Equal(ErrorCodes.SavingChanges, result.Error.Code);
        }
Esempio n. 5
0
    protected void btnGenerateSecret_Click(object sender, EventArgs e)
    {
        var hmac = new HMACSHA256();
        var key  = Base32Encoding.ToString(hmac.Key);

        txtGeneratedSecret.Text = key;
    }
Esempio n. 6
0
        /// <summary>
        /// 随机生成google验证 base32密钥
        /// </summary>
        /// <param name="length">种子长度</param>
        /// <returns></returns>
        public string GoogleKeyForRand(int length = 10)
        {
            var keys   = KeyGeneration.GenerateRandomKey(length);
            var keystr = Base32Encoding.ToString(keys);

            return(keystr);
        }
Esempio n. 7
0
        public void VerifyKeys(string secret, ulong counter, string code)
        {
            var authenticator = new CounterAuthenticator();
            var base32Secret  = Base32Encoding.ToString(Encoding.ASCII.GetBytes(secret));

            Assert.IsTrue(authenticator.CheckCode(base32Secret, code, counter));
        }
Esempio n. 8
0
 public string GetPlainSecret()
 {
     if (this.Key.ReadData().Length > 0)
     {
         if (this.Encoding == OtpSecretEncoding.Base32)
         {
             return(Base32Encoding.ToString(this.Key.ReadData()));
         }
         else if (this.Encoding == OtpSecretEncoding.Base64)
         {
             return(Convert.ToBase64String(this.Key.ReadData()));
         }
         else if (this.Encoding == OtpSecretEncoding.Hex)
         {
             return(MemUtil.ByteArrayToHexString(this.Key.ReadData()));
         }
         else if (this.Encoding == OtpSecretEncoding.UTF8)
         {
             return(StrUtil.Utf8.GetString(this.Key.ReadData()));
         }
         else
         {
             return(null);
         }
     }
     return(null);
 }
Esempio n. 9
0
        public async Task <IActionResult> SetupTotp()
        {
            ApplicationUser user = await _userManager.GetUserAsync(User);

            if (!user.TotpEnabled)
            {
                byte[] keyBytes;
                if (user.TotpSecret != null)
                {
                    keyBytes = user.TotpSecret;
                }
                else
                {
                    keyBytes = KeyGeneration.GenerateRandomKey(20);
                }

                string base32Key      = Base32Encoding.ToString(keyBytes);
                byte[] base32KeyBytes = Base32Encoding.ToBytes(base32Key);
                Totp   totp           = new Totp(base32KeyBytes);
                user.TotpSecret = keyBytes;
                await _userManager.UpdateAsync(user);

                QRCodeGenerator    qrGenerator  = new QRCodeGenerator();
                QRCodeData         qrCodeData   = qrGenerator.CreateQrCode($"otpauth://totp/SPSAuthChallenge:{user.UserName}?secret={base32Key}&issuer=SPSAuthChallenge", QRCodeGenerator.ECCLevel.Q);
                Base64QRCode       qrCode       = new Base64QRCode(qrCodeData);
                string             qrCodeBase64 = qrCode.GetGraphic(10);
                SetupTotpViewModel model        = new SetupTotpViewModel
                {
                    QRCodeBase64 = qrCodeBase64
                };
                return(View(model));
            }
            return(RedirectToAction(nameof(Index)));
        }
    private DirInfo CreateDirInfo(string physicalDirFile, string base64Ciphertext, DirInfo parent)
    {
        var filename = DecryptFileName(physicalDirFile, parent.ParentDirId);

        string[] lines = File.ReadAllLines(PathJoin(physicalDirFile, "dir.c9r"));
        string   dirID = lines[0];

        Debug.Assert(lines[0].Length == 36 && lines.Length == 1);

        var dirIdHash =
            Base32Encoding.ToString(sha1.ComputeHash(siv.Seal(Encoding.UTF8.GetBytes(dirID))));

        Debug.Assert(dirIdHash.Length == 32);

        var actualDirPath = PathJoin(dirIdHash.Substring(0, 2), dirIdHash.Substring(2));

        return(new DirInfo
        {
            Name = filename,
            VirtualPath = PathJoin(parent.VirtualPath, filename),
            PhysicalPath = PathJoin(vaultPath, "d", actualDirPath),
            ParentDirId = dirID,
            Level = parent.Level + 1
        });
    }
Esempio n. 11
0
        public async Task GetTwoFactorAsync(User user, TwoFactorProviderType provider)
        {
            if (user.TwoFactorEnabled && user.TwoFactorProvider.HasValue && user.TwoFactorProvider.Value == provider)
            {
                switch (provider)
                {
                case TwoFactorProviderType.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 TwoFactorProviderType.Authenticator:
                var key = KeyGeneration.GenerateRandomKey(20);
                user.AuthenticatorKey = Base32Encoding.ToString(key);
                break;

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

            await SaveUserAsync(user);
        }
Esempio n. 12
0
        public static (string seed, byte[] seedBytes) CreateSeed()
        {
            // must be based in a HashMode or it may not work with all client libraries. Specially JS libs
            var bytes = KeyGeneration.GenerateRandomKey(HASH_MODE);

            return(Base32Encoding.ToString(bytes), bytes);
        }
        public async Task <IActionResult> Configuration()
        {
            if (!Request.Form.ContainsKey("Email"))
            {
                return(Unauthorized());
            }

            var email = Request.Form
                        .Where(x => x.Key == "Email")
                        .Select(x => x.Value)
                        .FirstOrDefault()
                        .ToString()
                        .Clean();

            if (string.IsNullOrEmpty(email))
            {
                return(Unauthorized());
            }

            var user = await _userManager.FindByEmailAsync(email);

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

            // check for existing token
            var existingToken = user.Tokens.Where(x => x.LoginProvider == "Two-Factor").FirstOrDefault();

            if (existingToken != null)
            {
                user.Tokens.Remove(existingToken);
            }

            // generate new token
            var secret = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(20));

            user.TwoFactorEnabled = true;
            user.Tokens.Add(new IdentityUserToken <string>()
            {
                LoginProvider = "Two-Factor",
                Name          = user.Email,
                UserId        = user.Id,
                Value         = secret
            });

            var identityResult = await _userManager.UpdateAsync(user);

            if (!identityResult.Succeeded)
            {
                _logger.Exception(new Exception(identityResult.Errors.First().Description));
                return(BadRequest(identityResult.Errors.First().Description));
            }

            ViewData["Email"]    = user.Email;
            ViewData["Token"]    = secret;
            ViewData["LoginUrl"] = _appSettings.Application.MainSiteUrlTrim + "/Account/Login";
            return(View());
        }
Esempio n. 14
0
        public static Authenticator FromOtpAuthMigrationAuthenticator(OtpAuthMigration.Authenticator input)
        {
            string issuer;
            string username;

            // Google Auth may not have an issuer, just use the username instead
            if (String.IsNullOrEmpty(input.Issuer))
            {
                issuer   = input.Username.Trim().Truncate(32);
                username = null;
            }
            else
            {
                issuer = input.Issuer.Trim().Truncate(32);
                // For some odd reason the username field always follows a '[issuer]: [username]' format
                username = input.Username.Replace($"{input.Issuer}: ", "").Trim().Truncate(40);
            }

            var type = input.Type switch
            {
                OtpAuthMigration.Type.Totp => AuthenticatorType.Totp,
                OtpAuthMigration.Type.Hotp => AuthenticatorType.Hotp,
                _ => throw new InvalidAuthenticatorException()
            };

            var algorithm = input.Algorithm switch
            {
                OtpAuthMigration.Algorithm.Sha1 => OtpHashMode.Sha1,
                _ => throw new InvalidAuthenticatorException()
            };

            string secret;

            try
            {
                secret = Base32Encoding.ToString(input.Secret);
                secret = CleanSecret(secret);
            }
            catch
            {
                throw new InvalidAuthenticatorException();
            }

            var auth = new Authenticator()
            {
                Issuer    = issuer,
                Username  = username,
                Algorithm = algorithm,
                Type      = type,
                Secret    = secret,
                Counter   = input.Counter,
                Digits    = DefaultDigits,
                Period    = DefaultPeriod,
                Icon      = Shared.Data.Icon.FindServiceKeyByName(issuer)
            };

            auth.Validate();
            return(auth);
        }
Esempio n. 15
0
 public static string GetTTH(string filePath, out byte[][][] tigerTree)
 {
     lock (_hashCalculator)
     {
         tigerTree = _hashCalculator.GetTTHTree(filePath);
         return(Base32Encoding.ToString(tigerTree[tigerTree.GetLength(0) - 1][0]));
     }
 }
Esempio n. 16
0
        public MainWindow()
        {
            InitializeComponent();

            Label.Focus();
            Label.Text  = "one";
            Issuer.Text = "two";
            Secret.Text = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(20));
        }
Esempio n. 17
0
        public static string GenerateTotp(byte[] key)
        {
            var base32Secret = Base32Encoding.ToString(key);

            base32Secret = base32Secret.TrimEnd('=');
            var qrString = $"otpauth://totp/forumx?secret={base32Secret}&digits=6&period=30";

            return(qrString);
        }
        public Task <Result <InitiateAuthenticatorAppEnrollmentCommandResult, ErrorData> > Handle(
            InitiateAuthenticatorAppEnrollmentCommand request, CancellationToken cancellationToken)
        {
            var key = KeyGeneration.GenerateRandomKey();
            var keyAsBase32String = Base32Encoding.ToString(key);

            return(Task.FromResult(Result.Ok <InitiateAuthenticatorAppEnrollmentCommandResult, ErrorData>(
                                       new InitiateAuthenticatorAppEnrollmentCommandResult(keyAsBase32String))));
        }
 public Task <string> GenerateAsync(string purpose, UserManager <UserInfo> manager, UserInfo user)
 {
     if (string.IsNullOrEmpty(user.DualAuthenticationSecretKey))
     {
         var key          = KeyGeneration.GenerateRandomKey(10);
         var base32String = Base32Encoding.ToString(key);
         user.DualAuthenticationSecretKey = base32String;
     }
     return(Task.FromResult(user.DualAuthenticationSecretKey));
 }
Esempio n. 20
0
        public GoogleAuthenticator()
        {
            var key          = KeyGeneration.GenerateRandomKey(32);
            var base32String = Base32Encoding.ToString(key);

            _secret    = base32String;
            _totp      = new Totp(key);
            _digits    = 6;
            _period    = 30;
            _algorithm = "SHA1";
        }
Esempio n. 21
0
        public async Task <string> EnableTotp()
        {
            var localAccount = await _localAccountStorage.GetAsync(_identityAccessor.IdentityId);

            var result = Base32Encoding.ToString(localAccount.SharedTotpSecret);

            localAccount.TwoFactorTotpEnabled = DateTimeOffset.Now;

            await _localAccountStorage.UpdateAsync(localAccount);

            return(result);
        }
Esempio n. 22
0
        /// <summary>
        /// 根据提供的Key 生成google验证 base32密钥
        /// </summary>
        /// <param name="key">如果为空 采用随机生成方式</param>
        /// <returns></returns>
        public string GoogleKeyForKey(string key = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                return(GoogleKeyForRand(10));
            }

            var keys = Encoding.UTF8.GetBytes(key);

            var keystr = Base32Encoding.ToString(keys);

            return(keystr);
        }
Esempio n. 23
0
        public void VerifyUsedCounter()
        {
            var authenticator = new CounterAuthenticator();

            // Test Values from http://www.ietf.org/rfc/rfc4226.txt - Appendix D
            var base32Secret = Base32Encoding.ToString(Encoding.ASCII.GetBytes("12345678901234567890"));

            ulong usedCounter;

            Assert.True(authenticator.CheckCode(base32Secret, "520489", 0uL, out usedCounter));

            Assert.AreEqual(usedCounter, 9uL);
        }
Esempio n. 24
0
        private GoogleAuthenticatorModel GenerateGoogleAuthenticatorModel()
        {
            byte[] secretByte = KeyGeneration.GenerateRandomKey(20);
            string userName   = "******";
            string secretKey  = Base32Encoding.ToString(secretByte);
            string barcodeUrl = $"otpauth://totp/{userName}?secret={secretKey}&issuer=GoogleAuthenticatorLab";
            var    model      = new GoogleAuthenticatorModel
            {
                SecretKey  = secretKey,
                BarcodeUrl = barcodeUrl
            };

            return(model);
        }
Esempio n. 25
0
        private static string GetTotpUrl(byte[] key, string userName, string issuer, int timestep = 30, string prefix = null)
        {
            // if no prefix, we use the issuer
            prefix ??= issuer;

            // Escape any space, custom characters
            prefix = Uri.EscapeDataString(prefix);
            issuer = Uri.EscapeDataString(issuer);

            // Encode the key
            var secret = Base32Encoding.ToString(key);

            return($"otpauth://totp/{prefix}:{userName}?secret={secret}&period={timestep}&issuer={issuer}");
        }
Esempio n. 26
0
        public void Base32AuthCodeTest()
        {
            var secretKey = Base32Encoding.ToString(Encoding.UTF8.GetBytes("PJWUMZKAUUFQKJBAMD6VGJ6RULFVW4ZH"));
            var expected  = "551508";

            var tfa = new TwoFactorAuthenticator();

            var currentTime = 1416643820;

            // I actually think you are supposed to divide the time by 30 seconds?
            // Maybe need an overload that takes a DateTime?
            var actual = tfa.GeneratePINAtInterval(secretKey, currentTime, 6, true);

            actual.ShouldBe(expected);
        }
        private static async Task <string> GenerateUserTOTPSecretAsync(Guid accountId, string hashKey)
        {
            // refer: https://stackoverflow.com/questions/11743160/how-do-i-encode-and-decode-a-base64-string
            string plainText = accountId.ToString();

            byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes($"{hashKey}.{plainText}.{hashKey}");

            using (SHA256 sha256 = SHA256.Create())
            {
                Stream stream    = new MemoryStream(plainTextBytes);
                byte[] hashValue = await sha256.ComputeHashAsync(stream);

                return(Base32Encoding.ToString(hashValue));
            }
        }
Esempio n. 28
0
        /// <summary>
        /// The default constructor creates a new secret key and saves it to the property SecretKey.
        /// Used for registering a new user. Make sure to save SecretKey to your database under your user.
        /// </summary>
        /// <param name="Provider">The provider name for encoding in a QR code: e.g. yoursite.com</param>
        public TOTPProvider(string Provider)
        {
            this.Provider = Provider;

            // generate random key and convert it to base32 byte array
            var key = KeyGeneration.GenerateRandomKey(20);

            var base32String = Base32Encoding.ToString(key);

            SecretKey = base32String;
            var base32Bytes = Base32Encoding.ToBytes(SecretKey);

            // init a totp class with this client's key
            Totp = new Totp(base32Bytes);
        }
Esempio n. 29
0
        public string GetTotpUrl(byte[] key, string userName, string issuer, int timestep = 30, string prefix = null)
        {
            // if no prefix, we use the issuer
            prefix = prefix ?? issuer;

            // Escape any space, custom characters
            prefix = Uri.EscapeDataString(prefix);
            issuer = Uri.EscapeDataString(issuer);

            // Encode the key
            var secret = Base32Encoding.ToString(key);

            return(string.Format("otpauth://totp/{0}:{1}?secret={2}&period={3}&issuer={0}"
                                 , prefix, userName, secret, timestep, issuer));
        }
Esempio n. 30
0
        public async Task <TwoFactAuth> GetTwoFactAuthAsync(string email)
        {
            var user = await _ctx.Users.FirstOrDefaultAsync(x => x.Email == email);

            string unformattedKey = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey());


            return(new TwoFactAuth
            {
                AuthenticatorUri = GenerateQrCodeUri(user, unformattedKey),
                HasTwoFactorAuth = user.HasTwoFactorAuth,
                Hash = user.Id,
                SharedKey = FormatKey(user, unformattedKey)
            });
        }