static RsaAlgorithm() { try { keyFactory_ = System.KeyFactory.getInstance("RSA"); } catch (Exception ex) { ILOG.J2CsMapping.Util.Logging.Logger.getLogger(typeof(RsaAlgorithm).FullName) .log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex); } }
public void GenerateKey() { var template = "vvvvvvvvppppxxxxxxxx-wwwwxxxxxxxxxxxxxxxx-ssssssssxxxxxxxxxxxx-xxxxxxxxxxxxcccccccccccc-xxxxxxxxxxxxxxxxrrrr"; var test = new TestData { V = "34", P = "6", W = "8", S = "AB", C = "RSd", R = "3" }; var gen = new KeyFactory(template); var gkey = gen.Generate(test); var finalkey = gkey.CreateKey(); if ((finalkey.Length - 4) != ((gkey.LicenseTemplate.Length - 4) / 4)) { throw new Exception("Keys are not the same length"); } var result = gkey.DisassembleKey("v"); if (result != "34") { throw new Exception("The first tokens are not equal"); } result = gkey.DisassembleKey("p"); if (result != "6") { throw new Exception("The second tokens are not equal"); } result = gkey.DisassembleKey("w"); if (result != "8") { throw new Exception("The third tokens are not equal"); } result = gkey.DisassembleKey("s"); if (result != "AB") { throw new Exception("The third tokens are not equal"); } result = gkey.DisassembleKey("r"); if (result != "3") { throw new Exception("The third tokens are not equal"); } }
private void CanPadECCoordBytes() { var k = KeyFactory.FromPem(Keys.ES256Key_Alt1); var ecKey = (EcJsonWebKey)k.JsonWebKey; Assert.Equal("AJz0yAAXAwEmOhTRkjXxwgedbWO6gobYM3lWszrS68E", ecKey.X); Assert.Equal("vEEs4V0egJkNyM2Q4pp001zu14VcpQ0_Ei8xOOPxKZs", ecKey.Y); k = KeyFactory.FromPem(Keys.ES256Key); ecKey = (EcJsonWebKey)k.JsonWebKey; Assert.Equal("dHVy6M_8l7UibLdFPlhnbdNv-LROnx6_FcdyFArBd_s", ecKey.X); Assert.Equal("2xBzsnlAASQN0jQYuxdWybSzEQtsxoT-z7XGIDp0k_c", ecKey.Y); }
public void AncestorQuery() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Sample: AncestorQuery DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("Task"); Query query = new Query("Task") { Filter = Filter.HasAncestor(keyFactory.CreateKey("someTask")) }; // End sample }
public void BuilderWithParameter() { HiHelloService service = new HiHelloService(); ReflectionAggregateRootFactoryBuilder builder = new ReflectionAggregateRootFactoryBuilder() .AddKey() .AddHistory() .Add <IHelloService>(service); ReflectionAggregateRootFactory <AggregateWithParameters> factory = new ReflectionAggregateRootFactory <AggregateWithParameters>(builder); AggregateWithParameters instance = factory.Create(KeyFactory.Create(typeof(AggregateWithParameters)), new List <IEvent>()); Assert.AreEqual(service, instance.Service); }
protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); StartYear = new YearModel(DateTime.Today.Year - 8); CategoryKey = GuidKey.Create(CategoryGuid, KeyFactory.Empty(typeof(Category)).Type); CategoryName = await Queries.QueryAsync(new GetCategoryName(CategoryKey)); CategoryColor = await Queries.QueryAsync(new GetCategoryColor(CategoryKey)); CurrencyFormatter = await CurrencyFormatterFactory.CreateAsync(); await LoadAsync(); }
/** * Construct LogSignatureVerifiers for each of the trusted CT logs. * * @throws InvalidKeySpecException the CT log key isn't RSA or EC, the key is probably corrupt. * @throws NoSuchAlgorithmException the crypto provider couldn't supply the hashing algorithm or * the key algorithm. This probably means you are using an ancient or bad crypto provider. */ private void buildLogSignatureVerifiers() { MessageDigest hasher = MessageDigest.GetInstance(LOG_ID_HASH_ALGORITHM); foreach (string trustedLogKey in TRUSTED_LOG_KEYS) { hasher.Reset(); byte[] keyBytes = Base64.Decode(trustedLogKey); string logId = Base64.ToBase64String(hasher.Digest(keyBytes)); KeyFactory keyFactory = KeyFactory.GetInstance(determineKeyAlgorithm(keyBytes)); var publicKey = keyFactory.GeneratePublic(new X509EncodedKeySpec(keyBytes)); verifiers.Add(logId, new LogSignatureVerifier(new LogInfo(publicKey))); } }
/// <summary> /// Load the current account key /// </summary> /// <returns> </returns> private bool LoadAccountKey() { if (System.IO.File.Exists(_settingsFolder + "\\c-acc.key")) { string pem = System.IO.File.ReadAllText(_settingsFolder + "\\c-acc.key"); var key = KeyFactory.FromPem(pem); _acme = new AcmeContext(_serviceUri, key); return(true); } else { return(false); } }
public async Task ShowAsync(object parameter) { if (parameter is CategoryCreateParameter create) { key = KeyFactory.Empty(typeof(Category)); model = new CategoryNameDescriptionModel(null, null); } else if (parameter is CategoryRenameParameter rename) { key = rename.Key; model = await queryDispatcher.QueryAsync(new GetCategoryNameDescription(key)); Name = model.Name; Description = model.Description; } ContentDialogResult result = await ShowAsync(); if ((result == ContentDialogResult.Primary || IsEnterPressed) && (Name != model.Name || Description != model.Description)) { if (key.IsEmpty) { if (String.IsNullOrEmpty(Name)) { return; } Color color = ColorConverter.Map(Colors.Black); await commandDispatcher.HandleAsync(new CreateCategory(Name, Description, color)); Name = Name; } else { if (Name != model.Name) { await commandDispatcher.HandleAsync(new RenameCategory(key, Name)); Name = Name; } if (Description != model.Description) { await commandDispatcher.HandleAsync(new ChangeCategoryDescription(key, Description)); Description = Description; } } } }
private bool IsKeyValid(string file) { var key = File.ReadAllText(file); try { KeyFactory.FromPem(key); return(true); } catch { return(false); } }
public async Task<IKey> GetAccountKey(Uri serverUri) { // env settings overwrites user settings var envKey = environment.GetVar("CERTES_ACME_ACCOUNT_KEY"); if (envKey != null) { return KeyFactory.FromDer(Convert.FromBase64String(envKey)); } var settings = await LoadUserSettings(); var serverSetting = settings.Servers?.FirstOrDefault(s => s.ServerUri == serverUri); var der = serverSetting?.Key; return der == null ? null : KeyFactory.FromDer(der); }
public void CreateProblemKey() { var userAgent = Util.GetUserAgent(); var certes = new CertesACMEProvider(Util.GetAppDataFolder() + "\\certes", userAgent); var keyFound = false; newKey = null; var attempts = 0; while (!keyFound) { var generator = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); var generatorParams = new ECKeyGenerationParameters( CustomNamedCurves.GetOid("P-256"), new SecureRandom() ); generator.Init(generatorParams); var keyPair = generator.GenerateKeyPair(); var publicKey = (ECPublicKeyParameters)keyPair.Public; var xBytes = publicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned(); var yBytes = publicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned(); if (xBytes.Length != yBytes.Length) { System.Diagnostics.Debug.WriteLine($"Problem key found in {attempts} attempts"); keyFound = true; var pem = ""; using (var sr = new StringWriter()) { var pemWriter = new PemWriter(sr); pemWriter.WriteObject(keyPair); pem = sr.ToString(); } System.Diagnostics.Debug.WriteLine($"{pem}"); newKey = KeyFactory.FromPem(pem); } attempts++; } //certes.InitProvider().Wait(); }
public override void Execute(Protocol.Clients.PosStoreClient posStoreClient, Protocol.RequestInfos.PosStorePackageInfo package) { var jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings(); jsonSerializerSettings.Converters.Add(new BarcodeConverter()); var shoppingcart = package.Read <ShoppingCart>(jsonSerializerSettings); if (shoppingcart != null) { var shoppingCartCache = new ShoppingCartCache(); string key = KeyFactory.MachineKeyFactory(shoppingcart.MachineInformation.CompanyToken, shoppingcart.MachineInformation.StoreId, shoppingcart.MachineInformation.MachineSn, shoppingcart.MachineInformation.DeviceSn); shoppingCartCache.Set(key, shoppingcart); } }
public void KindlessQuery() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Sample: KindlessQuery KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "Task"); Key lastSeenKey = keyFactory.CreateKey(100L); Query query = new Query { Filter = Filter.GreaterThan(DatastoreConstants.KeyProperty, lastSeenKey) }; // End sample }
public void KeyQuery() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Sample: KeyQuery DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("Task"); Query query = new Query("Task") { Filter = Filter.GreaterThan(DatastoreConstants.KeyProperty, keyFactory.CreateKey("someTask")) }; // End sample }
public async Task ShouldThrowIfPrivateKeyIncorrect() { // Arrange var publicKey = KeyFactory.GenerateKeyPair().PublicKey; const string testData = "Test Data"; var dataBlock = await Encryptor.Encrypt(publicKey, testData); // Act var differentPrivateKey = KeyFactory.GenerateKeyPair().PrivateKey; var exception = await Should.ThrowAsync <InvalidOperationException>(() => Decryptor.Decrypt <string>(differentPrivateKey, dataBlock)); // Assert exception.Message.ShouldBe("There was a problem decrypting the data block. Potential data corruption or packet tampering has occurred."); }
public override Entity ToEntity(KeyFactory factory) => new Entity() { Key = GetKey(factory), ["name"] = Name, ["description"] = Description, ["demo_link"] = DemoLink, ["hidden_sections"] = (Entity[])(HiddenSections ?? Enumerable.Empty <Section>()).Select(section => section.ToEntity(null)).ToArray(), ["marketing_url"] = MarketingUrl, ["pictures"] = (Value[])(Pictures ?? Enumerable.Empty <string>()).Select(picture => ToPicValue(picture)).ToArray(), ["season"] = Season, ["sort_order"] = SortOrder, ["technologies"] = Technologies, ["year"] = Year };
internal DatastoreCounter(DatastoreDb datastore, IOptions <DatastoreCounterOptions> options, ILogger <DatastoreCounter> logger, IManagedTracer tracer) { _datastore = datastore; _options = options; _logger = logger; _tracer = tracer; var opts = options.Value; _keyFactory = new KeyFactory(datastore.ProjectId, datastore.NamespaceId, opts.Kind); }
public async Task <object> Execute(ArgumentSyntax syntax) { var(serverUri, key) = await ReadAccountKey(syntax, true, false); var orderUri = syntax.GetParameter <Uri>(OrderIdParam, true); var distinguishedName = syntax.GetOption <string>(DnOption); var outPath = syntax.GetOption <string>(OutOption); var providedKey = await syntax.ReadKey(PrivateKeyOption, "CERTES_CERT_KEY", File, environment); var privKey = providedKey ?? KeyFactory.NewKey(KeyAlgorithm.ES256); logger.Debug("Finalizing order from '{0}'.", serverUri); var acme = ContextFactory.Invoke(serverUri, key); var orderCtx = acme.Order(orderUri); var csr = await orderCtx.CreateCsr(privKey); if (!string.IsNullOrWhiteSpace(distinguishedName)) { csr.AddName(distinguishedName); } var order = await orderCtx.Finalize(csr.Generate()); // output private key only if it is generated and not being saved if (string.IsNullOrWhiteSpace(outPath) && providedKey == null) { return(new { location = orderCtx.Location, privateKey = privKey.ToDer(), resource = order, }); } else { if (providedKey == null) { await File.WriteAllText(outPath, privKey.ToPem()); } return(new { location = orderCtx.Location, resource = order, }); } }
/// <inheritdoc/> public ICryptographicKey ImportKeyPair(byte[] keyBlob, CryptographicPrivateKeyBlobType blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo) { Requires.NotNull(keyBlob, nameof(keyBlob)); RSAParameters parameters = KeyFormatter.GetFormatter(blobType) .Read(keyBlob) .ComputeFullPrivateKeyData(); IPrivateKey? privateKey = null; IPublicKey? publicKey = null; BigInteger? modulus = null, d = null, publicExponent = null; RSAPrivateKeySpec?privateKeySpec = null; RSAPublicKeySpec? publicKeySpec = null; try { #pragma warning disable CA2000 // Dispose objects before losing scope modulus = new BigInteger(1, parameters.Modulus); d = new BigInteger(1, parameters.D); privateKeySpec = new RSAPrivateKeySpec(modulus, d); var factory = KeyFactory.GetInstance("RSA"); if (factory is null) { throw new InvalidOperationException(Strings.UnsupportedAlgorithm); } privateKey = factory.GeneratePrivate(privateKeySpec) !; var privateRsaKey = privateKey.JavaCast <IRSAPrivateKey>() !; publicExponent = new BigInteger(1, parameters.Exponent); publicKeySpec = new RSAPublicKeySpec(privateRsaKey.Modulus, publicExponent); publicKey = factory.GeneratePublic(publicKeySpec) !; return(new RsaCryptographicKey(publicKey, privateKey, parameters, this.algorithm)); #pragma warning restore CA2000 // Dispose objects before losing scope } catch { publicExponent?.Dispose(); publicKeySpec?.Dispose(); privateKeySpec?.Dispose(); modulus?.Dispose(); d?.Dispose(); privateKey?.Dispose(); publicKey?.Dispose(); throw; } }
/// <summary> /// Generates an RSA keypair of the provided length using Java libraries /// and configures an RSACryptoServiceProvider with them for ease of use with .NET systems. /// This is much more performant than generating keys directly from an RSACryptoServiceProvider /// when running on an Android system. /// </summary> /// <returns></returns> public static RSACryptoServiceProvider GenerateRsaKeyPair(int keySize = 2048) { //Generate an RSA key-pair of the provided size. This approach is as fast as anything I have found for Android devices. //On a Nexus 6P, this code consistently creates a 2048-bit key-pair in less than 10 seconds while standard .NET libraries //and BouncyCastle all took anywhere from 10 - 30 seconds. var keyPairGenerator = KeyPairGenerator.GetInstance("RSA"); keyPairGenerator.Initialize(keySize); var keys = keyPairGenerator.GenerateKeyPair(); KeyFactory kf = KeyFactory.GetInstance("RSA"); var spec = (RSAPrivateCrtKeySpec)kf.GetKeySpec(keys.Private, Class.FromType(typeof(RSAPrivateCrtKeySpec))); //Create an Xml node for the provided element name using the provided number in Base64-string format as its value string FormatElement(string name, BigInteger value) { var bytes = value.ToByteArray(); int length = bytes.Length; if (length % 2 != 0 && bytes[0] == 0) //BigInteger is signed, so remove the extra byte { bytes = Arrays.CopyOfRange(bytes, 1, length); } var content = Base64.EncodeToString(bytes, Base64Flags.Default); return($"<{name}>{content}</{name}>"); } //Create an XML version of the private key var stb = new System.Text.StringBuilder(); stb.Append("<RSAKeyValue>"); stb.Append(FormatElement("Modulus", spec.Modulus)); stb.Append(FormatElement("Exponent", spec.PublicExponent)); stb.Append(FormatElement("P", spec.PrimeP)); stb.Append(FormatElement("Q", spec.PrimeQ)); stb.Append(FormatElement("DP", spec.PrimeExponentP)); stb.Append(FormatElement("DQ", spec.PrimeExponentQ)); stb.Append(FormatElement("InverseQ", spec.CrtCoefficient)); stb.Append(FormatElement("D", spec.PrivateExponent)); stb.Append("</RSAKeyValue>"); var privateKeyXml = stb.ToString(); //Configure an RSACryptoServiceProvider using the generated key XML var rsaCryptoServiceProvider = new RSACryptoServiceProvider(keySize); rsaCryptoServiceProvider.FromXmlString(privateKeyXml); return(rsaCryptoServiceProvider); }
public static async Task InitAsync(ILogger logger, CertificateMode certificateMode) { _logger = logger; _logger.LogInformation($"Initializing LetsEncrypt bits"); //ACCOUNT _logger.LogInformation(" Creating or Retrieving account"); var accountKeyFileName = Constants.AccountKeyFileName; if (Settings.UseStaging) { accountKeyFileName = "staging" + accountKeyFileName; } IAccountContext account; if (await AzureHelper.CheckIfFileExistsBlobStorageAsync(accountKeyFileName)) { _logger.LogInformation(" Retrieving existing account"); // Load the saved account key var pemKey = await AzureHelper.ReadFileFromBlobStorageToStringAsync(accountKeyFileName); var accountKey = KeyFactory.FromPem(pemKey); _acme = new AcmeContext(certificateMode == CertificateMode.Production ? WellKnownServers.LetsEncryptV2 : WellKnownServers.LetsEncryptStagingV2, accountKey); account = await _acme.Account(); } else { _logger.LogInformation(" Creating new account"); _acme = new AcmeContext(certificateMode == CertificateMode.Production ? WellKnownServers.LetsEncryptV2 : WellKnownServers.LetsEncryptStagingV2); account = await _acme.NewAccount(Settings.CertificateOwnerEmail, true); // Save the account key for later use var pemKey = _acme.AccountKey.ToPem(); await AzureHelper.SaveFileToBlobStorageAsync(accountKeyFileName, pemKey); } _logger.LogInformation($" Account set - { account.Location }"); _logger.LogInformation(Environment.NewLine); _logger.LogInformation("Loading Certificate Info for Issuance"); _certinfo = await BuildCertificaeInfoAsync(); _logger.LogInformation(" Certificate Info loaded"); _logger.LogInformation(Environment.NewLine); }
private void AddSampleBooks() { var client = DatastoreClient.Create(); var keyFactory = new KeyFactory(ProjectId, NamespaceId, BookKind); var entity = new Entity { Key = keyFactory.CreateKey("pride_and_prejudice"), ["title"] = "Pride and Prejudice", ["publication_date"] = new DateTime(1813, 1, 28, 0, 0, 0, DateTimeKind.Utc), ["author"] = "Jane Austen" }; var response = client.Commit(ProjectId, CommitRequest.Types.Mode.NonTransactional, new[] { entity.ToInsert() }); _prideAndPrejudiceKey = response.MutationResults[0].Key; }
private async Task <byte[]> CreateCertificate(IOrderContext order) { IKey privateKey = KeyFactory.NewKey(KeyAlgorithm.RS256); CertificateChain certificateChain = await order.Generate(new CsrInfo { CommonName = Hostname }, privateKey); PfxBuilder pfxBuilder = certificateChain.ToPfx(privateKey); byte[] pfx = pfxBuilder.Build(Hostname, string.Empty); return(pfx); }
public async Task <ChadderError> CreateNewKey() { var keypair = await KeyFactory.GenerateBook(); var pbk = await keypair.GetPublicBook(); var response = await AuthorizedRequest <BasicResponse>(Connection.AccountHub, "CreateNewKey", pbk.Serialize()); if (response.Error == ChadderError.OK) { db.LocalUser.PrivateKeyBookData = keypair.Serialize(); await sqlDB.UpdateAsync(db.LocalUser); } return(response.Error); }
public async Task AllocateIdsAsync() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: AllocateIdsAsync(*) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("message"); IReadOnlyList <Key> keys = await db.AllocateIdsAsync(keyFactory.CreateIncompleteKey(), keyFactory.CreateIncompleteKey()); // End snippet Assert.Equal(2, keys.Count); Assert.NotEqual(keys[0], keys[1]); }
public void AncestorPaths() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Sample: AncestorPaths KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "User"); Key taskKey = keyFactory.CreateKey("alice").WithElement("Task", "sampleTask"); Key multiLevelKey = keyFactory .CreateKey("alice") .WithElement("TaskList", "default") .WithElement("Task", "sampleTask"); // End sample }
// Used by TransactionReadAndWrite. Could promote to the fixture. private Key CreateAccount(string name, long balance) { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory factory = db.CreateKeyFactory("Account"); Entity entity = new Entity { Key = factory.CreateIncompleteKey(), ["name"] = name, ["balance"] = balance }; return(db.Insert(entity)); }
private async Task <IKey> GetOrCreateKey(Uri acmeDirectory, string host) { string secretName = $"privatekey{host}--{acmeDirectory.Host}"; var key = await this.certificateStore.GetSecret(secretName); if (string.IsNullOrEmpty(key)) { var privatekey = KeyFactory.NewKey(KeyAlgorithm.RS256); await this.certificateStore.SaveSecret(secretName, privatekey.ToPem()); return(privatekey); } return(KeyFactory.FromPem(key)); }
public void InsertBD(string InsertTweet, string[] tweetScore, DateTime fecha, Tweetinvi.Models.IPlace lugar) { #region db access ///////////////////////////////////////////// db access /////////////////////////////////// string credential_path = @"C:\Users\Javier\Downloads\IMAPBD-Misc\Sentiment analisis\imapbd\IMAPBD\IMAPBD\OAuth\IMAPBD - Load-db-access.json"; System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path); string projectID = "imapbd-load"; DatastoreDb db = DatastoreDb.Create(projectID, ""); string kind = "Lugar_Tweet"; KeyFactory keyFactory = db.CreateKeyFactory(kind); Key key = keyFactory.CreateIncompleteKey(); Entity task = new Entity(); task.Key = key; task.Properties.Add("tweet", InsertTweet); task.Properties.Add("tedioso", Convert.ToDouble(tweetScore[0])); task.Properties.Add("malo", Convert.ToDouble(tweetScore[1])); task.Properties.Add("bueno", Convert.ToDouble(tweetScore[2])); task.Properties.Add("regular", Convert.ToDouble(tweetScore[3])); task.Properties.Add("dia", fecha.DayOfWeek.ToString()); task.Properties.Add("mes", fecha.Month); task.Properties.Add("anio", fecha.Year); if (string.IsNullOrEmpty(lugar.Name)) { task.Properties.Add("lugar", ""); } else { task.Properties.Add("lugar", lugar.Name); } task.Properties.Add("lugar", lugar.Name); task.Properties.Add("pais", lugar.Country); using (DatastoreTransaction transaction = db.BeginTransaction()) { transaction.Upsert(task); transaction.Commit(); } ///////////////////////////////////////////// db access /////////////////////////////////// #endregion }
public Entity Materialize(int entityIndex, int typeIdIndex, TypeInfo type, Pair <int>[] entityColumns, Tuple tuple) { var result = entities[entityIndex]; if (result != null) { return(result); } TypeReferenceAccuracy accuracy; int typeId = EntityDataReader.ExtractTypeId(type, typeIdRegistry, tuple, typeIdIndex, out accuracy); if (typeId == TypeInfo.NoTypeId) { return(null); } bool canCache = accuracy == TypeReferenceAccuracy.ExactType; var materializationInfo = MaterializationContext.GetTypeMapping(entityIndex, type, typeId, entityColumns); Key key; var keyIndexes = materializationInfo.KeyIndexes; if (!KeyFactory.IsValidKeyTuple(tuple, keyIndexes)) { return(null); } if (keyIndexes.Length <= WellKnown.MaxGenericKeyLength) { key = KeyFactory.Materialize(Session.Domain, Session.StorageNodeId, materializationInfo.Type, tuple, accuracy, canCache, keyIndexes); } else { var keyTuple = materializationInfo.KeyTransform.Apply(TupleTransformType.TransformedTuple, tuple); key = KeyFactory.Materialize(Session.Domain, Session.StorageNodeId, materializationInfo.Type, keyTuple, accuracy, canCache, null); } if (accuracy == TypeReferenceAccuracy.ExactType) { var entityTuple = materializationInfo.Transform.Apply(TupleTransformType.Tuple, tuple); var entityState = Session.Handler.UpdateState(key, entityTuple); result = entityState.Entity; } else { result = Session.Query.SingleOrDefault(key); } entities[entityIndex] = result; return(result); }
public ComponentAccessKey ProvideComponentAccessKey(IKeyConsumer keyConsumer) { KeyFactory keyFactory = new KeyFactory(); return keyFactory.GenerateComponentAccessKey(SecurityIds.Password, SecurityIds.Salt, keyConsumer); }
/*============================================================================*/ /* Constructor */ /*============================================================================*/ /// <summary> /// Creates a command trigger map /// </summary> /// <param name="keyFactory">Factory function to creates keys</param> /// <param name="triggerFactory">Factory function to create triggers</param> public CommandTriggerMap (KeyFactory keyFactory, TriggerFactory triggerFactory) { _keyFactory = keyFactory; _triggerFactory = triggerFactory; }