Exemplo n.º 1
0
    protected void btnGenerateSecret_Click(object sender, EventArgs e)
    {
        var hmac = new HMACSHA256();
        var key  = Base32Encoding.ToString(hmac.Key);

        txtGeneratedSecret.Text = key;
    }
Exemplo n.º 2
0
        private Totp GetTotp(string secret)
        {
            var key  = Base32Encoding.ToBytes(secret);
            var totp = new Totp(key);

            return(totp);
        }
Exemplo n.º 3
0
        public static object GetKey2FA(string key)
        {
            object result;

            try
            {
                object obj;
                try
                {
                    byte[] array = Base32Encoding.ToBytes(key.Trim().Replace(" ", ""));
                    Totp   totp  = new Totp(array, 30, 0, 6, null);
                    obj = totp.ComputeTotp(DateTime.UtcNow);
                    goto IL_44;
                }
                catch (Exception)
                {
                }
                obj = null;
IL_44:
                result = obj;
            }
            catch (Exception exception)
            {
                return("");
            }
            return(result);
        }
Exemplo n.º 4
0
        static async Task Main()
        {
            string username = Environment.GetEnvironmentVariable("TESLA_USERNAME") ?? await RL("Username");

            string password = Environment.GetEnvironmentVariable("TESLA_PW") ?? await RL("Password");

            string mfaCode = (mfaCode = Environment.GetEnvironmentVariable("TESLA_KEY")) != null
                ? new Totp(Base32Encoding.ToBytes(mfaCode)).ComputeTotp()
                : await RL("MFA");

            var region = TeslaAccountRegion.Unknown;

            ServicePointManager.FindServicePoint(new Uri("https://auth.tesla.com")).ConnectionLeaseTimeout            = 60 * 1000;
            ServicePointManager.FindServicePoint(new Uri("https://auth.tesla.com")).ConnectionLimit                   = 10;
            ServicePointManager.FindServicePoint(new Uri("https://owner-api.teslamotors.com")).ConnectionLeaseTimeout = 60 * 1000;
            ServicePointManager.FindServicePoint(new Uri("https://owner-api.teslamotors.com")).ConnectionLimit        = 10;

            var authHelper = new TeslaAuthHelper("TeslaAuthHelperTest/1.0", region);

            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));

            var tokens = await authHelper.AuthenticateAsync(username, password, mfaCode, cts.Token);

            System.Console.WriteLine("Access token: " + tokens.AccessToken);
            System.Console.WriteLine("Refresh token: " + tokens.RefreshToken);
            System.Console.WriteLine("Created at: " + tokens.CreatedAt);
            System.Console.WriteLine("Expires in: " + tokens.ExpiresIn);

            var newToken = await authHelper.RefreshTokenAsync(tokens.RefreshToken, cts.Token);

            System.Console.WriteLine("Refreshed Access token: " + newToken.AccessToken);
            System.Console.WriteLine("New Refresh token: " + newToken.RefreshToken);
            System.Console.WriteLine("Refreshed token created at: " + newToken.CreatedAt);
            System.Console.WriteLine("Refreshed token expires in: " + newToken.ExpiresIn);
        }
        public void GetUriSuccess(HashAlgorithmType hashAlgorithm, byte period, byte digits)
        {
            var id     = Guid.NewGuid().ToString();
            var secret = new byte[32];

            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(secret);
            }

            var options = GetOptions();

            options.Value.HashAlgorithm   = hashAlgorithm;
            options.Value.NumberOfDigits  = digits;
            options.Value.PeriodInSeconds = period;
            var service = new AuthenticatorService(options, new DefaultSystemTime());
            var uri     = service.GetUri(id, secret);

            Assert.Equal(string.Format("otpauth://totp/{0}%3A{1}?secret={2}&issuer={0}&algorithm={3}&digits={4}&period={5}",
                                       Issuer,
                                       id,
                                       Base32Encoding.Encode(secret).Trim('='),
                                       hashAlgorithm.ToString(),
                                       digits,
                                       period
                                       ), uri);
        }
