private void Initialize(IEndPoint sourceEndPoint, IAsymmetricKey key, ISymmetricKey dummySymmetricKey) { Key = key; DummySymmetricKey = dummySymmetricKey; MessageHandler.Start(); NetworkHandler.Start(sourceEndPoint); }
public byte[] Decrypt(ISymmetricKey key, byte[] data) { if (!(key is AesSymmetricKey)) { throw new ArgumentException("Wrong key type", nameof(key)); } var aesKey = (AesSymmetricKey)key; using (var rijndaelManaged = new RijndaelManaged()) { rijndaelManaged.KeySize = 128; rijndaelManaged.Key = aesKey.Key; rijndaelManaged.GenerateIV(); using (var memoryStream = new MemoryStream(data)) { var iv = new byte[16]; memoryStream.Read(iv, 0, 16); rijndaelManaged.IV = iv; var decryptor = rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV); using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { using (var binaryReader = new BigEndianBinaryReader(cryptoStream)) { return(binaryReader.ReadBytes(binaryReader.ReadInt32())); } } } } }
public byte[] Encrypt(ISymmetricKey key, byte[] data) { if (!(key is AesSymmetricKey)) { throw new ArgumentException("Wrong key type", nameof(key)); } var aesKey = (AesSymmetricKey)key; using (var rijndaelManaged = new RijndaelManaged()) { rijndaelManaged.KeySize = 128; rijndaelManaged.Key = aesKey.Key; rijndaelManaged.GenerateIV(); using (var memoryStream = new MemoryStream()) { memoryStream.Write(rijndaelManaged.IV, 0, 16); var encryptor = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV); using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { using (var binaryWriter = new BigEndianBinaryWriter(cryptoStream)) { binaryWriter.Write(data.Length); binaryWriter.Write(data); } return(memoryStream.ToArray()); } } } }
public RecipientInfo Generate(ISymmetricKey contentEncryptionKey) { byte[] encryptedKeyBytes; try { encryptedKeyBytes = GenerateWrappedKey(contentEncryptionKey); } catch (Exception e) { throw new CmsException("exception wrapping content key: " + e.Message, e); } RecipientIdentifier recipId; if (issuerAndSerial != null) { recipId = new RecipientIdentifier(issuerAndSerial); } else { recipId = new RecipientIdentifier(new DerOctetString(subjectKeyIdentifier)); } return(new RecipientInfo(new KeyTransRecipientInfo(recipId, AlgorithmDetails, new DerOctetString(encryptedKeyBytes)))); }
public ConnectionRequestConfirmReplyMessage(List <DnmpNode> clients, ushort newId, IEndPoint newEndPoint, IEndPointFactory endPointFactory, ISymmetricKey key) { Clients = clients; NewId = newId; NewEndPoint = newEndPoint; this.endPointFactory = endPointFactory; this.key = key; }
public byte[] Decrypt(ISymmetricKey key, byte[] data) //-V3013 { if (!(key is PlainSymmetricKey)) { throw new ArgumentException("Wrong key type", nameof(key)); } return(data); }
private CmsEnvelopedData doGenerate( ICmsTypedData content, ICipherBuilderWithKey<AlgorithmIdentifier> contentEncryptor) { Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); AlgorithmIdentifier encAlgId; Asn1OctetString encContent; MemoryOutputStream bOut = new MemoryOutputStream(); try { ICipher cOut = contentEncryptor.BuildCipher(bOut); content.Write(cOut.Stream); cOut.Stream.Close(); } catch (IOException e) { throw new CmsException(e.Message, e); } byte[] encryptedContent = bOut.ToArray(); encAlgId = contentEncryptor.AlgorithmDetails; encContent = new BerOctetString(encryptedContent); ISymmetricKey encKey = contentEncryptor.Key; for (IEnumerator<IRecipientInfoGenerator> it = recipientInfoGenerators.GetEnumerator(); it.MoveNext();) { IRecipientInfoGenerator recipient = (IRecipientInfoGenerator)it.Current; recipientInfos.Add(recipient.Generate(encKey)); } EncryptedContentInfo eci = new EncryptedContentInfo( content.ContentType, encAlgId, encContent); Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(new Dictionary<string, object>()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(originatorInfo, new DerSet(recipientInfos), eci, unprotectedAttrSet)); return new CmsEnvelopedData(contentInfo); }
public override HMAC Initialize(ISymmetricKey key) { if (key == null) { throw new ArgumentNullException("key"); } SetKey(key.GetBytes()); return(this); }
public async Task EncryptAsync(Stream @in, Stream @out, ISymmetricKey symmetricKey, SymmetricAlgorithmType type) { if (@in == null) throw new ArgumentNullException(nameof(@in)); if (@out == null) throw new ArgumentNullException(nameof(@out)); if (symmetricKey == null) throw new ArgumentNullException(nameof(symmetricKey)); using (var rm = _symmetricAlgorithmFactory.Create(type)) using (var cs = new CryptoStream(@out, rm.CreateEncryptor(symmetricKey.Key, symmetricKey.IV), CryptoStreamMode.Write)) { await @in.CopyToAsync(cs); } }
public static IReturnsResult<ISymmetricCryptoService> MockDecryptAsync(this Mock<ISymmetricCryptoService> service, ISymmetricKey key, SymmetricAlgorithmType symmetricAlgorithmType, byte[] source, byte[] exp) { return service.Setup(x => x.DecryptAsync(It.IsAny<Stream>(), It.IsAny<Stream>(), key, symmetricAlgorithmType)) .Returns((Stream i, Stream o, ISymmetricKey sk, SymmetricAlgorithmType type) => { var msi = (MemoryStream) i; var mso = (MemoryStream) o; Assert.AreEqual(0, o.Length); mso.Write(exp, 0, exp.Length); CollectionAssert.AreEqual(source, msi.ToArray()); return Task.CompletedTask; }); }
protected override byte[] GenerateWrappedKey(ISymmetricKey contentKey) { AsymmetricRsaPublicKey rsaKey = asymmetricPublicKey as AsymmetricRsaPublicKey; if (rsaKey != null) { IKeyWrapper <FipsRsa.OaepWrapParameters> wrapper = CryptoServicesRegistrar.CreateService(rsaKey, new Security.SecureRandom()).CreateKeyWrapper(FipsRsa.WrapOaep.WithDigest(FipsShs.Sha1)); byte[] encKey = wrapper.Wrap(contentKey.GetKeyBytes()).Collect(); return(encKey); } throw new InvalidOperationException("algorithm for public key not matched"); }
public PkixContentEncryptor(DerObjectIdentifier encAlgorithm, SecureRandom random) { key = keyGenerators[encAlgorithm](random); algId = Utils.GetEncryptionSchemeIdentifier(encAlgorithm, random); IParameters <Algorithm> cipherParams = Utils.GetCipherParameters(algId); if (Utils.IsBlockMode(cipherParams.Algorithm)) { cipherBuilder = new PkixBlockCipherBuilder(algId, Utils.CreateBlockEncryptorBuilder(encAlgorithm, key.GetKeyBytes(), cipherParams)); } else if (Utils.IsAeadMode(cipherParams.Algorithm)) { cipherBuilder = new PkixAeadCipherBuilder(algId, Utils.CreateAeadEncryptorBuilder(encAlgorithm, key.GetKeyBytes(), cipherParams)); } else { cipherBuilder = new PkixCipherBuilder(algId, Utils.CreateEncryptorBuilder(encAlgorithm, key.GetKeyBytes(), cipherParams)); } }
public async Task ConnectAsync(IEndPoint endPoint, IEndPoint sourceEndPoint, bool invokeEvents, IAsymmetricKey key, ISymmetricKey dummySymmetricKey, byte[] selfCustomData) { await ConnectManyAsync(new[] { endPoint }, sourceEndPoint, invokeEvents, key, dummySymmetricKey, selfCustomData); }
internal KeyedHmacEngineProvider(ISymmetricKey key, HmacEngineProvider provider) : base(provider.MacSize * 8) { this.key = key; this.provider = provider; }
internal HmacProvider(ISymmetricKey key) { this.key = key; }
public abstract HMAC Initialize(ISymmetricKey key);
public static byte[] Decrypt(ISymmetricKey key, byte[] data) { return(key.GetAlgorithmInstance().Decrypt(key, data)); }
public async Task StartAsFirstNodeAsync(IEndPoint sourceEndPoint, IEndPoint publicEndPoint, IAsymmetricKey key, ISymmetricKey dummySymmetricKey, byte[] selfCustomData) { if (CurrentStatus != ClientStatus.NotConnected) { return; } if (selfCustomData.Length > 65000) //TODO { throw new DnmpException("Custom data length is larger than 65000 bytes"); } SelfCustomData = selfCustomData; SelfClient = new DnmpNode { Id = 0, EndPoint = publicEndPoint, CustomData = SelfCustomData }; Initialize(sourceEndPoint, key, dummySymmetricKey); CurrentStatus = ClientStatus.Connected; logger.Info($"Started as first node on {sourceEndPoint} [{publicEndPoint}]"); OnClientConnected?.Invoke(SelfClient.Id); OnConnected?.Invoke(); MessageInterface.Initialize(SelfClient.Id); await Task.Delay(0); }
public async Task ConnectManyAsync(IEndPoint[] endPoints, IEndPoint sourceEndPoint, bool invokeEvents, IAsymmetricKey key, ISymmetricKey dummySymmetricKey, byte[] selfCustomData) { if (CurrentStatus != ClientStatus.NotConnected) { return; } if (selfCustomData.Length > 65000) { throw new DnmpException("Custom data length is larger than 65000 bytes"); } SelfCustomData = selfCustomData; Initialize(sourceEndPoint, key, dummySymmetricKey); CurrentStatus = ClientStatus.Connecting; if (invokeEvents) { connectionTimeoutEvent = EventQueue.AddEvent(_ => { NetworkHandler.Stop(); MessageHandler.Stop(); ClientsById.Clear(); CurrentStatus = ClientStatus.NotConnected; OnConnectionTimeout?.Invoke(); }, null, DateTime.Now.AddMilliseconds(Config.ConnectionTimeout)); } else { connectionTimeoutEvent = EventQueue.AddEvent(_ => { CurrentStatus = ClientStatus.NotConnected; }, null, DateTime.Now.AddMilliseconds(Config.ConnectionTimeout)); } logger.Debug($"Trying to connect to {endPoints.Length} endpoints. First: {endPoints.FirstOrDefault()}"); foreach (var endPoint in endPoints) { logger.Debug($"Trying to connect to {endPoint}"); try { NetworkHandler.SendBaseMessage( new BaseMessage(new ConnectionRequestMessage(key.GetNetworkId(), true), 0xFFFF, 0xFFFF), endPoint); } catch (Exception e) { logger.Warn($"Caught exception while trying to connect: {e.GetType().Name}('{e.Message}')"); } } if (invokeEvents) { return; } SpinWait.SpinUntil(() => CurrentStatus == ClientStatus.Connecting || CurrentStatus == ClientStatus.Handshaking); if (CurrentStatus == ClientStatus.NotConnected) { throw new TimeoutException("Connection timeout"); } await Task.Delay(0); }
protected abstract byte[] GenerateWrappedKey(ISymmetricKey contentKey);
public ConnectionRequestConfirmReplyMessage(byte[] data, IEndPointFactory endPointFactory, ISymmetricKey key) { var dataReader = new BigEndianBinaryReader(new MemoryStream(SymmetricHelper.Decrypt(key, data))); NewId = dataReader.ReadUInt16(); NewEndPoint = endPointFactory.DeserializeEndPoint(dataReader.ReadBytes(dataReader.ReadUInt16())); var clientCount = dataReader.ReadUInt16(); for (var i = 0; i < clientCount; i++) { Clients.Add(new DnmpNode { Id = dataReader.ReadUInt16(), ParentId = dataReader.ReadUInt16(), EndPoint = endPointFactory.DeserializeEndPoint(dataReader.ReadBytes(dataReader.ReadUInt16())), CustomData = dataReader.ReadBytes(dataReader.ReadUInt16()) }); } }