protected void SetContent(Message message, String text) { MemoryStream mstream = new MemoryStream(); EndianBinaryWriter dataOut = new EndianBinaryWriter(mstream); dataOut.WriteString32(text); dataOut.Close(); message.Content = mstream.ToArray(); }
public static void Pack(String FolderPath, String OutFile) { string[] he = Directory.GetFiles(FolderPath, "*.he*"); string[] a = Directory.GetFiles(FolderPath, "*.(a)"); string[] b = Directory.GetFiles(FolderPath, "*.(b)"); MD5Entry game = new MD5Entry(); foreach (string s in he) { if (s.ToLower().EndsWith("he0")) { byte[] hash = System.Security.Cryptography.MD5.Create().ComputeHash(File.ReadAllBytes(s)); string hashs = BitConverter.ToString(hash).Replace("-", "").ToLower(); MD5Entry[] e = MD5Table.Where(ss => ss.hash == hashs).ToArray(); if (e.Length != 0) { game = e[0]; break; } else { System.Windows.Forms.MessageBox.Show("Unknown Game!\n" + hashs); game = new MD5Entry(hashs, "Unknown Game", 0); break; } return; } } if (game.name == null) return; //System.Windows.Forms.MessageBox.Show(String.Format("{0}\nHE {1}", game.name, game.version)); //-- Header (0xC) -- //0x00 - HEPA //0x04 - FileSize (BE!) //0x08 - HE Version //0x0A - Nr Files //-- File Index Block (0xC) -- //0x00 - File Id (he0 = 0, he1 = 1, he2 = 2, (a) = 1, (b) = 0xB) //0x04 - File Offset //0x08 - File Length //MemoryStream m = new MemoryStream(); EndianBinaryWriter er = new EndianBinaryWriter(/*m*/File.Create(OutFile), Endianness.LittleEndian); er.Write("HEPA", Encoding.ASCII, false); er.Write((UInt32)0); er.Write((UInt16)(game.version * 10)); er.Write((UInt16)(he.Length + a.Length + b.Length)); Dictionary<int, String> Files = new Dictionary<int, String>(); for (int i = 0; i < he.Length; i++) { char idx = he[i][he[i].Length - 1]; Files.Add((int)char.GetNumericValue(idx), he[i]); } if (a.Length != 0) Files.Add(1, a[0]); if (b.Length != 0) Files.Add(0xB, b[0]); int[] files = Files.Keys.ToArray(); Array.Sort(files); for (int i = 0; i < files.Length; i++) { er.Write((UInt32)(files[i])); er.Write((UInt32)0); er.Write((UInt32)0); } for (int i = 0; i < files.Length; i++) { byte[] d = File.ReadAllBytes(Files[files[i]]); if (files[i] == 0 || files[i] == 1) { for (int q = 0; q < d.Length; q++) { d[q] ^= 0x69; } } long curpos = er.BaseStream.Position; er.BaseStream.Position = 12 + i * 12 + 4; er.Write((UInt32)(curpos)); er.Write((UInt32)(d.Length)); er.BaseStream.Position = curpos; er.Write(d, 0, d.Length); } er.BaseStream.Position = 4; er.Endianness = Endianness.BigEndian; er.Write((UInt32)(er.BaseStream.Length)); //byte[] data = m.GetBuffer(); er.Close(); //File.Create(OutFile).Close(); //File.WriteAllBytes(OutFile, data); }
private static void ConvertToByaml(EndianBinaryReader reader, string outpath) { XmlDocument doc = new XmlDocument(); doc.Load(reader.BaseStream); if (doc.LastChild.Name != "yaml") throw new InvalidDataException(); List<string> nodes = new List<string>(); List<string> values = new List<string>(); List<string> data = new List<string>(); ByamlNode tree = ByamlNode.FromXml(doc, doc.LastChild, nodes, values, data); List<ByamlNode> flat = new List<ByamlNode>(); Stack<ByamlNode> process = new Stack<ByamlNode>(); List<string> sorted_nodes = new List<string>(); sorted_nodes.AddRange(nodes); sorted_nodes.Sort(StringComparer.Ordinal); List<string> sorted_values = new List<string>(); sorted_values.AddRange(values); sorted_values.Sort(StringComparer.Ordinal); process.Push(tree); while (process.Count > 0) { ByamlNode current = process.Pop(); flat.Add(current); if (current.GetType() == typeof(ByamlNode.NamedNode)) { ByamlNode.NamedNode cur = current as ByamlNode.NamedNode; SortedDictionary<int, ByamlNode> dict = new SortedDictionary<int, ByamlNode>(); Stack<ByamlNode> reverse = new Stack<ByamlNode>(); foreach (var item in cur.Nodes) { dict.Add(sorted_nodes.IndexOf(nodes[item.Key]), item.Value); reverse.Push(item.Value); } while (reverse.Count > 0) process.Push(reverse.Pop()); cur.Nodes.Clear(); foreach (var item in dict) cur.Nodes.Add(item); } else if (current.GetType() == typeof(ByamlNode.UnamedNode)) { Stack<ByamlNode> reverse = new Stack<ByamlNode>(); foreach (var item in (current as ByamlNode.UnamedNode).Nodes) { reverse.Push(item); } while (reverse.Count > 0) process.Push(reverse.Pop()); } else if (current.GetType() == typeof(ByamlNode.String)) { ByamlNode.String cur = current as ByamlNode.String; cur.Value = sorted_values.IndexOf(values[cur.Value]); } } using (EndianBinaryWriter writer = new EndianBinaryWriter(new FileStream(outpath, FileMode.Create))) { uint[] off = new uint[4]; for (int i = 0; i < 2; i++) { writer.BaseStream.Position = 0; writer.Write(0x42590001); writer.Write(off, 0, 4); if (sorted_nodes.Count > 0) { off[0] = (uint)writer.BaseStream.Position; int len = 8 + 4 * sorted_nodes.Count; writer.Write(sorted_nodes.Count | ((int)ByamlNodeType.StringList << 24)); foreach (var item in sorted_nodes) { writer.Write(len); len += item.Length + 1; } writer.Write(len); foreach (var item in sorted_nodes) writer.Write(item, Encoding.ASCII, true); writer.WritePadding(4, 0); } else off[0] = 0; if (sorted_values.Count > 0) { off[1] = (uint)writer.BaseStream.Position; int len = 8 + 4 * sorted_values.Count; writer.Write(sorted_values.Count | ((int)ByamlNodeType.StringList << 24)); foreach (var item in sorted_values) { writer.Write(len); len += item.Length + 1; } writer.Write(len); foreach (var item in sorted_values) writer.Write(item, Encoding.ASCII, true); writer.WritePadding(4, 0); } else off[1] = 0; if (data.Count > 0) { off[2] = (uint)writer.BaseStream.Position; int len = 8 + 4 * data.Count; writer.Write(data.Count | ((int)ByamlNodeType.BinaryDataList << 24)); foreach (var item in data) { byte[] val = Convert.FromBase64String(item); writer.Write(len); len += val.Length; } writer.Write(len); foreach (var item in data) { byte[] val = Convert.FromBase64String(item); writer.Write(val, 0, val.Length); } writer.WritePadding(4, 0); } else off[2] = 0; off[3] = (uint)writer.BaseStream.Position; foreach (var current in flat) { current.Address = writer.BaseStream.Position; if (current.GetType() == typeof(ByamlNode.NamedNode)) { ByamlNode.NamedNode cur = current as ByamlNode.NamedNode; writer.Write(cur.Nodes.Count | ((int)cur.Type << 24)); foreach (var item in cur.Nodes) { writer.Write(((int)item.Value.Type) | (item.Key << 8)); switch (item.Value.Type) { case ByamlNodeType.String: writer.Write((item.Value as ByamlNode.String).Value); break; case ByamlNodeType.Data: writer.Write((item.Value as ByamlNode.Data).Value); break; case ByamlNodeType.Boolean: writer.Write((item.Value as ByamlNode.Boolean).Value ? 1 : 0); break; case ByamlNodeType.Int: writer.Write((item.Value as ByamlNode.Int).Value); break; case ByamlNodeType.Single: writer.Write((item.Value as ByamlNode.Single).Value); break; case ByamlNodeType.UnamedNode: case ByamlNodeType.NamedNode: writer.Write((int)item.Value.Address); break; default: throw new NotImplementedException(); } } } else if (current.GetType() == typeof(ByamlNode.UnamedNode)) { ByamlNode.UnamedNode cur = current as ByamlNode.UnamedNode; writer.Write(cur.Nodes.Count | ((int)cur.Type << 24)); foreach (var item in cur.Nodes) writer.Write((byte)item.Type); writer.WritePadding(4, 0); foreach (var item in cur.Nodes) { switch (item.Type) { case ByamlNodeType.String: writer.Write((item as ByamlNode.String).Value); break; case ByamlNodeType.Data: writer.Write((item as ByamlNode.Data).Value); break; case ByamlNodeType.Boolean: writer.Write((item as ByamlNode.Boolean).Value ? 1 : 0); break; case ByamlNodeType.Int: writer.Write((item as ByamlNode.Int).Value); break; case ByamlNodeType.Single: writer.Write((item as ByamlNode.Single).Value); break; case ByamlNodeType.UnamedNode: case ByamlNodeType.NamedNode: writer.Write((int)item.Address); break; default: throw new NotImplementedException(); } } } } } writer.Close(); } }
private void SaveFiles() { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { string savePath = saveFileDialog1.FileName; FileStream originalArc = new FileStream(ArcFilePath, FileMode.Open); EndianBinaryReader reader = new EndianBinaryReader(originalArc, GameFormatReader.Common.Endian.Big); List<byte> testList = reader.ReadBytes((int)reader.BaseStream.Length).ToList(); reader.Close(); List<Message> exportList = new List<Message>(); foreach (Message mes in MessageList) { mes.ProofReadTagstoCodes(); Message temp = mes.Copy(); exportList.Add(temp); } byte[] newBMGFile = TextBankClass.ExportBMGFromPath(exportList); testList.RemoveRange(1344, testList.Count - 1344); testList.AddRange(newBMGFile); byte[] newBMCFile = ColorClass.BMCExporter(ColorList); testList.RemoveRange(256, newBMCFile.Length); testList.InsertRange(256, newBMCFile); FileStream testStream = new FileStream(savePath, FileMode.Create); EndianBinaryWriter writer = new EndianBinaryWriter(testStream, Endian.Big); writer.Write(testList.ToArray()); writer.BaseStream.Position = 128; writer.Write((int)newBMGFile.Length); writer.BaseStream.Position = 4; writer.Write((int)testList.Count); writer.Flush(); writer.Close(); } }
/// <summary> /// AIS Section Load command generation /// </summary> /// <param name="cf">The COFFfile object that the section comes from.</param> /// <param name="secHeader">The Hashtable object of the section header to load.</param> /// <param name="devAISGen">The specific device AIS generator object.</param> /// <returns>retType enumerator indicating success or failure.</returns> private static retType SecureAISSectionLoad( COFFFile cf, Hashtable secHeader, AISGen devAISGen, Boolean encryptSection) { UInt32 secSize = (UInt32)secHeader["byteSize"]; String secName = (String)secHeader["name"]; UInt32 runAddr = (UInt32)secHeader["phyAddr"]; UInt32 loadAddr = (UInt32)secHeader["virAddr"]; UInt32 numWords = (UInt32)secHeader["wordSize"]; UInt32[] secData = cf[secName]; Byte[] srcCRCData = new Byte[secSize + 8]; EndianBinaryWriter ebw = new EndianBinaryWriter( devAISGen.devAISStream, devAISGen.devEndian); EndianBinaryWriter sig_bw = new EndianBinaryWriter( devAISGen.signatureStream, devAISGen.devEndian); // Write Section_Load AIS command, load address, and size if (encryptSection) { ebw.Write((UInt32)AIS.EncSection_Load); ebw.Write(loadAddr); ebw.Write(secSize); sig_bw.Write((UInt32)AIS.EncSection_Load); sig_bw.Write(loadAddr); sig_bw.Write(secSize); devAISGen.signatureByteCnt += 12; } else { ebw.Write((UInt32)AIS.Section_Load); ebw.Write(loadAddr); ebw.Write(secSize); sig_bw.Write((UInt32)AIS.Section_Load); sig_bw.Write(loadAddr); sig_bw.Write(secSize); devAISGen.signatureByteCnt += 12; } // Now write contents if (!encryptSection) { // Non-encrypted section for (int k = 0; k < numWords; k++) { ebw.Write(secData[k]); sig_bw.Write(secData[k]); devAISGen.signatureByteCnt += 4; } } else { // Encrypted section // Write unencrypted data to the signature buffer for (int k = 0; k < numWords; k++) { sig_bw.Write(secData[k]); devAISGen.signatureByteCnt += 4; } Console.WriteLine("Wrote {0} bytes to signature buffer.", numWords *4); Byte[] tempData = new Byte[numWords * 4]; EndianBinaryWriter tempEbw = new EndianBinaryWriter(new MemoryStream(tempData), devAISGen.devEndian); // Write data to the tempData through the endian binary writer/memory stream for (int k = 0; k < numWords; k++) { tempEbw.Write(secData[k]); } tempEbw.Close(); // Encrypt data using CTS algorithm try { Byte[] encData = AesManagedUtil.AesCTSEncrypt(tempData,devAISGen.customerEncryptionKey,devAISGen.CEKInitialValue); // Write encrypted section data out to AIS data stream ebw.Write(encData); } catch(Exception e) { Console.WriteLine("Exception during encryption operation: {0}",e.Message); } } // Add this section's memory range, checking for overlap AddMemoryRange(devAISGen, loadAddr, loadAddr+secSize-1); // Check if we need to output DONE to the UART if (devAISGen.SendUARTSendDONE) { ebw.Write((UInt32)AIS.Jump); ebw.Write(devAISGen.UARTSendDONEAddr); sig_bw.Write((UInt32)AIS.Jump); sig_bw.Write(devAISGen.UARTSendDONEAddr); devAISGen.signatureByteCnt += 8; SecureAISInsertSignature(devAISGen.signatureStream,devAISGen); } // Check for need to do IDMA relocation if (loadAddr != runAddr) { Boolean LoadInCache = false, RunInL1PCache = false; for (int j = 0; j < devAISGen.Cache.Length; j++) { LoadInCache = (LoadInCache || devAISGen.Cache[j].InCache(loadAddr)); RunInL1PCache = (RunInL1PCache || ((devAISGen.Cache[j].InCache(runAddr)) && (devAISGen.Cache[j].level == CacheLevel.L1) && (devAISGen.Cache[j].type == CacheType.Program)) ); } Debug.DebugMSG("LoadInCache : {0}, RunInL1PCache: {1}", LoadInCache, RunInL1PCache); if (RunInL1PCache && LoadInCache) { //Write Set commands to make the IDMA do transfer // Write SET command ebw.Write((UInt32)AIS.Set); sig_bw.Write((UInt32)AIS.Set); //Write type field (32-bit only) ebw.Write((UInt32)0x3); sig_bw.Write((UInt32)0x3); // Write appropriate parameter address ebw.Write((UInt32)devAISGen.IDMA[1].IDMA_SRC_ADDR); sig_bw.Write((UInt32)devAISGen.IDMA[1].IDMA_SRC_ADDR); //Write data to write (the src address) ebw.Write((UInt32)loadAddr); sig_bw.Write((UInt32)loadAddr); //Write Sleep value ebw.Write((UInt32)0x0); sig_bw.Write((UInt32)0x0); devAISGen.signatureByteCnt += 20; SecureAISInsertSignature(devAISGen.signatureStream,devAISGen); // Write SET command ebw.Write((UInt32)AIS.Set); sig_bw.Write((UInt32)AIS.Set); //Write type field (32-bit only) ebw.Write((UInt32)0x3); sig_bw.Write((UInt32)0x3); // Write appropriate parameter address ebw.Write((UInt32)devAISGen.IDMA[1].IDMA_DEST_ADDR); sig_bw.Write((UInt32)devAISGen.IDMA[1].IDMA_DEST_ADDR); //Write data to write (the dest address) ebw.Write((UInt32)runAddr); sig_bw.Write((UInt32)runAddr); //Write Sleep value ebw.Write((UInt32)0x0); sig_bw.Write((UInt32)0x0); devAISGen.signatureByteCnt += 20; SecureAISInsertSignature(devAISGen.signatureStream,devAISGen); // Write SET command ebw.Write((UInt32)AIS.Set); sig_bw.Write((UInt32)AIS.Set); //Write type field (32-bit only) ebw.Write((UInt32)0x3); sig_bw.Write((UInt32)0x3); // Write appropriate parameter address ebw.Write((UInt32)devAISGen.IDMA[1].IDMA_CNT_ADDR); sig_bw.Write((UInt32)devAISGen.IDMA[1].IDMA_CNT_ADDR); //Write data to write (the byte count - must be multiple of four) ebw.Write((UInt32)(numWords * 4)); sig_bw.Write((UInt32)(numWords * 4)); //Write Sleep value ebw.Write((UInt32)0x1000); sig_bw.Write((UInt32)0x1000); devAISGen.signatureByteCnt += 20; SecureAISInsertSignature(devAISGen.signatureStream,devAISGen); // Check if we need to output DONE to the UART if (devAISGen.SendUARTSendDONE) { ebw.Write((UInt32)AIS.Jump); ebw.Write((UInt32)devAISGen.UARTSendDONEAddr); sig_bw.Write((UInt32)AIS.Jump); sig_bw.Write((UInt32)devAISGen.UARTSendDONEAddr); devAISGen.signatureByteCnt += 8; SecureAISInsertSignature(devAISGen.signatureStream,devAISGen); } } } Debug.DebugMSG("Secure Section Load complete"); return retType.SUCCESS; }
/// <summary> /// AIS Section Load command generation /// </summary> /// <param name="cf">The COFFfile object that the section comes from.</param> /// <param name="secHeader">The Hashtable object of the section header to load.</param> /// <param name="devAISGen">The specific device AIS generator object.</param> /// <returns>retType enumerator indicating success or failure.</returns> private static retType SecureAISBinarySectionLoad( String fileName, AISGen devAISGen, UInt32 loadAddress, Boolean encryptSection) { String secName = fileName; UInt32 loadAddr = loadAddress; UInt32 secSize = (UInt32) (((new FileInfo(fileName)).Length + 3) >> 2) << 2; Byte[] secData = new Byte[secSize]; Byte[] srcCRCData = new Byte[secSize + 8]; UInt32 numWords = secSize >> 2; // Read file data using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { if (fs.Read(secData,0,(Int32) fs.Length) != fs.Length) { Console.WriteLine("ERROR: Reading binary file {0} failed!", fileName); } } EndianBinaryWriter ebw = new EndianBinaryWriter( devAISGen.devAISStream, devAISGen.devEndian); EndianBinaryWriter sig_bw = new EndianBinaryWriter( devAISGen.signatureStream, devAISGen.devEndian); // Write Section_Load AIS command, load address, and size UInt32 sectionLoadCommand = (encryptSection ? (UInt32)AIS.EncSection_Load : (UInt32)AIS.Section_Load ); ebw.Write(sectionLoadCommand); ebw.Write(loadAddr); ebw.Write(secSize); sig_bw.Write(sectionLoadCommand); sig_bw.Write(loadAddr); sig_bw.Write(secSize); devAISGen.signatureByteCnt += 12; // Now write contents if (!encryptSection) { // Non-encrypted section for (int k = 0; k < numWords; k++) { ebw.Write(secData[k]); sig_bw.Write(secData[k]); devAISGen.signatureByteCnt += 4; } } else { // Encrypted section // Write unencrypted data to the signature buffer for (int k = 0; k < numWords; k++) { sig_bw.Write(secData[k]); devAISGen.signatureByteCnt += 4; } Console.WriteLine("Wrote {0} bytes to signature buffer.", numWords *4); Byte[] tempData = new Byte[numWords * 4]; EndianBinaryWriter tempEbw = new EndianBinaryWriter(new MemoryStream(tempData), devAISGen.devEndian); // Write data to the tempData through the endian binary writer/memory stream for (int k = 0; k < numWords; k++) { tempEbw.Write(secData[k]); } tempEbw.Close(); // Encrypt data using CTS algorithm try { Byte[] encData = AesManagedUtil.AesCTSEncrypt(tempData,devAISGen.customerEncryptionKey,devAISGen.CEKInitialValue); // Write encrypted section data out to AIS data stream ebw.Write(encData); } catch(Exception e) { Console.WriteLine("Exception during encryption operation: {0}",e.Message); } } // Add this section's memory range, checking for overlap AddMemoryRange(devAISGen, loadAddr, loadAddr+secSize-1); // Check if we need to output DONE to the UART if (devAISGen.SendUARTSendDONE) { ebw.Write((UInt32)AIS.Jump); ebw.Write(devAISGen.UARTSendDONEAddr); sig_bw.Write((UInt32)AIS.Jump); sig_bw.Write(devAISGen.UARTSendDONEAddr); devAISGen.signatureByteCnt += 8; SecureAISInsertSignature(devAISGen.signatureStream,devAISGen); } Debug.DebugMSG("Secure binary section load complete."); return retType.SUCCESS; }
public void LoadFromArc(string fileName) { string tempFileName = ""; using (FileStream yaz0TestStream = new FileStream(fileName, FileMode.Open)) { EndianBinaryReader yaz0TestReader = new EndianBinaryReader(yaz0TestStream, Endian.Big); string yaz0Test = yaz0TestReader.ReadString(4); if (yaz0Test == "Yaz0") { byte[] uncompressedArc = DecodeYaz0(yaz0TestReader); yaz0TestReader.Close(); fileName = Path.GetTempFileName(); tempFileName = fileName; FileInfo info = new FileInfo(fileName); info.Attributes = FileAttributes.Temporary; using (FileStream tempStream = new FileStream(fileName, FileMode.Open)) { EndianBinaryWriter tempWriter = new EndianBinaryWriter(tempStream, Endian.Big); tempWriter.Write(uncompressedArc); tempWriter.Flush(); tempWriter.Close(); } } } RARC loadedArc = new RARC(fileName); if (File.Exists(tempFileName)) { File.Delete(tempFileName); } FilesFromArc = new List<FileData>(); for (int i = 0; i < loadedArc.Nodes.Count(); i++) { for (int j = 0; j < loadedArc.Nodes[i].Entries.Count(); j++) { if (loadedArc.Nodes[i].Entries[j].Data != null) { FileData file = new FileData(); file.Name = loadedArc.Nodes[i].Entries[j].Name; file.Data = loadedArc.Nodes[i].Entries[j].Data; FilesFromArc.Add(file); } } } foreach (FileData file in FilesFromArc) { if (file.Name.Contains(".dzb")) { using (EndianBinaryReader reader = new EndianBinaryReader(file.Data, Endian.Big)) { Collision = new CollisionMesh(); Collision.Load(reader); } } if (file.Name.Contains(".dzs") || file.Name.Contains(".dzr")) { using (EndianBinaryReader reader = new EndianBinaryReader(file.Data, Endian.Big)) { Read(reader); } } if (file.Name.Contains(".bdl") || file.Name.Contains(".bmd")) { //Not implemented } } }
private void StoreContent() { if(this.dataOut != null) { if(this.Compressed == true) { MemoryStream final = new MemoryStream(); EndianBinaryWriter writer = new EndianBinaryWriter(final); this.dataOut.Close(); writer.Write(this.length); if(this.length > 0) { byte[] compressed = this.outputBuffer.ToArray(); writer.Write(compressed, 0, compressed.Length); } writer.Close(); base.Content = final.ToArray(); } else { this.dataOut.Close(); base.Content = outputBuffer.ToArray(); } this.dataOut = null; this.outputBuffer = null; } }