Exemplo n.º 6
0
        public static string DecryptString(string EncryptedText, Type baseOption)
        {
            byte[] encryptedTextBytes;
            if (baseOption == typeof(Int64))
            {
                encryptedTextBytes = Convert.FromBase64String(EncryptedText);
            }
            else
            {
                encryptedTextBytes = Base32Encoding.ToBytes(EncryptedText);
            }

            MemoryStream ms = new MemoryStream();

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


            byte[] rgbIV = Encoding.ASCII.GetBytes("lbavittzoaofgcqz");
            byte[] key   = Encoding.ASCII.GetBytes("rymnwalaspjdbygwagsxhzzcroywhciu");

            CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),
                                               CryptoStreamMode.Write);

            cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

            cs.Close();

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
Exemplo n.º 7
0
        public static bool IsValidSecret(string secret, AuthenticatorType type)
        {
            if (String.IsNullOrEmpty(secret))
            {
                return(false);
            }

            if (type.IsHmacBased())
            {
                try
                {
                    return(Base32Encoding.ToBytes(secret).Length > 0);
                }
                catch (ArgumentException)
                {
                    return(false);
                }
            }

            if (type == AuthenticatorType.MobileOtp)
            {
                return(secret.Length >= MobileOtp.SecretMinLength);
            }

            throw new ArgumentOutOfRangeException(nameof(type));
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
0
        private async void Done_Click(object sender, RoutedEventArgs e)
        {
            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            if (otp_secret.Text == "")
            {
                err_text.Text = resourceLoader.GetString("err_empty_secret");
            }
            else
            {
                try
                {
                    Base32Encoding.ToBytes(otp_secret.Text.Trim());
                    otp.Issuer    = otp_issuer.Text;
                    otp.Name      = otp_label.Text;
                    otp.Secret    = otp_secret.Text;
                    otp.Type      = otp_type.SelectedIndex;
                    otp.Algorithm = otp_algorithm.SelectedIndex;
                    otp.Digits    = (int)otp_digits.SelectedItem;
                    otp.Period    = (int)otp_period.SelectedItem;
                    otp.LogoType  = type;
                    otp.Logo      = logo;
                    await SqlAccess.Update_Item(otp);

                    MainPage.mainPage.init_data();
                    back();
                }
                catch
                {
                    err_text.Text = resourceLoader.GetString("err_wrong_secret");
                }
            }
        }
Exemplo n.º 10
0
        public string GenerateTotpCode(User user)
        {
            var totpSecretKey = Base32Encoding.ToBytes(user.TotpSecretKey);
            var totp          = new Totp(totpSecretKey);

            return(totp.ComputeTotp());
        }
        public async Task <IActionResult> VerifyTOTPCode(TOTPRequest request)
        {
            User user = _dbContext.Users.SingleOrDefault(u => u.Id == request.RequestorId);

            if (user is null)
            {
                return(NotFound("User does not exist."));
            }

            byte[] totpSecret = Base32Encoding.ToBytes(user.TOTPSecret);
            Totp   totp       = new Totp(totpSecret);

            VerificationWindow window = new VerificationWindow(previous: 1, future: 1);
            bool isValid = totp.VerifyTotp(request.Code, out var _, window);

            if (isValid)
            {
                MFAToken token = await MFAToken.GenerateAsync(user.AccountId, user.TOTPSecret);

                return(Ok(token));
            }
            else
            {
                return(BadRequest("Code is invalid."));
            }
        }
Exemplo n.º 12
0
        private async void Done_Click(object sender, RoutedEventArgs e)
        {
            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            if (otp_secret.Text == "")
            {
                err_text.Text = resourceLoader.GetString("err_empty_secret");
                scroll1.ChangeView(0, 0, 1);
            }
            else
            {
                try
                {
                    Base32Encoding.ToBytes(otp_secret.Text.Trim());
                    await SqlAccess.Add_Item(0, otp_issuer.Text, otp_label.Text, otp_secret.Text, otp_algorithm.SelectedIndex, (int)otp_digits.SelectedValue, (int)otp_period.SelectedValue, type, logo);

                    MainPage.mainPage.init_data();
                    back();
                }
                catch
                {
                    err_text.Text = resourceLoader.GetString("err_wrong_secret");
                    scroll1.ChangeView(0, 0, 1);
                }
            }
        }
Exemplo n.º 13
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);
 }
