public void TestUserCollectorWindows()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Assert.IsTrue(AsaHelpers.IsAdmin());
                var user     = System.Guid.NewGuid().ToString().Substring(0, 10);
                var password = "******" + CryptoHelpers.GetRandomString(13);

                var cmd = string.Format("user /add {0} {1}", user, password);
                ExternalCommandRunner.RunExternalCommand("net", cmd);

                var uac = new UserAccountCollector();
                uac.Execute();

                Assert.IsTrue(uac.Results.Any(x => x is UserAccountObject y && y.Name.Equals(user)));

                cmd = string.Format("user /delete {0}", user);
                ExternalCommandRunner.RunExternalCommand("net", cmd);
            }
        }
        public void Correctness256()
        {
            var plainText = "Hello world123456788993812371237123789123";
            var cipherKey256 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };

            var aes = AesContext.AES256;
            byte[] encrypted;
            using (var encryptor = aes.CreateEncryptor(cipherKey256, null))
            {
                encrypted = CryptoHelpers.EncryptString(encryptor, plainText);
            }

            string actual;
            using (var decryptor = aes.CreateDecryptor(cipherKey256, null))
            {
                actual = CryptoHelpers.DecryptToString(decryptor, encrypted);
            }

            Assert.Equal(plainText, actual);
        }
