public void CompressedMessage(IService service, CompressedMessage message, MessageReceivedEventArgs e) { var decompressed = message.Data.DecompressZLib(); ProudCoreOpCode opCode; byte[] data; using (var r = decompressed.ToBinaryReader()) { opCode = r.ReadEnum <ProudCoreOpCode>(); data = r.ReadToEnd(); } switch (opCode) { case ProudCoreOpCode.Rmi: var rmi = new RmiMessage(data) { IsRelayed = message.IsRelayed, SenderHostId = message.SenderHostId, TargetHostId = message.TargetHostId }; e.Message = rmi; _filter.OnMessageReceived(e); break; default: throw new ProudException("Invalid opCode inside CompressedMessage: " + opCode); } }
/// <summary> /// Writes the message. /// </summary> /// <param name="message">The message.</param> public void WriteMessage(CompressedMessage message) { Ensure.IsNotNull(message, nameof(message)); var writer = CreateBinaryWriter(); var stream = writer.BsonStream; var uncompressedMessageStream = message.OriginalMessageStream; var uncompressedMessageLength = uncompressedMessageStream.ReadInt32(); var requestId = uncompressedMessageStream.ReadInt32(); var responseTo = uncompressedMessageStream.ReadInt32(); var originalOpcode = (Opcode)uncompressedMessageStream.ReadInt32(); var compressorType = message.CompressorType; var compressor = _compressorSource.Get(compressorType); var messageStartPosition = stream.Position; stream.WriteInt32(0); // messageLength stream.WriteInt32(requestId); stream.WriteInt32(responseTo); stream.WriteInt32((int)Opcode.Compressed); stream.WriteInt32((int)originalOpcode); stream.WriteInt32(uncompressedMessageLength - MessageHeaderLength); stream.WriteByte((byte)compressorType); compressor.Compress(uncompressedMessageStream, stream); stream.BackpatchSize(messageStartPosition); }
internal Task ProcessAndSendMessage(MessageEventArgs e, EncryptContext context) { var message = (ProudMessage)e.Message; var data = message.ToArray(); CoreMessage coreMessage = new RmiMessage(data); if (message.Compress) { data = coreMessage.ToArray(); coreMessage = new CompressedMessage(data.Length, data.CompressZLib()); } if (message.Encrypt) { data = coreMessage.ToArray(); using (var w = new PooledMemoryStream(Service.ArrayPool).ToBinaryWriter(false)) { w.Write(context.EncryptCounter); w.Write(data); data = w.ToArray(); } data = context.Encrypt(data); coreMessage = new EncryptedReliableMessage(data); } e.Message = coreMessage; return(base.OnSendMessage(e)); }
public void CompressedMessage(IChannelHandlerContext context, CompressedMessage message, RecvContext recvContext) { var decompressed = message.Data.DecompressZLib(); recvContext.Message = Unpooled.WrappedBuffer(decompressed); context.Channel.Pipeline.Context <ProudFrameDecoder>().FireChannelRead(recvContext); }
public Task <bool> OnHandle(MessageContext context, CompressedMessage message) { var decompressed = message.Data.DecompressZLib(); var buffer = Unpooled.WrappedBuffer(decompressed); context.Message = buffer; context.ChannelHandlerContext.Channel.Pipeline.Context <MessageContextDecoder>().FireChannelRead(context); return(Task.FromResult(true)); }
public void Constructor_should_initialize_instance() { var compressorType = CompressorType.Zlib; var commandMessage = GetCommandMessage(); var result = new CompressedMessage(commandMessage, Mock.Of <BsonStream>(), compressorType); result.CompressorType.Should().Be(compressorType); result.OriginalMessage.ShouldBeEquivalentTo(commandMessage); result.MessageType.Should().Be(MongoDBMessageType.Compressed); }
protected override void Encode(IChannelHandlerContext context, SendContext message, List <object> output) { var buffer = message.Message as IByteBuffer; if (buffer == null) { throw new ProudException($"{nameof(SendContextEncoder)} can only handle {nameof(IByteBuffer)}"); } try { var data = buffer.ToArray(); ICoreMessage coreMessage = new RmiMessage(data); var session = context.Channel.GetAttribute(ChannelAttributes.Session).Get(); if (session == null) { return; } var server = context.Channel.GetAttribute(ChannelAttributes.Server).Get(); if (data.Length > server.Configuration.MessageMaxLength) { throw new ProudException("Message is longer than max messagelength!"); } //else if (data.Length > server.Configuration.MaxUncompressedMessageLength && // coreMessage.GetType() != typeof(CompressedMessage)) // message.SendOptions.Compress = true; if (message.SendOptions.Compress) { data = CoreMessageEncoder.Encode(coreMessage); coreMessage = new CompressedMessage(data.Length, data.CompressZLib()); } if (message.SendOptions.Encrypt) { data = CoreMessageEncoder.Encode(coreMessage); using (var src = new MemoryStream(data)) using (var dst = new MemoryStream()) { session.Crypt?.Encrypt(context.Allocator, EncryptMode.Secure, src, dst, true); data = dst.ToArray(); } coreMessage = new EncryptedReliableMessage(data, EncryptMode.Secure); } output.Add(coreMessage); } finally { buffer.Release(); } }
// static constructor static CompressedMessageJsonEncoderTests() { var document = new BsonDocument("x", 1); var sections = new[] { new Type0CommandMessageSection <BsonDocument>(document, BsonDocumentSerializer.Instance) }; var commandMessage = new CommandMessage(__requestId, __responseId, sections, false); __originalMessage = new CommandResponseMessage(commandMessage); __jsonMessage = CreateCompressedMessageJson(__originalMessage, __compressorType); __testMessage = new CompressedMessage(__originalMessage, null, __compressorType); __originalEncoderSelector = new CommandResponseMessageEncoderSelector(); }
private void CompressMessage( RequestMessage message, ByteBufferStream uncompressedMessageStream, ByteBufferStream compressedStream, MessageEncoderSettings messageEncoderSettings) { var compressedMessage = new CompressedMessage(message, uncompressedMessageStream, _sendCompressorType.Value); var compressedMessageEncoderFactory = new BinaryMessageEncoderFactory(compressedStream, messageEncoderSettings, _compressorSource); var compressedMessageEncoder = compressedMessageEncoderFactory.GetCompressedMessageEncoder(null); compressedMessageEncoder.WriteMessage(compressedMessage); }
protected override void Encode(IChannelHandlerContext context, SendContext message, List <object> output) { if (!(message.Message is IByteBuffer buffer)) { throw new ProudException($"{nameof(SendContextEncoder)} can only handle {nameof(IByteBuffer)}"); } try { var data = buffer.GetIoBuffer().ToArray(); ICoreMessage coreMessage = new RmiMessage(data); if (message.SendOptions.RelayFrom > 0) { data = CoreMessageEncoder.Encode(_serializer, coreMessage); coreMessage = new UnreliableRelay2Message(message.SendOptions.RelayFrom, data); } else { if (message.SendOptions.Compress) { data = CoreMessageEncoder.Encode(_serializer, coreMessage); coreMessage = new CompressedMessage(data.Length, data.CompressZLib()); } if (message.SendOptions.Encrypt) { data = CoreMessageEncoder.Encode(_serializer, coreMessage); var session = context.Channel.GetAttribute(ChannelAttributes.Session).Get(); using (var src = new MemoryStream(data)) using (var dst = new MemoryStream()) { session.Crypt.Encrypt(context.Allocator, EncryptMode.Secure, src, dst, true); data = dst.ToArray(); } coreMessage = new EncryptedReliableMessage(data, EncryptMode.Secure); } } output.Add(coreMessage); } finally { buffer.Release(); } }
private byte[] EncryptMessage(Message mToBeEncrypted, ulong[] lTargetKeyIDs) { CompressedMessage cmMessage = new CompressedMessage(); cmMessage.Compress(mToBeEncrypted); TransportablePublicKey[] tpkSelectedKeys = new TransportablePublicKey[lTargetKeyIDs.Length]; for (int i = 0; i < lTargetKeyIDs.Length; i++) { tpkSelectedKeys[i] = pkrKeyRing.Find(lTargetKeyIDs[i], true); } SymAlgorithms saAlgo = GetSymAlgorithmPreferences(tpkSelectedKeys); SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket(); SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo); saEncrypt.Mode = CipherMode.OpenPGP_CFB; saEncrypt.GenerateKey(); byte[] bKey = saEncrypt.Key; ESKSequence esksKeys = new ESKSequence(); esksKeys = CreateESKSequence(tpkSelectedKeys, AsymActions.Encrypt, saAlgo, bKey); ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor(); byte[] bMessage = cmMessage.GetEncoded(); byte[] bOutput = new byte[bMessage.Length]; ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0); bKey.Initialize(); int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length; sedpEncrypted.Body = new byte[iOutLength]; Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength); byte[] bESK = esksKeys.GetEncoded(); byte[] bEncrypted = sedpEncrypted.Generate(); byte[] bReturn = new byte[bESK.Length + bEncrypted.Length]; bESK.CopyTo(bReturn, 0); bEncrypted.CopyTo(bReturn, bESK.Length); return(bReturn); }
/// <summary> /// Writes the message. /// </summary> /// <param name="message">The message.</param> public void WriteMessage(CompressedMessage message) { Ensure.IsNotNull(message, nameof(message)); var writer = CreateJsonWriter(); writer.WriteStartDocument(); writer.WriteInt32("opcode", (int)Opcode.Compressed); writer.WriteInt32("compressorId", (int)message.CompressorType); using (var originalWriter = new StringWriter()) { var jsonEncoderFactory = new JsonMessageEncoderFactory(originalWriter, _encoderSettings); var originalEncoder = _originalEncoderSelector.GetEncoder(jsonEncoderFactory); originalEncoder.WriteMessage(message.OriginalMessage); writer.WriteString("compressedMessage", originalWriter.ToString()); } writer.WriteEndDocument(); }
protected override void Encode(IChannelHandlerContext context, SendContext message, List <object> output) { var buffer = message.Message as IByteBuffer; if (buffer == null) { throw new ProudException($"{nameof(SendContextEncoder)} can only handle {nameof(IByteBuffer)}"); } try { var data = buffer.ToArray(); ICoreMessage coreMessage = new RmiMessage(data); if (message.SendOptions.Compress) { data = CoreMessageEncoder.Encode(coreMessage); coreMessage = new CompressedMessage(data.Length, data.CompressZLib()); } if (message.SendOptions.Encrypt) { data = CoreMessageEncoder.Encode(coreMessage); var session = context.Channel.GetAttribute(ChannelAttributes.Session).Get(); using (var src = new MemoryStream(data)) using (var dst = new MemoryStream()) { session.Crypt.Encrypt(src, dst, true); data = dst.ToArray(); } coreMessage = new EncryptedReliableMessage(data); } output.Add(coreMessage); } finally { buffer.Release(); } }
public void Send(IPEndPoint remoteEndPoint, GossipMessage message) { Debug.Assert(remoteEndPoint != null); Debug.Assert(message != null); List <EventWaitHandle> eventsToTrigger = null; using (var ms = new MemoryStream()) { try { _configuration.Logger.Verbose("Sending {@Message} to {RemoteEndPoint}", message, remoteEndPoint); _messageEncoder.Encode(message, ms); List <byte[]> messageBytes = null; foreach (var broadcast in _broadcasts.GetBroadcasts(0, 4096)) { _configuration.Logger.Verbose("Sending {@Message} to {RemoteEndPoint}", broadcast.Message, remoteEndPoint); if (messageBytes == null) { messageBytes = new List <byte[]>(); messageBytes.Add(ms.ToArray()); ms.SetLength(0); } messageBytes.Add(broadcast.MessageBytes); if (broadcast.Event != null) { if (eventsToTrigger == null) { eventsToTrigger = new List <EventWaitHandle>(); } eventsToTrigger.Add(broadcast.Event); } } if (messageBytes != null) { message = new CompoundMessage(messageBytes); ms.SetLength(0); _messageEncoder.Encode(message, ms); } if (_configuration.CompressionType.HasValue) { _configuration.Logger.Verbose("Compressing {@Message} to {RemoteEndPoint} with {CompressionType}", message, remoteEndPoint, _configuration.CompressionType.Value); message = new CompressedMessage(_configuration.CompressionType.Value, message); ms.SetLength(0); _messageEncoder.Encode(message, ms); } } catch (Exception ex) { _configuration.Logger.Error(ex, "Unable to send message(s) to {RemoteEndPoint}.", remoteEndPoint); return; } _client.Send(remoteEndPoint, ms.ToArray()); if (eventsToTrigger != null) { foreach (var @event in eventsToTrigger) { @event.Set(); } } } }
public static void EncryptFiles(String[] strFiles, PublicKeyRing pkrPublicKeyRing, SecretKeyRing skrSecretKeyRing, bool bEncrypt, bool bSign) { PublicKeySelector pksSelectKeys = new PublicKeySelector(pkrPublicKeyRing); if (bEncrypt) { pksSelectKeys.ShowDialog(); if (pksSelectKeys.SelectedKeys.Count == 0) { MessageBox.Show("You did not select a public key to encrypt to. Doing nothing...", "Nothing Done..."); return; } } TransportableSecretKey tskKey = new TransportableSecretKey(); string strPassphrase = ""; if (bSign) { QueryPassphrase qpPassphrase = new QueryPassphrase(); qpPassphrase.ShowMyDialog(skrSecretKeyRing); tskKey = qpPassphrase.SelectedKey; strPassphrase = qpPassphrase.Passphrase; } Working wWorking = new Working(); wWorking.Show(); for (int i=0; i<strFiles.Length; i++) { byte[] bFileContent = new byte[0]; try { System.IO.FileStream fsFile = new FileStream(strFiles[i], FileMode.Open); BinaryReader brReader = new BinaryReader(fsFile); bFileContent = brReader.ReadBytes((int)fsFile.Length); brReader.Close(); fsFile.Close(); } catch (Exception e) { wWorking.Hide(); MessageBox.Show("An error occured while opening the file " + strFiles[i] + ": " + e.Message, "Error..."); return; } LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Binary); lmMessage.Binary = bFileContent; lmMessage.TimeCreated = DateTime.Now; int iLastBackslash = strFiles[i].LastIndexOf("\\"); lmMessage.Filename = strFiles[i].Substring(iLastBackslash + 1, strFiles[i].Length - iLastBackslash - 1); SharpPrivacy.OpenPGP.Messages.Message mEncryptionMessage = lmMessage; if (bSign) { SignedMessage smMessage = new SignedMessage(); smMessage.MessageSigned = lmMessage; SignaturePacket spPacket = new SignaturePacket(); spPacket.Version = SignaturePacketVersionNumbers.v3; SecretKeyPacket skpKey = tskKey.FindKey(AsymActions.Sign); spPacket.KeyID = skpKey.PublicKey.KeyID; spPacket.HashAlgorithm = HashAlgorithms.SHA1; spPacket.SignatureAlgorithm = skpKey.PublicKey.Algorithm; spPacket.TimeCreated = DateTime.Now; spPacket.SignatureType = SignatureTypes.TextSignature; spPacket.Sign(lmMessage.Binary, skpKey, strPassphrase); smMessage.Signature = spPacket; mEncryptionMessage = smMessage; } CompressedMessage cmMessage = new CompressedMessage(); cmMessage.Compress(mEncryptionMessage); wWorking.Progress(20/strFiles.Length); SymAlgorithms saAlgo = GetSymAlgorithmPreferences(pksSelectKeys.SelectedKeys); wWorking.Progress(10/strFiles.Length); byte[] bReturn = new byte[0]; if (bEncrypt) { SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket(); SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo); saEncrypt.Mode = CipherMode.OpenPGP_CFB; saEncrypt.GenerateKey(); byte[] bKey = saEncrypt.Key; ESKSequence esksKeys = new ESKSequence(); try { esksKeys = CreateESKSequence(pksSelectKeys.SelectedKeys, AsymActions.Encrypt, saAlgo, bKey); } catch (Exception e) { wWorking.Hide(); MessageBox.Show("The following error occured: " + e.Message, "Error..."); return; } wWorking.Progress(50/strFiles.Length); ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor(); byte[] bMessage = cmMessage.GetEncoded(); byte[] bOutput = new byte[bMessage.Length]; ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0); bKey.Initialize(); wWorking.Progress(10/strFiles.Length); int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length; sedpEncrypted.Body = new byte[iOutLength]; Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength); byte[] bESK = esksKeys.GetEncoded(); byte[] bEncrypted = sedpEncrypted.Generate(); bReturn = new byte[bESK.Length + bEncrypted.Length]; bESK.CopyTo(bReturn, 0); bEncrypted.CopyTo(bReturn, bESK.Length); } else { wWorking.Progress(60/strFiles.Length); bReturn = cmMessage.GetEncoded(); } wWorking.Progress(10/strFiles.Length); try { FileStream fsOut = new FileStream(strFiles[i] + ".asc", FileMode.CreateNew); BinaryWriter bwWrite = new BinaryWriter(fsOut); bwWrite.Write(bReturn); bwWrite.Close(); fsOut.Close(); } catch (IOException io) { MessageBox.Show("Could not write to file. The following error occured: " + io.Message, "Error..."); } } wWorking.Hide(); }
public static string EncryptText(string strMessage, PublicKeyRing pkrPublicKeyRing, SecretKeyRing skrSecretKeyRing, bool bSign) { PublicKeySelector pksSelectKeys = new PublicKeySelector(pkrPublicKeyRing); pksSelectKeys.ShowDialog(); TransportableSecretKey tskKey = new TransportableSecretKey(); string strPassphrase = ""; if (bSign) { QueryPassphrase qpPassphrase = new QueryPassphrase(); qpPassphrase.ShowMyDialog(skrSecretKeyRing); tskKey = qpPassphrase.SelectedKey; strPassphrase = qpPassphrase.Passphrase; } if (pksSelectKeys.SelectedKeys.Count == 0) return strMessage; Working wWorking = new Working(); wWorking.Show(); LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Text); lmMessage.Text = strMessage; lmMessage.TimeCreated = DateTime.Now; lmMessage.Filename = ""; SharpPrivacy.OpenPGP.Messages.Message mEncryptionMessage = lmMessage; if (bSign) { SignedMessage smMessage = new SignedMessage(); smMessage.MessageSigned = lmMessage; SignaturePacket spPacket = new SignaturePacket(); spPacket.Version = SignaturePacketVersionNumbers.v3; SecretKeyPacket skpKey = tskKey.FindKey(AsymActions.Sign); spPacket.KeyID = skpKey.PublicKey.KeyID; spPacket.HashAlgorithm = HashAlgorithms.SHA1; spPacket.SignatureAlgorithm = skpKey.PublicKey.Algorithm; spPacket.TimeCreated = DateTime.Now; spPacket.SignatureType = SignatureTypes.TextSignature; spPacket.Sign(lmMessage.Binary, skpKey, strPassphrase); smMessage.Signature = spPacket; mEncryptionMessage = smMessage; } CompressedMessage cmMessage = new CompressedMessage(); cmMessage.Compress(mEncryptionMessage); wWorking.Progress(20); SymAlgorithms saAlgo = GetSymAlgorithmPreferences(pksSelectKeys.SelectedKeys); SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket(); SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo); saEncrypt.Mode = CipherMode.OpenPGP_CFB; saEncrypt.GenerateKey(); byte[] bKey = saEncrypt.Key; wWorking.Progress(10); ESKSequence esksKeys = new ESKSequence(); try { esksKeys = CreateESKSequence(pksSelectKeys.SelectedKeys, AsymActions.Encrypt, saAlgo, bKey); } catch (Exception e) { wWorking.Hide(); MessageBox.Show("The following error occured: " + e.Message, "Error..."); return strMessage; } wWorking.Progress(50); ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor(); byte[] bMessage = cmMessage.GetEncoded(); byte[] bOutput = new byte[bMessage.Length]; ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0); bKey.Initialize(); wWorking.Progress(10); int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length; sedpEncrypted.Body = new byte[iOutLength]; Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength); byte[] bESK = esksKeys.GetEncoded(); byte[] bEncrypted = sedpEncrypted.Generate(); byte[] bReturn = new byte[bESK.Length + bEncrypted.Length]; bESK.CopyTo(bReturn, 0); bEncrypted.CopyTo(bReturn, bESK.Length); wWorking.Progress(10); string strReturn = Radix64.Encode(bReturn, true); strReturn = Armor.WrapMessage(strReturn); wWorking.Hide(); return strReturn; }
public static string EncryptText(string strMessage, PublicKeyRing pkrPublicKeyRing, SecretKeyRing skrSecretKeyRing, bool bSign) { PublicKeySelector pksSelectKeys = new PublicKeySelector(pkrPublicKeyRing); pksSelectKeys.ShowDialog(); TransportableSecretKey tskKey = new TransportableSecretKey(); string strPassphrase = ""; if (bSign) { QueryPassphrase qpPassphrase = new QueryPassphrase(); qpPassphrase.ShowMyDialog(skrSecretKeyRing); tskKey = qpPassphrase.SelectedKey; strPassphrase = qpPassphrase.Passphrase; } if (pksSelectKeys.SelectedKeys.Count == 0) { return(strMessage); } Working wWorking = new Working(); wWorking.Show(); LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Text); lmMessage.Text = strMessage; lmMessage.TimeCreated = DateTime.Now; lmMessage.Filename = ""; SharpPrivacy.OpenPGP.Messages.Message mEncryptionMessage = lmMessage; if (bSign) { SignedMessage smMessage = new SignedMessage(); smMessage.MessageSigned = lmMessage; SignaturePacket spPacket = new SignaturePacket(); spPacket.Version = SignaturePacketVersionNumbers.v3; SecretKeyPacket skpKey = tskKey.FindKey(AsymActions.Sign); spPacket.KeyID = skpKey.PublicKey.KeyID; spPacket.HashAlgorithm = HashAlgorithms.SHA1; spPacket.SignatureAlgorithm = skpKey.PublicKey.Algorithm; spPacket.TimeCreated = DateTime.Now; spPacket.SignatureType = SignatureTypes.TextSignature; spPacket.Sign(lmMessage.Binary, skpKey, strPassphrase); smMessage.Signature = spPacket; mEncryptionMessage = smMessage; } CompressedMessage cmMessage = new CompressedMessage(); cmMessage.Compress(mEncryptionMessage); wWorking.Progress(20); SymAlgorithms saAlgo = GetSymAlgorithmPreferences(pksSelectKeys.SelectedKeys); SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket(); SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo); saEncrypt.Mode = CipherMode.OpenPGP_CFB; saEncrypt.GenerateKey(); byte[] bKey = saEncrypt.Key; wWorking.Progress(10); ESKSequence esksKeys = new ESKSequence(); try { esksKeys = CreateESKSequence(pksSelectKeys.SelectedKeys, AsymActions.Encrypt, saAlgo, bKey); } catch (Exception e) { wWorking.Hide(); MessageBox.Show("The following error occured: " + e.Message, "Error..."); return(strMessage); } wWorking.Progress(50); ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor(); byte[] bMessage = cmMessage.GetEncoded(); byte[] bOutput = new byte[bMessage.Length]; ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0); bKey.Initialize(); wWorking.Progress(10); int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length; sedpEncrypted.Body = new byte[iOutLength]; Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength); byte[] bESK = esksKeys.GetEncoded(); byte[] bEncrypted = sedpEncrypted.Generate(); byte[] bReturn = new byte[bESK.Length + bEncrypted.Length]; bESK.CopyTo(bReturn, 0); bEncrypted.CopyTo(bReturn, bESK.Length); wWorking.Progress(10); string strReturn = Radix64.Encode(bReturn, true); strReturn = Armor.WrapMessage(strReturn); wWorking.Hide(); return(strReturn); }
public static void EncryptFiles(String[] strFiles, PublicKeyRing pkrPublicKeyRing, SecretKeyRing skrSecretKeyRing, bool bEncrypt, bool bSign) { PublicKeySelector pksSelectKeys = new PublicKeySelector(pkrPublicKeyRing); if (bEncrypt) { pksSelectKeys.ShowDialog(); if (pksSelectKeys.SelectedKeys.Count == 0) { MessageBox.Show("You did not select a public key to encrypt to. Doing nothing...", "Nothing Done..."); return; } } TransportableSecretKey tskKey = new TransportableSecretKey(); string strPassphrase = ""; if (bSign) { QueryPassphrase qpPassphrase = new QueryPassphrase(); qpPassphrase.ShowMyDialog(skrSecretKeyRing); tskKey = qpPassphrase.SelectedKey; strPassphrase = qpPassphrase.Passphrase; } Working wWorking = new Working(); wWorking.Show(); for (int i = 0; i < strFiles.Length; i++) { byte[] bFileContent = new byte[0]; try { System.IO.FileStream fsFile = new FileStream(strFiles[i], FileMode.Open); BinaryReader brReader = new BinaryReader(fsFile); bFileContent = brReader.ReadBytes((int)fsFile.Length); brReader.Close(); fsFile.Close(); } catch (Exception e) { wWorking.Hide(); MessageBox.Show("An error occured while opening the file " + strFiles[i] + ": " + e.Message, "Error..."); return; } LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Binary); lmMessage.Binary = bFileContent; lmMessage.TimeCreated = DateTime.Now; int iLastBackslash = strFiles[i].LastIndexOf("\\"); lmMessage.Filename = strFiles[i].Substring(iLastBackslash + 1, strFiles[i].Length - iLastBackslash - 1); SharpPrivacy.OpenPGP.Messages.Message mEncryptionMessage = lmMessage; if (bSign) { SignedMessage smMessage = new SignedMessage(); smMessage.MessageSigned = lmMessage; SignaturePacket spPacket = new SignaturePacket(); spPacket.Version = SignaturePacketVersionNumbers.v3; SecretKeyPacket skpKey = tskKey.FindKey(AsymActions.Sign); spPacket.KeyID = skpKey.PublicKey.KeyID; spPacket.HashAlgorithm = HashAlgorithms.SHA1; spPacket.SignatureAlgorithm = skpKey.PublicKey.Algorithm; spPacket.TimeCreated = DateTime.Now; spPacket.SignatureType = SignatureTypes.TextSignature; spPacket.Sign(lmMessage.Binary, skpKey, strPassphrase); smMessage.Signature = spPacket; mEncryptionMessage = smMessage; } CompressedMessage cmMessage = new CompressedMessage(); cmMessage.Compress(mEncryptionMessage); wWorking.Progress(20 / strFiles.Length); SymAlgorithms saAlgo = GetSymAlgorithmPreferences(pksSelectKeys.SelectedKeys); wWorking.Progress(10 / strFiles.Length); byte[] bReturn = new byte[0]; if (bEncrypt) { SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket(); SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo); saEncrypt.Mode = CipherMode.OpenPGP_CFB; saEncrypt.GenerateKey(); byte[] bKey = saEncrypt.Key; ESKSequence esksKeys = new ESKSequence(); try { esksKeys = CreateESKSequence(pksSelectKeys.SelectedKeys, AsymActions.Encrypt, saAlgo, bKey); } catch (Exception e) { wWorking.Hide(); MessageBox.Show("The following error occured: " + e.Message, "Error..."); return; } wWorking.Progress(50 / strFiles.Length); ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor(); byte[] bMessage = cmMessage.GetEncoded(); byte[] bOutput = new byte[bMessage.Length]; ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0); bKey.Initialize(); wWorking.Progress(10 / strFiles.Length); int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length; sedpEncrypted.Body = new byte[iOutLength]; Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength); byte[] bESK = esksKeys.GetEncoded(); byte[] bEncrypted = sedpEncrypted.Generate(); bReturn = new byte[bESK.Length + bEncrypted.Length]; bESK.CopyTo(bReturn, 0); bEncrypted.CopyTo(bReturn, bESK.Length); } else { wWorking.Progress(60 / strFiles.Length); bReturn = cmMessage.GetEncoded(); } wWorking.Progress(10 / strFiles.Length); try { FileStream fsOut = new FileStream(strFiles[i] + ".asc", FileMode.CreateNew); BinaryWriter bwWrite = new BinaryWriter(fsOut); bwWrite.Write(bReturn); bwWrite.Close(); fsOut.Close(); } catch (IOException io) { MessageBox.Show("Could not write to file. The following error occured: " + io.Message, "Error..."); } } wWorking.Hide(); }