public SendableObject(SmartFox conn, bool encrypt) { provider = EncryptionProvider.GetInstance(); sendEncrypted = encrypt; connection = conn; data = new SFSObject(); }
public PublicKeyMessage(SmartFox conn, EncryptionProvider provider) : base(conn, false) { packetName = "publickey"; data.PutSFSObject("key", new ClientPublicKey().ToSFSObject()); }
public static EncryptionProvider GetInstance() { if(provider == null) { provider = new EncryptionProvider(); } return provider; }
protected void Awake() { handlers = new Dictionary<string, IMessageHandler>(); Application.runInBackground = true; if (SmartFoxConnection.IsInitialized) { smartFox = SmartFoxConnection.Connection; } else { smartFox = new SmartFox(debug); } // Create encryption provider provider = EncryptionProvider.GetInstance(); smartFox.AddEventListener(SFSEvent.EXTENSION_RESPONSE, OnExtensionResponse); }
/// <summary> /// Initializes a new instance of the <see cref="MessagePublisher{T}"/> class. /// </summary> /// <param name="container">The componentry container.</param> /// <param name="serializer">The message serializer.</param> /// <param name="compressor">The message compressor.</param> /// <param name="encryption">The encryption configuration.</param> /// <param name="serviceName">The service name.</param> /// <param name="networkAddress">The publishers network address.</param> protected MessagePublisher( IComponentryContainer container, ISerializer <T> serializer, ICompressor compressor, EncryptionSettings encryption, Label serviceName, ZmqNetworkAddress networkAddress) : base(container) { this.serializer = serializer; this.compressor = compressor; this.socket = new PublisherSocket { Options = { Identity = Encoding.UTF8.GetBytes($"{serviceName.Value}-{this.Name.Value}"), Linger = TimeSpan.FromSeconds(1), }, }; this.networkAddress = networkAddress; if (encryption.UseEncryption) { EncryptionProvider.SetupSocket(encryption, this.socket); this.Logger.LogInformation(LogId.Network, $"{encryption.Algorithm} encryption setup for {this.networkAddress}"); } else { this.Logger.LogWarning(LogId.Network, $"No encryption setup for {this.networkAddress}"); } this.SentCount = 0; this.RegisterHandler <IEnvelope>(this.OnEnvelope); }
public bool ChangeMyPassword(LoginToken <AirlineCompany> token, string oldPassword, string newPassword, out bool isPasswordWrong) { bool isChanged = false; if (CheckToken(token)) { var utility_user = _utility_Class_UserDAO.GetUserByIdentifier(token.ActualUser); string utility_user_PASSWORD = string.Empty; if (utility_user.PASSWORD.Length > 50) { utility_user_PASSWORD = EncryptionProvider.Decryprt(utility_user.PASSWORD); } else { utility_user_PASSWORD = utility_user.PASSWORD; } if (utility_user_PASSWORD.Equals(oldPassword)) { _airlineDAO.Update(token.ActualUser, utility_user.USER_NAME, newPassword); } else { isPasswordWrong = true; //throw new WrongPasswordException(oldPassword); } var utility_userForChecking = _utility_Class_UserDAO.GetUserByIdentifier(token.ActualUser); if (utility_userForChecking.PASSWORD.Equals(newPassword)) { isChanged = true; } } isPasswordWrong = false; return(isChanged); }
public void EncryptionProviderUniqueIVTest() { var stringToEncrypt = "Hello World"; IEncryptionProvider encryptionProvider = new EncryptionProvider(); var encryptionKeys = encryptionProvider.GenerateSecretKeys(); var recoveryKey = encryptionProvider.EncodeSecretKeysToBase64(encryptionKeys); encryptionProvider.SetSecretKeys(encryptionKeys); var encryptedString = encryptionProvider.EncryptString(stringToEncrypt); var encryptedString2 = encryptionProvider.EncryptString(stringToEncrypt); Assert.AreNotEqual(encryptedString, encryptedString2); Assert.AreNotEqual(stringToEncrypt, encryptedString); encryptionProvider = new EncryptionProvider(); encryptionKeys = encryptionProvider.DecodeSecretKeysFromBase64(recoveryKey); encryptionProvider.SetSecretKeys(encryptionKeys); var decryptedString = encryptionProvider.DecryptString(encryptedString); Assert.AreEqual(stringToEncrypt, decryptedString); }
//private async Task<XDocument> LoadAsync(string path) //{ // StorageFolder sf = await ApplicationData.Current.LocalFolder.GetFolderAsync(@"data\"); // StorageFile file = await sf.GetFileAsync(Path.GetFileName(path)); // IBuffer ibuf = null; // byte[] b; // bool excCaught = false; // try // { // using (IRandomAccessStream ras = await file.OpenReadAsync()) // { // b = new byte[ras.Size]; // ibuf = await ras.ReadAsync(CryptographicBuffer.CreateFromByteArray(b), (uint)ras.Size, InputStreamOptions.None); // ras.Dispose(); // } // } // catch (System.UnauthorizedAccessException ex) // { // excCaught = true; // } // if (excCaught) // { // using (IRandomAccessStream ras = await file.OpenReadAsync()) // { // b = new byte[ras.Size]; // ibuf = await ras.ReadAsync(CryptographicBuffer.CreateFromByteArray(b), (uint)ras.Size, InputStreamOptions.None); // ras.Dispose(); // } // } // CryptographicBuffer.CopyToByteArray(ibuf, out b); // char[] ch = System.Text.Encoding.UTF8.GetChars(b); // string s = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, ibuf); // s = EncryptionProvider.Decrypt(s, EncryptionProvider.PublicKey); // StringReader sreader = new StringReader(s); // while (sreader.Peek() == 65279) // { // sreader.Read(); // } // XDocument xdoc = XDocument.Load(sreader, LoadOptions.None); // return xdoc; //} private async Task <XDocument> LoadAsync(string path) { StorageFolder sf = await ApplicationData.Current.LocalFolder.GetFolderAsync(@"data\"); StorageFile file = await sf.GetFileAsync(Path.GetFileName(path)); IBuffer ibuf = null; byte[] b; using (IRandomAccessStream ras = await file.OpenReadAsync()) { using (IInputStream inputStream = ras.GetInputStreamAt(0)) { ulong size = ras.Size; DataReader dataReader = new DataReader(inputStream); await dataReader.LoadAsync((uint)size); ibuf = dataReader.ReadBuffer((uint)size); inputStream.Dispose(); } ras.Dispose(); } CryptographicBuffer.CopyToByteArray(ibuf, out b); // char[] ch = System.Text.Encoding.UTF8.GetChars(b); // string s = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, ibuf); string s = EncryptionProvider.DecryptToString(ibuf); StringReader sreader = new StringReader(s); while (sreader.Peek() == 65279) { sreader.Read(); } XDocument xdoc = XDocument.Load(sreader, LoadOptions.None); return(xdoc); }
public static string Decrypt(string input) { string retVal = default(string); EncryptionProvider provider = GetEncryptionProvider(input); string cipherData = GetEncryptedText(input); switch (provider) { case EncryptionProvider.DPAPI: { retVal = CipherEngine.Decrypt(cipherData, provider, ""); break; } case EncryptionProvider.RSA: { string keyContainerName = GetRsaKeyContainerName(input); retVal = CipherEngine.Decrypt(cipherData, provider, keyContainerName); break; } } return(retVal); }
private bool NegotiateSessionKeys(Stream netStream, out EncryptionProvider decryptor, out EncryptionProvider encryptor, RSAHelper pubRSA, RSAHelper privRSA) { StreamReader reader = new StreamReader(netStream); StreamWriter writer = new StreamWriter(netStream); encryptor = new EncryptionProvider(); try { Packet packet = WriteEncryptor(pubRSA, encryptor); byte[] serializedPacket = ToySerializer.Serialize(packet); string sendData = pubRSA.EncryptToBase64String(serializedPacket); writer.WriteLine(sendData); // Writing the packet as a Base64 encoded string to the network stream in the current instance writer.Flush(); string read = reader.ReadLine(); // Getting response packet = ToySerializer.Deserialize <Packet>(privRSA.DecryptBase64String(read)); decryptor = GetDecryptor(privRSA, packet); } catch { decryptor = null; return(false); } return(true); }
private bool VerifySessionKeys(Stream netStream, EncryptionProvider encryptor, EncryptionProvider decryptor) { StreamReader reader = new StreamReader(netStream); StreamWriter writer = new StreamWriter(netStream); Packet rec = new Packet(); rec.Data = new byte[1]; rec.TypeID = (int)PacketType.Handshake; rec.ChannelID = CryptoCommon.GetPrngInt(); // Adding an element of randomness to our sent data rec.DestinationUserID = CryptoCommon.GetPrngInt(); // Adding an element of randomness to our sent data WriteLine(writer, rec, encryptor); int size; rec = ReadLine(reader, decryptor, out size); if (rec == null) { throw new Exception(string.Format("Unable to complete handshake, expected to read an encrypted packet from the input stream, got " + rec ?? "[nothing]")); } if (rec.TypeID != (int)PacketType.Handshake) { throw new Exception(string.Format("Unable to complete handshake, Expected packet with TypeID {0}", PacketType.Handshake)); } else { return(true); } }
public void WriteFinalHeader(EncryptionProvider encryption) { if (mEncoder != null) mEncoder.Flush(); var files = mFileSets.SelectMany(stream => stream.Files).ToArray(); if (files.Length != 0) { long headerOffset = mFileStream.Position; var headerStream = new master._7zip.Legacy.CrcBuilderStream(mFileStream); var writer = new BinaryWriter(headerStream, Encoding.Unicode); WriteNumber(writer, BlockType.Header); var inputStreams = mFileSets.SelectMany(fileset => fileset.InputStreams).ToArray(); if (inputStreams.Any(stream => stream.Size != 0)) { WriteNumber(writer, BlockType.MainStreamsInfo); WriteNumber(writer, BlockType.PackInfo); WriteNumber(writer, (ulong)0); // offset to input streams WriteNumber(writer, inputStreams.Length); WriteNumber(writer, BlockType.Size); foreach (var stream in inputStreams) WriteNumber(writer, stream.Size); WriteNumber(writer, BlockType.End); WriteNumber(writer, BlockType.UnpackInfo); WriteNumber(writer, BlockType.Folder); WriteNumber(writer, mFileSets.Count); writer.Write((byte)0); // inline data foreach (var fileset in mFileSets) { WriteNumber(writer, fileset.Coders.Length); var coderOffsetMap = new int[fileset.Coders.Length]; var outputStreamCount = 0; for (int i = 0; i < coderOffsetMap.Length; i++) { coderOffsetMap[i] = outputStreamCount; outputStreamCount += fileset.Coders[i].OutputStreams.Length; } var inputBindPairs = new List<Tuple<int, int>>(); var coderBindPairs = new List<Tuple<int, int>>(); var inputStreamCount = 0; foreach (var coder in fileset.Coders) { int idlen = coder.MethodId.GetLength(); if (idlen >= 8) throw new NotSupportedException(); int flags = idlen; if (coder.InputStreams.Length != 1 || coder.OutputStreams.Length != 1) flags |= 0x10; if (coder.Settings != null) flags |= 0x20; writer.Write((byte)flags); ulong id = coder.MethodId.Id; for (int i = idlen - 1; i >= 0; i--) writer.Write((byte)(id >> (i * 8))); if ((flags & 0x10) != 0) { WriteNumber(writer, coder.InputStreams.Length); WriteNumber(writer, coder.OutputStreams.Length); } if ((flags & 0x20) != 0) { WriteNumber(writer, coder.Settings.Length); writer.Write(coder.Settings); } if (coder.InputStreams.Length != 1 || coder.OutputStreams.Length != 1) throw new NotSupportedException(); foreach (var streamRef in coder.InputStreams) { if (streamRef is InputStreamRef) { var inputStreamRef = (InputStreamRef)streamRef; inputBindPairs.Add(Tuple.Create(inputStreamCount++, inputStreamRef.PackedStreamIndex)); } else { var coderStreamRef = (CoderStreamRef)streamRef; var index = coderOffsetMap[coderStreamRef.CoderIndex] + coderStreamRef.StreamIndex; coderBindPairs.Add(Tuple.Create(inputStreamCount++, index)); } } } Utils.Assert(coderBindPairs.Count == outputStreamCount - 1); Utils.Assert(inputBindPairs.Count == inputStreamCount - outputStreamCount + 1); foreach (var pair in coderBindPairs) { WriteNumber(writer, pair.Item1); WriteNumber(writer, pair.Item2); } if (inputBindPairs.Count > 1) { inputBindPairs.Sort((x, y) => x.Item2.CompareTo(y.Item2)); for (int i = 0; i < inputBindPairs.Count; i++) { if (inputBindPairs[i].Item2 != i) throw new Exception("Internal Error: mismatched coder bindings"); WriteNumber(writer, inputBindPairs[i].Item1); } } } WriteNumber(writer, BlockType.CodersUnpackSize); foreach (var fileset in mFileSets) foreach (var coder in fileset.Coders) foreach (var outputInfo in coder.OutputStreams) WriteNumber(writer, outputInfo.Size); { bool allHashes = true; bool anyHashes = false; // add padding so we can process blocks of 8 without running off the array // (all code needs to use the fileset count instead of the array length though) var hashes = new uint?[mFileSets.Count + 8]; for (int i = 0; i < mFileSets.Count; i++) { if ((hashes[i] = mFileSets[i].DataStream.GetHash(mFileSets[i])).HasValue) anyHashes = true; else allHashes = false; } if (anyHashes) { WriteNumber(writer, BlockType.CRC); if (allHashes) { writer.Write((byte)1); } else { writer.Write((byte)0); for (int i = 0; i < mFileSets.Count; i += 8) { byte bt = 0; for (int j = 0; j < 8; j++) { bt <<= 1; if (hashes[i + j] != null) bt |= (byte)1; } writer.Write(bt); } } for (int i = 0; i < mFileSets.Count; i++) if (hashes[i] != null) writer.Write(hashes[i].Value); } } WriteNumber(writer, BlockType.End); WriteNumber(writer, BlockType.SubStreamsInfo); WriteNumber(writer, BlockType.NumUnpackStream); foreach (var stream in mFileSets) WriteNumber(writer, stream.Files.Length); WriteNumber(writer, BlockType.Size); foreach (var stream in mFileSets) for (int i = 0; i < stream.Files.Length - 1; i++) WriteNumber(writer, stream.Files[i].Size); WriteNumber(writer, BlockType.End); WriteNumber(writer, BlockType.End); } WriteNumber(writer, BlockType.FilesInfo); WriteNumber(writer, files.Length); WriteNumber(writer, BlockType.Name); WriteNumber(writer, 1 + files.Sum(file => file.Name.Length + 1) * 2); writer.Write((byte)0); // inline names for (int i = 0; i < files.Length; i++) { string name = files[i].Name; for (int j = 0; j < name.Length; j++) writer.Write(name[j]); writer.Write('\0'); } /* had to disable empty streams and files because above BlockType.Size doesn't respect them * if a file is marked as empty stream it doesn't get a size/hash entry in the coder header above * however, to fix that, we'd need to skip coders with only empty files too, so its easier to do it this way for now if(files.Any(file => file.Size == 0)) { int emptyStreams = 0; WriteNumber(writer, BlockType.EmptyStream); WriteNumber(writer, (files.Length + 7) / 8); for(int i = 0; i < files.Length; i += 8) { int mask = 0; for(int j = 0; j < 8; j++) { if(i + j < files.Length && files[i + j].Size == 0) { mask |= 1 << (7 - j); emptyStreams++; } } writer.Write((byte)mask); } WriteNumber(writer, BlockType.EmptyFile); WriteNumber(writer, (emptyStreams + 7) / 8); for(int i = 0; i < emptyStreams; i += 8) { int mask = 0; for(int j = 0; j < 8; j++) if(i + j < emptyStreams) mask |= 1 << (7 - j); writer.Write((byte)mask); } } */ int ctimeCount = files.Count(file => file.CTime.HasValue); if (ctimeCount != 0) { WriteNumber(writer, BlockType.CTime); if (ctimeCount == files.Length) { WriteNumber(writer, 2 + ctimeCount * 8); writer.Write((byte)1); } else { WriteNumber(writer, (ctimeCount + 7) / 8 + 2 + ctimeCount * 8); writer.Write((byte)0); for (int i = 0; i < files.Length; i += 8) { int mask = 0; for (int j = 0; j < 8; j++) if (i + j < files.Length && files[i + j].CTime.HasValue) mask |= 1 << (7 - j); writer.Write((byte)mask); } } writer.Write((byte)0); // inline data for (int i = 0; i < files.Length; i++) if (files[i].CTime.HasValue) writer.Write(files[i].CTime.Value.ToFileTimeUtc()); } int atimeCount = files.Count(file => file.ATime.HasValue); if (atimeCount != 0) { WriteNumber(writer, BlockType.ATime); if (atimeCount == files.Length) { WriteNumber(writer, 2 + atimeCount * 8); writer.Write((byte)1); } else { WriteNumber(writer, (atimeCount + 7) / 8 + 2 + atimeCount * 8); writer.Write((byte)0); for (int i = 0; i < files.Length; i += 8) { int mask = 0; for (int j = 0; j < 8; j++) if (i + j < files.Length && files[i + j].ATime.HasValue) mask |= 1 << (7 - j); writer.Write((byte)mask); } } writer.Write((byte)0); // inline data for (int i = 0; i < files.Length; i++) if (files[i].ATime.HasValue) writer.Write(files[i].ATime.Value.ToFileTimeUtc()); } int mtimeCount = files.Count(file => file.MTime.HasValue); if (mtimeCount != 0) { WriteNumber(writer, BlockType.MTime); if (mtimeCount == files.Length) { WriteNumber(writer, 2 + mtimeCount * 8); writer.Write((byte)1); } else { WriteNumber(writer, (mtimeCount + 7) / 8 + 2 + mtimeCount * 8); writer.Write((byte)0); for (int i = 0; i < files.Length; i += 8) { int mask = 0; for (int j = 0; j < 8; j++) if (i + j < files.Length && files[i + j].MTime.HasValue) mask |= 1 << (7 - j); writer.Write((byte)mask); } } writer.Write((byte)0); // inline data for (int i = 0; i < files.Length; i++) if (files[i].MTime.HasValue) writer.Write(files[i].MTime.Value.ToFileTimeUtc()); } WriteNumber(writer, BlockType.End); uint headerCRC = headerStream.Finish(); long headerSize = mFileStream.Position - headerOffset; mFileStream.Position = mFileOrigin + 8; WriteHeaderInfo(new BinaryWriter(mFileStream, Encoding.Unicode), headerOffset - mFileOrigin - 0x20, headerSize, headerCRC); } mFileStream.Close(); // so we don't start overwriting stuff accidently by calling more functions }
protected ReceivableObject(bool encrypted) { provider = EncryptionProvider.GetInstance(); receiveEncrypted = encrypted; }
public static void Init( InitDelegate onInitComplete, string appId, HideUnityDelegate onHideUnity, string redirectUrl = null) { #if NETFX_CORE if (_client != null) { if (onInitComplete != null) { onInitComplete(); } return; } if (_web == null) { throw new MissingPlatformException(); } if (string.IsNullOrEmpty(appId)) { throw new ArgumentException("Invalid Facebook App ID"); } if (!string.IsNullOrEmpty(redirectUrl)) { _redirectUrl = redirectUrl; } _client = new FacebookClient(); _client.GetCompleted += HandleGetCompleted; AppId = _client.AppId = appId; _onHideUnity = onHideUnity; if (Settings.HasKey(TOKEN_KEY)) { AccessToken = EncryptionProvider.Decrypt(Settings.GetString(TOKEN_KEY), AppId); if (Settings.HasKey(EXPIRY_DATE)) { string expDate = EncryptionProvider.Decrypt(Settings.GetString(EXPIRY_DATE), AppId); Expires = DateTime.Parse(expDate, CultureInfo.InvariantCulture); } else { long expDate = Settings.GetLong(EXPIRY_DATE_BIN); Expires = DateTime.FromBinary(expDate); } _client.AccessToken = AccessToken; UserId = Settings.GetString(FBID_KEY); UserName = Settings.GetString(FBNAME_KEY); // verifies if the token has expired: if (DateTime.Compare(DateTime.UtcNow, Expires) > 0) { InvalidateData(); } //var task = TestAccessToken(); //task.Wait(); } if (onInitComplete != null) { onInitComplete(); } #else throw new PlatformNotSupportedException(""); #endif }
static EncryptionHelper() { encProv = new EncryptionProvider(); }
public void EncryptTest() { string userNamePayload = EncryptionProvider.Encrypt("Ji-Feng Tsai"); Assert.IsNotNull(userNamePayload); }
public void DecryptTest() { string userName = EncryptionProvider.Decrypt("bbZNJMF5fwxVk5F9ePLvkg=="); Assert.AreEqual(userName, "Ji-Feng Tsai"); }
public CertificateDownloadController(ICertificateRepository certificateRepository, IConfigurationRepository configurationRepository, EncryptionProvider cipher) { this.configurationRepository = configurationRepository; this.certificateRepository = certificateRepository; this.cipher = cipher; }
private static void AdjustFilesetForEncryption(FileSet fileset, EncryptionProvider encryption, long outputSize, uint? outputHash) { if (fileset.InputStreams.Length != 1) throw new NotSupportedException(); master._7zip.Legacy.CMethodId methodId; byte[] settings; encryption.GetCoderInfo(out methodId, out settings); var encryptedStreamRef = new InputStreamRef { PackedStreamIndex = 0 }; var decryptedStreamRef = new CoderStreamRef { CoderIndex = fileset.Coders.Length, StreamIndex = 0 }; // TODO: this is wrong, outputSize/outputHash is the INPUT of the decoder, // however see comment at call site for why this works for now // (we also need to replace the filesets input stream with our own // input stream, namely outputSize/outputHash) var decryptionCoder = new Coder { MethodId = methodId, Settings = settings, InputStreams = new[] { encryptedStreamRef }, OutputStreams = new[] { new CoderStream { Size = outputSize, Hash = outputHash } }, }; fileset.Coders = fileset.Coders .Select(x => AdjustCoderForEncryption(x, decryptedStreamRef)) .Concat(new[] { decryptionCoder }) .ToArray(); }
internal void Connect(ArchiveWriter writer) { Debug.Assert(writer != null && mWriter == null); mWriter = writer; mEncryption = writer.DefaultEncryptionProvider; if (mFlushed != null && mFlushed.Count != 0) { foreach (var item in mFlushed) mWriter.Encoder_WriteFileSet(item); mFlushed.Clear(); } if (mBuffer != null) { mBuffer.FullCopyTo(writer.mFileStream); mBuffer.SetLength(0); } }
/// <summary> /// Begins the handshake process on the specified <see cref="Socket"/> /// </summary> /// <param name="decryptor">This will be set to a <see cref="EncryptionProvider"/> that has been initialized with the negotiated (local) decryption key</param> /// <param name="encryptor">This will be set to a <see cref="EncryptionProvider"/> that has been initialized with the negotiated (remote) encryption key</param> /// <param name="privRSA">The <see cref="RSAHelper"/> to use to securely negotiate encryption / decryption keys</param> /// <param name="netStream">The already opened <see cref="NetworkStream"/> to use while shaking hands</param> /// <param name="s">The socket to handshake on</param> /// <param name="readLock">The object used to lock read access to the stream to one thread</param> /// <param name="writeLock">The object used to lock write access to the stream to one thread</param> /// <returns></returns> public bool Handshake(Stream netStream, Socket s, RSAHelper privRSA, out EncryptionProvider encryptor, out EncryptionProvider decryptor, ref object readLock, ref object writeLock) { RSAHelper pubRSA; encryptor = null; decryptor = null; try { lock (readLock) { lock (writeLock) { this.ownerComponent.LogInformation("[{0}] -> [{1}]: Exchanging RSA Public Keys", s.LocalEndPoint, s.RemoteEndPoint); ExchangePubKey(netStream, privRSA, out pubRSA); this.ownerComponent.LogInformation("[{0}] -> [{1}]: Negotiating Session Keys", s.LocalEndPoint, s.RemoteEndPoint); NegotiateSessionKeys(netStream, out decryptor, out encryptor, pubRSA, privRSA); this.ownerComponent.LogInformation("[{0}] -> [{1}]: Verifying Connection...", s.LocalEndPoint, s.RemoteEndPoint); bool succes = VerifySessionKeys(netStream, encryptor, decryptor); this.ownerComponent.LogInformation("[{0}] -> [{1}]: {2}", s.LocalEndPoint, s.RemoteEndPoint, succes ? "Success" : "Error"); return(succes); } } } catch (Exception e) { this.ownerComponent.LogException(e, System.Reflection.MethodBase.GetCurrentMethod()); return(false); } }
protected override void Load(ContainerBuilder builder) { // ISignatureProvider builder.Register( c => { ISignatureProvider signatureProvider = this.edgeHubConnectionString.Map( cs => { IotHubConnectionStringBuilder csBuilder = IotHubConnectionStringBuilder.Create(cs); return(new SharedAccessKeySignatureProvider(csBuilder.SharedAccessKey) as ISignatureProvider); }) .GetOrElse( () => { string edgeHubGenerationId = this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Generation ID missing")); string workloadUri = this.workloadUri.Expect(() => new InvalidOperationException("workloadUri is missing")); return(new HttpHsmSignatureProvider(this.edgeHubModuleId, edgeHubGenerationId, workloadUri, Service.Constants.WorkloadApiVersion) as ISignatureProvider); }); return(signatureProvider); }) .As <ISignatureProvider>() .SingleInstance(); // Detect system environment builder.Register(c => new SystemEnvironment()) .As <ISystemEnvironment>() .SingleInstance(); // DataBase options builder.Register(c => new Storage.RocksDb.RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), this.optimizeForPerformance)) .As <Storage.RocksDb.IRocksDbOptionsProvider>() .SingleInstance(); // IDbStoreProvider builder.Register( c => { var loggerFactory = c.Resolve <ILoggerFactory>(); ILogger logger = loggerFactory.CreateLogger(typeof(RoutingModule)); if (this.usePersistentStorage) { // Create partitions for messages and twins var partitionsList = new List <string> { Core.Constants.MessageStorePartitionKey, Core.Constants.TwinStorePartitionKey, Core.Constants.CheckpointStorePartitionKey }; try { IDbStoreProvider dbStoreprovider = Storage.RocksDb.DbStoreProvider.Create(c.Resolve <Storage.RocksDb.IRocksDbOptionsProvider>(), this.storagePath, partitionsList); logger.LogInformation($"Created persistent store at {this.storagePath}"); return(dbStoreprovider); } catch (Exception ex) when(!ExceptionEx.IsFatal(ex)) { logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store."); return(new InMemoryDbStoreProvider()); } } else { logger.LogInformation($"Using in-memory store"); return(new InMemoryDbStoreProvider()); } }) .As <IDbStoreProvider>() .SingleInstance(); // Task<IEncryptionProvider> builder.Register( async c => { IEncryptionProvider encryptionProvider = await this.workloadUri.Map( async uri => await EncryptionProvider.CreateAsync( this.storagePath, new Uri(uri), Service.Constants.WorkloadApiVersion, this.edgeHubModuleId, this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")), Service.Constants.InitializationVectorFileName) as IEncryptionProvider) .GetOrElse(() => Task.FromResult <IEncryptionProvider>(NullEncryptionProvider.Instance)); return(encryptionProvider); }) .As <Task <IEncryptionProvider> >() .SingleInstance(); // IStoreProvider builder.Register(c => new StoreProvider(c.Resolve <IDbStoreProvider>())) .As <IStoreProvider>() .SingleInstance(); // ITokenProvider builder.Register(c => new ModuleTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, TimeSpan.FromHours(1))) .Named <ITokenProvider>("EdgeHubClientAuthTokenProvider") .SingleInstance(); // ITokenProvider builder.Register(c => { string deviceId = WebUtility.UrlEncode(this.edgeDeviceId); string moduleId = WebUtility.UrlEncode(this.edgeHubModuleId); return(new ModuleTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, deviceId, moduleId, TimeSpan.FromHours(1))); }) .Named <ITokenProvider>("EdgeHubServiceAuthTokenProvider") .SingleInstance(); // Task<IKeyValueStore<string, string>> - EncryptedStore builder.Register( async c => { var storeProvider = c.Resolve <IStoreProvider>(); IEncryptionProvider encryptionProvider = await c.Resolve <Task <IEncryptionProvider> >(); IEntityStore <string, string> entityStore = storeProvider.GetEntityStore <string, string>("SecurityScopeCache"); IKeyValueStore <string, string> encryptedStore = new EncryptedStore <string, string>(entityStore, encryptionProvider); return(encryptedStore); }) .Named <Task <IKeyValueStore <string, string> > >("EncryptedStore") .SingleInstance(); // Task<IDeviceScopeIdentitiesCache> builder.Register( async c => { IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache; if (this.authenticationMode == AuthenticationMode.CloudAndScope || this.authenticationMode == AuthenticationMode.Scope) { var edgeHubTokenProvider = c.ResolveNamed <ITokenProvider>("EdgeHubServiceAuthTokenProvider"); IDeviceScopeApiClient securityScopesApiClient = new DeviceScopeApiClient(this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, 10, edgeHubTokenProvider); IServiceProxy serviceProxy = new ServiceProxy(securityScopesApiClient); IKeyValueStore <string, string> encryptedStore = await c.ResolveNamed <Task <IKeyValueStore <string, string> > >("EncryptedStore"); deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy, encryptedStore, this.scopeCacheRefreshRate); } else { deviceScopeIdentitiesCache = new NullDeviceScopeIdentitiesCache(); } return(deviceScopeIdentitiesCache); }) .As <Task <IDeviceScopeIdentitiesCache> >() .SingleInstance(); // Task<IAuthenticator> builder.Register(async c => { IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >(); IAuthenticator tokenAuthenticator; IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache; switch (this.authenticationMode) { case AuthenticationMode.Cloud: if (this.cacheTokens) { ICredentialsStore credentialsStore = await c.Resolve <Task <ICredentialsStore> >(); IAuthenticator authenticator = new CloudTokenAuthenticator(connectionManager); tokenAuthenticator = new TokenCacheAuthenticator(authenticator, credentialsStore, this.iothubHostName); } else { tokenAuthenticator = new CloudTokenAuthenticator(connectionManager); } break; case AuthenticationMode.Scope: deviceScopeIdentitiesCache = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >(); tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, new NullAuthenticator(), connectionManager); break; default: deviceScopeIdentitiesCache = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >(); IAuthenticator cloudAuthenticator = new CloudTokenAuthenticator(connectionManager); tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, cloudAuthenticator, connectionManager); break; } return(new Authenticator(tokenAuthenticator, this.edgeDeviceId, connectionManager) as IAuthenticator); }) .As <Task <IAuthenticator> >() .SingleInstance(); // IClientCredentialsFactory builder.Register(c => new ClientCredentialsFactory(this.iothubHostName, this.productInfo)) .As <IClientCredentialsFactory>() .SingleInstance(); base.Load(builder); }
/// <summary> /// Initializes a new instance of the <see cref="TestDealer"/> class. /// </summary> /// <param name="container">The componentry container.</param> /// <param name="headerSerializer">The header serializer.</param> /// <param name="requestSerializer">The outbound serializer.</param> /// <param name="responseSerializer">The inbound serializer.</param> /// <param name="compressor">The compressor.</param> /// <param name="encryption">The encryption settings.</param> /// <param name="serverReqAddress">The server request address to connect to.</param> /// <param name="serverResAddress">The server response address to connect to.</param> /// <param name="subName">The requesters sub-name.</param> public TestDealer( IComponentryContainer container, ISerializer <Dictionary <string, string> > headerSerializer, IMessageSerializer <Request> requestSerializer, IMessageSerializer <Response> responseSerializer, ICompressor compressor, EncryptionSettings encryption, ZmqNetworkAddress serverReqAddress, ZmqNetworkAddress serverResAddress, string subName = "") : base(container, subName) { this.headerSerializer = headerSerializer; this.requestSerializer = requestSerializer; this.responseSerializer = responseSerializer; this.compressor = compressor; this.socketOutbound = new DealerSocket { Options = { Identity = Encoding.UTF8.GetBytes(this.Name.Value), Linger = TimeSpan.FromSeconds(1), }, }; this.socketInbound = new DealerSocket { Options = { Identity = Encoding.UTF8.GetBytes(this.Name.Value), Linger = TimeSpan.FromSeconds(1), }, }; this.ClientId = new ClientId(this.Name.Value); this.ServerReqAddress = serverReqAddress; this.ServerResAddress = serverResAddress; if (encryption.UseEncryption) { EncryptionProvider.SetupSocket(encryption, this.socketOutbound); this.Logger.LogInformation( LogId.Network, $"{encryption.Algorithm} encryption setup for connections to {this.ServerReqAddress}"); EncryptionProvider.SetupSocket(encryption, this.socketInbound); this.Logger.LogInformation( LogId.Network, $"{encryption.Algorithm} encryption setup for connections to {this.ServerResAddress}"); } else { this.Logger.LogWarning( LogId.Network, $"No encryption setup for connections to {this.ServerReqAddress}"); this.Logger.LogWarning( LogId.Network, $"No encryption setup for connections to {this.ServerResAddress}"); } this.ReceivedCount = 0; this.SendCount = 0; }
/// <summary> /// Initializes a new instance of the <see cref="HashEncryption"/> class. /// </summary> /// <param name="provider">The provider.</param> public HashEncryption(EncryptionProvider provider) : this(provider, new CryptoSettingsWrapper()) { }
protected override void Load(ContainerBuilder builder) { // ISerde<ModuleSet> builder.Register( c => new ModuleSetSerde( new Dictionary <string, Type> { { DockerType, typeof(DockerModule) } })) .As <ISerde <ModuleSet> >() .SingleInstance(); // ISerde<DeploymentConfig> builder.Register( c => { ISerde <DeploymentConfig> serde = new TypeSpecificSerDe <DeploymentConfig>(DeploymentConfigTypeMapping); return(serde); }) .As <ISerde <DeploymentConfig> >() .SingleInstance(); // ISerde<DeploymentConfigInfo> builder.Register( c => { ISerde <DeploymentConfigInfo> serde = new TypeSpecificSerDe <DeploymentConfigInfo>(DeploymentConfigTypeMapping); return(serde); }) .As <ISerde <DeploymentConfigInfo> >() .SingleInstance(); // Detect system environment builder.Register(c => new SystemEnvironment()) .As <ISystemEnvironment>() .SingleInstance(); // IRocksDbOptionsProvider // For EdgeAgent, we don't need high performance from RocksDb, so always turn off optimizeForPerformance builder.Register(c => new RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), false)) .As <IRocksDbOptionsProvider>() .SingleInstance(); if (!this.usePersistentStorage && this.useBackupAndRestore) { // Backup and restore serialization builder.Register(c => new ProtoBufDataBackupRestore()) .As <IDataBackupRestore>() .SingleInstance(); } // IDbStoreProvider builder.Register( async c => { var loggerFactory = c.Resolve <ILoggerFactory>(); ILogger logger = loggerFactory.CreateLogger(typeof(AgentModule)); if (this.usePersistentStorage) { // Create partition for mma var partitionsList = new List <string> { "moduleState", "deploymentConfig" }; try { IDbStoreProvider dbStoreprovider = DbStoreProvider.Create( c.Resolve <IRocksDbOptionsProvider>(), this.storagePath, partitionsList); logger.LogInformation($"Created persistent store at {this.storagePath}"); return(dbStoreprovider); } catch (Exception ex) when(!ExceptionEx.IsFatal(ex)) { logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store."); IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c); return(dbStoreProvider); } } else { logger.LogInformation($"Using in-memory store"); IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c); return(dbStoreProvider); } }) .As <Task <IDbStoreProvider> >() .SingleInstance(); // Task<IStoreProvider> builder.Register(async c => { var dbStoreProvider = await c.Resolve <Task <IDbStoreProvider> >(); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); return(storeProvider); }) .As <Task <IStoreProvider> >() .SingleInstance(); // IEntityStore<string, ModuleState> builder.Register(async c => { IStoreProvider storeProvider = await c.Resolve <Task <IStoreProvider> >(); return(storeProvider.GetEntityStore <string, ModuleState>("moduleState")); }) .As <Task <IEntityStore <string, ModuleState> > >() .SingleInstance(); // IEntityStore<string, DeploymentConfigInfo> builder.Register(async c => { IStoreProvider storeProvider = await c.Resolve <Task <IStoreProvider> >(); return(storeProvider.GetEntityStore <string, string>("deploymentConfig")); }) .As <Task <IEntityStore <string, string> > >() .SingleInstance(); // IRestartManager builder.Register(c => new RestartPolicyManager(this.maxRestartCount, this.coolOffTimeUnitInSeconds)) .As <IRestartPolicyManager>() .SingleInstance(); // IPlanner builder.Register( async c => new HealthRestartPlanner( await c.Resolve <Task <ICommandFactory> >(), await c.Resolve <Task <IEntityStore <string, ModuleState> > >(), this.intensiveCareTime, c.Resolve <IRestartPolicyManager>()) as IPlanner) .As <Task <IPlanner> >() .SingleInstance(); // IPlanRunner builder.Register(c => new OrderedRetryPlanRunner(this.maxRestartCount, this.coolOffTimeUnitInSeconds, SystemTime.Instance)) .As <IPlanRunner>() .SingleInstance(); // IEncryptionDecryptionProvider builder.Register( async c => { IEncryptionProvider provider = await this.workloadUri.Map( async uri => { IEncryptionProvider encryptionProvider = await EncryptionProvider.CreateAsync( this.storagePath, uri, this.workloadApiVersion.Expect(() => new InvalidOperationException("Missing workload API version")), Constants.EdgeletClientApiVersion, this.moduleId, this.moduleGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")), Constants.EdgeletInitializationVectorFileName); return(encryptionProvider); }).GetOrElse(() => Task.FromResult <IEncryptionProvider>(NullEncryptionProvider.Instance)); return(provider); }) .As <Task <IEncryptionProvider> >() .SingleInstance(); // IAvailabilityMetric builder.Register(c => new AvailabilityMetrics(c.Resolve <IMetricsProvider>(), this.storagePath)) .As <IAvailabilityMetric>() .SingleInstance(); // Task<Agent> builder.Register( async c => { var configSource = c.Resolve <Task <IConfigSource> >(); var environmentProvider = c.Resolve <Task <IEnvironmentProvider> >(); var planner = c.Resolve <Task <IPlanner> >(); var planRunner = c.Resolve <IPlanRunner>(); var reporter = c.Resolve <IReporter>(); var moduleIdentityLifecycleManager = c.Resolve <IModuleIdentityLifecycleManager>(); var deploymentConfigInfoSerde = c.Resolve <ISerde <DeploymentConfigInfo> >(); var deploymentConfigInfoStore = await c.Resolve <Task <IEntityStore <string, string> > >(); var encryptionProvider = c.Resolve <Task <IEncryptionProvider> >(); var availabilityMetric = c.Resolve <IAvailabilityMetric>(); return(await Agent.Create( await configSource, await planner, planRunner, reporter, moduleIdentityLifecycleManager, await environmentProvider, deploymentConfigInfoStore, deploymentConfigInfoSerde, await encryptionProvider, availabilityMetric)); }) .As <Task <Agent> >() .SingleInstance(); base.Load(builder); }
public Utility_class_User ValidateUser(string username, string password) { foreach (var s in _registeredUsersLst) { if (s.USER_NAME.Length > 50 && s.PASSWORD.Length > 50) { if (username == EncryptionProvider.Decryprt(s.USER_NAME) && password == EncryptionProvider.Decryprt(s.PASSWORD)) { _registeredUser.PASSWORD = password; _registeredUser.USER_NAME = username; _registeredUser.USER_KIND = s.USER_KIND; break; } } } return(_registeredUser); }
protected override void Load(ContainerBuilder builder) { // IMessageConverter<IRoutingMessage> builder.Register(c => new RoutingMessageConverter()) .As <Core.IMessageConverter <IRoutingMessage> >() .SingleInstance(); // IRoutingPerfCounter builder.Register( c => { Routing.PerfCounter = NullRoutingPerfCounter.Instance; return(Routing.PerfCounter); }) .As <IRoutingPerfCounter>() .AutoActivate() .SingleInstance(); // IRoutingUserAnalyticsLogger builder.Register( c => { Routing.UserAnalyticsLogger = NullUserAnalyticsLogger.Instance; return(Routing.UserAnalyticsLogger); }) .As <IRoutingUserAnalyticsLogger>() .AutoActivate() .SingleInstance(); // IRoutingUserMetricLogger builder.Register( c => { Routing.UserMetricLogger = NullRoutingUserMetricLogger.Instance; return(Routing.UserMetricLogger); }) .As <IRoutingUserMetricLogger>() .AutoActivate() .SingleInstance(); // IMessageConverter<Message> builder.Register(c => new DeviceClientMessageConverter()) .As <Core.IMessageConverter <Message> >() .SingleInstance(); // IMessageConverter<Twin> builder.Register(c => new TwinMessageConverter()) .As <Core.IMessageConverter <Twin> >() .SingleInstance(); // IMessageConverter<TwinCollection> builder.Register(c => new TwinCollectionMessageConverter()) .As <Core.IMessageConverter <TwinCollection> >() .SingleInstance(); // IMessageConverterProvider builder.Register( c => new MessageConverterProvider(new Dictionary <Type, IMessageConverter>() { { typeof(Message), c.Resolve <Core.IMessageConverter <Message> >() }, { typeof(Twin), c.Resolve <Core.IMessageConverter <Twin> >() }, { typeof(TwinCollection), c.Resolve <Core.IMessageConverter <TwinCollection> >() } })) .As <Core.IMessageConverterProvider>() .SingleInstance(); // IDeviceConnectivityManager builder.Register( c => { IDeviceConnectivityManager deviceConnectivityManager = new DeviceConnectivityManager(this.connectivityCheckFrequency, TimeSpan.FromMinutes(2)); return(deviceConnectivityManager); }) .As <IDeviceConnectivityManager>() .SingleInstance(); // IDeviceClientProvider builder.Register(c => { IClientProvider underlyingClientProvider = new ClientProvider(); IClientProvider connectivityAwareClientProvider = new ConnectivityAwareClientProvider(underlyingClientProvider, c.Resolve <IDeviceConnectivityManager>()); return(connectivityAwareClientProvider); }) .As <IClientProvider>() .SingleInstance(); // ICloudConnectionProvider builder.Register(c => new CloudConnectionProvider(c.Resolve <Core.IMessageConverterProvider>(), this.connectionPoolSize, c.Resolve <IClientProvider>(), this.upstreamProtocol)) .As <ICloudConnectionProvider>() .SingleInstance(); if (this.isStoreAndForwardEnabled || this.cacheTokens) { // Detect system environment builder.Register(c => new SystemEnvironment()) .As <ISystemEnvironment>() .SingleInstance(); // DataBase options builder.Register(c => new Storage.RocksDb.RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), this.optimizeForPerformance)) .As <Storage.RocksDb.IRocksDbOptionsProvider>() .SingleInstance(); // IDbStore builder.Register( c => { var loggerFactory = c.Resolve <ILoggerFactory>(); ILogger logger = loggerFactory.CreateLogger(typeof(RoutingModule)); if (this.usePersistentStorage) { // Create partitions for messages and twins var partitionsList = new List <string> { Core.Constants.MessageStorePartitionKey, Core.Constants.TwinStorePartitionKey, Core.Constants.CheckpointStorePartitionKey }; try { IDbStoreProvider dbStoreprovider = Storage.RocksDb.DbStoreProvider.Create(c.Resolve <Storage.RocksDb.IRocksDbOptionsProvider>(), this.storagePath, partitionsList); logger.LogInformation($"Created persistent store at {this.storagePath}"); return(dbStoreprovider); } catch (Exception ex) when(!ExceptionEx.IsFatal(ex)) { logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store."); return(new InMemoryDbStoreProvider()); } } else { logger.LogInformation($"Using in-memory store"); return(new InMemoryDbStoreProvider()); } }) .As <IDbStoreProvider>() .SingleInstance(); } // Task<ICredentialsStore> builder.Register(async c => { if (this.cacheTokens) { var dbStoreProvider = c.Resolve <IDbStoreProvider>(); IEncryptionProvider encryptionProvider = await this.workloadUri.Map( async uri => await EncryptionProvider.CreateAsync( this.storagePath, new Uri(uri), Service.Constants.WorkloadApiVersion, this.edgeModuleId, this.edgeModuleGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")), Service.Constants.InitializationVectorFileName) as IEncryptionProvider) .GetOrElse(() => Task.FromResult <IEncryptionProvider>(NullEncryptionProvider.Instance)); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); IEntityStore <string, string> tokenCredentialsEntityStore = storeProvider.GetEntityStore <string, string>("tokenCredentials"); return(new TokenCredentialsStore(tokenCredentialsEntityStore, encryptionProvider)); } else { return(new NullCredentialsStore() as ICredentialsStore); } }) .As <Task <ICredentialsStore> >() .SingleInstance(); // IConnectionManager builder.Register(c => new ConnectionManager(c.Resolve <ICloudConnectionProvider>(), this.maxConnectedClients)) .As <IConnectionManager>() .SingleInstance(); // IEndpointFactory builder.Register(c => new EndpointFactory(c.Resolve <IConnectionManager>(), c.Resolve <Core.IMessageConverter <IRoutingMessage> >(), this.edgeDeviceId)) .As <IEndpointFactory>() .SingleInstance(); // RouteFactory builder.Register(c => new EdgeRouteFactory(c.Resolve <IEndpointFactory>())) .As <RouteFactory>() .SingleInstance(); // RouterConfig builder.Register(c => new RouterConfig(Enumerable.Empty <Route>())) .As <RouterConfig>() .SingleInstance(); if (!this.isStoreAndForwardEnabled) { // EndpointExecutorConfig builder.Register( c => { RetryStrategy defaultRetryStrategy = new FixedInterval(0, TimeSpan.FromSeconds(1)); TimeSpan defaultRevivePeriod = TimeSpan.FromHours(1); TimeSpan defaultTimeout = TimeSpan.FromSeconds(60); return(new EndpointExecutorConfig(defaultTimeout, defaultRetryStrategy, defaultRevivePeriod, true)); }) .As <EndpointExecutorConfig>() .SingleInstance(); // IEndpointExecutorFactory builder.Register(c => new SyncEndpointExecutorFactory(c.Resolve <EndpointExecutorConfig>())) .As <IEndpointExecutorFactory>() .SingleInstance(); // Task<Router> builder.Register( async c => { var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>(); var routerConfig = c.Resolve <RouterConfig>(); Router router = await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory); return(router); }) .As <Task <Router> >() .SingleInstance(); // ITwinManager builder.Register(c => TwinManager.CreateTwinManager(c.Resolve <IConnectionManager>(), c.Resolve <IMessageConverterProvider>(), Option.None <IStoreProvider>())) .As <ITwinManager>() .SingleInstance(); } else { // EndpointExecutorConfig builder.Register( c => { // Endpoint executor config values - // ExponentialBackoff - minBackoff = 1s, maxBackoff = 60s, delta (used to add randomness to backoff) - 1s (default) // Num of retries = int.MaxValue(we want to keep retrying till the message is sent) // Revive period - period for which the endpoint should be considered dead if it doesn't respond - 1 min (we want to try continuously till the message expires) // Timeout - time for which we want for the ack from the endpoint = 30s // TODO - Should the number of retries be tied to the Store and Forward ttl? Not // doing that right now as that value can be changed at runtime, but these settings // cannot. Need to make the number of retries dynamically configurable for that. TimeSpan minWait = TimeSpan.FromSeconds(1); TimeSpan maxWait = TimeSpan.FromSeconds(60); TimeSpan delta = TimeSpan.FromSeconds(1); int retries = int.MaxValue; RetryStrategy retryStrategy = new ExponentialBackoff(retries, minWait, maxWait, delta); TimeSpan timeout = TimeSpan.FromSeconds(30); TimeSpan revivePeriod = TimeSpan.FromSeconds(30); return(new EndpointExecutorConfig(timeout, retryStrategy, revivePeriod)); }) .As <EndpointExecutorConfig>() .SingleInstance(); // ICheckpointStore builder.Register(c => CheckpointStore.Create(c.Resolve <IDbStoreProvider>())) .As <ICheckpointStore>() .SingleInstance(); // IMessageStore builder.Register( c => { var checkpointStore = c.Resolve <ICheckpointStore>(); var dbStoreProvider = c.Resolve <IDbStoreProvider>(); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); IMessageStore messageStore = new MessageStore(storeProvider, checkpointStore, TimeSpan.MaxValue); return(messageStore); }) .As <IMessageStore>() .SingleInstance(); // IEndpointExecutorFactory builder.Register( c => { var endpointExecutorConfig = c.Resolve <EndpointExecutorConfig>(); var messageStore = c.Resolve <IMessageStore>(); IEndpointExecutorFactory endpointExecutorFactory = new StoringAsyncEndpointExecutorFactory(endpointExecutorConfig, new AsyncEndpointExecutorOptions(10, TimeSpan.FromSeconds(10)), messageStore); return(endpointExecutorFactory); }) .As <IEndpointExecutorFactory>() .SingleInstance(); // Task<Router> builder.Register( async c => { var checkpointStore = c.Resolve <ICheckpointStore>(); var routerConfig = c.Resolve <RouterConfig>(); var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>(); return(await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory, checkpointStore)); }) .As <Task <Router> >() .SingleInstance(); // ITwinManager builder.Register(c => TwinManager.CreateTwinManager(c.Resolve <IConnectionManager>(), c.Resolve <IMessageConverterProvider>(), Option.Some <IStoreProvider>(new StoreProvider(c.Resolve <IDbStoreProvider>())))) .As <ITwinManager>() .SingleInstance(); } // IClientCredentials "EdgeHubCredentials" builder.Register( c => { var identityFactory = c.Resolve <IClientCredentialsFactory>(); IClientCredentials edgeHubCredentials = this.connectionString.Map(cs => identityFactory.GetWithConnectionString(cs)).GetOrElse( () => identityFactory.GetWithIotEdged(this.edgeDeviceId, this.edgeModuleId)); return(edgeHubCredentials); }) .Named <IClientCredentials>("EdgeHubCredentials") .SingleInstance(); // Task<ICloudProxy> "EdgeHubCloudProxy" builder.Register( async c => { var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials"); var connectionManager = c.Resolve <IConnectionManager>(); Try <ICloudProxy> cloudProxyTry = await connectionManager.CreateCloudConnectionAsync(edgeHubCredentials); if (!cloudProxyTry.Success) { throw new EdgeHubConnectionException("Edge hub is unable to connect to IoT Hub", cloudProxyTry.Exception); } ICloudProxy cloudProxy = cloudProxyTry.Value; return(cloudProxy); }) .Named <Task <ICloudProxy> >("EdgeHubCloudProxy") .SingleInstance(); // Task<IEdgeHub> builder.Register( async c => { Router router = await c.Resolve <Task <Router> >(); IEdgeHub hub = new RoutingEdgeHub(router, c.Resolve <Core.IMessageConverter <IRoutingMessage> >(), c.Resolve <IConnectionManager>(), c.Resolve <ITwinManager>(), this.edgeDeviceId); return(hub); }) .As <Task <IEdgeHub> >() .SingleInstance(); // Task<ConfigUpdater> builder.Register( async c => { IMessageStore messageStore = this.isStoreAndForwardEnabled ? c.Resolve <IMessageStore>() : null; Router router = await c.Resolve <Task <Router> >(); var configUpdater = new ConfigUpdater(router, messageStore); return(configUpdater); }) .As <Task <ConfigUpdater> >() .SingleInstance(); // Task<IConfigSource> builder.Register( async c => { var routeFactory = c.Resolve <RouteFactory>(); if (this.useTwinConfig) { var connectionManager = c.Resolve <IConnectionManager>(); var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials"); var twinCollectionMessageConverter = c.Resolve <Core.IMessageConverter <TwinCollection> >(); var twinMessageConverter = c.Resolve <Core.IMessageConverter <Twin> >(); var twinManager = c.Resolve <ITwinManager>(); ICloudProxy cloudProxy = await c.ResolveNamed <Task <ICloudProxy> >("EdgeHubCloudProxy"); IEdgeHub edgeHub = await c.Resolve <Task <IEdgeHub> >(); IConfigSource edgeHubConnection = await EdgeHubConnection.Create( edgeHubCredentials.Identity as IModuleIdentity, edgeHub, twinManager, connectionManager, cloudProxy, routeFactory, twinCollectionMessageConverter, twinMessageConverter, this.versionInfo ); return(edgeHubConnection); } else { return(new LocalConfigSource(routeFactory, this.routes, this.storeAndForwardConfiguration)); } }) .As <Task <IConfigSource> >() .SingleInstance(); // Task<IConnectionProvider> builder.Register( async c => { IEdgeHub edgeHub = await c.Resolve <Task <IEdgeHub> >(); IConnectionProvider connectionProvider = new ConnectionProvider(c.Resolve <IConnectionManager>(), edgeHub); return(connectionProvider); }) .As <Task <IConnectionProvider> >() .SingleInstance(); base.Load(builder); }
public void EncryptionProvider_Constructor_EmptyKey_ThrowsException() { EncryptionProvider cipher = new EncryptionProvider(string.Empty); }
public void EncryptionProvider_Decrypt_InvalidNonce_ThrowsException() { EncryptionProvider cipher = new EncryptionProvider(validKey); cipher.Decrypt(validCiphertext, invalidNonce); }
public MailController(DaoContext context, JwtUserDto user, EncryptionProvider encryption) { this.context = context; this.user = user; this.encryption = encryption; }
protected override void Load(ContainerBuilder builder) { // IMetricsListener builder.Register( c => this.metricsConfig.Enabled ? new MetricsListener(this.metricsConfig.ListenerConfig, c.Resolve <IMetricsProvider>()) : new NullMetricsListener() as IMetricsListener) .As <IMetricsListener>() .SingleInstance(); // IMetricsProvider builder.Register( c => this.metricsConfig.Enabled ? new MetricsProvider(MetricsConstants.EdgeHubMetricPrefix, this.iothubHostName, this.edgeDeviceId, this.metricsConfig.HistogramMaxAge) : new NullMetricsProvider() as IMetricsProvider) .As <IMetricsProvider>() .SingleInstance(); // ISignatureProvider builder.Register( c => { ISignatureProvider signatureProvider = this.edgeHubConnectionString.Map( cs => { IotHubConnectionStringBuilder csBuilder = IotHubConnectionStringBuilder.Create(cs); return(new SharedAccessKeySignatureProvider(csBuilder.SharedAccessKey) as ISignatureProvider); }) .GetOrElse( () => { string edgeHubGenerationId = this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Generation ID missing")); string workloadUri = this.workloadUri.Expect(() => new InvalidOperationException("workloadUri is missing")); string workloadApiVersion = this.workloadApiVersion.Expect(() => new InvalidOperationException("workloadUri version is missing")); return(new HttpHsmSignatureProvider(this.edgeHubModuleId, edgeHubGenerationId, workloadUri, workloadApiVersion, Constants.WorkloadApiVersion) as ISignatureProvider); }); return(signatureProvider); }) .As <ISignatureProvider>() .SingleInstance(); // Detect system environment builder.Register(c => new SystemEnvironment()) .As <ISystemEnvironment>() .SingleInstance(); // DataBase options builder.Register(c => new RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), this.optimizeForPerformance, this.storageMaxTotalWalSize, this.storageMaxOpenFiles, this.storageLogLevel)) .As <IRocksDbOptionsProvider>() .SingleInstance(); if (!this.usePersistentStorage && this.useBackupAndRestore) { // Backup and restore serialization builder.Register(c => new ProtoBufDataBackupRestore()) .As <IDataBackupRestore>() .SingleInstance(); } // IStorageSpaceChecker builder.Register( c => { IStorageSpaceChecker spaceChecker = !this.usePersistentStorage ? new MemorySpaceChecker(() => 0L) as IStorageSpaceChecker : new NullStorageSpaceChecker(); return(spaceChecker); }) .As <IStorageSpaceChecker>() .SingleInstance(); // IDbStoreProvider builder.Register( async c => { var loggerFactory = c.Resolve <ILoggerFactory>(); ILogger logger = loggerFactory.CreateLogger(typeof(RoutingModule)); if (this.usePersistentStorage) { // Create partitions for messages and twins var partitionsList = new List <string> { Core.Constants.MessageStorePartitionKey, Core.Constants.TwinStorePartitionKey, Core.Constants.CheckpointStorePartitionKey }; try { IDbStoreProvider dbStoreProvider = DbStoreProvider.Create( c.Resolve <IRocksDbOptionsProvider>(), this.storagePath, partitionsList); logger.LogInformation($"Created persistent store at {this.storagePath}"); return(dbStoreProvider); } catch (Exception ex) when(!ex.IsFatal()) { logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store."); IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c); return(dbStoreProvider); } } else { logger.LogInformation($"Using in-memory store"); IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c); return(dbStoreProvider); } }) .As <Task <IDbStoreProvider> >() .SingleInstance(); // Task<Option<IEncryptionProvider>> builder.Register( async c => { Option <IEncryptionProvider> encryptionProviderOption = await this.workloadUri .Map( async uri => { var encryptionProvider = await EncryptionProvider.CreateAsync( this.storagePath, new Uri(uri), this.workloadApiVersion.Expect(() => new InvalidOperationException("Missing workload API version")), Constants.WorkloadApiVersion, this.edgeHubModuleId, this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")), Constants.InitializationVectorFileName) as IEncryptionProvider; return(Option.Some(encryptionProvider)); }) .GetOrElse(() => Task.FromResult(Option.None <IEncryptionProvider>())); return(encryptionProviderOption); }) .As <Task <Option <IEncryptionProvider> > >() .SingleInstance(); // Task<IStoreProvider> builder.Register(async c => { var dbStoreProvider = await c.Resolve <Task <IDbStoreProvider> >(); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); return(storeProvider); }) .As <Task <IStoreProvider> >() .SingleInstance(); // Task<IMetadataStore> builder.Register( async c => { var storeProvider = await c.Resolve <Task <IStoreProvider> >(); IKeyValueStore <string, string> entityStore = storeProvider.GetEntityStore <string, string>("ProductInfo", "MetadataStore"); IMetadataStore metadataStore = new MetadataStore(entityStore, this.productInfo); return(metadataStore); }) .As <Task <IMetadataStore> >() .SingleInstance(); // ITokenProvider builder.Register(c => new ClientTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, TimeSpan.FromHours(1))) .Named <ITokenProvider>("EdgeHubClientAuthTokenProvider") .SingleInstance(); // ITokenProvider builder.Register( c => { string deviceId = WebUtility.UrlEncode(this.edgeDeviceId); string moduleId = WebUtility.UrlEncode(this.edgeHubModuleId); return(new ClientTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, deviceId, moduleId, TimeSpan.FromHours(1))); }) .Named <ITokenProvider>("EdgeHubServiceAuthTokenProvider") .SingleInstance(); builder.Register( c => { var loggerFactory = c.Resolve <ILoggerFactory>(); var logger = loggerFactory.CreateLogger <RoutingModule>(); return(Proxy.Parse(this.proxy, logger)); }) .As <Option <IWebProxy> >() .SingleInstance(); // IServiceIdentityHierarchy builder.Register <IServiceIdentityHierarchy>( c => { if (this.nestedEdgeEnabled) { return(new ServiceIdentityTree(this.edgeDeviceId)); } else { return(new ServiceIdentityDictionary(this.edgeDeviceId)); } }) .As <IServiceIdentityHierarchy>() .SingleInstance(); // Task<IDeviceScopeIdentitiesCache> builder.Register( async c => { IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache; if (this.authenticationMode == AuthenticationMode.CloudAndScope || this.authenticationMode == AuthenticationMode.Scope) { var edgeHubTokenProvider = c.ResolveNamed <ITokenProvider>("EdgeHubServiceAuthTokenProvider"); var proxy = c.Resolve <Option <IWebProxy> >(); IServiceIdentityHierarchy serviceIdentityHierarchy = c.Resolve <IServiceIdentityHierarchy>(); string hostName = this.gatewayHostName.GetOrElse(this.iothubHostName); IDeviceScopeApiClientProvider securityScopesApiClientProvider = new DeviceScopeApiClientProvider(hostName, this.edgeDeviceId, this.edgeHubModuleId, 10, edgeHubTokenProvider, serviceIdentityHierarchy, proxy); IServiceProxy serviceProxy = new ServiceProxy(securityScopesApiClientProvider, this.nestedEdgeEnabled); IKeyValueStore <string, string> encryptedStore = await GetEncryptedStore(c, "DeviceScopeCache"); deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceIdentityHierarchy, serviceProxy, encryptedStore, this.scopeCacheRefreshRate, this.scopeCacheRefreshDelay); } else { deviceScopeIdentitiesCache = new NullDeviceScopeIdentitiesCache(); } return(deviceScopeIdentitiesCache); }) .As <Task <IDeviceScopeIdentitiesCache> >() .AutoActivate() .SingleInstance(); // IRegistryApiClient builder.Register( c => { string upstreamHostname = this.gatewayHostName.GetOrElse(this.iothubHostName); var proxy = c.Resolve <Option <IWebProxy> >(); var edgeHubTokenProvider = c.ResolveNamed <ITokenProvider>("EdgeHubServiceAuthTokenProvider"); return(new RegistryOnBehalfOfApiClient(upstreamHostname, proxy, edgeHubTokenProvider)); }) .As <IRegistryOnBehalfOfApiClient>() .SingleInstance(); // Task<ICredentialsCache> builder.Register( async c => { ICredentialsCache underlyingCredentialsCache; if (this.persistTokens) { IKeyValueStore <string, string> encryptedStore = await GetEncryptedStore(c, "CredentialsCache"); return(new PersistedTokenCredentialsCache(encryptedStore)); } else { underlyingCredentialsCache = new NullCredentialsCache(); } ICredentialsCache credentialsCache; if (this.nestedEdgeEnabled) { credentialsCache = new NestedCredentialsCache(underlyingCredentialsCache); } else { credentialsCache = new CredentialsCache(underlyingCredentialsCache); } return(credentialsCache); }) .As <Task <ICredentialsCache> >() .SingleInstance(); // Task<IAuthenticator> builder.Register( async c => { IAuthenticator tokenAuthenticator; IAuthenticator certificateAuthenticator; IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache; var credentialsCacheTask = c.Resolve <Task <ICredentialsCache> >(); // by default regardless of how the authenticationMode, X.509 certificate validation will always be scoped deviceScopeIdentitiesCache = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >(); certificateAuthenticator = new DeviceScopeCertificateAuthenticator(deviceScopeIdentitiesCache, new NullAuthenticator(), this.trustBundle, true, this.nestedEdgeEnabled); switch (this.authenticationMode) { case AuthenticationMode.Cloud: tokenAuthenticator = await this.GetCloudTokenAuthenticator(c); break; case AuthenticationMode.Scope: tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, new NullAuthenticator(), true, true, this.nestedEdgeEnabled); break; default: IAuthenticator cloudTokenAuthenticator = await this.GetCloudTokenAuthenticator(c); tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, cloudTokenAuthenticator, true, true, this.nestedEdgeEnabled); break; } ICredentialsCache credentialsCache = await credentialsCacheTask; return(new Authenticator(tokenAuthenticator, certificateAuthenticator, credentialsCache) as IAuthenticator); }) .As <Task <IAuthenticator> >() .SingleInstance(); // IClientCredentialsFactory builder.Register(c => new ClientCredentialsFactory(c.Resolve <IIdentityProvider>(), this.productInfo)) .As <IClientCredentialsFactory>() .SingleInstance(); // IClientCredentials "EdgeHubCredentials" builder.Register( c => { var identityFactory = c.Resolve <IClientCredentialsFactory>(); IClientCredentials edgeHubCredentials = this.edgeHubConnectionString.Map(cs => identityFactory.GetWithConnectionString(cs)).GetOrElse( () => identityFactory.GetWithIotEdged(this.edgeDeviceId, this.edgeHubModuleId)); return(edgeHubCredentials); }) .Named <IClientCredentials>("EdgeHubCredentials") .SingleInstance(); // ServiceIdentity "EdgeHubIdentity" builder.Register( c => { return(new ServiceIdentity( this.edgeDeviceId, this.edgeHubModuleId, deviceScope: null, parentScopes: new List <string>(), this.edgeHubGenerationId.GetOrElse("0"), capabilities: new List <string>(), new ServiceAuthentication(ServiceAuthenticationType.None), ServiceIdentityStatus.Enabled)); }) .Named <ServiceIdentity>("EdgeHubIdentity") .SingleInstance(); // ConnectionReauthenticator builder.Register( async c => { var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials"); var connectionManagerTask = c.Resolve <Task <IConnectionManager> >(); var authenticatorTask = c.Resolve <Task <IAuthenticator> >(); var credentialsCacheTask = c.Resolve <Task <ICredentialsCache> >(); var deviceScopeIdentitiesCacheTask = c.Resolve <Task <IDeviceScopeIdentitiesCache> >(); var deviceConnectivityManager = c.Resolve <IDeviceConnectivityManager>(); IConnectionManager connectionManager = await connectionManagerTask; IAuthenticator authenticator = await authenticatorTask; ICredentialsCache credentialsCache = await credentialsCacheTask; IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await deviceScopeIdentitiesCacheTask; var connectionReauthenticator = new ConnectionReauthenticator( connectionManager, authenticator, credentialsCache, deviceScopeIdentitiesCache, TimeSpan.FromMinutes(5), edgeHubCredentials.Identity, deviceConnectivityManager); return(connectionReauthenticator); }) .As <Task <ConnectionReauthenticator> >() .SingleInstance(); base.Load(builder); }
/// <summary> /// Sign an existing account in. /// </summary> /// <param name="model">User details to validate login.</param> /// <returns>Null on failure, User object on success.</returns> public User Login(User model) { User result = null; try { using (DataConnection db = new DataConnection()) { User query = (from user in db.User where user.Username == model.Username && user.Password == EncryptionProvider.Encrypt(model.Password) select user).SingleOrDefault(); if (query != null) { model.Id = query.Id; result = new User() { Id = query.Id, Username = query.Username, Password = query.Password, Role = query.Role }; } } } catch (Exception) { result = new User() { Role = "Error" }; } return(result); }
public static void SaveSetting(string key, string setting) { var encrypted = EncryptionProvider.Encrypt(setting, CurrentApp.AppId.ToString()); ApplicationData.Current.LocalSettings.Values[key] = encrypted; }
protected override void Load(ContainerBuilder builder) { // ISignatureProvider builder.Register( c => { ISignatureProvider signatureProvider = this.edgeHubConnectionString.Map( cs => { IotHubConnectionStringBuilder csBuilder = IotHubConnectionStringBuilder.Create(cs); return(new SharedAccessKeySignatureProvider(csBuilder.SharedAccessKey) as ISignatureProvider); }) .GetOrElse( () => { string edgeHubGenerationId = this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Generation ID missing")); string workloadUri = this.workloadUri.Expect(() => new InvalidOperationException("workloadUri is missing")); return(new HttpHsmSignatureProvider(this.edgeHubModuleId, edgeHubGenerationId, workloadUri, Constants.WorkloadApiVersion) as ISignatureProvider); }); return(signatureProvider); }) .As <ISignatureProvider>() .SingleInstance(); // Detect system environment builder.Register(c => new SystemEnvironment()) .As <ISystemEnvironment>() .SingleInstance(); // DataBase options builder.Register(c => new RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), this.optimizeForPerformance)) .As <IRocksDbOptionsProvider>() .SingleInstance(); // IDbStoreProvider builder.Register( c => { var loggerFactory = c.Resolve <ILoggerFactory>(); ILogger logger = loggerFactory.CreateLogger(typeof(RoutingModule)); if (this.usePersistentStorage) { // Create partitions for messages and twins var partitionsList = new List <string> { Core.Constants.MessageStorePartitionKey, Core.Constants.TwinStorePartitionKey, Core.Constants.CheckpointStorePartitionKey }; try { IDbStoreProvider dbStoreprovider = DbStoreProvider.Create( c.Resolve <IRocksDbOptionsProvider>(), this.storagePath, partitionsList); logger.LogInformation($"Created persistent store at {this.storagePath}"); return(dbStoreprovider); } catch (Exception ex) when(!ExceptionEx.IsFatal(ex)) { logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store."); return(new InMemoryDbStoreProvider()); } } else { logger.LogInformation($"Using in-memory store"); return(new InMemoryDbStoreProvider()); } }) .As <IDbStoreProvider>() .SingleInstance(); // Task<Option<IEncryptionProvider>> builder.Register( async c => { Option <IEncryptionProvider> encryptionProviderOption = await this.workloadUri .Map( async uri => { var encryptionProvider = await EncryptionProvider.CreateAsync( this.storagePath, new Uri(uri), Constants.WorkloadApiVersion, this.edgeHubModuleId, this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")), Constants.InitializationVectorFileName) as IEncryptionProvider; return(Option.Some(encryptionProvider)); }) .GetOrElse(() => Task.FromResult(Option.None <IEncryptionProvider>())); return(encryptionProviderOption); }) .As <Task <Option <IEncryptionProvider> > >() .SingleInstance(); // IStoreProvider builder.Register(c => new StoreProvider(c.Resolve <IDbStoreProvider>())) .As <IStoreProvider>() .SingleInstance(); // ITokenProvider builder.Register(c => new ClientTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, TimeSpan.FromHours(1))) .Named <ITokenProvider>("EdgeHubClientAuthTokenProvider") .SingleInstance(); // ITokenProvider builder.Register( c => { string deviceId = WebUtility.UrlEncode(this.edgeDeviceId); string moduleId = WebUtility.UrlEncode(this.edgeHubModuleId); return(new ClientTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, deviceId, moduleId, TimeSpan.FromHours(1))); }) .Named <ITokenProvider>("EdgeHubServiceAuthTokenProvider") .SingleInstance(); // Task<IDeviceScopeIdentitiesCache> builder.Register( async c => { IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache; if (this.authenticationMode == AuthenticationMode.CloudAndScope || this.authenticationMode == AuthenticationMode.Scope) { var edgeHubTokenProvider = c.ResolveNamed <ITokenProvider>("EdgeHubServiceAuthTokenProvider"); IDeviceScopeApiClient securityScopesApiClient = new DeviceScopeApiClient(this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, 10, edgeHubTokenProvider); IServiceProxy serviceProxy = new ServiceProxy(securityScopesApiClient); IKeyValueStore <string, string> encryptedStore = await GetEncryptedStore(c, "DeviceScopeCache"); deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy, encryptedStore, this.scopeCacheRefreshRate); } else { deviceScopeIdentitiesCache = new NullDeviceScopeIdentitiesCache(); } return(deviceScopeIdentitiesCache); }) .As <Task <IDeviceScopeIdentitiesCache> >() .AutoActivate() .SingleInstance(); // Task<ICredentialsCache> builder.Register( async c => { ICredentialsCache underlyingCredentialsCache; if (this.persistTokens) { IKeyValueStore <string, string> encryptedStore = await GetEncryptedStore(c, "CredentialsCache"); return(new PersistedTokenCredentialsCache(encryptedStore)); } else { underlyingCredentialsCache = new NullCredentialsCache(); } ICredentialsCache credentialsCache = new CredentialsCache(underlyingCredentialsCache); return(credentialsCache); }) .As <Task <ICredentialsCache> >() .SingleInstance(); // Task<IAuthenticator> builder.Register( async c => { IAuthenticator tokenAuthenticator; IAuthenticator certificateAuthenticator; IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache; var credentialsCacheTask = c.Resolve <Task <ICredentialsCache> >(); // by default regardless of how the authenticationMode, X.509 certificate validation will always be scoped deviceScopeIdentitiesCache = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >(); certificateAuthenticator = new DeviceScopeCertificateAuthenticator(deviceScopeIdentitiesCache, new NullAuthenticator(), this.trustBundle, true); switch (this.authenticationMode) { case AuthenticationMode.Cloud: tokenAuthenticator = await this.GetCloudTokenAuthenticator(c); break; case AuthenticationMode.Scope: tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, new NullAuthenticator(), true, true); break; default: IAuthenticator cloudTokenAuthenticator = await this.GetCloudTokenAuthenticator(c); tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, cloudTokenAuthenticator, true, true); break; } ICredentialsCache credentialsCache = await credentialsCacheTask; return(new Authenticator(tokenAuthenticator, certificateAuthenticator, credentialsCache) as IAuthenticator); }) .As <Task <IAuthenticator> >() .SingleInstance(); // IClientCredentialsFactory builder.Register(c => new ClientCredentialsFactory(c.Resolve <IIdentityProvider>(), this.productInfo)) .As <IClientCredentialsFactory>() .SingleInstance(); // ConnectionReauthenticator builder.Register( async c => { var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials"); var connectionManagerTask = c.Resolve <Task <IConnectionManager> >(); var authenticatorTask = c.Resolve <Task <IAuthenticator> >(); var credentialsCacheTask = c.Resolve <Task <ICredentialsCache> >(); var deviceScopeIdentitiesCacheTask = c.Resolve <Task <IDeviceScopeIdentitiesCache> >(); var deviceConnectivityManager = c.Resolve <IDeviceConnectivityManager>(); IConnectionManager connectionManager = await connectionManagerTask; IAuthenticator authenticator = await authenticatorTask; ICredentialsCache credentialsCache = await credentialsCacheTask; IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await deviceScopeIdentitiesCacheTask; var connectionReauthenticator = new ConnectionReauthenticator( connectionManager, authenticator, credentialsCache, deviceScopeIdentitiesCache, TimeSpan.FromMinutes(5), edgeHubCredentials.Identity, deviceConnectivityManager); return(connectionReauthenticator); }) .As <Task <ConnectionReauthenticator> >() .SingleInstance(); base.Load(builder); }
/// <summary> /// Computes the unique key of the <see cref="Type"/>. /// </summary> /// <param name="type"></param> /// <returns></returns> public static string Key(this Type type) { return(EncryptionProvider.Hash(type.AssemblyQualifiedName())); }
private void InitializeApp(IServiceCollection services, AppSettings appSettings) { //singleton pattern here was a huge mistake, i'm going to fix this. LiteDbConfigurationRepository configurationRepository = new LiteDbConfigurationRepository(databaseLocator.GetConfigurationRepositoryConnectionString()); appConfig = configurationRepository.GetAppConfig(); ActiveDirectoryRepository activeDirectory = new ActiveDirectoryRepository(); EncryptionProvider cipher = new EncryptionProvider(appConfig.EncryptionKey); services.AddSingleton <EncryptionProvider>(cipher); services.AddSingleton <IActiveDirectoryAuthenticator>(activeDirectory); services.AddSingleton <IActiveDirectoryRepository>(activeDirectory); IdentityAuthenticationLogic identityAuthenticationLogic = new IdentityAuthenticationLogic(configurationRepository, activeDirectory); services.AddSingleton <IdentityAuthenticationLogic>(); ICertificateRepository certificateRepository = new LiteDbCertificateRepository(databaseLocator.GetCertificateRepositoryConnectionString()); RuntimeCacheRepository runtimeCacheRepository = null; LiteDbAuditRepository auditRepository = new LiteDbAuditRepository(databaseLocator.GetAuditRepositoryConnectionString()); IAuditLogic auditLogic = new AuditLogic(auditRepository, configurationRepository); services.AddSingleton <IAuditLogic>(auditLogic); IAuthorizationLogic authorizationLogic = new AuthorizationLogic(configurationRepository, auditLogic); IScriptManagementLogic scriptManagement = new ScriptManagementLogic(configurationRepository, authorizationLogic); services.AddSingleton <IScriptManagementLogic>(scriptManagement); IPowershellEngine powershellEngine = new PowershellEngine(auditLogic, scriptManagement); services.AddSingleton <IPowershellEngine>(powershellEngine); RoleManagementLogic roleManagementLogic = new RoleManagementLogic(configurationRepository, authorizationLogic); services.AddSingleton <RoleManagementLogic>(roleManagementLogic); UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository, authorizationLogic); services.AddSingleton <UserManagementLogic>(userManagementLogic); SecurityPrincipalLogic securityPrincipalLogic = new SecurityPrincipalLogic(roleManagementLogic, userManagementLogic); services.AddSingleton <SecurityPrincipalLogic>(); AdcsTemplateLogic adcsTemplateLogic = new AdcsTemplateLogic(configurationRepository, activeDirectory); services.AddSingleton <AdcsTemplateLogic>(adcsTemplateLogic); services.AddSingleton <IAuthorizationLogic>(authorizationLogic); services.AddSingleton <IConfigurationRepository>(configurationRepository); ICertificateProvider certificateProvider = new Win32CertificateProvider(); services.AddSingleton <ICertificateProvider>(certificateProvider); services.AddSingleton <ICertificateRepository>(certificateRepository); ActiveDirectoryIdentityProviderLogic activeDirectoryIdentityProviderLogic = new ActiveDirectoryIdentityProviderLogic(configurationRepository); services.AddSingleton <ActiveDirectoryIdentityProviderLogic>(activeDirectoryIdentityProviderLogic); certificateManagementLogic = new CertificateManagementLogic( configurationRepository, certificateRepository, authorizationLogic, auditLogic, securityPrincipalLogic, cipher); services.AddSingleton <CertificateManagementLogic>(certificateManagementLogic); PrivateCertificateProcessing privateCertificateProcessing = new PrivateCertificateProcessing(certificateRepository, configurationRepository, certificateProvider, authorizationLogic, adcsTemplateLogic, auditLogic); services.AddSingleton <IPrivateCertificateProcessing>(privateCertificateProcessing); services.AddSingleton <NodeLogic>(new NodeLogic(configurationRepository, authorizationLogic, activeDirectoryIdentityProviderLogic, powershellEngine, auditLogic, certificateManagementLogic, privateCertificateProcessing)); services.AddSingleton <IRuntimeConfigurationState>( new RuntimeConfigurationState(configurationRepository, runtimeCacheRepository) { InitialSetupComplete = initialSetupComplete }); services.AddSingleton <IClientsideConfigurationProvider>(new ClientsideConfigurationProvider(configurationRepository)); services.AddSingleton <AnalyticsLogic>(new AnalyticsLogic(configurationRepository, certificateRepository, auditRepository)); services.AddSingleton <DataRenderingProvider>(new DataRenderingProvider()); oidcLogic = new OpenIdConnectIdentityProviderLogic(configurationRepository, authorizationLogic); services.AddSingleton <IOpenIdConnectIdentityProviderLogic>(oidcLogic); }
/// <summary> /// Initializes a new instance of the <see cref="MessageServer"/> class. /// </summary> /// <param name="container">The componentry container.</param> /// <param name="messagingAdapter">The message bus adapter.</param> /// <param name="headerSerializer">The header serializer.</param> /// <param name="requestSerializer">The request serializer.</param> /// <param name="responseSerializer">The response serializer.</param> /// <param name="compressor">The message compressor.</param> /// <param name="encryption">The encryption configuration.</param> /// <param name="serviceName">The service name.</param> /// <param name="requestAddress">The inbound zmq network address.</param> /// <param name="responseAddress">The outbound zmq network address.</param> protected MessageServer( IComponentryContainer container, IMessageBusAdapter messagingAdapter, ISerializer <Dictionary <string, string> > headerSerializer, IMessageSerializer <Request> requestSerializer, IMessageSerializer <Response> responseSerializer, ICompressor compressor, EncryptionSettings encryption, Label serviceName, ZmqNetworkAddress requestAddress, ZmqNetworkAddress responseAddress) : base(container, messagingAdapter) { this.serverId = new ServerId(this.Name.Value); this.headerSerializer = headerSerializer; this.requestSerializer = requestSerializer; this.responseSerializer = responseSerializer; this.compressor = compressor; this.serviceName = serviceName; this.socketInbound = new RouterSocket { Options = { Identity = Encoding.UTF8.GetBytes($"{this.serviceName.Value}-{this.Name.Value}"), Linger = TimeSpan.FromSeconds(1), TcpKeepalive = true, TcpKeepaliveInterval = TimeSpan.FromSeconds(2), RouterHandover = true, }, }; this.socketOutbound = new RouterSocket { Options = { Identity = Encoding.UTF8.GetBytes($"{this.serviceName.Value}-{this.Name.Value}"), Linger = TimeSpan.FromSeconds(1), TcpKeepalive = true, TcpKeepaliveInterval = TimeSpan.FromSeconds(2), RouterMandatory = true, RouterHandover = true, }, }; this.requestAddress = requestAddress; this.responseAddress = responseAddress; this.peers = new Dictionary <ClientId, SessionId>(); this.correlationIndex = new ConcurrentDictionary <Guid, Address>(); this.queue = new MessageQueue( container, this.socketInbound, this.socketOutbound, this.HandlePayload); if (encryption.UseEncryption) { EncryptionProvider.SetupSocket(encryption, this.socketInbound); this.Logger.LogInformation( LogId.Network, $"{encryption.Algorithm} encryption setup for {this.requestAddress}"); EncryptionProvider.SetupSocket(encryption, this.socketOutbound); this.Logger.LogInformation( LogId.Network, $"{encryption.Algorithm} encryption setup for {this.responseAddress}"); } else { this.Logger.LogWarning( LogId.Network, $"No encryption setup for {this.requestAddress}"); this.Logger.LogWarning( LogId.Network, $"No encryption setup for {this.responseAddress}"); } this.ReceivedCount = 0; this.SentCount = 0; }