Example #3
0
        public async Task EvilNodeDetectionTest()
        {
            var firstRound = await BootMiner.GetCurrentRoundInformation.CallAsync(new Empty());

            var randomHashes = Enumerable.Range(0, MinersCount).Select(_ => Hash.Generate()).ToList();
            var triggers     = Enumerable.Range(0, MinersCount).Select(i => new DPoSTriggerInformation
            {
                PublicKey  = ByteString.CopyFrom(InitialMinersKeyPairs[i].PublicKey),
                RandomHash = randomHashes[i]
            }).ToDictionary(t => t.PublicKey.ToHex(), t => t);

            var voter = GetConsensusContractTester(VotersKeyPairs[0]);
            var oneMoreCandidateKeyPair = CryptoHelpers.GenerateKeyPair();

            await GetTokenContractTester(BootMinerKeyPair).Transfer.SendAsync(new TransferInput
            {
                Symbol = "ELF",
                Amount = 10_0000,
                To     = Address.FromPublicKey(oneMoreCandidateKeyPair.PublicKey)
            });
Example #4
0
        public void OffChainDecryptMessageTest()
        {
            var message         = Hash.Generate().ToHex();
            var secrets         = SecretSharingHelper.EncodeSecret(message, MinimumCount, MinersCount);
            var encryptedValues = new Dictionary <string, byte[]>();
            var decryptedValues = new Dictionary <string, byte[]>();
            var ownerKeyPair    = InitialMinersKeyPairs[0];
            var othersKeyPairs  = InitialMinersKeyPairs.Skip(1).ToList();
            var decryptResult   = "";

            var initial = 0;

            foreach (var keyPair in othersKeyPairs)
            {
                var encryptedMessage = CryptoHelpers.EncryptMessage(ownerKeyPair.PrivateKey, keyPair.PublicKey,
                                                                    Encoding.UTF8.GetBytes(secrets[initial++]));
                encryptedValues.Add(keyPair.PublicKey.ToHex(), encryptedMessage);
            }

            // Check encrypted values.
            encryptedValues.Count.ShouldBe(MinersCount - 1);

            // Others try to recover.
            foreach (var keyPair in othersKeyPairs)
            {
                var cipherMessage  = encryptedValues[keyPair.PublicKey.ToHex()];
                var decryptMessage =
                    CryptoHelpers.DecryptMessage(ownerKeyPair.PublicKey, keyPair.PrivateKey, cipherMessage);
                decryptedValues.Add(keyPair.PublicKey.ToHex(), decryptMessage);

                if (decryptedValues.Count >= MinimumCount)
                {
                    decryptResult = SecretSharingHelper.DecodeSecret(
                        decryptedValues.Values.Select(v => Encoding.UTF8.GetString(v)).ToList(),
                        Enumerable.Range(1, MinimumCount).ToList(), MinimumCount);
                    break;
                }
            }

            decryptResult.ShouldBe(message);
        }
Example #5
0
        public async Task <string> SignHash(string address, string password, string hash)
        {
            var tryOpen = await KeyStore.OpenAsync(address, password);

            if (tryOpen == AElfKeyStore.Errors.WrongPassword)
            {
                throw new JsonRpcServiceException(Error.WrongPassword, Error.Message[Error.WrongPassword]);
            }

            var kp = KeyStore.GetAccountKeyPair(address);

            if (kp == null)
            {
                throw new JsonRpcServiceException(Error.AccountNotExist, Error.Message[Error.AccountNotExist]);
            }

            var toSig     = ByteArrayHelpers.FromHexString(hash);
            var signature = CryptoHelpers.SignWithPrivateKey(kp.PrivateKey, toSig);

            return(signature.ToHex());
        }
Example #6
0
        public void InitialTesters(Timestamp blockchainStartTime)
        {
            for (var i = 0; i < MinersCount; i++)
            {
                var keyPair = CryptoHelpers.GenerateKeyPair();
                MinersKeyPairs.Add(keyPair);
            }

            foreach (var minersKeyPair in MinersKeyPairs)
            {
                var tester = new ContractTester <DPoSContractTestAElfModule>(ChainId, minersKeyPair);
                AsyncHelper.RunSync(() =>
                                    tester.InitialCustomizedChainAsync(MinersKeyPairs.Select(m => m.PublicKey.ToHex()).ToList(), 4000,
                                                                       blockchainStartTime));
                Testers.Add(tester);
            }

            AsyncHelper.RunSync(() => Testers.RunConsensusAsync(2));

            ConsensusContractAddress = Testers[0].GetConsensusContractAddress();
        }
Example #7
0
        public async Task NextTerm_GetConsensusCommand()
        {
            const int minersCount = 3;

            var starter = new ContractTester <DPoSContractTestAElfModule>();

            var minersKeyPairs = Enumerable.Range(0, minersCount).Select(_ => CryptoHelpers.GenerateKeyPair()).ToList();
            await starter.InitialChainAndTokenAsync(minersKeyPairs);

            var miners = Enumerable.Range(0, minersCount)
                         .Select(i => starter.CreateNewContractTester(minersKeyPairs[i])).ToList();

            // Produce several blocks.
            await miners.ProduceNormalBlocks(minersCount);

            // Unable to change term.
            {
                var extraBlockMiner = miners.AnyOne();
                var timestamp       = DateTime.UtcNow.AddMilliseconds(minersCount * MiningInterval + MiningInterval)
                                      .ToTimestamp();
                var command = await extraBlockMiner.GetConsensusCommandAsync(timestamp);

                Assert.Equal(DPoSBehaviour.NextRound, DPoSHint.Parser.ParseFrom(command.Hint).Behaviour);
            }

            // Terminate current round then produce several blocks with fake timestamp.
            await miners.ChangeRoundAsync();

            await miners.ProduceNormalBlocks(minersCount,
                                             DateTime.UtcNow.AddMinutes(ConsensusDPoSConsts.DaysEachTerm + 1).ToTimestamp());

            // Able to changer term.
            {
                var extraBlockMiner = miners.AnyOne();
                var timestamp       = DateTime.UtcNow.AddMinutes(ConsensusDPoSConsts.DaysEachTerm + 2).ToTimestamp();
                var command         = await extraBlockMiner.GetConsensusCommandAsync(timestamp);

                Assert.Equal(DPoSBehaviour.NextTerm, DPoSHint.Parser.ParseFrom(command.Hint).Behaviour);
            }
        }
        public static async Task <List <ContractTester <DPoSContractTestAElfModule> > > GenerateCandidatesAsync(
            this ContractTester <DPoSContractTestAElfModule> starter, int number)
        {
            var candidatesKeyPairs  = new List <ECKeyPair>();
            var candidates          = new List <ContractTester <DPoSContractTestAElfModule> >();
            var transferTxs         = new List <Transaction>();
            var announceElectionTxs = new List <Transaction>();

            for (var i = 0; i < number; i++)
            {
                var candidateKeyPair = CryptoHelpers.GenerateKeyPair();
                transferTxs.Add(await starter.GenerateTransactionAsync(starter.GetTokenContractAddress(),
                                                                       nameof(TokenContract.Transfer), starter.KeyPair, new TransferInput
                {
                    To     = Address.FromPublicKey(candidateKeyPair.PublicKey),
                    Amount = DPoSContractConsts.LockTokenForElection,
                    Symbol = "ELF"
                }));
                announceElectionTxs.Add(await starter.GenerateTransactionAsync(starter.GetConsensusContractAddress(),
                                                                               nameof(ConsensusContract.AnnounceElection), candidateKeyPair,
                                                                               new Alias
                {
                    Value = $"{candidateKeyPair.PublicKey.ToHex().Substring(0, DPoSContractConsts.AliasLimit)}"
                }));
                candidatesKeyPairs.Add(candidateKeyPair);
            }

            // Package Transfer txs.
            await starter.MineAsync(transferTxs);

            // Package AnnounceElection txs.
            await starter.MineAsync(announceElectionTxs);

            foreach (var candidatesKeyPair in candidatesKeyPairs)
            {
                candidates.Add(starter.CreateNewContractTester(candidatesKeyPair));
            }

            return(candidates);
        }
        public void Correctness256Binary()
        {
            var plainText = "Hello world1234567889938123712371237891231111111111111111000010101010011sds";
            var inputBytes = System.Text.Encoding.Default.GetBytes(plainText);

            var cipherKey256 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };

            var aes = AesContext.AES256;
            byte[] encrypted;
            using (var encryptor = aes.CreateEncryptor(cipherKey256, null))
            {
                encrypted = CryptoHelpers.EncryptBytes(encryptor, inputBytes);
            }

            string actual;
            using (var decryptor = aes.CreateDecryptor(cipherKey256, null))
            {
                actual = CryptoHelpers.DecryptToString(decryptor, encrypted);
            }

            Assert.Equal(plainText, actual);
        }
