Exemple #1
0
        public async Task Should_not_add_to_indexes_if_name_is_taken()
        {
            var token = RandomHash.Simple();

            A.CallTo(() => cache.ReserveAsync(appId.Id, appId.Name))
            .Returns(token);

            A.CallTo(() => cache.GetAppIdsAsync(A <string[]> .That.Is(appId.Name)))
            .Returns(new List <DomainId> {
                appId.Id
            });

            var command = Create(appId.Name);

            var context =
                new CommandContext(command, commandBus)
                .Complete();

            await Assert.ThrowsAsync <ValidationException>(() => sut.HandleAsync(context));

            A.CallTo(() => cache.AddAsync(A <DomainId> ._, A <string> ._))
            .MustNotHaveHappened();

            A.CallTo(() => cache.RemoveReservationAsync(token))
            .MustHaveHappened();
        }
Exemple #2
0
        public async Task Should_also_add_to_user_index_if_app_is_created_by_client()
        {
            var token = RandomHash.Simple();

            A.CallTo(() => indexByName.ReserveAsync(appId.Id, appId.Name))
            .Returns(token);

            var command = CreateFromClient(appId.Name);

            var context =
                new CommandContext(command, commandBus)
                .Complete();

            await sut.HandleAsync(context);

            A.CallTo(() => indexByName.AddAsync(token))
            .MustHaveHappened();

            A.CallTo(() => indexByName.RemoveReservationAsync(A <string> ._))
            .MustNotHaveHappened();

            A.CallTo(() => indexForClient.AddAsync(appId.Id))
            .MustHaveHappened();

            A.CallTo(() => indexForUser.AddAsync(appId.Id))
            .MustNotHaveHappened();
        }