Exemplo n.º 14
0
        public void TimeBasedTokenizationWorks(DateTime time, string expectedOTP)
        {
            Target.Secret = Base32Encoding.ToBytes("AAAAAAAAAAAA");
            var otp = Target.GenerateOTP(time);

            Assert.Equal(expectedOTP, otp);
        }
Exemplo n.º 15
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));
        }
        private void FromFilename(string name, out long startTime, out int fileSize)
        {
            var segments = name.Split('-');

            startTime = BitConverter.ToInt64(Base32Encoding.ToBytes(segments[0]), 0);
            fileSize  = BitConverter.ToInt32(Base32Encoding.ToBytes(segments[1]), 0);
        }
Exemplo n.º 17
0
    static int Main(string[] args)
    {
        if (!CommandLineSwitch.TryParse <Options>(ref args, out var options, out var err))
        {
            Console.WriteLine($"ERROR: {err}");
            return(-1);
        }
        if (string.IsNullOrEmpty(options.Key))
        {
            Console.WriteLine("ERROR: Secret Key is not specified.");
            ShowUsage();
            return(-1);
        }

        var secretKey = default(byte[]);

        try { secretKey = Base32Encoding.ToBytes(options.Key); }
        catch (ArgumentException)
        {
            Console.WriteLine("ERROR: Invalid key format.");
            return(-1);
        }

        var totp     = new Totp(secretKey);
        var totpCode = totp.ComputeTotp();

        Console.WriteLine(totpCode);
        return(0);
    }
Exemplo n.º 18
0
        public async Task IncrementHotp(int position)
        {
            if (Authenticators.ElementAtOrDefault(position) == null)
            {
                return;
            }

            var info = Authenticators[position];
            var auth = GetAuthenticator(info);

            if (auth.Type != AuthenticatorType.Hotp)
            {
                return;
            }

            var secret = Base32Encoding.ToBytes(auth.Secret);
            var hotp   = new Hotp(secret, auth.Algorithm);

            auth.Counter++;
            auth.Code      = hotp.ComputeHOTP(auth.Counter);
            auth.TimeRenew = DateTime.Now.AddSeconds(10);

            Authenticators[position] = auth;
            await _connection.UpdateAsync(auth);
        }
Exemplo n.º 19
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));
            }
        }
Exemplo n.º 20
0
        public bool Validate(string code, string secret)
        {
            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentNullException(nameof(code));
            }

            if (string.IsNullOrEmpty(secret))
            {
                throw new ArgumentNullException(nameof(secret));
            }

            var secretBase32 = Base32String
                               .Encode(Encoding.UTF8.GetBytes(secret));

            var totpProvider = new Totp(
                secretKey: Base32Encoding.ToBytes(secretBase32),
                mode: OtpHashMode.Sha256,
                step: 30);

            return(totpProvider.VerifyTotp(
                       DateTime.UtcNow,
                       code,
                       out _,
                       VerificationWindow.RfcSpecifiedNetworkDelay));
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
0
        private async Task <Result <ValidateAppMfaCodeAgainstCurrentUserCommandResult, ErrorData> > Process(
            ValidateAppMfaCodeAgainstCurrentUserCommand request,
            CancellationToken cancellationToken)
        {
            var currentUserMaybe = this._currentAuthenticatedUserProvider.CurrentAuthenticatedUser;

            if (currentUserMaybe.HasNoValue)
            {
                return(Result.Fail <ValidateAppMfaCodeAgainstCurrentUserCommandResult, ErrorData>(new ErrorData(ErrorCodes.UserNotFound)));
            }

            var userMaybe = await this._userRepository.Find(currentUserMaybe.Value.UserId, cancellationToken);

            if (userMaybe.HasNoValue)
            {
                return(Result.Fail <ValidateAppMfaCodeAgainstCurrentUserCommandResult, ErrorData>(new ErrorData(ErrorCodes.UserNotFound)));
            }

            var user = userMaybe.Value;

            var authApp = user.AuthenticatorApps.SingleOrDefault(x => x.WhenRevoked == null);

            if (authApp == null)
            {
                return(Result.Fail <ValidateAppMfaCodeAgainstCurrentUserCommandResult, ErrorData>(new ErrorData(ErrorCodes.NoAuthenticatorAppEnrolled)));
            }

            var secretBytes = Base32Encoding.ToBytes(authApp.Key);
            var topt        = new Totp(secretBytes);
            var isVerified  = topt.VerifyTotp(request.Code, out _);

            return(isVerified
                ? Result.Ok <ValidateAppMfaCodeAgainstCurrentUserCommandResult, ErrorData>(new ValidateAppMfaCodeAgainstCurrentUserCommandResult(user.Id))
                : Result.Fail <ValidateAppMfaCodeAgainstCurrentUserCommandResult, ErrorData>(new ErrorData(ErrorCodes.MfaCodeNotValid)));
        }
        public string GenerateSecretKey()
        {
            var key          = KeyGeneration.GenerateRandomKey(_SecretKeyLength);
            var base32String = Base32Encoding.ToString(key);

            return(base32String.Replace("=", ""));
        }