Example #10
0
        private static void SeedUsers(DbContext dataContext)
        {
            var users = dataContext.Set <User>();

            if (users.Any())
            {
                AddAdminUser(dataContext);
                return;
            }

            AddAdminUser(dataContext);
            for (int i = 0; i < 20; i++)
            {
                users.Add(new User
                {
                    Email    = $"email{i}@aimscompanies.com",
                    Password = CryptoHelpers.HashPassword($"password{i}"),
                    Company  = $"Company{i}",
                    Role     = Roles.Customer
                });
            }
        }
        public void End2EndVerification()
        {
            var goodScalars = CryptoHelpers.GetScalars(x => !x.IsOverflow && !x.IsZero);

            foreach (var secret1 in goodScalars)
            {
                foreach (var secret2 in goodScalars.Where(x => x != secret1))
                {
                    var secrets     = new[] { secret1, secret2 };
                    var generators  = new[] { Generators.G, Generators.Ga };
                    var publicPoint = GroupElement.Infinity;
                    foreach (var(secret, generator) in secrets.ZipForceEqualLength(generators))
                    {
                        publicPoint += secret * generator;
                    }
                    Statement statement = new Statement(publicPoint, generators);
                    var       knowledge = new KnowledgeOfRepParams(secrets, statement);
                    var       proof     = Prover.CreateProof(knowledge);
                    Assert.True(Verifier.Verify(proof, statement));
                }
            }
        }
Example #12
0
        public void SignAndVerifyTransaction()
        {
            ECKeyPair   keyPair = CryptoHelpers.GenerateKeyPair();
            Transaction tx      = new Transaction();

            tx.From           = Address.FromPublicKey(keyPair.PublicKey);
            tx.To             = Address.Generate();
            tx.Params         = ByteString.CopyFrom(new byte[0]);
            tx.MethodName     = "TestMethod";
            tx.Params         = ByteString.Empty;
            tx.RefBlockNumber = 1;
            tx.RefBlockPrefix = ByteString.Empty;

            // Serialize and hash the transaction
            Hash hash = tx.GetHash();

            // Sign the hash
            var signature = CryptoHelpers.SignWithPrivateKey(keyPair.PrivateKey, hash.DumpByteArray());

            tx.Signature = ByteString.CopyFrom(signature);
            Assert.True(tx.VerifySignature());
        }
        public async Task <IActionResult> Login(LoginViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(View(GetViewModel(vm)));
            }
            var user = await dbContext.Set <User>().SingleOrDefaultAsync(x => x.Email == vm.Email);

            if (user == null)
            {
                return(DenyLogin(vm));
            }

            if (!CryptoHelpers.VerifyPassword(vm.Password, user.Password))
            {
                return(DenyLogin(vm));
            }

            await CreateAuthenticationTicket(user, vm.RemeberMe);

            return(RedirectUser(vm.ReturnUrl));
        }