Exemple #3
0
        /// <summary>
        /// Шифрует файл открытого текста, используя шифр Rijndael в режиме CBC, с помощью соли HMAC SHA-512 с паролем.
        /// Произвольный 128-битный вектор инициализации генерируется для шифра.
        /// </summary>
        /// <param name="plaintextFile">Файл открытого текста для шифрования.</param>
        /// <param name="ciphertextFile">Полученный файл зашифрованного текста.</param>
        /// <param name="password">Пароль для шифрования файла с открытым текстом.</param>
        /// <param name="keySize">Размер ключа шифрования. 256-бит сильнее, но медленнее.</param>
        public void Encrypt(string plaintextFile, string ciphertextFile, string password, KeySize keySize)
        {
            // Создайте новый файл зашифрованного текста, чтобы записать зашифрованный текст в
            using (var fsc = new FileStream(ciphertextFile, FileMode.Create, FileAccess.Write))
            {
                // Сохраните IV в начале файла зашифрованного текста
                var iv = RandomHash.GenerateRandomBytes(InitializationVectorSize);
                fsc.Write(iv, 0, iv.Length);

                // Создать CryptoStream для шифрования открытого текста
                using (var cs = new CryptoStream(fsc, CreateEncryptor(password, iv, keySize), CryptoStreamMode.Write))
                {
                    // Откройте файл открытого текста.
                    using (var fsp = new FileStream(plaintextFile, FileMode.Open, FileAccess.Read))
                    {
                        // Создаем буфер для обработки файла открытого текста в кусках
                        // Чтение целого файла в память может вызвать
                        // исключения из памяти, если файл большой
                        var buffer = new byte[4096];

                        // Чтение фрагмента из файла открытого текста
                        int bytesRead;
                        while ((bytesRead = fsp.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            // Шифровать открытый текст и записать его в файл зашифрованного текста
                            cs.Write(buffer, 0, bytesRead);
                        }

                        // Завершить шифрование
                        cs.FlushFinalBlock();
                    }
                }
            }
        }
Exemple #4
0
        private async Task GenerateClientSecretAsync(string id)
        {
            var update = new UserValues {
                ClientSecret = RandomHash.New()
            };

            await userService.UpdateAsync(id, update);
        }
Exemple #5
0
        private async Task GenerateClientSecretAsync(string id)
        {
            var update = new UserValues {
                ClientSecret = RandomHash.New()
            };

            await userService.UpdateAsync(id, update, ct : HttpContext.RequestAborted);
        }
Exemple #6
0
        public static Task <IdentityResult> GenerateClientSecretAsync(this UserManager <IdentityUser> userManager, IdentityUser user)
        {
            var claims = new List <Claim> {
                new Claim(SquidexClaimTypes.ClientSecret, RandomHash.New())
            };

            return(userManager.SyncClaimsAsync(user, claims));
        }
Exemple #7
0
        public static Task <IdentityResult> GenerateClientSecretAsync(this UserManager <IdentityUser> userManager, IdentityUser user)
        {
            var update = new UserValues
            {
                ClientSecret = RandomHash.New()
            };

            return(update.SyncClaims(userManager, user));
        }
Exemple #8
0
        private async Task GenerateClientSecretAsync(string id,
                                                     CancellationToken ct)
        {
            var update = new UserValues {
                ClientSecret = RandomHash.New()
            };

            await userService.UpdateAsync(id, update, ct : ct);
        }
Exemple #9
0
    public Perlin(int size, float amplitude, int frequency, Int32 seed)
    {
        m_size      = size;
        m_amplitude = amplitude;
        m_frequency = frequency;

        m_generator    = new RandomHash(seed);
        m_distribution = new UniformFloatDistribution(-amplitude, amplitude);
    }
Exemple #10
0
        public static User Create(string appId, string userId)
        {
            var user = new User {
                AppId = appId, Id = userId
            };

            user.ApiKey = RandomHash.New();

            return(user);
        }
Exemple #11
0
        /// <summary>
        /// Шифрует открытый текст, используя режим Encrypt-MAC через шифра Rijndael в
        /// CBC с паролем, полученным из соли HMAC SHA-512. Случайная 128-битная инициализация
        /// Вектор создается для шифра.
        /// </summary>
        /// <param name="plaintext">Открытый текст для шифрования.</param>
        /// <param name="password">Пароль для шифрования открытого текста.</param>
        /// <param name="keySize">Размер ключа шифрования. 256-бит сильнее, но медленнее.</param>
        /// <returns>Шифрованный текст EncM с кодировкой Base64.</returns>
        public new string Encrypt(byte[] plaintext, string password, KeySize keySize)
        {
            // Генерация случайного IV
            var iv = RandomHash.GenerateRandomBytes(InitializationVectorSize);

            // Шифровать открытый текст
            var etmCiphertext = Encrypt(plaintext, password, iv, keySize);

            // Кодировать зашифрованный текст EtM
            return(Convert.ToBase64String(etmCiphertext));
        }
Exemple #12
0
        public AppImage(string mimeType, string?etag = null)
        {
            Guard.NotNullOrEmpty(mimeType, nameof(mimeType));

            MimeType = mimeType;

            if (string.IsNullOrWhiteSpace(etag))
            {
                Etag = RandomHash.Simple();
            }
            else
            {
                Etag = etag;
            }
        }
Exemple #13
0
        public Task ExecuteAsync(User user, IServiceProvider serviceProvider, CancellationToken ct)
        {
            Validate <Validator> .It(this);

            if (FullName != null)
            {
                user.FullName = FullName;
            }

            if (EmailAddress != null)
            {
                user.EmailAddress = EmailAddress;
            }

            if (PhoneNumber != null)
            {
                user.PhoneNumber = PhoneNumber;
            }

            if (PreferredLanguage != null)
            {
                user.PreferredLanguage = PreferredLanguage;
            }

            if (PreferredTimezone != null)
            {
                user.PreferredTimezone = PreferredTimezone;
            }

            if (RequiresWhitelistedTopics != null)
            {
                user.RequiresWhitelistedTopics = RequiresWhitelistedTopics.Value;
            }

            if (Settings != null)
            {
                user.Settings = Settings;
            }

            if (string.IsNullOrWhiteSpace(user.ApiKey))
            {
                user.ApiKey = RandomHash.New();
            }

            return(Task.CompletedTask);
        }
Exemple #14
0
    public static void InitializeHashGrid(int seed)
    {
        _hashGrid = new RandomHash[_sqrtHashGridSize * _sqrtHashGridSize];

// Store the default state of Random
        Random.State currentState = Random.state;

        Random.InitState(seed);

// Get random values
        for (int i = 0; i < _hashGrid.Length; i++)
        {
            _hashGrid[i] = new RandomHash(5);
        }

// Restore the default state of random to ensure randomness
        Random.state = currentState;
    }
Exemple #15
0
        public async Task Should_clear_reservation_when_schema_creation_failed()
        {
            var token = RandomHash.Simple();

            A.CallTo(() => index.ReserveAsync(schemaId.Id, schemaId.Name))
            .Returns(token);

            var context =
                new CommandContext(Create(schemaId.Name), commandBus);

            await sut.HandleAsync(context);

            A.CallTo(() => index.AddAsync(token))
            .MustNotHaveHappened();

            A.CallTo(() => index.RemoveReservationAsync(token))
            .MustHaveHappened();
        }
Exemple #16
0
        public async Task Should_add_schema_to_index_on_create()
        {
            var token = RandomHash.Simple();

            A.CallTo(() => index.ReserveAsync(schemaId.Id, schemaId.Name))
            .Returns(token);

            var context =
                new CommandContext(Create(schemaId.Name), commandBus)
                .Complete();

            await sut.HandleAsync(context);

            A.CallTo(() => index.AddAsync(token))
            .MustHaveHappened();

            A.CallTo(() => index.RemoveReservationAsync(A <string> .Ignored))
            .MustNotHaveHappened();
        }
    public void AddSpecialFeature(
        Hex hex,
        Vector3 position,
        float hexOuterRadius,
        int wrapSize
    ) {
        Transform instance = Instantiate(special[hex.SpecialIndex - 1]);

        instance.localPosition = HexagonPoint.Perturb(
            position,
            hexOuterRadius,
            wrapSize
        );

        RandomHash rootHash = HexagonPoint.SampleHashGrid(position);
        float e = rootHash.GetValue(4);

        instance.localRotation = Quaternion.Euler(0f, 360f * e, 0f);
        instance.SetParent(_container, false);
    }
Exemple #18
0
        public async Task Should_clear_reservation_if_app_creation_failed()
        {
            var token = RandomHash.Simple();

            A.CallTo(() => cache.ReserveAsync(appId.Id, appId.Name))
            .Returns(token);

            var command = CreateFromClient(appId.Name);

            var context =
                new CommandContext(command, commandBus);

            await sut.HandleAsync(context);

            A.CallTo(() => cache.AddAsync(A <DomainId> ._, A <string> ._))
            .MustNotHaveHappened();

            A.CallTo(() => cache.RemoveReservationAsync(token))
            .MustHaveHappened();
        }
Exemple #19
0
        public async Task Should_add_app_to_indexes_if_creating()
        {
            var token = RandomHash.Simple();

            A.CallTo(() => cache.ReserveAsync(appId.Id, appId.Name))
            .Returns(token);

            var command = Create(appId.Name);

            var context =
                new CommandContext(command, commandBus)
                .Complete();

            await sut.HandleAsync(context);

            A.CallTo(() => cache.AddAsync(appId.Id, appId.Name))
            .MustHaveHappened();

            A.CallTo(() => cache.RemoveReservationAsync(token))
            .MustHaveHappened();
        }
Exemple #20
0
        public async Task Should_add_app_to_indexes_on_create()
        {
            var token = RandomHash.Simple();

            A.CallTo(() => indexByName.ReserveAsync(appId.Id, appId.Name))
            .Returns(token);

            var context =
                new CommandContext(Create(appId.Name), commandBus)
                .Complete();

            await sut.HandleAsync(context);

            A.CallTo(() => indexByName.AddAsync(token))
            .MustHaveHappened();

            A.CallTo(() => indexByName.RemoveReservationAsync(A <string> ._))
            .MustNotHaveHappened();

            A.CallTo(() => indexByUser.AddAsync(appId.Id))
            .MustHaveHappened();
        }
Exemple #21
0
        public async Task Should_clear_reservation_when_app_creation_failed()
        {
            var token = RandomHash.Simple();

            A.CallTo(() => indexByName.ReserveAsync(appId.Id, appId.Name))
            .Returns(token);

            var command = CreateFromClient(appId.Name);

            var context =
                new CommandContext(command, commandBus);

            await sut.HandleAsync(context);

            A.CallTo(() => indexByName.AddAsync(token))
            .MustNotHaveHappened();

            A.CallTo(() => indexByName.RemoveReservationAsync(token))
            .MustHaveHappened();

            A.CallTo(() => indexForUser.AddAsync(appId.Id))
            .MustNotHaveHappened();
        }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="hashGridSize">
///     The size of the hash grid. The larger this value, the
///     less reptition of random values across a given range
///     of coordinates. To eliminate repitition this value should
///     be equal to the maximum x or y coordinate, which ever is
///     larger.
/// </param>
/// <param name="hashGridScale">
///     Density of the the unique values per unit square. A value
///     of 1 produces a unique value for every unique coordinate,
///     while a value of .25f produces a unique value every 4 unique
///     coordinates square.
/// </param>
/// <param name="seed">
///     The random seed value used to create the values in the
///     hash grid.
/// </param>
/// <param name="randomValuesPerCooridnate">
///     The number of random values stored per coordinate.
/// </param>
    public RandomHashGrid(
        int hashGridSize,
        float hashGridScale,
        int seed,
        int randomValuesPerCooridnate
        )
    {
        _hashGridSize  = hashGridSize;
        _hashGridScale = hashGridScale;

        _grid = new RandomHash[hashGridSize * hashGridSize];

// Snapshot the current random state and initialize new random state with seed.
        Random.State snapshot = RandomState.Snapshot(seed);

// Populate grid with RandomHash structs.
        for (int i = 0; i < _grid.Length; i++)
        {
            _grid[i] = new RandomHash(randomValuesPerCooridnate);
        }

// Restore random state from snapshot.
        Random.state = snapshot;
    }
        public static List <PoissonDisc> Sample2D(uint seed, double minRadius, Vector3D regionSize, int k = 4, bool createNeighbours = false, Vector3D centerPos = null, Func <Vector3D, float> calcRadius = null)
        {
            List <PoissonDisc> points    = new List <PoissonDisc>();
            double             maxRadius = 0f;
            int searchZone = 2;

            RandomHash hash     = new RandomHash(seed);
            double     cellSize = minRadius * 2 / 1.41421356237; // Minimum distance between cells divided by sqrt(2)

            int[,] grid = new int[(int)Math.Ceiling(regionSize.X / cellSize), (int)Math.Ceiling(regionSize.Y / cellSize)];
            List <PoissonDisc> spawnPoints = new List <PoissonDisc>
            {
                new PoissonDisc(centerPos ?? regionSize / 2, minRadius)
            };

            points.Add(spawnPoints[0]);
            grid[(int)(spawnPoints[0].position.X / cellSize), (int)(spawnPoints[0].position.Y / cellSize)] = points.Count;

            int currVal = 0;

            while (spawnPoints.Count > 0)
            {
                int         spawnIndex  = hash.Next(0, spawnPoints.Count, ++currVal);
                PoissonDisc spawnCentre = spawnPoints[spawnIndex];

                bool   candidateAccepted = false;
                double randRot           = hash.NextDouble(0, 1, currVal);
                double nextRadius        = calcRadius == null ? minRadius : calcRadius(spawnCentre.position);
                double distance          = spawnCentre.radius + nextRadius;
                double r = distance + 0.0000001;

                for (int j = 0; j < k; j++)
                {
                    double theta = pi * (randRot + 1.0 * j / k);

                    double x = spawnCentre.position.X + r * Math.Cos(theta);
                    double y = spawnCentre.position.Y + r * Math.Sin(theta);

                    Vector3D candidate = new Vector3D(x, y, 0);
                    if (IsValid2D(candidate, nextRadius, searchZone, regionSize, cellSize, grid, points))
                    {
                        if (distance > maxRadius)
                        {
                            maxRadius  = distance;
                            searchZone = (int)Math.Ceiling(distance / cellSize);
                        }
                        PoissonDisc disc = new PoissonDisc(candidate, nextRadius);
                        points.Add(disc);
                        spawnPoints.Add(disc);
                        grid[(int)(candidate.X / cellSize), (int)(candidate.Y / cellSize)] = points.Count;
                        candidateAccepted = true;
                        break;
                    }
                }
                if (!candidateAccepted)
                {
                    spawnPoints.RemoveAt(spawnIndex);
                }
            }

            if (createNeighbours)
            {
                return(CreateNeighbourList2D(points, grid, searchZone));
            }

            return(points);
        }
Exemple #24
0
        public void Configure(OpenIddictServerOptions options)
        {
            var collection = database.GetCollection <MongoDbKey>("Identity_Key6");

            var key = collection.Find(x => x.Id == "Default").FirstOrDefault();

            RsaSecurityKey securityKey;

            if (key == null)
            {
                securityKey = new RsaSecurityKey(RSA.Create(2048))
                {
                    KeyId = RandomHash.New()
                };

                key = new MongoDbKey {
                    Id = "Default", Key = securityKey.KeyId
                };

                if (securityKey.Rsa != null)
                {
                    var parameters = securityKey.Rsa.ExportParameters(true);

                    key.Parameters = MongoDbKeyParameters.Create(parameters);
                }
                else
                {
                    key.Parameters = MongoDbKeyParameters.Create(securityKey.Parameters);
                }

                try
                {
                    collection.InsertOne(key);
                }
                catch (MongoWriteException ex)
                {
                    if (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
                    {
                        key = collection.Find(x => x.Id == "Default").FirstOrDefault();
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            if (key == null)
            {
                throw new InvalidOperationException("Cannot read key.");
            }

            securityKey = new RsaSecurityKey(key.Parameters.ToParameters())
            {
                KeyId = key.Key
            };

            options.SigningCredentials.Add(
                new SigningCredentials(securityKey,
                                       SecurityAlgorithms.RsaSha256));

            options.EncryptionCredentials.Add(new EncryptingCredentials(securityKey,
                                                                        SecurityAlgorithms.RsaOAEP,
                                                                        SecurityAlgorithms.Aes256CbcHmacSha512));
        }
        public void RunTest()
        {
            RandomHash random = new RandomHash();

            random.Next(5, 10, 1, 5, 24);
        }
 public AttachClient()
 {
     Secret = RandomHash.New();
 }
Exemple #27
0
 public Task <string> GenerateUserTokenAsync(string appId, string userId)
 {
     return(Task.FromResult(RandomHash.New()));
 }
Exemple #28
0
        public async Task ExecuteAsync(App app, IServiceProvider serviceProvider, CancellationToken ct)
        {
            Validate <Validator> .It(this);

            if (!string.Equals(EmailAddress, app.EmailAddress, StringComparison.OrdinalIgnoreCase))
            {
                var emailServer = serviceProvider.GetRequiredService <IEmailServer>() !;

                if (!string.IsNullOrWhiteSpace(app.EmailAddress))
                {
                    await emailServer.RemoveEmailAddressAsync(app.EmailAddress, ct);
                }

                if (!string.IsNullOrWhiteSpace(EmailAddress))
                {
                    var appRepository = serviceProvider.GetRequiredService <IAppRepository>();

                    var(existing, _) = await appRepository.GetByEmailAddressAsync(EmailAddress, ct);

                    if (existing != null)
                    {
                        throw new DomainException("The email address is already in use by another app.");
                    }

                    var status = await emailServer.AddEmailAddressAsync(EmailAddress, ct);

                    app.EmailVerificationStatus = status;
                }

                app.EmailAddress = EmailAddress ?? string.Empty;
            }

            if (Name != null)
            {
                app.Name = Name;
            }

            if (EmailName != null)
            {
                app.EmailName = EmailName;
            }

            if (FirebaseProject != null)
            {
                app.FirebaseProject = FirebaseProject;
            }

            if (FirebaseCredential != null)
            {
                app.FirebaseCredential = FirebaseCredential;
            }

            if (WebhookUrl != null)
            {
                app.WebhookUrl = WebhookUrl;
            }

            if (ConfirmUrl != null)
            {
                app.ConfirmUrl = ConfirmUrl;
            }

            if (AllowEmail != null)
            {
                app.AllowEmail = AllowEmail.Value;
            }

            if (AllowSms != null)
            {
                app.AllowSms = AllowSms.Value;
            }

            if (Languages != null)
            {
                app.Languages = Languages;
            }

            if (app.ApiKeys.Count == 0)
            {
                app.ApiKeys[RandomHash.New()] = NotifoRoles.AppAdmin;
                app.ApiKeys[RandomHash.New()] = NotifoRoles.AppAdmin;
                app.ApiKeys[RandomHash.New()] = NotifoRoles.AppWebManager;
                app.ApiKeys[RandomHash.New()] = NotifoRoles.AppWebManager;
            }

            if (app.Contributors.Count == 0 && !string.IsNullOrWhiteSpace(UserId))
            {
                app.Contributors[UserId] = NotifoRoles.AppOwner;
            }
        }
    private void AddWallSegment (
        Vector3 pivot, Hex pivotHex,
        Vector3 left, Hex leftHex,
        Vector3 right, Hex rightHex,
        float hexOuterRadius,
        int wrapSize
    ) {
        if (pivotHex.IsUnderwater) {
            return;
        }

        bool hasLeftWall = !leftHex.IsUnderwater &&
                            pivotHex.GetEdgeType(leftHex) != ElevationEdgeTypes.Cliff;

        bool hasRightWall = !rightHex.IsUnderwater &&
                            pivotHex.GetEdgeType(rightHex) != ElevationEdgeTypes.Cliff;

        if (hasLeftWall) {
            if (hasRightWall) {
                bool hasTower = false;

                if (leftHex.elevation == rightHex.elevation) {
                    RandomHash rootHash = HexagonPoint.SampleHashGrid (
                        (pivot + left + right) * 1f / 3f
                    );

                    float e = rootHash.GetValue(4);

                    hasTower = e < HexagonPoint.wallTowerThreshold;
                }

                AddWallSegment(
                    pivot,
                    left,
                    pivot,
                    right,
                    hexOuterRadius,
                    wrapSize,
                    hasTower
                );
            }
            else if (leftHex.elevation < rightHex.elevation) {
                AddWallWedge(
                    pivot,
                    left,
                    right,
                    hexOuterRadius,
                    wrapSize
                );
            }
            else {
                AddWallCap(
                    pivot,
                    left,
                    hexOuterRadius,
                    wrapSize
                );
            }
        }
        else if (hasRightWall) {
            if (rightHex.elevation < leftHex.elevation) {
                AddWallWedge(
                    right,
                    pivot,
                    left,
                    hexOuterRadius,
                    wrapSize
                );
            }
            else
            {
                AddWallCap(
                    right,
                    pivot,
                    hexOuterRadius,
                    wrapSize
                );
            }
        }
    }
    public void AddFeature(
        Hex hex,
        Vector3 position,
        float hexOuterRadius,
        int wrapSize
    ) {

        if (hex.IsSpecial) {
            return;
        }

/* Randomness of rotation is obtained by sampling a Hash
* World rather than using Random, so the rotation of objects
* will not be changed when the hex is refreshed.
*/

        RandomHash randomHash = HexagonPoint.SampleHashGrid(position);
        float a = randomHash.GetValue(0);
        float b = randomHash.GetValue(1);
        float c = randomHash.GetValue(2);
        float d = randomHash.GetValue(3);
        float e = randomHash.GetValue(4);

        Transform prefab = PickPrefab(
            urbanCollections, hex.UrbanLevel, a, d
        );

        Transform otherPrefab = PickPrefab(
            farmCollections, hex.FarmLevel, b, d
        );

        float usedHash = randomHash.GetValue(0);
        if (prefab) {
            if (otherPrefab && b < a) {
                prefab = otherPrefab;
                usedHash = b;
            }
        }
        else if (otherPrefab) {
            prefab = otherPrefab;
            usedHash = b;
        }

        otherPrefab = PickPrefab (
            plantCollections, hex.PlantLevel, c, d
        );

        if (prefab) {
            if (otherPrefab && c < usedHash) {
                prefab = otherPrefab;
            }
        }
        else if (otherPrefab) {
            prefab = otherPrefab;
        }
        else {
            return;
        }

        if (!prefab) {
            return;
        }

        Transform instance = Instantiate(prefab);

        instance.localPosition = HexagonPoint.Perturb(
            position,
            hexOuterRadius,
            wrapSize
        );
        
        instance.localRotation = Quaternion.Euler(0f, 360f * e, 0f);

        instance.SetParent(_container, false);
    }