public async Task Invoke(HttpContext httpContext, IKeyFactory keyFactory, ILogger <UserIdMiddleWare> logger) { Guid userId = default; bool generateNew = true; if (httpContext.Request.Cookies.TryGetValue("UserSession", out string UserSession)) { generateNew = !TryDecryptUserId(keyFactory, out userId, UserSession, logger); } if (generateNew) { userId = Guid.NewGuid(); } httpContext.Items["GameUserId"] = userId; string encryptedSession = EncryptUserId(keyFactory, userId); httpContext.Response.Cookies.Append("UserSession", encryptedSession, new CookieOptions { Expires = DateTimeOffset.UtcNow.AddMinutes(5) }); await _next(httpContext); }
public IKey SerializeToKey(object instance, string inRootName, ILogPrinter inLogger) { IKey root = IKeyFactory.CreateKey(inRootName); Serialize(instance, root, inLogger); return(root); }
private static bool TryDecryptUserId(IKeyFactory keyFactory, out Guid userId, string UserSession, ILogger <UserIdMiddleWare> logger) { try { using Aes aes = Aes.Create(); aes.Key = keyFactory.Create(_keyname); aes.IV = keyFactory.Create(_ivname); ICryptoTransform decryptor = aes.CreateDecryptor(); using MemoryStream ms = new MemoryStream(Convert.FromBase64String(UserSession)); using CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); using StreamReader sr = new StreamReader(cs); string decryptedUserSession = sr.ReadToEnd(); return(Guid.TryParse(decryptedUserSession, out userId)); } catch (Exception e) { logger.LogWarning(e, "Unable to decrypt the user session cookie."); userId = default; return(false); } }
public void TestMethod3() { ResetTestState(); Console.WriteLine(MethodBase.GetCurrentMethod().Name); var v1 = new CTestClassCollectionsAtom(); v1.Init1(); Console.WriteLine("Key1:"); IKey key = IKeyFactory.CreateKey("RootKey"); _serializer.Serialize(v1, key, this); string text = key.SaveToString(); Console.WriteLine(text); int mem_sz = key.GetMemorySize(); byte[] array = new byte[mem_sz]; key.BinarySerialize(array, 0); Console.WriteLine($"Array Size: {array.Length} bytes"); Console.WriteLine("Key2:"); IKey key2 = IKeyFactory.CreateKey(array, 0); text = key2.SaveToString(); Console.WriteLine(text); var v2 = _serializer.Deserialize <CTestClassCollectionsAtom>(key2, this); CheckInternalErrors(); Assert.AreEqual(v1, v2); }
public KeyOperations([NotNull] IKeyFactory keyFactory) { if (keyFactory == null) { throw new ArgumentNullException(nameof(keyFactory)); } this.keyFactory = keyFactory; }
public RedirectableStore( IStorageFactory storageFactory, IKeyFactory keyFactory, IMapper mapper) { _storageFactory = storageFactory; _keyFactory = keyFactory; _mapper = mapper; }
public CloudDatastoreStorageFactory( IEnvConfigurationStore configurationStore, IEntityAnalyzer entityAnalyzer, IKeyFactory keyFactory) { _configurationStore = configurationStore; _entityAnalyzer = entityAnalyzer; _keyFactory = keyFactory; }
//public string SerializeToCascade(object instance, string inRootName, ILogPrinter inLogger) public string SerializeToCascade(object instance, ILogPrinter inLogger) { //IKey key = SerializeToKey(instance, string.Empty, inLogger); IKey key = IKeyFactory.CreateArrayKey(null); Serialize(instance, key, inLogger); string text = key.SaveToString(); return(text); }
public CloudDatastoreStorage( IEnvConfigurationStore configurationStore, IEntityAnalyzer entityAnalyzer, IKeyFactory keyFactory) { _configurationStore = configurationStore; _entityAnalyzer = entityAnalyzer; _serializer = new CloudDatastoreEntitySerializer <T>(entityAnalyzer); _keyFactory = keyFactory; }
public bool EnsureKey(IKeyFactory keyFactory = null) { if (_fieldList.All(f => f.FieldType != FieldType.Key)) { AddHashKey(keyFactory); return(true); } return(false); }
public MultiKeyOperation(IKeyFactory keyFactory, Func <IKeyId, CancellationToken, Task <T> > operation, Func <T, bool> resultValidator, TimeSpan?timeBetweenKeyScansWithKey = null, TimeSpan?timeBetweenKeyScansNoKeyDetected = null) { this.keyFactory = keyFactory; this.operation = operation; this.resultValidator = resultValidator; this.timeBetweenKeyScansWithKey = timeBetweenKeyScansWithKey ?? defaultTimeBetweenKeyScansWithKey; this.timeBetweenKeyScansNoKeyDetected = timeBetweenKeyScansNoKeyDetected ?? defaultTimeBetweenKeyScansNoKeyDetected; }
public bool AddFactory(IKeyFactory factory, out string errorMessage) { if (_factories.Any(x => x.GetType() == factory.GetType())) { errorMessage = string.Format("Factory of type <{0}> already exists.", factory.GetType().Name); return(false); } _factories.Add(factory); errorMessage = string.Empty; return(true); }
public FieldMapperSet(string tableName, bool inlineFields, IEnumerable <IFieldMapper> mappers, Func <string, string> referenceNameFormatter = null, IKeyFactory keyFactory = null, string fieldNamePrefix = null) : base(fieldNamePrefix ?? "", tableName, mappers) { InlineFields = inlineFields; ReferenceNameFormatter = referenceNameFormatter; HashKeyFactory = keyFactory ?? KeyFactory.Default; }
public FieldMapperSet(string tableName, bool inlineFields, IEnumerable<IFieldMapper> mappers, Func<string, string> referenceNameFormatter = null, IKeyFactory keyFactory = null, string fieldNamePrefix = null) : base(fieldNamePrefix ?? "", tableName, mappers) { InlineFields = inlineFields; ReferenceNameFormatter = referenceNameFormatter; HashKeyFactory = keyFactory ?? KeyFactory.Default; }
public void AddHashKey(IKeyFactory keyFactory = null) { if (HashKey.HasValue) { throw new InvalidOperationException("A hash key has already been added"); } KeyFactory = keyFactory ?? Keys.KeyFactory.Default; _fieldList.Add(_hashKeyField = KeyFactory.GetKeyField(Schema)); _hashKeyField.Hide = true; UpdateSchema(); }
private static string EncryptUserId(IKeyFactory keyFactory, Guid userId) { using Aes aes = Aes.Create(); aes.Key = keyFactory.Create(_keyname); aes.IV = keyFactory.Create(_ivname); ICryptoTransform encryptor = aes.CreateEncryptor(); using MemoryStream ms = new MemoryStream(); using CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); using StreamWriter sw = new StreamWriter(cs); sw.Write(userId.ToString()); sw.Flush(); cs.FlushFinalBlock(); return(Convert.ToBase64String(ms.ToArray())); }
public void TestMethod1() { ResetTestState(); Console.WriteLine(MethodBase.GetCurrentMethod().Name); CTestBase v1 = new CTestBase(); v1.Init1(); Console.WriteLine("Key1:"); IKey key = IKeyFactory.CreateKey("RootKey"); _serializer.Serialize(v1, key, this); string text = key.SaveToString(); //BaseInt: 7 //BaseNullable: 9 //BaseFloat: 101.909 //BaseString: str2 //BaseEnum: TestEnumValue3 Console.WriteLine(text); //string input = "sun"; //byte[] array = Encoding.UTF8.GetBytes(input); int mem_sz = key.GetMemorySize(); byte[] array = new byte[mem_sz]; key.BinarySerialize(array, 0); Console.WriteLine($"Array Size: {array.Length} bytes"); Console.WriteLine("Key2:"); IKey key2 = IKeyFactory.CreateKey(array, 0); text = key2.SaveToString(); Console.WriteLine(text); var v2 = _serializer.Deserialize <CTestBase>(key2, this); CheckInternalErrors(); Assert.AreEqual(v1, v2); }
public ObjectContainerManager(SerializationInfo info, StreamingContext context) { _objectContainerStore = (ObjectContainerStore)info.GetValue("objectContainerStore", typeof(ObjectContainerStore)); _objectContainerFactory = (ObjectContainerFactory)info.GetValue("objectContainerFactory", typeof(ObjectContainerFactory)); _keyFactory = (KeyGenerator)info.GetValue("keyfactory", typeof(KeyGenerator)); }
public ObjectContainerManager(IObjectContainerStore objectContainerStore, IObjectContainerFactory objectContainerFactory, IKeyFactory keyFactory) { _objectContainerStore = objectContainerStore; _objectContainerFactory = objectContainerFactory; _keyFactory = keyFactory; }
public U2FClient([NotNull] ISender sender, [NotNull] IKeyFactory keyFactory) : this(sender, null, null, new KeyOperations(keyFactory), BouncyCastleClientCrypto.Instance) { }
public ComponentDispatcher(IKeyFactory <ComponentKeyType, IKeyComponentToCreate> factory) { _factory = factory; }
public U2FClient([NotNull] ISender sender, [CanBeNull] CheckAppIdOrOrigin originChecker, [CanBeNull] CheckAppIdOrOrigin appIdChecker, [NotNull] IKeyFactory keyFactory, [NotNull] IClientCrypto crypto) : this(sender, originChecker, appIdChecker, new KeyOperations(keyFactory), crypto) { }
public MicroUrlKeyGenerator(IStorageFactory storageFactory, IKeyFactory keyFactory, IKeyValidationService keyValidationService) { _storageFactory = storageFactory; _keyFactory = keyFactory; _keyValidationService = keyValidationService; }
public KeyFactoryProcess(IKeyFactory <ProcessKey, IProcess> factory) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); }
object DeserializeClass(object inInstance, IKey inKey, Type type, int inStructDeep, ILogPrinter inLogger) { IKey type_key = inKey.GetChild("RealObjectType"); if (type_key != null) { string type_name = type_key.GetValueAsString(0); string assembly_name = type_key.GetValueAsString(1); try { Assembly assembly = Assembly.Load(assembly_name); Type obj_type = assembly.GetType(type_name, true); if (obj_type != null) { type = obj_type; } } catch (Exception ex) { LogError(inLogger, string.Format("Cant take type from RealObjectType {0}. Exception: {1}", type_name, ex.Message)); } } object instance = inInstance; if (instance == null) { instance = _reflectionProvider.Instantiate(type, inLogger); } if (instance != null) { //MethodInfo mi = type.GetMethod("DeserializationFromCscd", new Type[] { typeof(CascadeParser.IKey), typeof(CascadeParser.ILogPrinter) }); MethodInfo mi = type.GetMethod("DeserializationFromCscd", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (mi != null) { if (inKey != null && !inKey.IsEmpty) { IKey key = inKey; mi.Invoke(instance, new object[] { key, inLogger }); } } else { MemberInfo[] member_infos = _reflectionProvider.GetSerializableMembers(type); foreach (MemberInfo memberInfo in member_infos) { SCustomMemberParams member_params = GetMemberParams(memberInfo); Type memberType = memberInfo.GetMemberType(); IKey sub_key = inKey.GetChild(member_params.ChangedName); if (sub_key == null) { sub_key = inKey.GetChild(member_params.Name); } if (sub_key != null) { object readValue; if (member_params.Converter != null) { readValue = member_params.Converter.ReadKey(sub_key, inLogger); } else { readValue = DeserializeInternal(null, sub_key, memberType, 0, inStructDeep + 1, inLogger); } // This dirty check is naive and doesn't provide performance benefits //if (memberType.IsClass && readValue != currentValue && (readValue == null || !readValue.Equals(currentValue))) _reflectionProvider.SetValue(memberInfo, instance, readValue, inLogger); } else if (member_params.DefaultValue != null) { _reflectionProvider.SetValue(memberInfo, instance, member_params.DefaultValue, inLogger); } else if (memberType.IsClass || memberType.IsStruct()) { object already_exists_member = _reflectionProvider.GetValue(memberInfo, instance); if (already_exists_member != null) { //for set default values inside this object already_exists_member = DeserializeInternal(already_exists_member, IKeyFactory.CreateKey(string.Empty), memberType, 0, inStructDeep + 1, inLogger); if (already_exists_member != null) { _reflectionProvider.SetValue(memberInfo, instance, already_exists_member, inLogger); } } } } } mi = type.GetMethod("OnDeserializedMethod", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (mi != null) { var context = new StreamingContext(StreamingContextStates.Other); mi.Invoke(instance, new object[] { context }); } } return(instance); }
/****************************************************************************/ public RotatingEncryptorFactory(IEncryptorFactory encryptorFactory, ICache cache, IKeyFactory keyFactory) { _encryptorFactory = encryptorFactory; _cache = cache; _keyFactory = keyFactory; }
public bool EnsureKey(IKeyFactory keyFactory = null) { if (_fieldList.All(f => f.FieldType != FieldType.Key)) { AddHashKey(keyFactory); return true; } return false; }
public void AddHashKey(IKeyFactory keyFactory = null) { if( HashKey.HasValue) throw new InvalidOperationException("A hash key has already been added"); KeyFactory = keyFactory ?? Keys.KeyFactory.Default; _fieldList.Add(_hashKeyField = KeyFactory.GetKeyField(Schema)); _hashKeyField.Hide = true; UpdateSchema(); }
public EntityAnalyzer(IKeyFactory keyFactory) =>
public AttributeComponentDispatcher(IKeyFactory <string, IAttributeComponentToCreate> factory) { _factory = factory; }
public RateContext(string @namespace, Granularity[] granularities) { this.Namespace = @namespace; this.KeyFactory = new DefaultKeyFactory(this.Namespace); this.Granularities = granularities != null && granularities.Length == 0 ? new DefaultGranularityProvider().GetGranularities() : granularities; }
public KeyRepository(IDataContext context, IKeyFactory keyFactory) { _context = context; _keyFactory = keyFactory; }