Example #14
0
        public void Test_Decrypt_Message()
        {
            var alice = CryptoHelpers.GenerateKeyPair();
            var bob   = CryptoHelpers.GenerateKeyPair();
            var sam   = CryptoHelpers.GenerateKeyPair();

            // Alice want to transmit plain text "aelf" to Bob.

            var plainText  = Encoding.UTF8.GetBytes(Hash.Generate().ToHex());
            var cipherText = CryptoHelpers.EncryptMessage(alice.PrivateKey, bob.PublicKey, plainText);

            // Bob decrypt the message.
            var decrypt = CryptoHelpers.DecryptMessage(alice.PublicKey, bob.PrivateKey, cipherText);

            Assert.True(decrypt.BytesEqual(plainText));

            // Sam can't decrypt this message.
            var func = new Func <byte[]>(() => CryptoHelpers.DecryptMessage(alice.PublicKey, sam.PrivateKey,
                                                                            cipherText));

            Assert.Throws <VirgilCryptoException>(func);
        }
Example #15
0
        public void Test_Recover_Public_key()
        {
            var keyPair = CryptoHelpers.GenerateKeyPair();

            var messageBytes1 = Encoding.UTF8.GetBytes("Hello world.");
            var messageHash1  = SHA256.Create().ComputeHash(messageBytes1);

            var messageBytes2 = Encoding.UTF8.GetBytes("Hello aelf.");
            var messageHash2  = SHA256.Create().ComputeHash(messageBytes2);

            var signature1 = CryptoHelpers.SignWithPrivateKey(keyPair.PrivateKey, messageHash1);

            var recoverResult1 = CryptoHelpers.RecoverPublicKey(signature1, messageHash1, out var publicKey1);

            Assert.True(recoverResult1);
            Assert.True(publicKey1.BytesEqual(keyPair.PublicKey));

            var recoverResult2 = CryptoHelpers.RecoverPublicKey(signature1, messageHash2, out var publicKey2);

            Assert.True(recoverResult2);
            Assert.False(publicKey2.BytesEqual(keyPair.PublicKey));
        }
        public static bool TryDecryptArchiveKey(
            this UserKeyAuthorization authorization,
            UserKey userKey,
            SecuritySettings securitySettings,
            out ArchiveKey archiveKey)
        {
            ArgCheck.NotNull(authorization, nameof(authorization));
            ArgCheck.NotNull(userKey, nameof(userKey));
            ArgCheck.IsValid(securitySettings, nameof(securitySettings));

            archiveKey = null;

            if (!CryptoHelpers.SecureEquals(userKey.KeyId, authorization.KeyId))
            {
                return(false);
            }

            try
            {
                // The SecureArchive file format requires that the friendly name and keyId be
                // checked for tampering when using authenticated cyphers.
                var additionalData = Encoding.UTF8.GetBytes(authorization.FriendlyName + authorization.KeyId);

                var cryptoStrategy      = CryptoHelpers.GetCryptoStrategy(securitySettings.EncryptionAlgo);
                var decryptedArchiveKey = userKey.Decrypt(cryptoStrategy, authorization.EncryptedArchiveKey, additionalData);

                if (!decryptedArchiveKey.IsEmpty)
                {
                    archiveKey = new ArchiveKey(decryptedArchiveKey.ToArray());
                }
            }
            catch
            {
                return(false);
            }

            return(archiveKey != null);
        }
