public override void HandleMessage(Streams.XmppStream stream, Message msg, XmppHandlerContext context) { //Private msg if (msg.Type==MessageType.chat) { if (Member.ResolveRoomJid(msg.From)==null) { //Error msg.SwitchDirection(); msg.From = Member.RoomFrom; msg.Type = MessageType.error; msg.Error = new Error(ErrorCondition.ItemNotFound); context.Sender.SendTo(stream, msg); } else { //Send msg.To = Member.RealJid; msg.From = Member.ResolveRoomJid(msg.From); Member.Send(msg); } } else { msg.SwitchDirection(); msg.From = Member.RoomFrom; msg.Type = MessageType.error; msg.Error = new Error(ErrorCondition.BadRequest); context.Sender.SendTo(stream, msg); } }
public static void Main(string[] args) { server = new Bizarrefish.WebLib.HTTPServer<VisorSessionData>(8080,"../../WebStatic"); ajaxHandler = new AjaxHandler<VisorSessionData>(server); tvs = new TestVisorService(Directory.GetCurrentDirectory()); Streams<VisorSessionData> streams = new Streams<VisorSessionData>(server, tvs); Results.tvs = tvs; Results.streams = streams; Plans.tvs = tvs; Machines.tvs = tvs; Status.tvs = tvs; Tests.tvs = tvs; Tests.streams = streams; ajaxHandler.AddClass<Results>(); ajaxHandler.AddClass<Plans>(); ajaxHandler.AddClass<Machines>(); ajaxHandler.AddClass<Status>(); ajaxHandler.AddClass<Tests>(); File.Delete("../../ajax.js"); File.WriteAllText("../../WebStatic/ajax.js", ajaxHandler.GetJavascript()); server.Start(); }
public override void HandlePresence(Streams.XmppStream stream, Presence presence, XmppHandlerContext context) { if (presence.Type == PresenceType.available || presence.Type == PresenceType.unavailable) { if (!ReferenceEquals(Member.Stream, stream)) { //Set stream Member.Stream = stream; if (presence.Type == PresenceType.available) { //If stream changed then we should broadcast presences Member.ReEnterRoom(); } } Member.ChangePesence(presence); } else { //Bad request presence.SwitchDirection(); presence.From = Member.RoomFrom; presence.Type = PresenceType.error; presence.Error = new Error(ErrorCondition.BadRequest); context.Sender.SendTo(stream, presence); } }
public void WriteToFileEx5(Streams ss) { var fs = new BinaryReader() // Compliant as it is getting a non-local IDisposable as an argument { BaseStream = ss.Stream }; }
public void SetUp() { _mockStreamingManager = MockRepository.GenerateMock<IStreamingManager>(); _mockPriceStreamFactory = MockRepository.GenerateMock<IPriceStreamFactory>(); _mockNewsStreamFactory = MockRepository.GenerateMock<INewsStreamFactory>(); _mockOrderStreamFactory = MockRepository.GenerateMock<IOrderStreamFactory>(); _streams = new Streams(_mockStreamingManager, _mockPriceStreamFactory, _mockNewsStreamFactory, _mockOrderStreamFactory); _mockLsCityindexStreamingConnection = MockRepository.GenerateMock<ILsCityindexStreamingConnection>(); _mockLStreamingClientAccountConnection = MockRepository.GenerateMock<ILsStreamingClientAccountConnection>(); _mockApiConnection = MockRepository.GenerateMock<IApiConnection>(); _mockLightStreamerConnectionManager = MockRepository.GenerateMock<LightStreamerConnectionManager>(_mockApiConnection); }
public override IQ HandleIQ(Streams.XmppStream stream, IQ iq, XmppHandlerContext context) { Unique unique = (Unique)iq.SelectSingleElement(typeof(Unique)); if (unique != null) { // Gen unique id unique.Value = UniqueId.CreateNewId(16); iq.Type = IqType.result; iq.SwitchDirection(); return iq; } iq.SwitchDirection(); iq.Type = IqType.error; iq.Error = new Error(ErrorType.cancel, ErrorCondition.ItemNotFound); return iq; }
public override void HandlePresence(Streams.XmppStream stream, Presence presence, XmppHandlerContext context) { string userName = presence.To.Resource; if (!string.IsNullOrEmpty(userName) && presence.Type == PresenceType.available) { //New member MucRoomMember member = Room.GetRealMember(presence.From); if (member != null) { if (ReferenceEquals(stream, member.Stream)) { if (!Room.TryNickChange(presence)) { ErrorPresence(presence, ErrorCondition.NotAcceptable); context.Sender.SendTo(stream, presence); } } else { //Conflict. user with this jid already in room ErrorPresence(presence, ErrorCondition.Conflict); context.Sender.SendTo(stream, presence); } } else { //Doesn't exists MucRoomMember newMember = new MucRoomMember(Room, presence.To, presence.From, stream, context); Room.TryEnterRoom(newMember, presence); } } else { ErrorPresence(presence, ErrorCondition.BadRequest); context.Sender.SendTo(stream, presence); } }
public byte[] Any(Streams request) { return Guid.Parse(request.Text).ToByteArray(); }
/* * PGP decrypt a given stream. */ public void Decrypt(Stream inputStream, Stream outputStream, Stream privateKeyStream, string passPhrase) { if (inputStream == null) { throw new ArgumentException(nameof(inputStream)); } if (outputStream == null) { throw new ArgumentException(nameof(outputStream)); } if (privateKeyStream == null) { throw new ArgumentException(nameof(privateKeyStream)); } if (passPhrase == null) { passPhrase = String.Empty; } PgpObjectFactory objFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); PgpObject obj = null; if (objFactory != null) { obj = objFactory.NextPgpObject(); } // the first object might be a PGP marker packet. PgpEncryptedDataList enc = null; if (obj is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)obj; } else { enc = (PgpEncryptedDataList)objFactory.NextPgpObject(); } // decrypt PgpPrivateKey privateKey = null; PgpPublicKeyEncryptedData pbe = null; foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { privateKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray()); if (privateKey != null) { pbe = pked; break; } } if (privateKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pbe.GetDataStream(privateKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = plainFact.NextPgpObject(); } if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file."); } }
private MTConnect.Application.Streams.ReturnData GetSample(Streams header, Data.AgentInfo ac, DeviceConfiguration config) { MTConnect.Application.Streams.ReturnData result = null; string address = ac.Address; int port = ac.Port; string deviceName = ac.DeviceName; // Set Proxy Settings var proxy = new HTTP.ProxySettings(); proxy.Address = ac.ProxyAddress; proxy.Port = ac.ProxyPort; SampleInfo info = GetSampleInfo(header, config); if (info != null) { if (info.Count > 0) { DateTime requestTimestamp = DateTime.Now; string url = HTTP.GetUrl(address, port, deviceName) + "sample?from=" + info.From.ToString() + "&count=" + info.Count.ToString(); result = MTConnect.Application.Streams.Requests.Get(url, proxy, ac.Heartbeat / 2, 2); if (result != null) { UpdateAgentData(header.InstanceId, info.From + info.Count); if (verbose) Logger.Log("Sample Successful : " + url + " @ " + requestTimestamp.ToString("o"), LogLineType.Console); } else { Logger.Log("Sample Error : " + url + " @ " + requestTimestamp.ToString("o")); } } else UpdateAgentData(header.InstanceId, header.LastSequence); } return result; }
private bool TryCalculateIrmBodyTag(StoreDriverDeliveryEventArgsImpl argsImpl) { MessageItem messageItem = null; bool result; try { OrganizationId organizationId = argsImpl.ADRecipientCache.OrganizationId; MessageItem replayItem = argsImpl.ReplayItem; using (Attachment attachment = this.TryOpenFirstAttachment(replayItem)) { StreamAttachmentBase streamAttachmentBase = attachment as StreamAttachmentBase; if (streamAttachmentBase == null) { ConversationsProcessingAgent.tracer.TraceError((long)this.GetHashCode(), "message.rpmsg attachment is not of the correct type"); return(false); } using (Stream contentStream = streamAttachmentBase.GetContentStream(PropertyOpenMode.ReadOnly)) { if (contentStream == null) { ConversationsProcessingAgent.tracer.TraceError((long)this.GetHashCode(), "The rights protected message is not properly formatted"); return(false); } using (DrmEmailMessageContainer drmEmailMessageContainer = new DrmEmailMessageContainer()) { try { drmEmailMessageContainer.Load(contentStream, (object param0) => Streams.CreateTemporaryStorageStream()); } catch (InvalidRpmsgFormatException) { ConversationsProcessingAgent.tracer.TraceError((long)this.GetHashCode(), "The rights protected message is not properly formatted"); return(false); } string text = null; if (!argsImpl.MailItemDeliver.MbxTransportMailItem.ExtendedProperties.TryGetValue <string>("Microsoft.Exchange.RightsManagement.TransportDecryptionUL", out text) || string.IsNullOrEmpty(text)) { ConversationsProcessingAgent.tracer.TraceError((long)this.GetHashCode(), "Failed to load the useLicense"); return(false); } try { Uri licenseUri; XmlNode[] array; bool flag; RmsClientManager.GetLicensingUri(organizationId, drmEmailMessageContainer.PublishLicense, out licenseUri, out array, out flag); RpMsgToMsgConverter rpMsgToMsgConverter = new RpMsgToMsgConverter(drmEmailMessageContainer, organizationId, false); RmsClientManagerContext context = new RmsClientManagerContext(organizationId, RmsClientManagerContext.ContextId.MessageId, replayItem.InternetMessageId, argsImpl.ADRecipientCache, new RmsLatencyTracker(argsImpl.MailItemDeliver.MbxTransportMailItem.LatencyTracker), drmEmailMessageContainer.PublishLicense); using (DisposableTenantLicensePair disposableTenantLicensePair = RmsClientManager.AcquireTenantLicenses(context, licenseUri)) { messageItem = rpMsgToMsgConverter.ConvertRpmsgToMsg(replayItem, text, disposableTenantLicensePair.EnablingPrincipalRac); } } catch (RightsManagementException arg) { ConversationsProcessingAgent.tracer.TraceError <RightsManagementException>((long)this.GetHashCode(), "Conversion failed: {0}", arg); return(false); } catch (InvalidRpmsgFormatException arg2) { ConversationsProcessingAgent.tracer.TraceError <InvalidRpmsgFormatException>((long)this.GetHashCode(), "Conversion failed: {0}", arg2); return(false); } catch (ExchangeConfigurationException arg3) { ConversationsProcessingAgent.tracer.TraceError <ExchangeConfigurationException>((long)this.GetHashCode(), "Conversion failed: {0}", arg3); return(false); } catch (AttachmentProtectionException arg4) { ConversationsProcessingAgent.tracer.TraceError <AttachmentProtectionException>((long)this.GetHashCode(), "Conversion failed: {0}", arg4); return(false); } } } } this.bodyTag = messageItem.Body.CalculateBodyTag(out this.latestMessageWordCount); if (messageItem.AttachmentCollection.Count == 0) { this.forceAllAttachmentsHidden = true; } else { foreach (AttachmentHandle attachmentHandle in messageItem.AttachmentCollection) { if (!attachmentHandle.IsInline) { break; } this.forceAllAttachmentsHidden = true; } } result = true; } finally { if (messageItem != null) { messageItem.Dispose(); } } return(result); }
public override int Read(byte[] buf, int off, int len) { return(Streams.ReadFully(base.s, buf, off, len)); }
/// <summary> /// /// </summary> /// <param name="inputStream"></param> /// <param name="filename"></param> /// <param name="privateKeyStream"></param> /// <param name="passPhrase"></param> /// <returns></returns> public static IEnumerable <Tuple <string, Stream> > DecompressStreamFilesPGP(this Stream inputStream, string filename, Stream privateKeyStream, string passPhrase) { var response = new List <Tuple <string, Stream> >(); var outputMemoryStream = new MemoryStream(); try { var pgpFactory = default(PgpObjectFactory); var encryptedDataList = default(PgpEncryptedDataList); var obj = default(PgpObject); var privateKey = default(PgpPrivateKey); var encryptedData = default(PgpPublicKeyEncryptedData); var ringBundle = default(PgpSecretKeyRingBundle); pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key ringBundle = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); if (pgpFactory != null) { obj = pgpFactory.NextPgpObject(); } // the first object might be a PGP marker packet. if (obj is PgpEncryptedDataList) { encryptedDataList = (PgpEncryptedDataList)obj; } else { encryptedDataList = (PgpEncryptedDataList)pgpFactory.NextPgpObject(); } // decrypt foreach (PgpPublicKeyEncryptedData pked in encryptedDataList.GetEncryptedDataObjects()) { privateKey = FindSecretKey(ringBundle, pked.KeyId, passPhrase.ToCharArray()); if (privateKey != null) { encryptedData = pked; break; } } if (privateKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = encryptedData.GetDataStream(privateKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; //using (Stream output = File.Create(outputFile)) //{ Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputMemoryStream); //} } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; //using (Stream output = File.Create(outputFile)) //{ Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputMemoryStream); //} } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; //using (Stream fOut = File.Create(outputFile)) //{ Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, outputMemoryStream); //} } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } } catch (PgpException ex) { throw ex; } response .Add( Tuple.Create <string, Stream>( filename.Replace(@"\", " ").Replace(@"/", " "), outputMemoryStream)); return(response); }
public void WriteToFileEx2(Streams ss) { var fs = new BinaryReader(s.Stream); // Compliant as it is getting a non-local IDisposable as an argument }
static void FillPixelBuffer(Header header, FrameBuffer frameBuffer, Direction dir, Streams streams) { PixelBufferEntry[] cellBuffer = new PixelBufferEntry[frameBuffer.cells.Length]; int pixelMask = 0; int[] read_pixel = new int[4]; int pb_idx = -1; for (int f = 0; f < header.framesPerDir; ++f) { Frame frame = dir.frames[f]; int cell0_x = (frame.box.xMin - dir.box.xMin) / 4; int cell0_y = (frame.box.yMin - dir.box.yMin) / 4; CreateFrameCells(dir.box, frame); // dcc_prepare_frame_cells int buffCellIndex = cell0_x + cell0_y * frameBuffer.nb_cell_w; int frameCellIndex = 0; for (int y = 0; y < frame.nb_cell_h; ++y) { for (int x = 0; x < frame.nb_cell_w; ++x, ++frameCellIndex) { int curr_cell = buffCellIndex + x; if (cellBuffer[curr_cell].val != null) { if (streams.equalCell != null && streams.equalCell.ReadBool() != 0) { continue; } pixelMask = streams.pixelMask.ReadLessThanByte(4); } else { pixelMask = 0x0f; } read_pixel[0] = read_pixel[1] = read_pixel[2] = read_pixel[3] = 0; int last_pixel = 0; int nb_pix = nb_pix_table[pixelMask]; int encodingType = 0; if (nb_pix != 0 && streams.encodingType != null) { encodingType = streams.encodingType.ReadBool(); } int decoded_pix = 0; for (int i = 0; i < nb_pix; i++) { if (encodingType != 0) { read_pixel[i] = streams.rawPixel.ReadByte(); } else { read_pixel[i] = last_pixel; int pix_displ = streams.pixelCode.ReadLessThanByte(4); read_pixel[i] += pix_displ; while (pix_displ == 15) { pix_displ = streams.pixelCode.ReadLessThanByte(4); read_pixel[i] += pix_displ; } } if (read_pixel[i] == last_pixel) { read_pixel[i] = 0; // discard this pixel break; // stop the decoding of pixels } else { last_pixel = read_pixel[i]; decoded_pix++; } } // we have the 4 pixels code for the new entry in pixel_buffer PixelBufferEntry old_entry = cellBuffer[curr_cell]; pb_idx++; var newEntry = new PixelBufferEntry(); newEntry.val = new byte[4]; int curr_idx = decoded_pix - 1; for (int i = 0; i < 4; i++) { if ((pixelMask & (1 << i)) != 0) { if (curr_idx >= 0) // if stack is not empty, pop it { newEntry.val[i] = (byte)read_pixel[curr_idx--]; } } else { newEntry.val[i] = old_entry.val[i]; } } newEntry.frame = f; newEntry.frameCellIndex = frameCellIndex; pixelBuffer[pb_idx] = newEntry; cellBuffer[curr_cell] = newEntry; } buffCellIndex += frameBuffer.nb_cell_w; } } for (int i = 0; i <= pb_idx; i++) { for (int x = 0; x < 4; x++) { int y = pixelBuffer[i].val[x]; pixelBuffer[i].val[x] = dir.pixel_values[y]; } } pixelBuffer[pb_idx + 1].frame = -1; }
public static void Save(Stream stream, bool compress, SoftwareModel softwareModel, bool loadColors, bool loadUVs, bool loadNormals) { var writer = new BinaryWriter(stream); // meta data writer.Write(Streams.MakeFourCC('R', 'M', 'F', 'T')); // tag writer.Write(1.0f); // version writer.Write(false); //compress);// TODO: add zip compression // frames writer.Write(softwareModel.FrameStart); writer.Write(softwareModel.FrameEnd); writer.Write(softwareModel.FPS); // materials writer.Write(softwareModel.Materials.Count); foreach (var material in softwareModel.Materials) { writer.Write(material.Name); // values1 writer.Write(material.Values1.Count); foreach (var value in material.Values1) { writer.Write(value.Key); writer.Write(value.Value); } // values2 writer.Write(material.Values2.Count); foreach (var value in material.Values2) { writer.Write(value.Key); writer.WriteVector(value.Value); } // values3 writer.Write(material.Values3.Count); foreach (var value in material.Values3) { writer.Write(value.Key); writer.WriteVector(value.Value); } // values4 writer.Write(material.Values4.Count); foreach (var value in material.Values4) { writer.Write(value.Key); writer.WriteVector(value.Value); } // textures writer.Write(material.Textures.Count); foreach (var texture in material.Textures) { writer.Write(texture.Key); writer.Write(texture.Value); } } // meshes writer.Write(softwareModel.Meshes.Count); foreach (var mesh in softwareModel.Meshes) { Mesh.Write(writer, softwareModel, mesh, loadColors, loadUVs, loadNormals); } // actions writer.Write(softwareModel.Actions.Count); foreach (var action in softwareModel.Actions) { Action.Write(writer, action); } // armatures writer.Write(softwareModel.Armatures.Count); foreach (var armature in softwareModel.Armatures) { Armature.Write(writer, armature); } // objects writer.Write(softwareModel.Objects.Count); foreach (var o in softwareModel.Objects) { Object.Write(writer, o); } }
public static async void Save(string filename, bool compress, SoftwareModel softwareModel, bool loadColors, bool loadUVs, bool loadNormals) { using (var file = await Streams.SaveFile(filename, FolderLocations.Unknown))
private void init(string filename, Stream stream, string contentDirectory, Dictionary <string, Type> materialTypes, List <MaterialFieldBinder> value1BinderTypes, List <MaterialFieldBinder> value2BinderTypes, List <MaterialFieldBinder> value3BinderTypes, List <MaterialFieldBinder> value4BinderTypes, List <MaterialFieldBinder> textureBinderTypes, Dictionary <string, string> fileExtOverrides, int classicInstanceCount, Loader.LoadedCallbackMethod loadedCallback) { try { var reader = new BinaryReader(stream); // meta data if (reader.ReadInt32() != Streams.MakeFourCC('R', 'M', 'F', 'T')) { Debug.ThrowError("Error", "Not a ReignModel file: " + filename); } float version = reader.ReadSingle(); if (version != 1.0f) { Debug.ThrowError("Error", "Unsuported model version: " + version.ToString()); } bool compressed = reader.ReadBoolean(); // frames FrameStart = reader.ReadSingle(); FrameEnd = reader.ReadSingle(); FrameCount = FrameEnd - FrameStart; FPS = reader.ReadSingle(); // materials int materialCount = reader.ReadInt32(); Materials = new MaterialI[materialCount]; Textures = new List <ITexture2D>(); for (int i = 0; i != materialCount; ++i) { string name = reader.ReadString(); // create material bool pass = false; foreach (var materialType in (Dictionary <string, Type>)materialTypes) { if (materialType.Key == name) { Materials[i] = (MaterialI)Activator.CreateInstance(materialType.Value); Materials[i].Name = name; pass = true; break; } } if (!pass) { Debug.ThrowError("Model", "Failed to find a valid material type for: " + name); } var material = Materials[i]; // values1 var values1 = new Dictionary <string, float>(); int valueCount = reader.ReadInt32(); for (int i2 = 0; i2 != valueCount; ++i2) { values1.Add(reader.ReadString(), reader.ReadSingle()); } bindTypes(material, values1, value1BinderTypes, contentDirectory, fileExtOverrides, handleFoundValueBinder); // values2 var values2 = new Dictionary <string, Vector2>(); valueCount = reader.ReadInt32(); for (int i2 = 0; i2 != valueCount; ++i2) { values2.Add(reader.ReadString(), reader.ReadVector2()); } bindTypes(material, values2, value2BinderTypes, contentDirectory, fileExtOverrides, handleFoundValueBinder); // values3 var values3 = new Dictionary <string, Vector3>(); valueCount = reader.ReadInt32(); for (int i2 = 0; i2 != valueCount; ++i2) { values3.Add(reader.ReadString(), reader.ReadVector3()); } bindTypes(material, values3, value3BinderTypes, contentDirectory, fileExtOverrides, handleFoundValueBinder); // values4 var values4 = new Dictionary <string, Vector4>(); valueCount = reader.ReadInt32(); for (int i2 = 0; i2 != valueCount; ++i2) { values4.Add(reader.ReadString(), reader.ReadVector4()); } bindTypes(material, values4, value4BinderTypes, contentDirectory, fileExtOverrides, handleFoundValueBinder); // textures var textures = new Dictionary <string, string>(); int textureCount = reader.ReadInt32(); for (int i2 = 0; i2 != textureCount; ++i2) { textures.Add(reader.ReadString(), reader.ReadString()); } bindTypes(material, textures, textureBinderTypes, contentDirectory, fileExtOverrides, handleFoundTextureBinder); } // meshes int meshCount = reader.ReadInt32(); Meshes = new Mesh[meshCount]; for (int i = 0; i != meshCount; ++i) { Meshes[i] = new Mesh(reader, this, classicInstanceCount); } // actions int actionCount = reader.ReadInt32(); Actions = new Action[actionCount]; for (int i = 0; i != actionCount; ++i) { Actions[i] = new Action(reader); } // armatures int armatureCount = reader.ReadInt32(); Armatures = new Armature[armatureCount]; for (int i = 0; i != armatureCount; ++i) { Armatures[i] = new Armature(reader); } // objects int objectCount = reader.ReadInt32(); Objects = new Object[objectCount]; for (int i = 0; i != objectCount; ++i) { string type = reader.ReadString(); if (type == "MESH") { Objects[i] = new ObjectMesh(reader, this); } else if (type == "ARMATURE") { Objects[i] = new ObjectArmature(reader, this); } else { Debug.ThrowError("Mesh", "Unsuported Object type: " + type); } } // link objects foreach (var o in Objects) { o.linkObjects(Objects); } } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return; } if (Textures.Count == 0) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } else { new LoadWaiter(Textures.ToArray(), delegate(object sender, bool succeeded) { if (succeeded) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } else { FailedToLoad = true; Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } } }); } }
/* * decrypt a given stream. */ public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile) { try { PgpObjectFactory pgpF = null; PgpEncryptedDataList enc = null; PgpObject o = null; PgpPrivateKey sKey = null; PgpPublicKeyEncryptedData pbe = null; PgpSecretKeyRingBundle pgpSec = null; pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); if (pgpF != null) { o = pgpF.NextPgpObject(); } // the first object might be a PGP marker packet. if (o is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)o; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } // decrypt foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { sKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray()); if (sKey != null) { pbe = pked; break; } } if (sKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pbe.GetDataStream(sKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; using (Stream output = File.Create(outputFile)) { Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; using (Stream output = File.Create(outputFile)) { Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; using (Stream fOut = File.Create(outputFile)) { Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, fOut); } } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } #region commented code //if (pbe.IsIntegrityProtected()) //{ // if (!pbe.Verify()) // msg = "message failed integrity check."; // //Console.Error.WriteLine("message failed integrity check"); // else // msg = "message integrity check passed."; // //Console.Error.WriteLine("message integrity check passed"); //} //else //{ // msg = "no message integrity check."; // //Console.Error.WriteLine("no message integrity check"); //} #endregion commented code } catch (PgpException ex) { throw ex; } }
public virtual void Write(Stream output) { CheckSingleUsage(); Streams.PipeAll(input, output); Platform.Dispose(input); }
public void EjectAll() { _operations.Clear(); _eventOperations.Clear(); Streams.Clear(); }
public StreamInformation InformationFromResolution(string reolution) { return(Streams.FirstOrDefault(e => e.Resolution == reolution)); }
public override void HandleMessage(Streams.XmppStream stream, Message msg, XmppHandlerContext context) { User user = (User) msg.SelectSingleElement(typeof (User)); if (user != null) { HandleUserMessage(msg, user, stream); } else { //Groupchat message MucRoomMember member = Room.GetRealMember(msg.From); if (member != null && ReferenceEquals(member.Stream, stream) && member.Role != Role.none) { if (msg.Type == MessageType.groupchat) { if (msg.Subject!=null) { Room.ChangeSubject(member, msg.Subject); } else { MessageBroadcast(msg, member); } } else { msg.SwitchDirection(); msg.Type = MessageType.error; msg.Error = new Error(ErrorCondition.NotAcceptable); context.Sender.SendTo(stream, msg); } } else { msg.SwitchDirection(); msg.Type = MessageType.error; msg.Error = new Error(ErrorCondition.Forbidden); context.Sender.SendTo(stream, msg); } } }
static void MakeFrames(Header header, Direction dir, FrameBuffer frameBuffer, Streams streams, List <Texture2D> textures, Sprite[] sprites) { const int padding = 2; int textureWidth = Mathf.NextPowerOfTwo((dir.box.width + padding) * header.framesPerDir); int textureHeight = Mathf.NextPowerOfTwo(dir.box.height + padding); textureWidth = Mathf.Min(1024, textureWidth); var packer = new TexturePacker(textureWidth, textureHeight); Texture2D texture = null; Color32[] pixels = null; for (int c = 0; c < frameBuffer.cells.Length; c++) { frameBuffer.cells[c].w = -1; frameBuffer.cells[c].h = -1; } int pb_idx = 0; PixelBufferEntry pbe = pixelBuffer[pb_idx]; for (int f = 0; f < header.framesPerDir; f++) { Frame frame = dir.frames[f]; var pack = packer.put(dir.box.width + padding, dir.box.height + padding); if (pack.newTexture) { if (texture != null) { texture.SetPixels32(pixels); texture.Apply(false); } texture = new Texture2D(textureWidth, textureHeight, TextureFormat.RGBA32, false); pixels = new Color32[textureWidth * textureHeight]; textures.Add(texture); } frame.texture = texture; frame.texturePixels = pixels; frame.textureX = pack.x; frame.textureY = pack.y; var textureRect = new Rect(frame.textureX, frame.textureY, dir.box.width, dir.box.height); var pivot = new Vector2(-dir.box.xMin / (float)dir.box.width, dir.box.yMax / (float)dir.box.height); sprites[f] = Sprite.Create(texture, textureRect, pivot, Iso.pixelsPerUnit, extrude: 0, meshType: SpriteMeshType.FullRect); int nb_cell = frame.nb_cell_w * frame.nb_cell_h; for (int c = 0; c < nb_cell; c++) { Cell cell = frame.cells[c]; // buffer cell int cell_x = cell.x0 >> 2; int cell_y = cell.y0 >> 2; int cell_idx = cell_x + (cell_y * frameBuffer.nb_cell_w); // equal cell checks if ((pbe.frame != f) || (pbe.frameCellIndex != c)) { // this buffer cell have an equalcell bit set to 1 so copy the frame cell Cell buff_cell = frameBuffer.cells[cell_idx]; if (cell.w == buff_cell.w && cell.h == buff_cell.h) { Frame refFrame = dir.frames[f - 1]; int textureY = refFrame.textureY + dir.box.height - buff_cell.y0; int textureX = refFrame.textureX + buff_cell.x0; int srcOffset = textureWidth * textureY + textureX; textureY = frame.textureY + dir.box.height - cell.y0; textureX = frame.textureX + cell.x0; int dstOffset = textureWidth * textureY + textureX; for (int y = 0; y < cell.h; y++) { System.Array.Copy(refFrame.texturePixels, srcOffset, frame.texturePixels, dstOffset, cell.w); srcOffset -= textureWidth; dstOffset -= textureWidth; } } } else { // fill the frame cell with pixels if (pbe.val[0] == pbe.val[1]) { // fill FRAME cell to color val[0] //clear_to_color(cell->bmp, pbe->val[0]); } else { int nb_bit; if (pbe.val[1] == pbe.val[2]) { nb_bit = 1; } else { nb_bit = 2; } // fill FRAME cell with pixels int textureY = frame.textureY + dir.box.height - cell.y0; int textureX = frame.textureX + cell.x0; int offset = textureWidth * textureY + textureX; for (int y = 0; y < cell.h; ++y) { for (int x = 0; x < cell.w; ++x) { int pix = streams.pixelCode.ReadLessThanByte(nb_bit); Color32 color = Palette.palette[pbe.val[pix]]; frame.texturePixels[offset + x] = color; } offset -= textureWidth; } } // next pixelbuffer entry pb_idx++; pbe = pixelBuffer[pb_idx]; } // for the buffer cell that was used by this frame cell, // save the width & size of the current frame cell // (needed for further tests about equalcell) // and save its origin, for further copy when equalcell frameBuffer.cells[cell_idx] = cell; } } if (texture != null) { texture.SetPixels32(pixels); texture.Apply(false); } }
public void DecryptAndVerify(Stream inputStream, Stream outputStream, Stream publicKeyStream, Stream privateKeyStream, string passPhrase) { if (inputStream == null) { throw new ArgumentException(nameof(inputStream)); } if (outputStream == null) { throw new ArgumentException(nameof(outputStream)); } if (publicKeyStream == null) { throw new ArgumentException(nameof(publicKeyStream)); } if (privateKeyStream == null) { throw new ArgumentException(nameof(privateKeyStream)); } if (passPhrase == null) { passPhrase = String.Empty; } ChoPGPEncryptionKeys encryptionKeys = new ChoPGPEncryptionKeys(publicKeyStream, privateKeyStream, passPhrase); if (encryptionKeys == null) { throw new ArgumentNullException("Encryption Key not found."); } PgpPublicKeyEncryptedData publicKeyED = ExtractPublicKeyEncryptedData(inputStream); if (publicKeyED.KeyId != encryptionKeys.PublicKey.KeyId) { throw new PgpException(String.Format("Failed to verify file.")); } PgpObject message = GetClearCompressedMessage(publicKeyED, encryptionKeys); if (message is PgpCompressedData) { message = ProcessCompressedMessage(message); PgpLiteralData literalData = (PgpLiteralData)message; using (Stream literalDataStream = literalData.GetInputStream()) { Streams.PipeAll(literalDataStream, outputStream); } } else if (message is PgpLiteralData) { PgpLiteralData literalData = (PgpLiteralData)message; using (Stream literalDataStream = literalData.GetInputStream()) { Streams.PipeAll(literalDataStream, outputStream); } } else { throw new PgpException("Message is not a simple encrypted file."); } return; }
/// <summary>Return the decrypted data stream for the packet.</summary> public Stream GetDataStream( PgpPrivateKey privKey) { byte[] sessionData = RecoverSessionData(privKey); if (!ConfirmCheckSum(sessionData)) { throw new PgpKeyValidationException("key checksum failed"); } SymmetricKeyAlgorithmTag symmAlg = (SymmetricKeyAlgorithmTag)sessionData[0]; if (symmAlg == SymmetricKeyAlgorithmTag.Null) { return(encData.GetInputStream()); } IBufferedCipher cipher; string cipherName = PgpUtilities.GetSymmetricCipherName(symmAlg); string cName = cipherName; try { if (encData is SymmetricEncIntegrityPacket) { cName += "/CFB/NoPadding"; } else { cName += "/OpenPGPCFB/NoPadding"; } cipher = CipherUtilities.GetCipher(cName); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("exception creating cipher", e); } try { KeyParameter key = ParameterUtilities.CreateKeyParameter( cipherName, sessionData, 1, sessionData.Length - 3); byte[] iv = new byte[cipher.GetBlockSize()]; cipher.Init(false, new ParametersWithIV(key, iv)); encStream = BcpgInputStream.Wrap(new CipherStream(encData.GetInputStream(), cipher, null)); if (encData is SymmetricEncIntegrityPacket) { truncStream = new TruncatedStream(encStream); string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); IDigest digest = DigestUtilities.GetDigest(digestName); encStream = new DigestStream(truncStream, digest, null); } if (Streams.ReadFully(encStream, iv, 0, iv.Length) < iv.Length) { throw new EndOfStreamException("unexpected end of stream."); } int v1 = encStream.ReadByte(); int v2 = encStream.ReadByte(); if (v1 < 0 || v2 < 0) { throw new EndOfStreamException("unexpected end of stream."); } // Note: the oracle attack on the "quick check" bytes is deemed // a security risk for typical public key encryption usages, // therefore we do not perform the check. // bool repeatCheckPassed = // iv[iv.Length - 2] == (byte)v1 // && iv[iv.Length - 1] == (byte)v2; // // // Note: some versions of PGP appear to produce 0 for the extra // // bytes rather than repeating the two previous bytes // bool zeroesCheckPassed = // v1 == 0 // && v2 == 0; // // if (!repeatCheckPassed && !zeroesCheckPassed) // { // throw new PgpDataValidationException("quick check failed."); // } return(encStream); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception starting decryption", e); } }
public void Drain() { Streams.Drain(_in); Platform.Dispose(_in); }
public void Reset() { _operations.Clear(); _eventOperations.Clear(); Streams.Clear(); }
public StreamsController([NotNull] Streams streams, [NotNull] Observers observers, [NotNull] ILogger <StreamsController> logger) { this.streams = streams ?? throw new ArgumentNullException(nameof(streams)); this.observers = observers ?? throw new ArgumentNullException(nameof(observers)); this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); }
public bool HasOutstandingWork() { return(_operations.Any() || Streams.Any() || _eventOperations.Any()); }
IEnumerable <IEvent> IChangeSet.GetEvents() { return(Streams.SelectMany(x => x.Events)); }
//Descrypt message here public static Stream PgpDecrypt( this Stream encryptedData, string armoredPrivateKey, string privateKeyPassword, Encoding armorEncoding = null) { armorEncoding = armorEncoding ?? Encoding.UTF8; var stream = PgpUtilities.GetDecoderStream(encryptedData); var layeredStreams = new List <Stream> { stream }; //this is to clean up/ dispose of any layered streams. var dataObjectFactory = new PgpObjectFactory(stream); var dataObject = dataObjectFactory.NextPgpObject(); Dictionary <long, PgpSecretKey> secretKeys; using (var privateKeyStream = armoredPrivateKey.Streamify(armorEncoding)) { var secRings = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)).GetKeyRings() .OfType <PgpSecretKeyRing>(); var pgpSecretKeyRings = secRings as PgpSecretKeyRing[] ?? secRings.ToArray(); if (!pgpSecretKeyRings.Any()) { throw new ArgumentException("No secret keys found."); } secretKeys = pgpSecretKeyRings.SelectMany(x => x.GetSecretKeys().OfType <PgpSecretKey>()) .ToDictionary(key => key.KeyId, value => value); } while (!(dataObject is PgpLiteralData) && dataObject != null) { try { var compressedData = dataObject as PgpCompressedData; var listedData = dataObject as PgpEncryptedDataList; //strip away the compression stream if (compressedData != null) { stream = compressedData.GetDataStream(); layeredStreams.Add(stream); dataObjectFactory = new PgpObjectFactory(stream); } //strip the PgpEncryptedDataList if (listedData != null) { var encryptedDataList = listedData.GetEncryptedDataObjects() .OfType <PgpPublicKeyEncryptedData>().First(); var decryptionKey = secretKeys[encryptedDataList.KeyId] .ExtractPrivateKey(privateKeyPassword.ToCharArray()); stream = encryptedDataList.GetDataStream(decryptionKey); layeredStreams.Add(stream); dataObjectFactory = new PgpObjectFactory(stream); } dataObject = dataObjectFactory.NextPgpObject(); } catch (Exception ex) { //Log exception here. throw new PgpException("Failed to strip encapsulating streams.", ex); } } foreach (var layeredStream in layeredStreams) { layeredStream.Close(); layeredStream.Dispose(); } if (dataObject == null) { return(null); } var literalData = (PgpLiteralData)dataObject; var ms = new MemoryStream(); using (var clearData = literalData.GetInputStream()) { Streams.PipeAll(clearData, ms); } ms.Position = 0; return(ms); }
private SampleInfo GetSampleInfo(Streams header, DeviceConfiguration config) { var result = new SampleInfo(); //Get Sequence Number to use ----------------------- long first = header.FirstSequence; if (!startFromFirst) { first = header.LastSequence; startFromFirst = true; } else if (lastInstanceId == agentInstanceId && lastSequenceSampled > 0 && lastSequenceSampled >= header.FirstSequence) { first = lastSequenceSampled; } else if (first > 0) { // Increment some sequences since the Agent might change the first sequence // before the Sample request gets read // (should be fixed in Agent to automatically read the first 'available' sequence // instead of returning an error) first += 20; } result.From = first; // Get Last Sequence Number available from Header long last = header.LastSequence; // Calculate Sample count long sampleCount = last - first; if (sampleCount > MaxSampleCount) { sampleCount = MaxSampleCount; last = first + MaxSampleCount; } result.Count = sampleCount; return result; }
/* * decrypt a given stream. */ public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile, Stream publicKeyStream) { try { bool deleteOutputFile = false; PgpEncryptedDataList enc; PgpObject o = null; PgpPrivateKey sKey = null; PgpPublicKeyEncryptedData pbe = null; var pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key var pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); if (pgpF != null) { o = pgpF.NextPgpObject(); } // the first object might be a PGP marker packet. if (o is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)o; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } // decrypt foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { sKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray()); if (sKey != null) { pbe = pked; break; } } if (sKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pbe.GetDataStream(sKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { PgpOnePassSignature ops = ((PgpOnePassSignatureList)message)[0]; PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream)); //USE THE BELOW TO CHECK FOR A FAILING SIGNATURE VERIFICATION. //THE CERTIFICATE MATCHING THE KEY ID MUST BE IN THE PUBLIC KEY RING. //long fakeKeyId = 3008998260528343108L; //PgpPublicKey key = pgpRing.GetPublicKey(fakeKeyId); PgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId); ops.InitVerify(key); message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; //THE OUTPUT FILENAME WILL BE BASED ON THE INPUT PARAMETER VALUE TO THIS METHOD. IF YOU WANT TO KEEP THE //ORIGINAL FILENAME, UNCOMMENT THE FOLLOWING LINE. //if (!String.IsNullOrEmpty(Ld.FileName)) // outputFile = Ld.FileName; using (Stream output = File.Create(outputFile)) { Stream dIn = Ld.GetInputStream(); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); output.WriteByte((byte)ch); } output.Close(); } PgpSignatureList p3 = (PgpSignatureList)of.NextPgpObject(); PgpSignature firstSig = p3[0]; if (ops.Verify(firstSig)) { Console.Out.WriteLine("signature verified."); } else { Console.Out.WriteLine("signature verification failed."); //YOU MAY OPT TO DELETE THE OUTPUT FILE IN THE EVENT THAT VERIFICATION FAILS. //FILE DELETION HAPPENS FURTHER DOWN IN THIS METHOD //AN ALTERNATIVE IS TO LOG THESE VERIFICATION FAILURE MESSAGES, BUT KEEP THE OUTPUT FILE FOR FURTHER ANALYSIS //deleteOutputFile = true; } } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; using (Stream output = File.Create(outputFile)) { Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; using (Stream fOut = File.Create(outFileName)) { Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, fOut); } } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } #region commented code if (pbe.IsIntegrityProtected()) { if (!pbe.Verify()) { //msg = "message failed integrity check."; Console.Error.WriteLine("message failed integrity check"); //YOU MAY OPT TO DELETE THE OUTPUT FILE IN THE EVENT THAT THE INTEGRITY PROTECTION CHECK FAILS. //FILE DELETION HAPPENS FURTHER DOWN IN THIS METHOD. //AN ALTERNATIVE IS TO LOG THESE VERIFICATION FAILURE MESSAGES, BUT KEEP THE OUTPUT FILE FOR FURTHER ANALYSIS //deleteOutputFile = true; } else { //msg = "message integrity check passed."; Console.Error.WriteLine("message integrity check passed"); } } else { //msg = "no message integrity check."; Console.Error.WriteLine("no message integrity check"); } if (deleteOutputFile) { File.Delete(outputFile); } #endregion commented code } catch (PgpException ex) { throw; } }
protected void WriteBerBody(Stream contentStream) { Streams.PipeAll(contentStream, base.Out); }
public static byte[] StreamToByteArray( Stream inStream) { return(Streams.ReadAll(inStream)); }
public void TestSha1WithRsaEncapsulatedBufferedStream() { IList certList = new ArrayList(); MemoryStream bOut = new MemoryStream(); certList.Add(OrigCert); certList.Add(SignCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); // // find unbuffered length // CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1); gen.AddCertificates(x509Certs); Stream sigOut = gen.Open(bOut, true); for (int i = 0; i != 2000; i++) { sigOut.WriteByte((byte)(i & 0xff)); } sigOut.Close(); CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray()); sp.GetSignedContent().Drain(); VerifySignatures(sp); int unbufferedLength = bOut.ToArray().Length; // // find buffered length with buffered stream - should be equal // bOut.SetLength(0); gen = new CmsSignedDataStreamGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1); gen.AddCertificates(x509Certs); sigOut = gen.Open(bOut, true); byte[] data = new byte[2000]; for (int i = 0; i != 2000; i++) { data[i] = (byte)(i & 0xff); } Streams.PipeAll(new MemoryStream(data, false), sigOut); sigOut.Close(); VerifyEncodedData(bOut); Assert.AreEqual(unbufferedLength, bOut.ToArray().Length); }
public static void SetStreamFunction(Streams.PlStreamType streamType, StreamsFunction functionType, Delegate function) { //int size_of_IOSTREAM = 136; PrologCLR.PinObject(function); int size_of_IOSTREAM; int offset_to_poninter_of_IOFUNCTIONS; int size_of_pointer; if (Is64Bit()) { size_of_IOSTREAM = 232; offset_to_poninter_of_IOFUNCTIONS = 104; size_of_pointer = 8; } else { size_of_IOSTREAM = 144; offset_to_poninter_of_IOFUNCTIONS = 72; size_of_pointer = 4; } #if USESAFELIB IntPtr callbackFunctionPtr = Marshal.GetFunctionPointerForDelegate(function); IntPtr address_std_stream_array; if (Embedded.IsLinux) { address_std_stream_array = NativeMethodsLinux.GetProcAddress(m_hLibrary, "S__iob"); } else { address_std_stream_array = NativeMethodsWindows.GetProcAddress(m_hLibrary, "S__iob"); } IntPtr function_array_out = Marshal.ReadIntPtr(address_std_stream_array, (size_of_IOSTREAM * (int)streamType) + offset_to_poninter_of_IOFUNCTIONS); #if false #if _PL_X64 Marshal.WriteIntPtr(new IntPtr(function_array_out.ToInt64() + (size_of_pointer * (int)functionType)), callbackFunctionPtr); #else Marshal.WriteIntPtr(new IntPtr(function_array_out.ToInt32() + (size_of_pointer * (int)functionType)), callbackFunctionPtr); #endif // _PL_X64 #endif // false if (Is64Bit()) { Marshal.WriteIntPtr(new IntPtr(function_array_out.ToInt64() + (size_of_pointer * (int)functionType)), callbackFunctionPtr); } else { Marshal.WriteIntPtr(new IntPtr(function_array_out.ToInt32() + (size_of_pointer * (int)functionType)), callbackFunctionPtr); } #endif // USESAFELIB }
/// <summary> /// Used for quickly reading bytes for a length that is not a multiple of 0x200 /// </summary> public static byte[] ReadBytes(ref Streams.Reader br, long length) { byte[] buffer = br.ReadBytes((int)VariousFunctions.UpToNearest200(length)); List<byte> b = buffer.ToList<byte>(); b.RemoveRange((int)length, buffer.Length - (int)length); buffer = b.ToArray(); return buffer; }
protected virtual bool init(DisposableI parent, string fileName, Image image, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback) { try { if (usage == BufferUsages.Read && !isRenderTarget) { Debug.ThrowError("Texture2D", "Only RenderTargets may be readable"); } video = parent.FindParentOrSelfWithException <Video>(); if (!isRenderTarget) { if (fileName != null || image != null) { #if SILVERLIGHT texture = new X.Texture2D(video.Device, image.Size.Width, image.Size.Height, image.Mipmaps.Length != 0, Video.surfaceFormat(surfaceFormat)); for (int i = 0; i != image.Mipmaps.Length; ++i) { var mipmap = image.Mipmaps[i]; texture.SetData <byte>(i, null, mipmap.Data, 0, mipmap.Data.Length); } #else texture = parent.FindParentOrSelfWithException <RootDisposable>().Content.Load <X.Texture2D>(Streams.StripFileExt(fileName)); loadedFromContentManager = true; #endif } else { texture = new X.Texture2D(video.Device, width, height, generateMipmaps, Video.surfaceFormat(surfaceFormat)); } Size = new Size2(texture.Width, texture.Height); PixelByteSize = Image.CalculatePixelByteSize(surfaceFormat, texture.Width, texture.Height); } else { Size = new Size2(width, height); PixelByteSize = Image.CalculatePixelByteSize(surfaceFormat, width, height); } TexelOffset = (1 / Size.ToVector2()) * .5f; SizeF = Size.ToVector2(); } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } if (!isRenderTarget) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } return(true); }
internal static bool Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile) { PgpPrivateKey sKey = null; PgpPublicKeyEncryptedData pbe = null; var pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key var pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); var o = pgpF.NextPgpObject(); PgpEncryptedDataList enc; // the first object might be a PGP marker packet. if (o is PgpEncryptedDataList list) { enc = list; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } // decrypt foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { sKey = PgpServices.FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray()); if (sKey == null) { continue; } pbe = pked; break; } if (sKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact; using (var clear = pbe.GetDataStream(sKey)) { plainFact = new PgpObjectFactory(clear); } var message = plainFact.NextPgpObject(); switch (message) { case PgpCompressedData cData: { PgpObjectFactory of; using (var compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); var ld = (PgpLiteralData)message; using (var output = File.Create(outputFile)) { var unc = ld.GetInputStream(); Streams.PipeAll(unc, output); } } else { var ld = (PgpLiteralData)message; using (var output = File.Create(outputFile)) { var unc = ld.GetInputStream(); Streams.PipeAll(unc, output); } } break; } case PgpLiteralData ld: { using (var fOut = File.Create(outputFile)) { var unc = ld.GetInputStream(); Streams.PipeAll(unc, fOut); } break; } case PgpOnePassSignatureList _: throw new PgpException("Encrypted message contains a signed message - not literal data."); default: throw new PgpException("Message is not a simple encrypted file - type unknown."); } return(true); }
public static void HandOverStreamsForNextScene(Streams streams) { streams.OnHandedOver(); _handedOverStreams.Add(streams); }
public static byte[] StreamToByteArray( Stream inStream, int limit) { return(Streams.ReadAllLimited(inStream, limit)); }
public void DecryptFileAndVerify(string inputFilePath, string outputFilePath, string publicKeyFilePath, string privateKeyFilePath, string passPhrase) { if (String.IsNullOrEmpty(inputFilePath)) { throw new ArgumentException(nameof(inputFilePath)); } if (String.IsNullOrEmpty(outputFilePath)) { throw new ArgumentException(nameof(outputFilePath)); } if (String.IsNullOrEmpty(publicKeyFilePath)) { throw new ArgumentException(nameof(publicKeyFilePath)); } if (String.IsNullOrEmpty(privateKeyFilePath)) { throw new ArgumentException(nameof(privateKeyFilePath)); } if (passPhrase == null) { passPhrase = String.Empty; } if (!File.Exists(inputFilePath)) { throw new FileNotFoundException(String.Format("Encrypted File [{0}] not found.", inputFilePath)); } if (!File.Exists(publicKeyFilePath)) { throw new FileNotFoundException(String.Format("Public Key File [{0}] not found.", publicKeyFilePath)); } if (!File.Exists(privateKeyFilePath)) { throw new FileNotFoundException(String.Format("Private Key File [{0}] not found.", privateKeyFilePath)); } ChoPGPEncryptionKeys encryptionKeys = new ChoPGPEncryptionKeys(publicKeyFilePath, privateKeyFilePath, passPhrase); if (encryptionKeys == null) { throw new ArgumentNullException("Encryption Key not found."); } using (Stream inputStream = File.OpenRead(inputFilePath)) { PgpPublicKeyEncryptedData publicKeyED = ExtractPublicKeyEncryptedData(inputStream); if (publicKeyED.KeyId != encryptionKeys.PublicKey.KeyId) { throw new PgpException(String.Format("Failed to verify file.")); } PgpObject message = GetClearCompressedMessage(publicKeyED, encryptionKeys); if (message is PgpCompressedData) { message = ProcessCompressedMessage(message); PgpLiteralData literalData = (PgpLiteralData)message; using (Stream outputFile = File.Create(outputFilePath)) { using (Stream literalDataStream = literalData.GetInputStream()) { Streams.PipeAll(literalDataStream, outputFile); } } } else if (message is PgpLiteralData) { PgpLiteralData literalData = (PgpLiteralData)message; using (Stream outputFile = File.Create(outputFilePath)) { using (Stream literalDataStream = literalData.GetInputStream()) { Streams.PipeAll(literalDataStream, outputFile); } } } else { throw new PgpException("Message is not a simple encrypted file."); } } return; }