Exemplo n.º 24
0
        private async Task<ResultWithError<ErrorData>> Process(
            EnrollAuthenticatorAppCommand request, CancellationToken cancellationToken)
        {
            var currentUserMaybe = this._currentAuthenticatedUserProvider.CurrentAuthenticatedUser;
            if (currentUserMaybe.HasValue && currentUserMaybe.Value is AuthenticatedUser currentUser)
            {
                var userMaybe = await this._userRepository.Find(currentUser.UserId, cancellationToken);

                if (userMaybe.HasNoValue)
                {
                    return ResultWithError.Fail(new ErrorData(ErrorCodes.UserNotFound));
                }

                var user = userMaybe.Value;

                if (user.AuthenticatorApps.Any(x => x.WhenRevoked == null))
                {
                    return ResultWithError.Fail(new ErrorData(ErrorCodes.AuthenticatorAppAlreadyEnrolled));
                }

                var secretBytes = Base32Encoding.ToBytes(request.Key);
                var topt = new Totp(secretBytes);
                var isVerified = topt.VerifyTotp(request.Code, out _);
                if (!isVerified)
                {
                    return ResultWithError.Fail(new ErrorData(ErrorCodes.FailedVerifyingAuthenticatorCode));
                }

                user.EnrollAuthenticatorApp(Guid.NewGuid(), request.Key, this._clock.GetCurrentInstant().ToDateTimeUtc());

                return ResultWithError.Ok<ErrorData>();
            }

            return ResultWithError.Fail(new ErrorData(ErrorCodes.UserNotFound));
        }
Exemplo n.º 25
0
    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
        });
    }
Exemplo n.º 26
0
        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());
        }
Exemplo n.º 27
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);
        }
        public Task <bool> ValidateAsync(string purpose, string token, UserManager <UserInfo> manager, UserInfo user)
        {
            var  otp             = new Totp(Base32Encoding.ToBytes(user.DualAuthenticationSecretKey));
            long timeStepMatched = 0;
            var  isValid         = otp.VerifyTotp(token, out timeStepMatched, new VerificationWindow(1, 1));

            return(Task.FromResult(isValid));
        }
Exemplo n.º 29
0
        private string GetTOTPCode(string token)
        {
            var bytes = Base32Encoding.ToBytes(token);

            var totp = new Totp(bytes);

            return(totp.ComputeTotp());
        }
Exemplo n.º 30
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]));
     }
 }