Example #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //should be moved to Configuration
            services.AddDbContext <TunderDbContext>(options =>
                                                    options.UseSqlServer(Configuration.GetConnectionString("TunderDevDb")));

            services.AddAutoMapper();

            services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);



            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = CryptoHelpers.GetSymmetricSecurityKey(Configuration),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            //DI


            services.AddScoped(typeof(IUserRepository), typeof(UserRepository));
            services.AddScoped(typeof(IEcoleRepository), typeof(EcoleRepository));
            services.AddScoped(typeof(IProfesseurRepository), typeof(ProfesseurRepository));

            services.AddScoped(typeof(IAuthService), typeof(AuthService));
            services.AddScoped(typeof(INotificationService), typeof(NotificationService));
            services.AddScoped(typeof(IThrottleService), typeof(ThrottleService));
            services.AddScoped(typeof(ICachingService), typeof(CachingService));
        }
        public async Task <ServiceResponse <UserDto> > Register(UserRegisterDto registerDto)
        {
            var validationResult = await userValidator.ValidateAsync(registerDto);

            if (!validationResult.IsValid)
            {
                return(new ServiceResponse <UserDto>(validationResult));
            }
            var newUser = new User
            {
                BillingAddress = registerDto.BillingAddress,
                Email          = registerDto.Email,
                Password       = CryptoHelpers.HashPassword(registerDto.Password),
                Role           = Roles.Customer
            };

            dbContext.Add(newUser);
            await dbContext.SaveChangesAsync();

            var userDto = await GetUserByEmail(newUser.Email);

            return(userDto);
        }
Example #19
0
        public async Task CreateContractTesterTest()
        {
            var tester = new ContractTester <ContractTestAElfModule>();
            await tester.InitialChainAsync();

            var zeroContractAddress = tester.GetContractAddress(Hash.Empty);
            var tx = await tester.GenerateTransactionAsync(zeroContractAddress,
                                                           "DeploySmartContract",
                                                           new ContractDeploymentInput()
            {
                Category = SmartContractTestConstants.TestRunnerCategory,
                Code     = ByteString.CopyFrom(File.ReadAllBytes(typeof(TokenContract).Assembly.Location))
            });

            await tester.MineAsync(new List <Transaction> {
                tx
            });

            var newTester = tester.CreateNewContractTester(CryptoHelpers.GenerateKeyPair());
            var chain     = await newTester.GetChainAsync();

            Assert.Equal(2L, chain.BestChainHeight);
        }
Example #20
0
        public void SetStatus(string planUniqueName, long planInstanceId, [FromBody] string planString)
        {
            InitPlanServer();

            string context = GetContext(nameof(SetStatus),
                                        nameof(planUniqueName), planUniqueName, nameof(planInstanceId), planInstanceId,
                                        nameof(planString), planString);

            planString = CryptoHelpers.Decode(planString);
            Plan plan = Plan.FromYaml(new StringReader(planString));

            try
            {
                SynapseServer.Logger.Debug(context);
                _server.UpdatePlanStatus(plan);
            }
            catch (Exception ex)
            {
                SynapseServer.Logger.Error(
                    Utilities.UnwindException(context, ex, asSingleLine: true));
                throw;
            }
        }
Example #21
0
        private static void AddAdminUser(DbContext dataContext)
        {
            var users = dataContext.Set <User>();

            if (users.Any(x => x.Email == "*****@*****.**"))
            {
                return;
            }
            users.Add(new User
            {
                Email          = $"*****@*****.**",
                Password       = CryptoHelpers.HashPassword("password"),
                Role           = Roles.Admin,
                BillingAddress = new Address
                {
                    AddressLine1 = "123 place St",
                    City         = "Hammond",
                    State        = "LA",
                    ZipCode      = "70403"
                }
            });
            dataContext.SaveChanges();
        }
Example #22
0
        public void Write(RegistryObject obj)
        {
            try
            {
                string hashSeed = String.Format("{0}{1}", obj.Key, JsonConvert.SerializeObject(obj));

                using (var cmd = new SqliteCommand(SQL_INSERT, DatabaseManager.Connection, DatabaseManager.Transaction))
                {
                    cmd.Parameters.AddWithValue("@run_id", this.runId);
                    cmd.Parameters.AddWithValue("@row_key", CryptoHelpers.CreateHash(hashSeed));
                    cmd.Parameters.AddWithValue("@key", obj.Key);

                    cmd.Parameters.AddWithValue("@value", JsonConvert.SerializeObject(obj.Values));


                    cmd.Parameters.AddWithValue("@subkeys", JsonConvert.SerializeObject(obj.Subkeys));
                    cmd.Parameters.AddWithValue("@permissions", obj.Permissions);
                    cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(obj));

                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception e)
                    {
                        Log.Debug(e.GetType() + "thrown in registry collector");
                        Telemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
                    }
                }
            }
            catch (Exception)
            {
                Log.Debug("Had trouble writing {0}", obj.Key);
            }

            customCrawlHandler?.Invoke(obj);
        }
