├── DS3SaveUnpacker ├── App.config ├── packages.config ├── Properties │ ├── Settings.settings │ ├── Settings.Designer.cs │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ └── Resources.resx ├── Utils.cs ├── BND4EntryHeader.cs ├── BND4Header.cs ├── GenBitConverter.cs ├── BND4Entry.cs ├── BinRW.cs ├── DS3SaveUnpacker.csproj ├── Program.cs └── BND4File.cs ├── LICENSE ├── DS3SaveUnpacker.sln ├── README.md ├── .gitattributes └── .gitignore /DS3SaveUnpacker/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/Utils.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace DS3SaveUnpacker 8 | { 9 | static class Utils 10 | { 11 | /// 12 | /// Throw an exception when the given condition fails. 13 | /// 14 | /// 15 | /// 16 | public static void Assert(bool condition, string message = "Assertion error") 17 | { 18 | if (!condition) { throw new Exception(message); } 19 | } 20 | 21 | /// 22 | /// Throw an exception when the given condition fails. 23 | /// 24 | /// 25 | /// 26 | public static void Assert(Func condition, string message = "Assertion error") 27 | { 28 | if (!condition()) { throw new Exception(message); } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 William Tremblay 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace DS3SaveUnpacker.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.4.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DS3SaveUnpacker.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29709.97 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DS3SaveUnpacker", "DS3SaveUnpacker\DS3SaveUnpacker.csproj", "{1B8E5BE4-78F7-4674-9170-2F08EC9CB4B0}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {1B8E5BE4-78F7-4674-9170-2F08EC9CB4B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {1B8E5BE4-78F7-4674-9170-2F08EC9CB4B0}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {1B8E5BE4-78F7-4674-9170-2F08EC9CB4B0}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {1B8E5BE4-78F7-4674-9170-2F08EC9CB4B0}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {5C96798D-1AF5-42F3-A4E0-095F594B4DD3} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("DS3SaveEditor")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("DS3SaveEditor")] 13 | [assembly: AssemblyCopyright("Copyright © 2020")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("1b8e5be4-78f7-4674-9170-2f08ec9cb4b0")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/BND4EntryHeader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Runtime.InteropServices; 7 | 8 | namespace DS3SaveUnpacker 9 | { 10 | [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 0x20)] 11 | struct BND4EntryHeader 12 | { 13 | /// 14 | /// Padding (50 00 00 00 FF FF FF FF in little-endian) 15 | /// 16 | public ulong padding; 17 | /// 18 | /// Size (in bytes) of the entry data. 19 | /// 20 | public ulong entrySize; 21 | /// 22 | /// Offset of the entry data in the BND4 file. 23 | /// 24 | public uint entryDataOffset; 25 | /// 26 | /// Offset of the entry name in the BND4 file. 27 | /// 28 | public uint entryNameOffset; 29 | /// 30 | /// Unused. Should be 0 31 | /// 32 | public ulong unused; 33 | 34 | /// 35 | /// Create a BND4 entry header with given parameters. 36 | /// 37 | /// 38 | /// 39 | /// 40 | public BND4EntryHeader(ulong entrySize, uint entryDataOffset, uint entryNameOffset) 41 | { 42 | padding = 0xFFFFFFFF00000050UL; 43 | unused = 0; 44 | 45 | this.entrySize = entrySize; 46 | this.entryDataOffset = entryDataOffset; 47 | this.entryNameOffset = entryNameOffset; 48 | } 49 | 50 | /// 51 | /// Throw an exception if this header does not make sense. 52 | /// 53 | public void AssertIntegrity() 54 | { 55 | Utils.Assert(padding == 0xFFFFFFFF00000050UL, "Invalid BND4 entry header"); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DS3SavePatcher 2 | 3 | Simple console program with a few features related to Dark Souls III saves: 4 | - Pack/Unpack encrypted Dark Souls III save (SL2) files 5 | - Pack/Unpack unencrypted BND4 archives (Supports only those with 32 byte headers) 6 | - Patch a Dark Souls III save (SL2) file to change the linked account, allowing save transfer across accounts. 7 | 8 | This program was specifically made for this last feature, and serves as an alternative to the [DS3 Save Manager](http://l3g.space/files/SystemTest/?Main_Page:Dark_Souls_III). The DS3 Save Manager seems to use some kind of DLL/code injection and **may** thus cause a soft ban (*Note: I don't know if the author avoided this or how good the game's code integrity check is*). This tool directly modifies the linked Steam account ID stored in the save file, and **should** pass the save consistency check, *IF the provided safe is already valid*. However, it is very new and some testing will be required to ensure this. 9 | 10 | ## Regarding unpacking/packing saves 11 | When unpacking a save, you get 12 `USER_DATA XXX` files. Those numbered `000` to `009` are the character save slots. I know `010` stores some global information (including the linked account ID and character slot info), but I have not looked deeply into it. Similarly, the `011` entry appears to be in the DCX format, and I did not investigate its contents. 12 | 13 | **Note that loading a modified save back into the game can lead to a softban. Either experiment on an account that is already penalized or completely block the game's connection to the Internet (_being offline on Steam is NOT enough_), and be sure you know what you are doing!** 14 | 15 | ## Dark Souls III save format information 16 | Dark Souls III saves are stored as BND4 archives, a binder file format used by FromSoftware since Dark Souls II. In the case of DS3, each `USER_DATA XXX` contains the following data: 17 | - A 16-byte MD5 checksum of the encrypted data (including the IV) 18 | - The 16-byte initialisation vector (IV) used for encryption 19 | - The entry data, encrypted using 128-bit AES-CBC with the key `FD464D695E69A39A10E319A7ACE8B7FA`. Credit to [Atvaark](https://github.com/Atvaark) for finding this key. More information about FromSoft file formats are available on his [ 20 | DarkSoulsIII.FileFormats](https://github.com/Atvaark/DarkSoulsIII.FileFormats) repo. 21 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace DS3SaveUnpacker.Properties { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DS3SaveUnpacker.Properties.Resources", typeof(Resources).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/BND4Header.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Runtime.InteropServices; 7 | 8 | namespace DS3SaveUnpacker 9 | { 10 | [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 0x40)] 11 | struct BND4Header 12 | { 13 | /// 14 | /// BND version header. This should be the ANSI for "BND4", or 0x3444_4E42. 15 | /// 16 | public uint BNDVers; 17 | /// 18 | /// Don't know what's here, its 8 bytes (0x0001_0000_0000_0000). 19 | /// 20 | public ulong unknown1; 21 | /// 22 | /// Number of subfiles contained in the BND4 file. 23 | /// 24 | public uint fileCnt; 25 | /// 26 | /// Don't know what's here, its 8 bytes (0x0000_0000_0000_0040). 27 | /// 28 | public ulong unknown2; 29 | /// 30 | /// Signature. Should be 0x_3130_3030_3030_3030. 31 | /// 32 | public ulong signature; 33 | /// 34 | /// Size of the BND entry headers. Should be 32. 35 | /// 36 | public ulong entryHeaderSize; 37 | /// 38 | /// Position in the file at which entry data begins. 39 | /// 40 | public ulong dataOffset; 41 | /// 42 | /// If the entry names are Unicode wide chars 43 | /// 44 | [MarshalAs(UnmanagedType.I1)] 45 | public bool isUnicode; 46 | /// 47 | /// I don't know what's here 48 | /// 49 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 15)] 50 | public byte[] unknown3; 51 | 52 | /// 53 | /// Create a BND4Header with given parameters. 54 | /// 55 | /// 56 | /// 57 | /// 58 | public BND4Header(uint fileCnt, ulong dataOffset, bool isUnicode) 59 | { 60 | BNDVers = 0x3444_4E42; 61 | unknown1 = 0x0001_0000_0000_0000; 62 | unknown2 = 0x0000_0000_0000_0040; 63 | signature = 0x3130_3030_3030_3030; 64 | unknown3 = "200000000000000000000000000000".hexToBytes(); 65 | entryHeaderSize = 0x20; 66 | 67 | this.fileCnt = fileCnt; 68 | this.dataOffset = dataOffset; 69 | this.isUnicode = isUnicode; 70 | } 71 | 72 | /// 73 | /// Throw an exception if this header does not make sense. 74 | /// 75 | public void AssertIntegrity() 76 | { 77 | Utils.Assert(BNDVers == 0x3444_4E42 && signature == 0x3130_3030_3030_3030, "Invalid BND4 header"); 78 | Utils.Assert(entryHeaderSize == 0x20, "Unsupported entry header size"); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/GenBitConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Runtime.InteropServices; 7 | using System.IO; 8 | 9 | namespace DS3SaveUnpacker 10 | { 11 | static class GenBitConverter 12 | { 13 | /// 14 | /// Convert structure to bytes. 15 | /// 16 | /// 17 | /// 18 | /// 19 | public static byte[] ToBytes(T obj) where T : struct 20 | { 21 | int size = Marshal.SizeOf(obj); 22 | byte[] arr = new byte[size]; 23 | 24 | IntPtr ptr = Marshal.AllocHGlobal(size); 25 | Marshal.StructureToPtr(obj, ptr, false); 26 | Marshal.Copy(ptr, arr, 0, size); 27 | Marshal.FreeHGlobal(ptr); 28 | 29 | return arr; 30 | } 31 | 32 | /// 33 | /// Convert bytes to structure. 34 | /// 35 | /// 36 | /// 37 | /// 38 | public static T ToStruct(byte[] buffer) where T : struct 39 | { 40 | int size = Marshal.SizeOf(); 41 | IntPtr ptr = Marshal.AllocHGlobal(size); 42 | 43 | Marshal.Copy(buffer, 0, ptr, size); 44 | T obj = Marshal.PtrToStructure(ptr); 45 | Marshal.FreeHGlobal(ptr); 46 | 47 | return obj; 48 | } 49 | 50 | /// 51 | /// Read a structure from a stream 52 | /// 53 | /// 54 | /// 55 | /// 56 | public static T ReadStruct(this Stream fs) where T : struct 57 | { 58 | int size = Marshal.SizeOf(); 59 | 60 | byte[] buff = new byte[size]; 61 | fs.Read(buff, 0, size); 62 | 63 | return ToStruct(buff); 64 | } 65 | 66 | /// 67 | /// Read a structure from a BinaryReader 68 | /// 69 | /// 70 | /// 71 | /// 72 | public static T ReadStruct(this BinaryReader bin) where T : struct 73 | { 74 | int size = Marshal.SizeOf(); 75 | 76 | byte[] buff = new byte[size]; 77 | bin.Read(buff, 0, size); 78 | 79 | return ToStruct(buff); 80 | } 81 | 82 | /// 83 | /// Write a structure to a stream. 84 | /// 85 | /// 86 | /// 87 | /// 88 | public static void WriteStruct(this Stream fs, T obj) where T : struct 89 | { 90 | byte[] buff = ToBytes(obj); 91 | fs.Write(buff, 0, buff.Length); 92 | } 93 | 94 | /// 95 | /// Write a structure to a BinaryWriter. 96 | /// 97 | /// 98 | /// 99 | /// 100 | public static void WriteStruct(this BinaryWriter bin, T obj) where T : struct 101 | { 102 | byte[] buff = ToBytes(obj); 103 | bin.Write(buff, 0, buff.Length); 104 | } 105 | 106 | public static byte[] hexToBytes(this string hex) 107 | { 108 | byte[] data = new byte[hex.Length / 2]; 109 | for (int i = 0; i < hex.Length; i+=2) 110 | { 111 | data[i/2] = byte.Parse(hex.Substring(i,2), System.Globalization.NumberStyles.HexNumber); 112 | } 113 | return data; 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/BND4Entry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Security.Cryptography; 7 | using System.IO; 8 | 9 | namespace DS3SaveUnpacker 10 | { 11 | class BND4Entry 12 | { 13 | private const bool DEBUG = true; 14 | 15 | /// 16 | /// Encryption key for DS3 USERDATA subfiles. 17 | /// 18 | public static readonly byte[] DS3_KEY = "FD464D695E69A39A10E319A7ACE8B7FA".hexToBytes(); 19 | 20 | /// 21 | /// Header of this BND4 entry. 22 | /// 23 | public BND4EntryHeader header; 24 | /// 25 | /// Name of this BND4 entry. 26 | /// 27 | public string name; 28 | 29 | /// 30 | /// Raw data stored in the entry. 31 | /// 32 | public byte[] data; 33 | 34 | /// 35 | /// Default constructor 36 | /// 37 | public BND4Entry() { } 38 | 39 | /// 40 | /// Initialize a BND4Entry with default properties, specifying the use of encryption. 41 | /// 42 | public BND4Entry(string name, byte[] data) 43 | { 44 | this.name = name; 45 | this.data = data; 46 | } 47 | 48 | /// 49 | /// Decrypt the entry data, assuming 128bit AES-CBC for DS3 saves. 50 | /// 51 | /// 52 | public byte[] DecryptData() 53 | { 54 | if (DEBUG) Console.WriteLine(string.Format("[BND4Entry] DECRYPT ENTRY DATA OF '{0}'", name)); 55 | 56 | Aes AES = Aes.Create(); 57 | AES.Mode = CipherMode.CBC; 58 | AES.BlockSize = 128; 59 | AES.Padding = PaddingMode.PKCS7; 60 | 61 | byte[] IV = new byte[16]; 62 | Array.Copy(this.data, 16, IV, 0, 16); 63 | AES.IV = IV; 64 | 65 | AES.Key = DS3_KEY; 66 | 67 | byte[] buff = new byte[data.Length - 32]; 68 | using (MemoryStream m = new MemoryStream(this.data, 32, data.Length - 32)) 69 | { 70 | var crypto = new CryptoStream(m, AES.CreateDecryptor(), CryptoStreamMode.Read); 71 | var decryptLen = crypto.Read(buff, 0, data.Length - 32); 72 | Array.Resize(ref buff, decryptLen); 73 | } 74 | return buff; 75 | } 76 | 77 | public void SetEncryptedData(byte[] newData, bool usePreviousIV = true) 78 | { 79 | if (DEBUG) Console.WriteLine(string.Format("[BND4Entry] SET ENCRYPTED DATA OF '{0}'", name)); 80 | 81 | var AES = Aes.Create(); 82 | AES.Mode = CipherMode.CBC; 83 | AES.BlockSize = 128; 84 | AES.Padding = PaddingMode.PKCS7; 85 | 86 | if (usePreviousIV) 87 | { 88 | byte[] IV = new byte[16]; 89 | Array.Copy(this.data, 16, IV, 0, 16); 90 | AES.IV = IV; 91 | } 92 | else 93 | { 94 | AES.GenerateIV(); 95 | } 96 | 97 | AES.Key = DS3_KEY; 98 | 99 | int padLen = 16 - newData.Length % 16; 100 | data = new byte[32 + newData.Length + padLen]; 101 | Array.Copy(AES.IV, 0, data, 16, 16); 102 | 103 | using (MemoryStream m = new MemoryStream(data, 32, data.Length - 32, true)) 104 | { 105 | var crypto = new CryptoStream(m, AES.CreateEncryptor(), CryptoStreamMode.Write); 106 | crypto.Write(newData, 0, newData.Length); 107 | crypto.FlushFinalBlock(); 108 | } 109 | 110 | if (DEBUG) Console.WriteLine(string.Format("[BND4Entry] SIGN ENCRYPTED ENTRY DATA OF '{0}'", name)); 111 | 112 | var md5 = MD5.Create(); 113 | byte[] checksum = md5.ComputeHash(data, 16, data.Length - 16); 114 | Array.Copy(checksum, 0, data, 0, 16); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/BinRW.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.IO; 7 | 8 | namespace DS3SaveUnpacker 9 | { 10 | class BinReader: BinaryReader 11 | { 12 | /// 13 | /// LIFO stack to keep track of the positions across StepInto and StepOut calls 14 | /// 15 | protected Stack positions; 16 | 17 | public BinReader(Stream stream) : base(stream) 18 | { 19 | positions = new Stack(); 20 | } 21 | 22 | /// 23 | /// Step into an offset. Call to come back to the last position. 24 | /// 25 | /// 26 | public void StepInto(long offset) 27 | { 28 | positions.Push(this.BaseStream.Position); 29 | this.BaseStream.Position = offset; 30 | } 31 | 32 | /// 33 | /// Step out and back to the position before the last call. 34 | /// 35 | /// 36 | public void StepOut() 37 | { 38 | this.BaseStream.Position = positions.Pop(); 39 | } 40 | 41 | /// 42 | /// Read a 2-byte wide null-terminated string. 43 | /// 44 | /// 45 | public string ReadWideString() 46 | { 47 | StringBuilder sb = new StringBuilder(); 48 | ushort chr = ReadUInt16(); 49 | while (chr != 0) 50 | { 51 | sb.Append(char.ConvertFromUtf32(chr)); 52 | chr = ReadUInt16(); 53 | } 54 | return sb.ToString(); 55 | } 56 | 57 | /// 58 | /// Read a 1-byte wide ShiftJIS null-terminated string. 59 | /// 60 | /// 61 | public string ReadShiftJIS() 62 | { 63 | List buffer = new List(); 64 | byte chr = ReadByte(); 65 | while (chr != 0) 66 | { 67 | buffer.Add(chr); 68 | chr = ReadByte(); 69 | } 70 | return Encoding.GetEncoding("shift_jis").GetString(buffer.ToArray()); 71 | } 72 | } 73 | 74 | class BinWriter: BinaryWriter 75 | { 76 | /// 77 | /// LIFO stack to keep track of the positions across StepInto and StepOut calls 78 | /// 79 | protected Stack positions; 80 | 81 | public BinWriter(Stream stream) : base(stream) 82 | { 83 | positions = new Stack(); 84 | } 85 | 86 | /// 87 | /// Step into an offset. Call to come back to the last position. 88 | /// 89 | /// 90 | public void StepInto(long offset) 91 | { 92 | positions.Push(this.BaseStream.Position); 93 | this.BaseStream.Position = offset; 94 | } 95 | 96 | /// 97 | /// Step out and back to the position before the last call. 98 | /// 99 | /// 100 | public void StepOut() 101 | { 102 | this.BaseStream.Position = positions.Pop(); 103 | } 104 | 105 | /// 106 | /// Write a 2-byte wide null-terminated string. 107 | /// 108 | /// 109 | public void WriteWideString(string s) 110 | { 111 | foreach (char chr in s) 112 | { 113 | Write((ushort)chr); 114 | } 115 | Write((ushort)0); 116 | } 117 | 118 | /// 119 | /// Write a 1-byte wide ShiftJIS null-terminated string. 120 | /// 121 | /// 122 | public void WriteShiftJIS(string str) 123 | { 124 | byte[] bytes = Encoding.GetEncoding("shift_jis").GetBytes(str); 125 | Array.Resize(ref bytes, bytes.Length + 1); 126 | Write(bytes); 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/DS3SaveUnpacker.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {1B8E5BE4-78F7-4674-9170-2F08EC9CB4B0} 8 | Exe 9 | DS3SaveUnpacker 10 | DS3SaveUnpacker 11 | v4.7.2 12 | 512 13 | true 14 | true 15 | 16 | 17 | x64 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | x64 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | ..\packages\WindowsAPICodePack-Core.1.1.1\lib\Microsoft.WindowsAPICodePack.dll 41 | 42 | 43 | ..\packages\WindowsAPICodePack-Shell.1.1.1\lib\Microsoft.WindowsAPICodePack.Shell.dll 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | ResXFileCodeGenerator 69 | Resources.Designer.cs 70 | Designer 71 | 72 | 73 | True 74 | Resources.resx 75 | True 76 | 77 | 78 | 79 | SettingsSingleFileGenerator 80 | Settings.Designer.cs 81 | 82 | 83 | True 84 | Settings.settings 85 | True 86 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /DS3SaveUnpacker/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using System.Runtime.InteropServices; 6 | using System.IO; 7 | using System.Windows.Forms; 8 | using Microsoft.WindowsAPICodePack.Dialogs; 9 | 10 | namespace DS3SaveUnpacker 11 | { 12 | static class Program 13 | { 14 | [STAThread] 15 | static void Main() 16 | { 17 | while (true) 18 | { 19 | Console.Clear(); 20 | Console.WriteLine(@"Choose action: 21 | [1] Unpack encrypted SL2 save file 22 | [2] Pack encrypted SL2 save file 23 | [3] Unpack unencrypted BND4 archive 24 | [4] Pack unencrypted BND4 archive 25 | [5] Patch SL2 save file linked account 26 | [6] Recursively patch all saves in a folder 27 | [7] Exit 28 | "); 29 | 30 | char key; 31 | do { key = Console.ReadKey(true).KeyChar; } while (key < '1' || key > '7'); 32 | if (key == '7') { return; } 33 | 34 | // Get default DS3 Save location & prompt open save file 35 | var ds3Folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DarkSoulsIII\\"); 36 | 37 | if (key == '2' || key == '4') 38 | { 39 | var diagFolder = new CommonOpenFileDialog() 40 | { 41 | Title = "Select unpack directory", 42 | IsFolderPicker = true, 43 | InitialDirectory = ds3Folder 44 | }; 45 | if (diagFolder.ShowDialog() != CommonFileDialogResult.Ok) { continue; } 46 | BND4File file = BND4File.Pack(diagFolder.FileName, key == '2'); 47 | 48 | var diagSave = new SaveFileDialog() 49 | { 50 | Title = "Save packet file at...", 51 | DefaultExt = "sl2", 52 | FileName = "DS30000.sl2", 53 | InitialDirectory = ds3Folder 54 | }; 55 | if (diagSave.ShowDialog() != DialogResult.OK) { continue; } 56 | 57 | file.Save(diagSave.FileName); 58 | 59 | Console.Write("\nDone, press any key to return to menu"); 60 | Console.ReadKey(true); 61 | continue; 62 | } 63 | 64 | if (key == '6') 65 | { 66 | var diagFolder = new CommonOpenFileDialog() 67 | { 68 | Title = "Select root directory", 69 | IsFolderPicker = true, 70 | InitialDirectory = ds3Folder 71 | }; 72 | if (diagFolder.ShowDialog() != CommonFileDialogResult.Ok) { continue; } 73 | 74 | Console.WriteLine("Proceed carefully. Entering the wrong ID will make the save unreadable."); 75 | 76 | ulong steamID = 0; 77 | while (steamID == 0) 78 | { 79 | Console.Write("Enter your 64-bit Steam ID (number in profile URL): "); 80 | if (!ulong.TryParse(Console.ReadLine(), out steamID)) 81 | { 82 | Console.WriteLine("Please input a valid number."); 83 | } 84 | } 85 | 86 | foreach (string saveFile in Directory.EnumerateFiles(diagFolder.FileName, "*.sl2", SearchOption.AllDirectories)) 87 | { 88 | Console.WriteLine(" Patching " + saveFile + "..."); 89 | 90 | BND4File BND = new BND4File(saveFile); 91 | 92 | BND.PatchDS3AccountFlag(steamID); 93 | BND.Save(saveFile); 94 | } 95 | 96 | Console.Write("\nDone, press any key to return to menu"); 97 | Console.ReadKey(true); 98 | continue; 99 | } 100 | 101 | var diagOpen = new OpenFileDialog() 102 | { 103 | Title = "Select BND4/SL2 file", 104 | DefaultExt = "sl2", 105 | CheckFileExists = true, 106 | CheckPathExists = true, 107 | Multiselect = false, 108 | InitialDirectory = ds3Folder 109 | }; 110 | if (diagOpen.ShowDialog() != DialogResult.OK) { continue; } 111 | 112 | if (key == '1' || key == '3') 113 | { 114 | var diagFolder = new CommonOpenFileDialog() 115 | { 116 | Title = "Select unpack directory", 117 | IsFolderPicker = true, 118 | InitialDirectory = ds3Folder 119 | }; 120 | if (diagFolder.ShowDialog() != CommonFileDialogResult.Ok) { continue; } 121 | BND4File.Unpack(diagOpen.FileName, diagFolder.FileName, key == '1'); 122 | } 123 | if (key == '5') 124 | { 125 | var save = new BND4File(diagOpen.FileName); 126 | Console.WriteLine("Proceed carefully. Entering the wrong ID will make the save unreadable."); 127 | 128 | ulong steamID = 0; 129 | while (steamID == 0) 130 | { 131 | Console.Write("Enter your 64-bit Steam ID (number in profile URL): "); 132 | if (!ulong.TryParse(Console.ReadLine(), out steamID)) 133 | { 134 | Console.WriteLine("Please input a valid number."); 135 | } 136 | } 137 | 138 | save.PatchDS3AccountFlag(steamID); 139 | 140 | var diagSave = new SaveFileDialog() 141 | { 142 | Title = "Save patched file at...", 143 | DefaultExt = "sl2", 144 | FileName = "DS30000.sl2", 145 | InitialDirectory = ds3Folder 146 | }; 147 | if (diagSave.ShowDialog() != DialogResult.OK) { continue; } 148 | 149 | save.Save(diagSave.FileName); 150 | } 151 | 152 | Console.Write("\nDone, press any key to return to menu"); 153 | Console.ReadKey(true); 154 | } 155 | } 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /DS3SaveUnpacker/BND4File.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.IO; 7 | using System.Runtime.InteropServices; 8 | 9 | namespace DS3SaveUnpacker 10 | { 11 | class BND4File 12 | { 13 | private const bool DEBUG = true; 14 | 15 | /// 16 | /// BND4 file header. 17 | /// 18 | public BND4Header header; 19 | /// 20 | /// The entries of the BND4 file. 21 | /// 22 | public BND4Entry[] entries; 23 | 24 | /// 25 | /// True if the encoding used for the save names is UTF-16. 26 | /// 27 | public bool isUnicode; 28 | 29 | /// 30 | /// Create empty, non-initialized BND4 file. 31 | /// 32 | public BND4File() 33 | { 34 | 35 | } 36 | 37 | /// 38 | /// Load a BND4 archive from a file. 39 | /// 40 | /// 41 | public BND4File(string filePath) 42 | { 43 | LoadInPlace(filePath); 44 | } 45 | 46 | /// 47 | /// Recalculate the BND4 headers from entry data. 48 | /// 49 | public void CalculateHeaders() 50 | { 51 | if (DEBUG) Console.WriteLine("[DEBUG] RECALCULATE HEADERS"); 52 | 53 | // 1st pass, do names 54 | uint cDataOffset = (uint)(Marshal.SizeOf() + entries.Length * Marshal.SizeOf()); 55 | foreach (BND4Entry entry in entries) 56 | { 57 | entry.header = new BND4EntryHeader((ulong)entry.data.Length, 0, cDataOffset); 58 | cDataOffset += (isUnicode ? 2U : 1U) * (uint)(entry.name.Length + 1); 59 | } 60 | // Pad cDataOffset to a multiple of 16 bytes 61 | cDataOffset += (16U - cDataOffset % 16U) % 16U; 62 | // Fix main header 63 | header = new BND4Header((uint)entries.Length, cDataOffset, isUnicode); 64 | // 2nd pass, do file offsets 65 | foreach (BND4Entry entry in entries) 66 | { 67 | entry.header.entryDataOffset = cDataOffset; 68 | cDataOffset += (uint)entry.header.entrySize; 69 | // Pad to a multiple of 16 bytes 70 | cDataOffset += (16U - cDataOffset % 16U) % 16U; 71 | } 72 | } 73 | 74 | /// 75 | /// Load a BND4 file into the existing object, overwriting existing data. 76 | /// 77 | /// 78 | public void LoadInPlace(string filePath) 79 | { 80 | Utils.Assert(File.Exists(filePath), "File does not exist"); 81 | 82 | using (BinReader bin = new BinReader(File.OpenRead(filePath))) 83 | { 84 | if (DEBUG) Console.WriteLine("[DEBUG] READ BND4 HEADERS"); 85 | 86 | header = bin.ReadStruct(); 87 | header.AssertIntegrity(); 88 | isUnicode = header.isUnicode; 89 | 90 | entries = new BND4Entry[header.fileCnt]; 91 | 92 | for (int i = 0; i < header.fileCnt; i++) 93 | { 94 | if (DEBUG) Console.WriteLine(string.Format("[DEBUG] READ ENTRY HEADER {0}/{1}", i + 1, header.fileCnt)); 95 | 96 | entries[i] = new BND4Entry(); 97 | entries[i].header = bin.ReadStruct(); 98 | entries[i].header.AssertIntegrity(); 99 | 100 | if (DEBUG) Console.WriteLine(string.Format("[DEBUG] READ ENTRY NAME {0}/{1}", i + 1, header.fileCnt)); 101 | 102 | bin.StepInto(entries[i].header.entryNameOffset); 103 | entries[i].name = header.isUnicode ? bin.ReadWideString() : bin.ReadShiftJIS(); 104 | bin.StepOut(); 105 | 106 | if (DEBUG) Console.WriteLine(string.Format("[DEBUG] READ ENTRY DATA {0}/{1}", i + 1, header.fileCnt)); 107 | 108 | bin.StepInto(entries[i].header.entryDataOffset); 109 | entries[i].data = bin.ReadBytes((int)entries[i].header.entrySize); 110 | bin.StepOut(); 111 | } 112 | 113 | if (DEBUG) Console.WriteLine("[DEBUG] READ COMPLETE"); 114 | } 115 | } 116 | 117 | /// 118 | /// Load a BND4 archive from a file and return a object. 119 | /// 120 | /// 121 | public static BND4File Load(string filePath) 122 | { 123 | var BND = new BND4File(); 124 | BND.LoadInPlace(filePath); 125 | return BND; 126 | } 127 | 128 | /// 129 | /// Update BND4 headers and save the archive. 130 | /// 131 | /// 132 | public void Save(string filePath) 133 | { 134 | if (DEBUG) Console.WriteLine("[DEBUG] SAVING BND4 ARCHIVE..."); 135 | 136 | CalculateHeaders(); 137 | 138 | using (BinWriter bin = new BinWriter(File.OpenWrite(filePath))) 139 | { 140 | if (DEBUG) Console.WriteLine("[DEBUG] WRITE BND4 HEADERS"); 141 | 142 | bin.WriteStruct(header); 143 | 144 | foreach (BND4Entry entry in entries) 145 | { 146 | if (DEBUG) Console.WriteLine(string.Format("[DEBUG] WRITE ENTRY HEADER '{0}'", entry.name)); 147 | 148 | bin.WriteStruct(entry.header); 149 | 150 | if (DEBUG) Console.WriteLine(string.Format("[DEBUG] WRITE ENTRY HEADER NAME '{0}'", entry.name)); 151 | 152 | bin.StepInto(entry.header.entryNameOffset); 153 | if (header.isUnicode) { bin.WriteWideString(entry.name); } 154 | else { bin.WriteShiftJIS(entry.name); } 155 | bin.StepOut(); 156 | 157 | if (DEBUG) Console.WriteLine(string.Format("[DEBUG] WRITE ENTRY HEADER DATA '{0}'", entry.name)); 158 | 159 | bin.StepInto(entry.header.entryDataOffset); 160 | bin.Write(entry.data); 161 | bin.StepOut(); 162 | } 163 | }; 164 | 165 | if (DEBUG) Console.WriteLine("[DEBUG] SAVING COMPLETED"); 166 | } 167 | 168 | public BND4Entry findEntryByName(string name) 169 | { 170 | foreach (BND4Entry entry in entries) 171 | { 172 | if (entry.name == name) { return entry; } 173 | } 174 | return null; 175 | } 176 | 177 | /// 178 | /// Unpack the archive files into a folder. 179 | /// 180 | public void Unpack(string folder = "", bool decrypt = true) 181 | { 182 | if (DEBUG) Console.WriteLine("[DEBUG] UNPACKING ENTRY DATA..."); 183 | 184 | if (!Directory.Exists(folder)) 185 | { 186 | Directory.CreateDirectory(folder); 187 | } 188 | 189 | foreach (BND4Entry entry in entries) 190 | { 191 | if (decrypt) 192 | { 193 | byte[] decrypted = entry.DecryptData(); 194 | File.WriteAllBytes(Path.Combine(folder, entry.name), decrypted); 195 | } 196 | else 197 | { 198 | File.WriteAllBytes(Path.Combine(folder, entry.name), entry.data); 199 | } 200 | } 201 | 202 | if (DEBUG) Console.WriteLine("[DEBUG] ENTRY DATA UNPACKED"); 203 | } 204 | 205 | /// 206 | /// Unpack a BND4 file into a folder. 207 | /// 208 | /// 209 | /// 210 | /// 211 | public static void Unpack(string filePath, string folder, bool decrypt = true) 212 | { 213 | var BND = new BND4File(filePath); 214 | BND.Unpack(folder, decrypt); 215 | } 216 | 217 | /// 218 | /// Create a BND4File object from subfiles stored in a folder. 219 | /// 220 | /// 221 | /// 222 | /// 223 | public static BND4File Pack(string folder, bool encrypt = true) 224 | { 225 | if (DEBUG) Console.WriteLine("[DEBUG] PACKING FOLDER INTO BND4 ARCHIVE..."); 226 | 227 | Utils.Assert(Directory.Exists(folder), "Folder does not exist"); 228 | 229 | string[] files = Directory.GetFiles(folder); 230 | Utils.Assert(files.Length != 0, "No subfiles to add to archive"); 231 | 232 | var BND = new BND4File(); 233 | BND.isUnicode = true; 234 | BND.entries = new BND4Entry[files.Length]; 235 | 236 | for (int i = 0; i < files.Length; i++) 237 | { 238 | BND.entries[i] = new BND4Entry(); 239 | BND.entries[i].name = Path.GetFileName(files[i]); 240 | 241 | byte[] data = File.ReadAllBytes(files[i]); 242 | if (encrypt) { BND.entries[i].SetEncryptedData(data, false); } 243 | else { BND.entries[i].data = data; } 244 | } 245 | 246 | if (DEBUG) Console.WriteLine("[DEBUG] PACKING COMPLETED"); 247 | 248 | return BND; 249 | } 250 | 251 | /// 252 | /// Pack a BND4 file from subfiles stored in a folder. 253 | /// 254 | /// 255 | /// 256 | /// 257 | public static void Pack(string folder, string filePath, bool encrypt = true) 258 | { 259 | var BND = Pack(folder, encrypt); 260 | BND.Save(filePath); 261 | } 262 | 263 | /// 264 | /// Patch the DS3 account flag that controls if a save can be opened by a user. 265 | /// 266 | /// 267 | public void PatchDS3AccountFlag(ulong steamID) 268 | { 269 | if (DEBUG) Console.WriteLine("[DEBUG] PATCH MENU ACCOUNT FLAG..."); 270 | 271 | BND4Entry menuEntry = entries[10]; 272 | // Overwrite account flag in menu file (Responsible for "Cannot load save" msg on startup) 273 | byte[] menuData = menuEntry.DecryptData(); 274 | Array.Copy(BitConverter.GetBytes(steamID), 0, menuData, 0x8, 8); 275 | menuEntry.SetEncryptedData(menuData); 276 | // Get used save slots bool array to overwrite save-specific account flags 277 | byte[] usedCharSlots = new byte[10]; 278 | Array.Copy(menuData, 0x1098, usedCharSlots, 0, 10); 279 | // For each used char. slot, patch its account flag 280 | for (int i = 0; i < 10; i++) 281 | { 282 | if (0 == usedCharSlots[i]) { continue; } 283 | if (DEBUG) Console.WriteLine("[DEBUG] PATCH ACCOUNT FLAG CHAR #" + i.ToString()); 284 | 285 | byte[] slotData = entries[i].DecryptData(); 286 | // This offset always seems to go 0x6F under the account flag 287 | uint flagOffset = BitConverter.ToUInt32(slotData, 0x58) + 0x6F; 288 | Array.Copy(BitConverter.GetBytes(steamID), 0, slotData, flagOffset, 8); 289 | entries[i].SetEncryptedData(slotData); 290 | } 291 | 292 | if (DEBUG) Console.WriteLine("[DEBUG] ACCOUNT FLAG PATCHED"); 293 | } 294 | } 295 | } 296 | --------------------------------------------------------------------------------