Exemplo n.º 31
0
		public void TestCtor()
		{
			try // null alphabet
			{
				var x = new Base32Encoding(null);

				Assert.Fail(typeof(ArgumentNullException).ToString());
			}
			catch (ArgumentNullException)
			{
			}

			try // bad length alphabet
			{
				var x = new Base32Encoding("1245645");

				Assert.Fail(typeof(ArgumentException).ToString());
			}
			catch (ArgumentException)
			{
			}

			try // look-up table null
			{
				var x = new Base32Encoding(Base32Encoding.Hex.Alphabet, (Byte[]) null);

				Assert.Fail(typeof(ArgumentNullException).ToString());
			}
			catch (ArgumentNullException)
			{
			}

			try // look-up table bad length
			{
				var x = new Base32Encoding(Base32Encoding.Hex.Alphabet, new Byte[20]);

				Assert.Fail(typeof(ArgumentNullException).ToString());
			}
			catch (ArgumentException)
			{
			}
		}
Exemplo n.º 32
0
		public static TryResult<String> TryToBase32String(Value128 data, Base32Encoding base32Encoding)
		{
			if (base32Encoding == null)
			{
				return encodeFailResult;
			}

			Char[] result;

			// Get padding symbol
			var paddingSymbol = base32Encoding.PaddingSymbol;

			if (paddingSymbol.HasValue)
			{
				result = new Char[32];

				// Set padding
				result[26] = result[27] = result[28] = result[29] = result[30] = result[31] = paddingSymbol.Value;
			}
			else
			{
				result = new Char[26];
			}

			var higherHalf = data.HigherHalf;

			var lowerHalf = data.LowerHalf;

			// Get alphabet
			var alphabet = base32Encoding.Alphabet;

			for (Int32 indexH = 0, indexL = 13, shiftH = 59, shiftL = 58; indexH < 12; indexH++, indexL++, shiftH -= 5, shiftL -= 5)
			{
				result[indexH] = alphabet[(Int32) (higherHalf >> shiftH) & 0x1F];

				result[indexL] = alphabet[(Int32) (lowerHalf >> shiftL) & 0x1F];
			}

			result[12] = alphabet[(Int32) (((higherHalf << 1) & 0x1E) | ((lowerHalf >> 63) & 0x01))];

			result[25] = alphabet[(Int32) ((lowerHalf << 2) & 0x1C)];

			return TryResult<String>.CreateSuccess(new String(result));
		}
Exemplo n.º 33
0
		public static TryResult<Value128> TryFromBase32String(String data, Int32 offset, Base32Encoding base32Encoding)
		{
			// Check input values
			if ((data == null) || (offset > data.Length - base32EncodedSymbolsCount) || (base32Encoding == null))
			{
				return convertFailResult;
			}

			// Get look-up table
			var lookupTable = base32Encoding.LookupTable;

			var lastIndex = offset + 12;

			var symbol12 = (UInt64) lookupTable[data[lastIndex] & 0x7F];

			var symbol25 = (UInt64) lookupTable[data[offset + 25] & 0x7F];

			// Check symbol
			if ((symbol12 | symbol25) == 0xFF)
			{
				return convertFailResult;
			}

			// Calculate higher half
			var higherHalf = symbol12 >> 1;

			// Calculate lower half
			var lowerHalf = symbol12 << 63 | symbol25 >> 2;

			// Decode symbols
			for (Int32 indexH = offset, indexL = offset + 13, shiftH = 59, shiftL = 58; indexH < lastIndex; indexH++, indexL++, shiftH -= 5, shiftL -= 5)
			{
				// Get symbols
				var symbolH = data[indexH] & 0x7F;

				var symbolL = data[indexL] & 0x7F;

				// Get symbols values
				var symbolHValue = (UInt64) lookupTable[symbolH];

				var symbolLValue = (UInt64) lookupTable[symbolL];

				// Check symbol
				if ((symbolHValue | symbolLValue) == 0xFF)
				{
					return convertFailResult;
				}

				higherHalf |= symbolHValue << shiftH;

				lowerHalf |= symbolLValue << shiftL;
			}

			// Initialize a new instance
			var result = new Value128(higherHalf, lowerHalf);

			return TryResult<Value128>.CreateSuccess(result);
		}