Example #23
0
        public Tester(ECKeyPair keyPair, int port, params int[] bootNodes)
        {
            KeyPair = keyPair ?? CryptoHelpers.GenerateKeyPair();

            Application =
                AbpApplicationFactory.Create <TesterAElfModule>(options =>
            {
                options.UseAutofac();

                options.Services.AddTransient(o =>
                {
                    var mockService = new Mock <IAccountService>();
                    mockService.Setup(a => a.SignAsync(It.IsAny <byte[]>())).Returns <byte[]>(data =>
                                                                                              Task.FromResult(CryptoHelpers.SignWithPrivateKey(KeyPair.PrivateKey, data)));

                    mockService.Setup(a => a.VerifySignatureAsync(It.IsAny <byte[]>(), It.IsAny <byte[]>(),
                                                                  It.IsAny <byte[]>()
                                                                  )).Returns <byte[], byte[], byte[]>((signature, data, publicKey) =>
                    {
                        var recoverResult =
                            CryptoHelpers.RecoverPublicKey(signature, data, out var recoverPublicKey);
                        return(Task.FromResult(recoverResult && publicKey.BytesEqual(recoverPublicKey)));
                    });

                    mockService.Setup(a => a.GetPublicKeyAsync()).ReturnsAsync(KeyPair.PublicKey);

                    return(mockService.Object);
                });


                options.Services.Configure <NetworkOptions>(o =>
                {
                    o.ListeningPort = port;
                    o.BootNodes     = bootNodes.ToList().Select(n => $"127.0.0.1:{n.ToString()}").ToList();
                });
            });
        }
        public void Write(StoreLocation storeLocation, StoreName storeName, X509Certificate2 obj)
        {
            try
            {
                recordCounter++;
                var cmd = new SqliteCommand(SQL_INSERT, DatabaseManager.Connection, DatabaseManager.Transaction);
                cmd.Parameters.AddWithValue("@run_id", runId);
                cmd.Parameters.AddWithValue("@store_location", storeLocation.ToString());
                cmd.Parameters.AddWithValue("@store_name", storeName.ToString());
                cmd.Parameters.AddWithValue("@hash", obj.GetCertHashString());
                cmd.Parameters.AddWithValue("@hash_plus_store", obj.GetCertHashString() + storeLocation.ToString() + storeName.ToString());
                cmd.Parameters.AddWithValue("@cn", obj.Subject);

                if (obj.HasPrivateKey)
                {
                    cmd.Parameters.AddWithValue("@pkcs12", "redacted");
                }
                else
                {
                    cmd.Parameters.AddWithValue("@pkcs12", obj.Export(X509ContentType.Pkcs12));
                }

                cmd.Parameters.AddWithValue("@row_key", CryptoHelpers.CreateHash(runId + recordCounter));

                cmd.ExecuteNonQuery();
            }
            catch (NullReferenceException e)
            {
                Log.Warning(e.StackTrace);
            }
            catch (Microsoft.Data.Sqlite.SqliteException e)
            {
                Log.Warning(e.Message);
                //This catches duplicate certificates
            }
        }
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;

            services.AddSingleton(o => Mock.Of <IAElfNetworkServer>());
            services.AddSingleton(o => Mock.Of <IPeerPool>());

            services.AddSingleton(o => Mock.Of <INetworkService>());

            // When testing contract and packaging transactions, no need to generate and schedule real consensus stuff.
            context.Services.AddSingleton(o => Mock.Of <IConsensusService>());
            context.Services.AddSingleton(o => Mock.Of <IConsensusInformationGenerationService>());
            context.Services.AddSingleton(o => Mock.Of <IConsensusScheduler>());

            Configure <ChainOptions>(o => { o.ChainId = ChainHelpers.ConvertBase58ToChainId("AELF"); });

            var ecKeyPair = CryptoHelpers.GenerateKeyPair();

            context.Services.AddTransient(o =>
            {
                var mockService = new Mock <IAccountService>();
                mockService.Setup(a => a.SignAsync(It.IsAny <byte[]>())).Returns <byte[]>(data =>
                                                                                          Task.FromResult(CryptoHelpers.SignWithPrivateKey(ecKeyPair.PrivateKey, data)));

                mockService.Setup(a => a.VerifySignatureAsync(It.IsAny <byte[]>(), It.IsAny <byte[]>(), It.IsAny <byte[]>()
                                                              )).Returns <byte[], byte[], byte[]>((signature, data, publicKey) =>
                {
                    var recoverResult = CryptoHelpers.RecoverPublicKey(signature, data, out var recoverPublicKey);
                    return(Task.FromResult(recoverResult && publicKey.BytesEqual(recoverPublicKey)));
                });

                mockService.Setup(a => a.GetPublicKeyAsync()).ReturnsAsync(ecKeyPair.PublicKey);

                return(mockService.Object);
            });
        }
Example #26
0
        private ContractTester(IAbpApplicationWithInternalServiceProvider application, ECKeyPair keyPair)
        {
            application.Services.AddTransient(o =>
            {
                var mockService = new Mock <IAccountService>();
                mockService.Setup(a => a.SignAsync(It.IsAny <byte[]>())).Returns <byte[]>(data =>
                                                                                          Task.FromResult(CryptoHelpers.SignWithPrivateKey(keyPair.PrivateKey, data)));

                mockService.Setup(a => a.VerifySignatureAsync(It.IsAny <byte[]>(), It.IsAny <byte[]>(), It.IsAny <byte[]>()
                                                              )).Returns <byte[], byte[], byte[]>((signature, data, publicKey) =>
                {
                    var recoverResult = CryptoHelpers.RecoverPublicKey(signature, data, out var recoverPublicKey);
                    return(Task.FromResult(recoverResult && publicKey.BytesEqual(recoverPublicKey)));
                });

                mockService.Setup(a => a.GetPublicKeyAsync()).ReturnsAsync(keyPair.PublicKey);

                return(mockService.Object);
            });

            Application = application;

            KeyPair = keyPair;
        }
Example #27
0
 void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     if (e.Data != null)
     {
         string data = CryptoHelpers.Decode(e.Data);
         try
         {
             HandlerProgressCancelEventArgs args = HandlerProgressCancelEventArgs.DeserializeSimple(data, true);
             OnProgress(args);
         }
         catch
         {
             try
             {
                 LogMessageEventArgs args = LogMessageEventArgs.DeserializeSimple(data, true);
                 OnLogMessage(args);
             }
             catch
             {
                 throw new Exception("Could not deserialize output into known args type");
             }
         }
     }
 }
Example #28
0
        public void TestUserCollectorWindows()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Assert.IsTrue(AsaHelpers.IsAdmin());
                var FirstRunId  = "TestUserCollector-1";
                var SecondRunId = "TestUserCollector-2";

                var fwc = new UserAccountCollector(FirstRunId);
                fwc.Execute();

                var user     = System.Guid.NewGuid().ToString().Substring(0, 10);
                var password = "******" + CryptoHelpers.GetRandomString(13);

                var cmd = string.Format("user /add {0} {1}", user, password);
                ExternalCommandRunner.RunExternalCommand("net", cmd);

                var serviceName = System.Guid.NewGuid();

                fwc = new UserAccountCollector(SecondRunId);
                fwc.Execute();

                cmd = string.Format("user /delete {0}", user);
                ExternalCommandRunner.RunExternalCommand("net", cmd);

                BaseCompare bc = new BaseCompare();
                if (!bc.TryCompare(FirstRunId, SecondRunId))
                {
                    Assert.Fail();
                }

                var results = bc.Results;
                Assert.IsTrue(results.ContainsKey("USER_CREATED"));
                Assert.IsTrue(results["USER_CREATED"].Where(x => x.Identity.Contains(user)).Count() > 0);
            }
        }
Example #29
0
 public string GetHash()
 {
     return(CryptoHelpers.CreateHash(JsonConvert.SerializeObject(this)));
 }
Example #30
0
    public async Task BanningTestsAsync()
    {
        (_, IRPCClient rpc, Network network, Coordinator coordinator, _, _, _) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);

        Money   denomination                  = Money.Coins(0.1m);
        decimal coordinatorFeePercent         = 0.1m;
        int     anonymitySet                  = 3;
        int     connectionConfirmationTimeout = 120;
        var     roundConfig = RegTestFixture.CreateRoundConfig(denomination, 140, 0.7, coordinatorFeePercent, anonymitySet, 240, connectionConfirmationTimeout, 1, 1, 1, 24, true, 11);

        coordinator.RoundConfig.UpdateOrDefault(roundConfig, toFile: true);
        coordinator.AbortAllRoundsInInputRegistration("");

        await rpc.GenerateAsync(3);         // So to make sure we have enough money.

        Uri baseUri        = new(RegTestFixture.BackendEndPoint);
        var fundingTxCount = 0;
        List <(Requester requester, BlindedOutputWithNonceIndex blinded, BitcoinAddress activeOutputAddress, BitcoinAddress changeOutputAddress, IEnumerable <InputProofModel> inputProofModels, List <(Key key, BitcoinAddress address, uint256 txHash, Transaction tx, OutPoint input)> userInputData)> inputRegistrationUsers = new();
        CoordinatorRound?round = null;

        for (int i = 0; i < roundConfig.AnonymitySet; i++)
        {
            List <(Key key, BitcoinAddress inputAddress, uint256 txHash, Transaction tx, OutPoint input)> userInputData = new();
            var activeOutputAddress = new Key().GetAddress(ScriptPubKeyType.Segwit, network);
            var changeOutputAddress = new Key().GetAddress(ScriptPubKeyType.Segwit, network);
            Assert.True(coordinator.TryGetCurrentInputRegisterableRound(out round));
            Requester requester = new();
            var       nonce     = round !.NonceProvider.GetNextNonce();

            BlindedOutputWithNonceIndex blinded = new(nonce.N, requester.BlindScript(round.MixingLevels.GetBaseLevel().SignerKey.PubKey, nonce.R, activeOutputAddress.ScriptPubKey));
            uint256 blindedOutputScriptsHash    = new(Hashes.SHA256(blinded.BlindedOutput.ToBytes()));

            List <InputProofModel> inputProofModels = new();
            int numberOfInputs    = CryptoHelpers.RandomInt(1, 6);
            var receiveSatoshiSum = 0;
            for (int j = 0; j < numberOfInputs; j++)
            {
                Key key            = new();
                var receiveSatoshi = CryptoHelpers.RandomInt(1000, 100000000);
                receiveSatoshiSum += receiveSatoshi;
                if (j == numberOfInputs - 1)
                {
                    receiveSatoshi = 100000000;
                }
                var     inputAddress = key.PubKey.GetAddress(ScriptPubKeyType.Segwit, network);
                uint256 txHash       = await rpc.SendToAddressAsync(inputAddress, Money.Satoshis(receiveSatoshi));

                fundingTxCount++;
                Assert.NotNull(txHash);
                Transaction transaction = await rpc.GetRawTransactionAsync(txHash);

                var coin = transaction.Outputs.GetCoins(inputAddress.ScriptPubKey).Single();

                OutPoint input      = coin.Outpoint;
                var      inputProof = new InputProofModel {
                    Input = input, Proof = key.SignCompact(blindedOutputScriptsHash)
                };
                inputProofModels.Add(inputProof);

                GetTxOutResponse?getTxOutResponse = await rpc.GetTxOutAsync(input.Hash, (int)input.N, includeMempool : true);

                // Check if inputs are unspent.
                Assert.NotNull(getTxOutResponse);

                userInputData.Add((key, inputAddress, txHash, transaction, input));
            }

            inputRegistrationUsers.Add((requester, blinded, activeOutputAddress, changeOutputAddress, inputProofModels, userInputData));
        }

        var mempool = await rpc.GetRawMempoolAsync();

        Assert.Equal(inputRegistrationUsers.SelectMany(x => x.userInputData).Count(), mempool.Length);

        while ((await rpc.GetRawMempoolAsync()).Length != 0)
        {
            await rpc.GenerateAsync(1);
        }

        List <Task <AliceClient4> > aliceClients = new();

        foreach (var user in inputRegistrationUsers)
        {
            aliceClients.Add(AliceClientBase.CreateNewAsync(round !.RoundId, new[] { user.activeOutputAddress }, new[] { round !.MixingLevels.GetBaseLevel().SignerKey.PubKey }, new[] { user.requester }, network, user.changeOutputAddress, new[] { user.blinded }, user.inputProofModels, BackendHttpClient));