├── S63Tools
├── Sample
│ └── PERMIT.TXT
├── S63Tools
│ ├── S63Tools.csproj
│ ├── Program.cs
│ ├── Form1.cs
│ ├── Form1.resx
│ ├── Crc32.cs
│ ├── Form1.Designer.cs
│ ├── S63Tools.cs
│ └── BlowFish.cs
└── S63Tools.sln
└── .gitignore
/S63Tools/Sample/PERMIT.TXT:
--------------------------------------------------------------------------------
1 | :DATE 20220101 00:00
2 | :VERSION 2
3 | :ENC
4 | ABCDE01234567891011121314151617181920212223242526272829303132333,0,2,AB,
5 | ABCDF01234567891011121314151617181920212223242526272829303132333,0,2,AB,
6 | :ECS
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ################################################################################
2 | # This .gitignore file was automatically created by Microsoft(R) Visual Studio.
3 | ################################################################################
4 |
5 | /S63Tools/.vs
6 | /S63Tools/S63Tools/obj
7 | /S63Tools/S63Tools/bin
8 | *.user
9 |
--------------------------------------------------------------------------------
/S63Tools/S63Tools/S63Tools.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WinExe
5 | net8.0-windows
6 | enable
7 | true
8 | enable
9 | true
10 |
11 |
12 |
--------------------------------------------------------------------------------
/S63Tools/S63Tools/Program.cs:
--------------------------------------------------------------------------------
1 | namespace S63Tools
2 | {
3 | internal static class Program
4 | {
5 | ///
6 | /// The main entry point for the application.
7 | ///
8 | [STAThread]
9 | static void Main()
10 | {
11 | // To customize application configuration such as set high DPI settings or default font,
12 | // see https://aka.ms/applicationconfiguration.
13 | ApplicationConfiguration.Initialize();
14 | Application.Run(new Form1());
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/S63Tools/S63Tools.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.1.32421.90
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "S63Tools", "S63Tools\S63Tools.csproj", "{863B3D25-2F6B-49C1-A075-9F3C7B08DD2A}"
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 | {863B3D25-2F6B-49C1-A075-9F3C7B08DD2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {863B3D25-2F6B-49C1-A075-9F3C7B08DD2A}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {863B3D25-2F6B-49C1-A075-9F3C7B08DD2A}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {863B3D25-2F6B-49C1-A075-9F3C7B08DD2A}.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 = {ED5EE353-1C2E-42F3-A859-A2CF3BFBE28D}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/S63Tools/S63Tools/Form1.cs:
--------------------------------------------------------------------------------
1 | using System.Buffers.Binary;
2 | using System.IO.Compression;
3 | using System.Security.Cryptography;
4 | using System.Text;
5 |
6 | namespace S63Tools
7 | {
8 | public partial class Form1 : Form
9 | {
10 | private readonly int _zipHeader = 0x04034b50; // 'P', 'K', 3, 4
11 | private byte[]? _hardwareId;
12 |
13 | public Form1()
14 | {
15 | InitializeComponent();
16 | }
17 |
18 | private void buttonCalculate_Click(object sender, EventArgs e)
19 | {
20 | string permit = textBoxUserPermit.Text;
21 |
22 | try
23 | {
24 | var hwId = S63Tools.HackUserPermit(permit, out var mId, out var keyBytes);
25 | _hardwareId = hwId;
26 | labelMId.Text = $"x{mId:X4} ({(char)(mId >> 8)}{(char)(mId & 0xff)})";
27 | labelMKey.Text = Encoding.ASCII.GetString(keyBytes ?? Array.Empty());
28 | labelHwId.Text = Encoding.ASCII.GetString(hwId ?? Array.Empty());
29 | }
30 | catch (Exception ex)
31 | {
32 | MessageBox.Show(ex.Message);
33 | }
34 | }
35 |
36 | private void buttonCalculateFromCellPermit_Click(object sender, EventArgs e)
37 | {
38 | if (openFileDialogPermit.ShowDialog() != DialogResult.OK)
39 | {
40 | return;
41 | }
42 |
43 | try
44 | {
45 | var hwId = S63Tools.HackCellPermit(openFileDialogPermit.FileName);
46 | _hardwareId = hwId;
47 | labelMId.Text = "-";
48 | labelMKey.Text = "-";
49 | labelHwId.Text = Encoding.ASCII.GetString(hwId ?? Array.Empty());
50 | }
51 | catch (Exception ex)
52 | {
53 | MessageBox.Show(ex.Message);
54 | }
55 | }
56 |
57 | private void buttonDecryptCells_Click(object sender, EventArgs e)
58 | {
59 | var hwId = _hardwareId;
60 | if (hwId == null)
61 | {
62 | MessageBox.Show("First decrypt the HW_ID.");
63 | return;
64 | }
65 |
66 | var permits = new Dictionary();
67 | if (openFileDialogPermit.ShowDialog() != DialogResult.OK)
68 | {
69 | return;
70 | }
71 |
72 | if (folderBrowserDialog1.ShowDialog() != DialogResult.OK)
73 | {
74 | return;
75 | }
76 |
77 | S63Tools.LoadPermit(openFileDialogPermit.FileName, permits, new[] { hwId });
78 |
79 | foreach (var file in Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories))
80 | {
81 | var ext = Path.GetExtension(file).TrimStart('.');
82 | if (!int.TryParse(ext, out _))
83 | {
84 | continue;
85 | }
86 |
87 | byte[]? zipData = null;
88 | var data = File.ReadAllBytes(file);
89 | string fn = Path.GetFileNameWithoutExtension(file);
90 | if (permits.TryGetValue(fn, out var cellKeys))
91 | {
92 | var blow = new BlowFish(cellKeys.Item1);
93 | var decFile = blow.Decrypt(data, CipherMode.ECB);
94 |
95 | int header = BinaryPrimitives.ReadInt32LittleEndian(decFile);
96 | if (header != _zipHeader)
97 | {
98 | blow = new BlowFish(cellKeys.Item2);
99 | decFile = blow.Decrypt(data, CipherMode.ECB);
100 | header = BinaryPrimitives.ReadInt32LittleEndian(decFile);
101 | }
102 |
103 | if (header == _zipHeader)
104 | {
105 | zipData = decFile;
106 | }
107 | }
108 |
109 | if (zipData == null)
110 | {
111 | continue;
112 | }
113 |
114 | var zip = new ZipArchive(new MemoryStream(zipData));
115 | var entry = zip.Entries[0];
116 |
117 | data = new byte[entry.Length];
118 | int read = 0;
119 | var stream = entry.Open();
120 | while (read != data.Length)
121 | {
122 | read += stream.Read(data, read, data.Length - read);
123 | }
124 |
125 | File.WriteAllBytes(Path.Combine(folderBrowserDialog1.SelectedPath, "..", Path.GetFileName(file)), data);
126 | }
127 | }
128 | }
129 | }
--------------------------------------------------------------------------------
/S63Tools/S63Tools/Form1.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 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | 17, 17
122 |
123 |
124 | 186, 17
125 |
126 |
--------------------------------------------------------------------------------
/S63Tools/S63Tools/Crc32.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Security.Cryptography;
5 | using System.Text;
6 |
7 | ///
8 | /// Implements a 32-bit CRC hash algorithm compatible with Zip etc.
9 | ///
10 | ///
11 | ///
12 | /// Crc32 should only be used for backward compatibility with older file formats
13 | /// and algorithms. It is not secure enough for new applications.
14 | /// If you need to call multiple times for the same data either use the HashAlgorithm
15 | /// interface or remember that the result of one Compute call needs to be ~ (XOR) before
16 | /// being passed in as the seed for the next Compute call.
17 | ///
18 | public sealed class Crc32 : HashAlgorithm
19 | {
20 | ///
21 | /// The default polynomial
22 | ///
23 | private const uint DefaultPolynomial = 0xedb88320u;
24 |
25 | ///
26 | /// The default seed
27 | ///
28 | private const uint DefaultSeed = 0xffffffffu;
29 |
30 | ///
31 | /// The default table
32 | ///
33 | private static uint[] _defaultTable;
34 |
35 | ///
36 | /// The seed
37 | ///
38 | private readonly uint _seed;
39 |
40 | ///
41 | /// The table
42 | ///
43 | private readonly uint[] _table;
44 |
45 | ///
46 | /// The hash
47 | ///
48 | private uint _hash;
49 |
50 | ///
51 | /// Initializes a new instance of the class.
52 | ///
53 | public Crc32() : this(DefaultPolynomial, DefaultSeed)
54 | {
55 | }
56 |
57 | ///
58 | /// Initializes a new instance of the class.
59 | ///
60 | /// The polynomial.
61 | /// The seed.
62 | public Crc32(uint polynomial, uint seed)
63 | {
64 | _table = InitializeTable(polynomial);
65 | _seed = _hash = seed;
66 | }
67 |
68 | ///
69 | /// Initializes an implementation of the class.
70 | ///
71 | public override void Initialize()
72 | {
73 | _hash = _seed;
74 | }
75 |
76 | ///
77 | /// When overridden in a derived class, routes data written to the object into the hash algorithm for computing the
78 | /// hash.
79 | ///
80 | /// The input to compute the hash code for.
81 | /// The offset into the byte array from which to begin using data.
82 | /// The number of bytes in the byte array to use as data.
83 | protected override void HashCore(byte[] array, int ibStart, int cbSize)
84 | {
85 | _hash = CalculateHash(_table, _hash, array, ibStart, cbSize);
86 | }
87 |
88 | ///
89 | /// When overridden in a derived class, finalizes the hash computation after the last data is processed by the
90 | /// cryptographic stream object.
91 | ///
92 | ///
93 | /// The computed hash code.
94 | ///
95 | protected override byte[] HashFinal()
96 | {
97 | var hashBuffer = UInt32ToBigEndianBytes(~_hash);
98 | HashValue = hashBuffer;
99 | return hashBuffer;
100 | }
101 |
102 | ///
103 | /// Gets the size, in bits, of the computed hash code.
104 | ///
105 | public override int HashSize => 32;
106 |
107 | ///
108 | /// Computes the specified buffer.
109 | ///
110 | /// The buffer.
111 | ///
112 | public static uint Compute(Span buffer)
113 | {
114 | return Compute(DefaultSeed, buffer);
115 | }
116 |
117 | ///
118 | /// Computes the specified seed.
119 | ///
120 | /// The seed.
121 | /// The buffer.
122 | ///
123 | public static uint Compute(uint seed, Span buffer)
124 | {
125 | return Compute(DefaultPolynomial, seed, buffer);
126 | }
127 |
128 | ///
129 | /// Computes the specified polynomial.
130 | ///
131 | /// The polynomial.
132 | /// The seed.
133 | /// The buffer.
134 | ///
135 | public static uint Compute(uint polynomial, uint seed, Span buffer)
136 | {
137 | return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
138 | }
139 |
140 | ///
141 | /// Initializes the table.
142 | ///
143 | /// The polynomial.
144 | ///
145 | private static uint[] InitializeTable(uint polynomial)
146 | {
147 | if (polynomial == DefaultPolynomial && _defaultTable != null) return _defaultTable;
148 |
149 | var createTable = new uint[256];
150 | for (int i = 0; i < 256; i++)
151 | {
152 | uint entry = (uint)i;
153 | for (int j = 0; j < 8; j++)
154 | if ((entry & 1) == 1)
155 | entry = (entry >> 1) ^ polynomial;
156 | else
157 | entry = entry >> 1;
158 | createTable[i] = entry;
159 | }
160 |
161 | if (polynomial == DefaultPolynomial) _defaultTable = createTable;
162 |
163 | return createTable;
164 | }
165 |
166 | private static uint CalculateHash(uint[] table, uint seed, Span buffer, int start, int size)
167 | {
168 | uint crc = seed;
169 | for (int i = start; i < size - start; i++) crc = (crc >> 8) ^ table[buffer[i] ^ (crc & 0xff)];
170 | return crc;
171 | }
172 |
173 | private static byte[] UInt32ToBigEndianBytes(uint uint32)
174 | {
175 | var result = BitConverter.GetBytes(uint32);
176 |
177 | if (BitConverter.IsLittleEndian) Array.Reverse(result);
178 |
179 | return result;
180 | }
181 |
182 | public string ComputeHashString(byte[] buffer)
183 | {
184 | var hash = ComputeHash(buffer);
185 | var sb = new StringBuilder(8);
186 | foreach (byte b in hash) sb.Append(b.ToString("X2"));
187 |
188 | return sb.ToString();
189 | }
190 | }
--------------------------------------------------------------------------------
/S63Tools/S63Tools/Form1.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace S63Tools
2 | {
3 | partial class Form1
4 | {
5 | ///
6 | /// Required designer variable.
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// Clean up any resources being used.
12 | ///
13 | /// true if managed resources should be disposed; otherwise, false.
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Windows Form Designer generated code
24 |
25 | ///
26 | /// Required method for Designer support - do not modify
27 | /// the contents of this method with the code editor.
28 | ///
29 | private void InitializeComponent()
30 | {
31 | textBoxUserPermit = new TextBox();
32 | label1 = new Label();
33 | buttonCalculate = new Button();
34 | labelMId = new Label();
35 | label2 = new Label();
36 | label3 = new Label();
37 | label4 = new Label();
38 | labelMKey = new Label();
39 | labelHwId = new Label();
40 | openFileDialogPermit = new OpenFileDialog();
41 | buttonDecryptCells = new Button();
42 | folderBrowserDialog1 = new FolderBrowserDialog();
43 | label5 = new Label();
44 | buttonCalculateFromCellPermit = new Button();
45 | SuspendLayout();
46 | //
47 | // textBoxUserPermit
48 | //
49 | textBoxUserPermit.Location = new Point(89, 12);
50 | textBoxUserPermit.Name = "textBoxUserPermit";
51 | textBoxUserPermit.Size = new Size(217, 23);
52 | textBoxUserPermit.TabIndex = 0;
53 | //
54 | // label1
55 | //
56 | label1.AutoSize = true;
57 | label1.Location = new Point(12, 15);
58 | label1.Name = "label1";
59 | label1.Size = new Size(71, 15);
60 | label1.TabIndex = 1;
61 | label1.Text = "User Permit:";
62 | //
63 | // buttonCalculate
64 | //
65 | buttonCalculate.Location = new Point(312, 12);
66 | buttonCalculate.Name = "buttonCalculate";
67 | buttonCalculate.Size = new Size(75, 23);
68 | buttonCalculate.TabIndex = 2;
69 | buttonCalculate.Text = "Calculate";
70 | buttonCalculate.UseVisualStyleBackColor = true;
71 | buttonCalculate.Click += buttonCalculate_Click;
72 | //
73 | // labelMId
74 | //
75 | labelMId.AutoSize = true;
76 | labelMId.Location = new Point(89, 55);
77 | labelMId.Name = "labelMId";
78 | labelMId.Size = new Size(12, 15);
79 | labelMId.TabIndex = 3;
80 | labelMId.Text = "-";
81 | //
82 | // label2
83 | //
84 | label2.AutoSize = true;
85 | label2.Location = new Point(12, 55);
86 | label2.Name = "label2";
87 | label2.Size = new Size(37, 15);
88 | label2.TabIndex = 4;
89 | label2.Text = "M_ID:";
90 | //
91 | // label3
92 | //
93 | label3.AutoSize = true;
94 | label3.Location = new Point(12, 79);
95 | label3.Name = "label3";
96 | label3.Size = new Size(46, 15);
97 | label3.TabIndex = 5;
98 | label3.Text = "M_KEY:";
99 | //
100 | // label4
101 | //
102 | label4.AutoSize = true;
103 | label4.Location = new Point(12, 104);
104 | label4.Name = "label4";
105 | label4.Size = new Size(46, 15);
106 | label4.TabIndex = 6;
107 | label4.Text = "HW_ID:";
108 | //
109 | // labelMKey
110 | //
111 | labelMKey.AutoSize = true;
112 | labelMKey.Location = new Point(89, 79);
113 | labelMKey.Name = "labelMKey";
114 | labelMKey.Size = new Size(12, 15);
115 | labelMKey.TabIndex = 7;
116 | labelMKey.Text = "-";
117 | //
118 | // labelHwId
119 | //
120 | labelHwId.AutoSize = true;
121 | labelHwId.Location = new Point(89, 104);
122 | labelHwId.Name = "labelHwId";
123 | labelHwId.Size = new Size(12, 15);
124 | labelHwId.TabIndex = 8;
125 | labelHwId.Text = "-";
126 | //
127 | // openFileDialogPermit
128 | //
129 | openFileDialogPermit.FileName = "PERMIT.TXT";
130 | openFileDialogPermit.Filter = "Permit files|*.txt";
131 | //
132 | // buttonDecryptCells
133 | //
134 | buttonDecryptCells.Location = new Point(12, 145);
135 | buttonDecryptCells.Name = "buttonDecryptCells";
136 | buttonDecryptCells.Size = new Size(269, 79);
137 | buttonDecryptCells.TabIndex = 9;
138 | buttonDecryptCells.Text = "Decrypt cells. First select the PERMIT.TXT file, then select the (root) folder which contains the encrypted cells.";
139 | buttonDecryptCells.UseVisualStyleBackColor = true;
140 | buttonDecryptCells.Click += buttonDecryptCells_Click;
141 | //
142 | // label5
143 | //
144 | label5.AutoSize = true;
145 | label5.Location = new Point(393, 15);
146 | label5.Name = "label5";
147 | label5.Size = new Size(23, 15);
148 | label5.TabIndex = 10;
149 | label5.Text = "OR";
150 | //
151 | // buttonCalculateFromCellPermit
152 | //
153 | buttonCalculateFromCellPermit.Location = new Point(422, 11);
154 | buttonCalculateFromCellPermit.Name = "buttonCalculateFromCellPermit";
155 | buttonCalculateFromCellPermit.Size = new Size(182, 23);
156 | buttonCalculateFromCellPermit.TabIndex = 11;
157 | buttonCalculateFromCellPermit.Text = "Calculate from PERMIT.TXT";
158 | buttonCalculateFromCellPermit.UseVisualStyleBackColor = true;
159 | buttonCalculateFromCellPermit.Click += buttonCalculateFromCellPermit_Click;
160 | //
161 | // Form1
162 | //
163 | AutoScaleDimensions = new SizeF(7F, 15F);
164 | AutoScaleMode = AutoScaleMode.Font;
165 | ClientSize = new Size(800, 450);
166 | Controls.Add(buttonCalculateFromCellPermit);
167 | Controls.Add(label5);
168 | Controls.Add(buttonDecryptCells);
169 | Controls.Add(labelHwId);
170 | Controls.Add(labelMKey);
171 | Controls.Add(label4);
172 | Controls.Add(label3);
173 | Controls.Add(label2);
174 | Controls.Add(labelMId);
175 | Controls.Add(buttonCalculate);
176 | Controls.Add(label1);
177 | Controls.Add(textBoxUserPermit);
178 | Name = "Form1";
179 | Text = "S63 Tools";
180 | ResumeLayout(false);
181 | PerformLayout();
182 | }
183 |
184 | #endregion
185 |
186 | private TextBox textBoxUserPermit;
187 | private Label label1;
188 | private Button buttonCalculate;
189 | private Label labelMId;
190 | private Label label2;
191 | private Label label3;
192 | private Label label4;
193 | private Label labelMKey;
194 | private Label labelHwId;
195 | private OpenFileDialog openFileDialogPermit;
196 | private Button buttonDecryptCells;
197 | private FolderBrowserDialog folderBrowserDialog1;
198 | private Label label5;
199 | private Button buttonCalculateFromCellPermit;
200 | }
201 | }
--------------------------------------------------------------------------------
/S63Tools/S63Tools/S63Tools.cs:
--------------------------------------------------------------------------------
1 | using System.Buffers;
2 | using System.Buffers.Binary;
3 | using System.Buffers.Text;
4 | using System.Diagnostics;
5 | using System.Text;
6 |
7 | namespace S63Tools;
8 |
9 | public class S63Tools
10 | {
11 | private static readonly byte[] Hex = "0123456789ABCDEF"u8.ToArray();
12 |
13 | public static string CreateUserPermit(byte[] hwId, byte[] key, ushort mId)
14 | {
15 | if (hwId.Length != 5)
16 | {
17 | throw new Exception("Invalid HW ID length.");
18 | }
19 |
20 | Span hwIdBlock = stackalloc byte[8];
21 | hwId.CopyTo(hwIdBlock);
22 | hwIdBlock[5] = 3;
23 | hwIdBlock[6] = 3;
24 | hwIdBlock[7] = 3;
25 |
26 | var blow = new BlowFish(key);
27 | var enc = blow.EncryptECB(hwIdBlock);
28 |
29 | var permit = new byte[28];
30 | for (int i = 0; i < enc.Length; i++)
31 | {
32 | Utf8Formatter.TryFormat(enc[i], permit.AsSpan(2 * i), out _, new StandardFormat('X', 2));
33 | }
34 |
35 | uint crc = Crc32.Compute(permit.AsSpan(0, 16));
36 | Utf8Formatter.TryFormat(crc, permit.AsSpan(16), out _, new StandardFormat('X', 8));
37 | Utf8Formatter.TryFormat(mId, permit.AsSpan(24), out _, new StandardFormat('X', 4));
38 |
39 | return Encoding.ASCII.GetString(permit);
40 | }
41 |
42 | public static byte[] DecryptUserPermit(string userPermit, byte[] key, out ushort mId)
43 | {
44 | var permit = Encoding.ASCII.GetBytes(userPermit);
45 | uint crc = Crc32.Compute(permit.AsSpan(0, 16));
46 |
47 | Utf8Parser.TryParse(permit.AsSpan(16, 8), out uint crc2, out _, 'X');
48 |
49 | if (crc != crc2)
50 | {
51 | throw new Exception("Invalid CRC.");
52 | }
53 |
54 | Utf8Parser.TryParse(permit.AsSpan(24, 4), out mId, out _, 'X');
55 |
56 | var blow = new BlowFish(key);
57 | Span hwIdBlock = stackalloc byte[8];
58 | for (int i = 0; i < hwIdBlock.Length; i++)
59 | {
60 | Utf8Parser.TryParse(permit.AsSpan(i * 2, 2), out byte b, out _, 'X');
61 | hwIdBlock[i] = b;
62 | }
63 |
64 | hwIdBlock = blow.DecryptCBC(hwIdBlock);
65 |
66 | if (hwIdBlock.Length != 8)
67 | {
68 | throw new Exception("Invalid HW ID length.");
69 | }
70 |
71 | if (hwIdBlock[5] != 3 || hwIdBlock[6] != 3 || hwIdBlock[7] != 3)
72 | {
73 | throw new Exception("Invalid HW ID.");
74 | }
75 |
76 | return hwIdBlock.Slice(0, 5).ToArray();
77 | }
78 |
79 | public static string CreateCellPermit(byte[] hwId, string cellName, DateTime expiryDate, byte[] ck1, byte[] ck2)
80 | {
81 | if (hwId.Length != 5)
82 | {
83 | throw new Exception("Invalid HW ID length.");
84 | }
85 |
86 | if (ck1.Length != 5)
87 | {
88 | throw new Exception("Invalid Cell Key 1 length.");
89 | }
90 |
91 | if (ck2.Length != 5)
92 | {
93 | throw new Exception("Invalid Cell Key 2 length.");
94 | }
95 |
96 | var hwId6 = new byte[6];
97 | hwId.AsSpan().CopyTo(hwId6);
98 | hwId6[5] = hwId[0];
99 |
100 | var permit = new byte[64];
101 | Encoding.ASCII.GetBytes(cellName, permit.AsSpan());
102 | Utf8Formatter.TryFormat(expiryDate.Year, permit.AsSpan(8), out _, new StandardFormat('D', 4));
103 | Utf8Formatter.TryFormat(expiryDate.Month, permit.AsSpan(12), out _, new StandardFormat('D', 2));
104 | Utf8Formatter.TryFormat(expiryDate.Day, permit.AsSpan(14), out _, new StandardFormat('D', 2));
105 |
106 | Span block = stackalloc byte[8];
107 | var blow = new BlowFish(hwId6);
108 |
109 | ck1.CopyTo(block);
110 | block[5] = 3;
111 | block[6] = 3;
112 | block[7] = 3;
113 |
114 | var eck = blow.EncryptECB(block);
115 | for (int i = 0; i < eck.Length; i++)
116 | {
117 | Utf8Formatter.TryFormat(eck[i], permit.AsSpan(16 + 2 * i), out _, new StandardFormat('X', 2));
118 | }
119 |
120 | ck2.CopyTo(block);
121 | block[5] = 3;
122 | block[6] = 3;
123 | block[7] = 3;
124 |
125 | eck = blow.EncryptECB(block);
126 | for (int i = 0; i < eck.Length; i++)
127 | {
128 | Utf8Formatter.TryFormat(eck[i], permit.AsSpan(32 + 2 * i), out _, new StandardFormat('X', 2));
129 | }
130 |
131 | uint crc = Crc32.Compute(permit.AsSpan(0, 48));
132 |
133 | BinaryPrimitives.TryWriteUInt32BigEndian(block, crc);
134 | block[4] = 4;
135 | block[5] = 4;
136 | block[6] = 4;
137 | block[7] = 4;
138 |
139 | var encHash = blow.EncryptECB(block);
140 | for (int i = 0; i < encHash.Length; i++)
141 | {
142 | Utf8Formatter.TryFormat(encHash[i], permit.AsSpan(48 + 2 * i), out _, new StandardFormat('X', 2));
143 | }
144 |
145 | return Encoding.ASCII.GetString(permit);
146 | }
147 |
148 | public static bool TryDecryptCellPermit(string cellPermit, byte[] hwId, out byte[] ck1, out byte[] ck2)
149 | {
150 | var permit = Encoding.ASCII.GetBytes(cellPermit);
151 | uint crc = Crc32.Compute(permit.AsSpan(0, 48));
152 |
153 | Span hwId6 = stackalloc byte[6];
154 | hwId.AsSpan().CopyTo(hwId6);
155 | hwId6[5] = hwId[0];
156 |
157 | Span block = stackalloc byte[8];
158 | var blow = new BlowFish(hwId6);
159 |
160 | for (int i = 0; i < 8; i++)
161 | {
162 | Utf8Parser.TryParse(permit.AsSpan(48 + i * 2, 2), out byte b, out _, 'X');
163 | block[i] = b;
164 | }
165 |
166 | var crcBlock = blow.DecryptCBC(block);
167 | if (crcBlock[4] != 4 || crcBlock[5] != 4 || crcBlock[6] != 4 || crcBlock[7] != 4)
168 | {
169 | // Invalid CRC.
170 | ck1 = null;
171 | ck2 = null;
172 | return false;
173 | }
174 |
175 | uint crc2 = BinaryPrimitives.ReadUInt32BigEndian(crcBlock);
176 | if (crc != crc2)
177 | {
178 | // Invalid CRC.
179 | ck1 = null;
180 | ck2 = null;
181 | return false;
182 | }
183 |
184 | for (int i = 0; i < 8; i++)
185 | {
186 | Utf8Parser.TryParse(permit.AsSpan(16 + i * 2, 2), out byte b, out _, 'X');
187 | block[i] = b;
188 | }
189 |
190 | var ck1Block = blow.DecryptCBC(block);
191 | if (ck1Block[5] != 3 || ck1Block[6] != 3 || ck1Block[7] != 3)
192 | {
193 | // Invalid Cell Key 1.
194 | ck1 = null;
195 | ck2 = null;
196 | return false;
197 | }
198 |
199 | ck1 = ck1Block.AsSpan(0, 5).ToArray();
200 |
201 | for (int i = 0; i < 8; i++)
202 | {
203 | Utf8Parser.TryParse(permit.AsSpan(32 + i * 2, 2), out byte b, out _, 'X');
204 | block[i] = b;
205 | }
206 |
207 | var ck2Block = blow.DecryptCBC(block);
208 | if (ck2Block[5] != 3 || ck2Block[6] != 3 || ck2Block[7] != 3)
209 | {
210 | // Invalid Cell Key 2.
211 | ck1 = null;
212 | ck2 = null;
213 | return false;
214 | }
215 |
216 | ck2 = ck2Block.AsSpan(0, 5).ToArray();
217 | return true;
218 | }
219 |
220 | public static byte[]? HackUserPermit(string userPermit, out ushort mId, out byte[]? keyBytes)
221 | {
222 | var permit = Encoding.ASCII.GetBytes(userPermit);
223 | if (permit.Length < 28)
224 | {
225 | throw new Exception("Invalid user permit.");
226 | }
227 |
228 | uint crc = Crc32.Compute(permit.AsSpan(0, 16));
229 |
230 | Utf8Parser.TryParse(permit.AsSpan(16, 8), out uint crc2, out _, 'X');
231 |
232 | if (crc != crc2)
233 | {
234 | throw new Exception("Invalid CRC.");
235 | }
236 |
237 | Utf8Parser.TryParse(permit.AsSpan(24, 4), out mId, out _, 'X');
238 |
239 | Span hwIdBlockDef = stackalloc byte[8];
240 | for (int i = 0; i < hwIdBlockDef.Length; i++)
241 | {
242 | Utf8Parser.TryParse(permit.AsSpan(i * 2, 2), out byte b, out _, 'X');
243 | hwIdBlockDef[i] = b;
244 | }
245 |
246 | long t = Stopwatch.GetTimestamp();
247 | var finder = new KeyFinder(hwIdBlockDef);
248 | finder.FindKey();
249 |
250 | var elapsed = Stopwatch.GetElapsedTime(t);
251 | Debug.WriteLine("elapsed: " + elapsed);
252 |
253 | keyBytes = finder.FoundKey;
254 | return finder.FoundHwId;
255 | }
256 |
257 | public static byte[]? HackCellPermit(string permitPath)
258 | {
259 | var lines = File.ReadAllLines(permitPath);
260 | string cellPermit = null;
261 | foreach (string line in lines)
262 | {
263 | if (line.StartsWith(':'))
264 | {
265 | continue;
266 | }
267 |
268 | var parts = line.Split(',');
269 | if (parts.Length > 2)
270 | {
271 | cellPermit = parts[0];
272 | }
273 | }
274 |
275 | if (cellPermit != null)
276 | {
277 | var permit = Encoding.ASCII.GetBytes(cellPermit);
278 | uint crc = Crc32.Compute(permit.AsSpan(0, 48));
279 |
280 | Span blockData = stackalloc byte[24];
281 | for (int i = 0; i < 24; i++)
282 | {
283 | Utf8Parser.TryParse(permit.AsSpan(16 + i * 2, 2), out byte b, out _, 'X');
284 | blockData[i] = b;
285 | }
286 |
287 | long t = Stopwatch.GetTimestamp();
288 | var finder = new KeyFinder(blockData, crc);
289 | finder.FindHardwareId();
290 |
291 | var elapsed = Stopwatch.GetElapsedTime(t);
292 | Debug.WriteLine("elapsed: " + elapsed);
293 |
294 | return finder.FoundHwId;
295 | }
296 |
297 | throw new Exception("Failed to decrypt the permits.");
298 | }
299 |
300 | private class KeyFinder
301 | {
302 | private readonly byte[] _blockData;
303 | private readonly uint _crc;
304 | private int _i;
305 |
306 | public volatile byte[]? FoundKey;
307 | public volatile byte[]? FoundHwId;
308 |
309 | public KeyFinder(Span hwIdBlockDef, uint crc = 0)
310 | {
311 | _blockData = hwIdBlockDef.ToArray();
312 | _crc = crc;
313 | }
314 |
315 | private void FindKeyThreadFunc()
316 | {
317 | var key = new byte[5];
318 | Span hwIdBlock = stackalloc byte[8];
319 | var blow = new BlowFish();
320 |
321 | while (true)
322 | {
323 | int i = Interlocked.Increment(ref _i) - 1;
324 | if (i >= 0x100000 || FoundKey != null)
325 | {
326 | break;
327 | }
328 |
329 | key[4] = Hex[i & 0xf];
330 | key[3] = Hex[(i >> 4) & 0xf];
331 | key[2] = Hex[(i >> 8) & 0xf];
332 | key[1] = Hex[(i >> 12) & 0xf];
333 | key[0] = Hex[(i >> 16) & 0xf];
334 |
335 | blow.SetupKey5(key);
336 |
337 | _blockData.CopyTo(hwIdBlock);
338 | blow.DecryptCBC8(hwIdBlock);
339 |
340 | if (hwIdBlock[5] != 3 || hwIdBlock[6] != 3 || hwIdBlock[7] != 3)
341 | {
342 | continue;
343 | }
344 |
345 | FoundKey = key;
346 | FoundHwId = hwIdBlock.Slice(0, 5).ToArray();
347 | break;
348 | }
349 | }
350 |
351 | private void FindHwIdThreadFunc()
352 | {
353 | Span hwId6 = stackalloc byte[6];
354 | var block1 = _blockData.AsSpan(0, 8);
355 | var block2 = _blockData.AsSpan(8, 8);
356 | var blockCrc = _blockData.AsSpan(16, 8);
357 | while (true)
358 | {
359 | int i = Interlocked.Increment(ref _i) - 1;
360 | if (i >= 0x100000 || FoundHwId != null)
361 | {
362 | break;
363 | }
364 |
365 | hwId6[4] = Hex[i & 0xf];
366 | hwId6[3] = Hex[(i >> 4) & 0xf];
367 | hwId6[2] = Hex[(i >> 8) & 0xf];
368 | hwId6[1] = Hex[(i >> 12) & 0xf];
369 | hwId6[0] = Hex[(i >> 16) & 0xf];
370 | hwId6[5] = hwId6[0];
371 |
372 | var blow = new BlowFish(hwId6);
373 |
374 | var crcBlock = blow.DecryptCBC(blockCrc);
375 | if (crcBlock[4] != 4 || crcBlock[5] != 4 || crcBlock[6] != 4 || crcBlock[7] != 4)
376 | {
377 | // Invalid CRC.
378 | continue;
379 | }
380 |
381 | uint crc = BinaryPrimitives.ReadUInt32BigEndian(crcBlock);
382 | if (_crc != crc)
383 | {
384 | // Invalid CRC.
385 | continue;
386 | }
387 |
388 | var ck1Block = blow.DecryptCBC(block1);
389 | if (ck1Block[5] != 3 || ck1Block[6] != 3 || ck1Block[7] != 3)
390 | {
391 | // Invalid Cell Key 1.
392 | continue;
393 | }
394 |
395 | var ck2Block = blow.DecryptCBC(block2);
396 | if (ck2Block[5] != 3 || ck2Block[6] != 3 || ck2Block[7] != 3)
397 | {
398 | // Invalid Cell Key 2.
399 | continue;
400 | }
401 |
402 | //ck1 = ck1Block.AsSpan(0, 5).ToArray();
403 | //ck2 = ck2Block.AsSpan(0, 5).ToArray();
404 | FoundHwId = hwId6.Slice(0, 5).ToArray();
405 | break;
406 | }
407 | }
408 |
409 | private void Start(ThreadStart threadFunc)
410 | {
411 | var threads = new List();
412 | for (int i = 0; i < Environment.ProcessorCount; i++)
413 | {
414 | var t = new Thread(threadFunc);
415 | threads.Add(t);
416 | t.Start();
417 | }
418 |
419 | foreach (var thread in threads)
420 | {
421 | thread.Join();
422 | }
423 | }
424 |
425 | public void FindKey()
426 | {
427 | Start(FindKeyThreadFunc);
428 | }
429 |
430 | public void FindHardwareId()
431 | {
432 | Start(FindHwIdThreadFunc);
433 | }
434 | }
435 |
436 | public static void LoadPermit(string permitPath, Dictionary permits, byte[][] hardwareIds)
437 | {
438 | Exception exception = null;
439 | foreach (var hardwareId in hardwareIds)
440 | {
441 | try
442 | {
443 | if (TryLoadPermit(permitPath, permits, hardwareId))
444 | {
445 | return;
446 | }
447 | }
448 | catch (Exception ex)
449 | {
450 | exception = ex;
451 | }
452 | }
453 |
454 | if (exception != null)
455 | {
456 | throw exception;
457 | }
458 |
459 | throw new Exception("Failed to load the permits.");
460 | }
461 |
462 | public static bool TryLoadPermit(string permitPath, Dictionary permits, byte[] hardwareId)
463 | {
464 | var lines = File.ReadAllLines(permitPath);
465 | foreach (string line in lines)
466 | {
467 | if (line.StartsWith(':'))
468 | {
469 | continue;
470 | }
471 |
472 | var parts = line.Split(',');
473 | if (parts.Length > 2)
474 | {
475 | string permit = parts[0];
476 | if (!TryDecryptCellPermit(permit, hardwareId, out var ck1, out var ck2))
477 | {
478 | return false;
479 | }
480 |
481 | string cellName = permit.Substring(0, 8);
482 | permits[cellName] = (ck1, ck2);
483 | }
484 | }
485 |
486 | return true;
487 | }
488 | }
489 |
--------------------------------------------------------------------------------
/S63Tools/S63Tools/BlowFish.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Buffers.Binary;
3 | using System.Collections.Generic;
4 | using System.IO;
5 | using System.Linq;
6 | using System.Security.Cryptography;
7 |
8 | ///
9 | /// Blowfish encryption class.
10 | ///
11 | public sealed class BlowFish : IDisposable
12 | {
13 | // SBLOCKS ARE THE HEX DIGITS OF PI.
14 | // The amount of hex digits can be increased if you want to experiment with more rounds and longer key lengths
15 | private static readonly uint[] SetupP = {
16 | 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
17 | 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
18 | 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b,
19 | };
20 |
21 | private static readonly uint[] SetupS0 = {
22 | 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
23 | 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
24 | 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
25 | 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
26 | 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
27 | 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
28 | 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
29 | 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
30 | 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
31 | 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
32 | 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
33 | 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
34 | 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
35 | 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
36 | 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
37 | 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
38 | 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
39 | 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
40 | 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
41 | 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
42 | 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
43 | 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
44 | 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
45 | 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
46 | 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
47 | 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
48 | 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
49 | 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
50 | 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
51 | 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
52 | 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
53 | 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
54 | 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
55 | 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
56 | 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
57 | 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
58 | 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
59 | 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
60 | 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
61 | 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
62 | 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
63 | 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
64 | 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
65 | };
66 |
67 | private static readonly uint[] SetupS1 = {
68 | 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
69 | 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
70 | 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
71 | 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
72 | 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
73 | 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
74 | 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
75 | 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
76 | 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
77 | 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
78 | 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
79 | 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
80 | 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
81 | 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
82 | 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
83 | 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
84 | 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
85 | 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
86 | 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
87 | 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
88 | 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
89 | 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
90 | 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
91 | 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
92 | 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
93 | 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
94 | 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
95 | 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
96 | 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
97 | 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
98 | 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
99 | 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
100 | 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
101 | 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
102 | 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
103 | 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
104 | 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
105 | 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
106 | 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
107 | 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
108 | 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
109 | 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
110 | 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
111 | };
112 |
113 | private static readonly uint[] SetupS2 = {
114 | 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
115 | 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
116 | 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
117 | 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
118 | 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
119 | 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
120 | 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
121 | 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
122 | 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
123 | 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
124 | 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
125 | 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
126 | 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
127 | 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
128 | 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
129 | 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
130 | 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
131 | 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
132 | 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
133 | 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
134 | 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
135 | 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
136 | 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
137 | 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
138 | 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
139 | 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
140 | 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
141 | 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
142 | 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
143 | 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
144 | 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
145 | 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
146 | 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
147 | 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
148 | 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
149 | 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
150 | 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
151 | 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
152 | 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
153 | 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
154 | 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
155 | 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
156 | 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
157 | };
158 |
159 | private static readonly uint[] SetupS3 = {
160 | 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
161 | 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
162 | 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
163 | 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
164 | 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
165 | 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
166 | 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
167 | 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
168 | 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
169 | 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
170 | 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
171 | 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
172 | 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
173 | 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
174 | 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
175 | 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
176 | 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
177 | 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
178 | 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
179 | 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
180 | 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
181 | 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
182 | 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
183 | 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
184 | 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
185 | 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
186 | 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
187 | 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
188 | 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
189 | 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
190 | 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
191 | 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
192 | 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
193 | 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
194 | 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
195 | 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
196 | 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
197 | 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
198 | 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
199 | 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
200 | 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
201 | 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
202 | 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6,
203 | };
204 |
205 | private RandomNumberGenerator _randomSource = RandomNumberGenerator.Create();
206 |
207 | // SBLOCKS
208 | private readonly uint[] _bfS0 = new uint[256];
209 | private readonly uint[] _bfS1 = new uint[256];
210 | private readonly uint[] _bfS2 = new uint[256];
211 | private readonly uint[] _bfS3 = new uint[256];
212 | private readonly uint[] _bfP = new uint[18];
213 |
214 | // HALF-BLOCKS
215 | private uint _xlPar;
216 | private uint _xrPar;
217 | private readonly byte[] _initVector = new byte[8];
218 |
219 | ///
220 | /// Initializes a new instance of the class with the byte key provided.
221 | ///
222 | public BlowFish()
223 | {
224 | }
225 |
226 | ///
227 | /// Initializes a new instance of the class with the byte key provided.
228 | ///
229 | /// Cipher key as a byte array.
230 | public BlowFish(ReadOnlySpan cipherKey)
231 | {
232 | if (cipherKey == null)
233 | {
234 | throw new ArgumentNullException(nameof(cipherKey));
235 | }
236 |
237 | SetupKey(cipherKey);
238 | }
239 |
240 | ///
241 | /// Gets a value indicating whether this object is disposed or not.
242 | ///
243 | ///
244 | /// A value indicating whether this object is disposed or not.
245 | ///
246 | public bool IsDisposed { get; private set; }
247 |
248 | ///
249 | /// Gets or sets initialization vector for CBC mode.
250 | ///
251 | ///
252 | /// Initialization vector for CBC mode.
253 | ///
254 | public IEnumerable IV
255 | {
256 | get => _initVector;
257 | set
258 | {
259 | if (value == null)
260 | {
261 | _initVector.AsSpan().Clear();
262 | return;
263 | }
264 |
265 | var iv = value.ToArray().AsSpan();
266 | if (iv.Length == 8)
267 | {
268 | iv.CopyTo(_initVector);
269 | }
270 | else
271 | {
272 | throw new InvalidOperationException("Invalid IV Size");
273 | }
274 | }
275 | }
276 |
277 | ///
278 | /// Gets or sets a value indicating whether non standard blowfish mode.
279 | ///
280 | ///
281 | /// A value indicating whether non standard blowfish mode.
282 | ///
283 | public bool NonStandard { get; set; }
284 |
285 | ///
286 | /// XoR encrypts two 8 bit blocks.
287 | ///
288 | /// 8 bit block 1.
289 | /// 8 bit block 2.
290 | public static void XorBlock(Span block, Span iv)
291 | {
292 | if (block.Length is 0)
293 | {
294 | throw new ArgumentNullException(nameof(block));
295 | }
296 |
297 | if (iv.Length == 0)
298 | {
299 | throw new ArgumentNullException(nameof(iv));
300 | }
301 |
302 | XorBlock_private(block, iv);
303 | }
304 |
305 | ///
306 | /// XoR encrypts two 8 bit blocks.
307 | ///
308 | /// 8 bit block 1.
309 | /// 8 bit block 2.
310 | public static void XorBlock(Stream block, byte[] iv)
311 | {
312 | if (block is null)
313 | {
314 | throw new ArgumentNullException(nameof(block));
315 | }
316 |
317 | if (block is MemoryStream ms)
318 | {
319 | XorBlock(ms.GetBuffer(), iv);
320 | }
321 | }
322 |
323 | ///
324 | /// Encrypts a byte array in CBC mode.
325 | /// IV must be created and saved manually.
326 | ///
327 | /// Plaintext data to encrypt.
328 | /// Ciphertext.
329 | public byte[] EncryptCBC(Span pt)
330 | {
331 | int paddedLen = pt.Length;
332 | var pt8 = pt.ToArray();
333 |
334 | if (paddedLen % 8 != 0)
335 | {
336 | paddedLen = ((paddedLen >> 3) + 1) << 3;
337 | pt8 = new byte[paddedLen];
338 | pt.CopyTo(pt8);
339 | }
340 |
341 | Crypt_CBC(pt8, false);
342 | return pt8;
343 | }
344 |
345 | ///
346 | /// Encrypts a byte array in CBC mode.
347 | /// IV must be created and saved manually.
348 | ///
349 | /// Plaintext data to encrypt.
350 | public void EncryptCBC8(Span text)
351 | {
352 | XorBlock_private(text, _initVector);
353 | BlockEncrypt(text);
354 | }
355 |
356 | ///
357 | /// Decrypts a byte array in CBC mode.
358 | /// IV must be created and saved manually.
359 | ///
360 | /// Ciphertext data to decrypt.
361 | /// Plaintext.
362 | public byte[] DecryptCBC(Span ct)
363 | {
364 | int paddedLen = ct.Length;
365 | var ct8 = ct.ToArray();
366 |
367 | if (paddedLen % 8 != 0)
368 | {
369 | paddedLen = ((paddedLen >> 3) + 1) << 3;
370 | ct8 = new byte[paddedLen];
371 | ct.CopyTo(ct8);
372 | }
373 |
374 | Crypt_CBC(ct8, true);
375 | return ct8;
376 | }
377 |
378 | ///
379 | /// Decrypts a byte array in CBC mode.
380 | /// IV must be created and saved manually.
381 | ///
382 | /// Ciphertext data to decrypt.
383 | public void DecryptCBC8(Span text)
384 | {
385 | BlockDecrypt(text);
386 | XorBlock_private(text, _initVector);
387 | }
388 |
389 | ///
390 | /// Encrypts a byte array in ECB mode.
391 | ///
392 | /// Plaintext data.
393 | /// Ciphertext bytes.
394 | public byte[] EncryptECB(Span pt)
395 | {
396 | if (pt == null) throw new ArgumentNullException(nameof(pt));
397 |
398 | return Crypt_ECB(pt.ToArray(), false);
399 | }
400 |
401 | ///
402 | /// Decrypts a byte array.
403 | ///
404 | /// Ciphertext byte array.
405 | /// Cipher mode.
406 | /// Plaintext or if mode is not .
407 | public byte[] Decrypt(byte[] cipherText, CipherMode mode)
408 | => mode switch
409 | {
410 | CipherMode.ECB => Decrypt_ECB(cipherText),
411 | CipherMode.CBC or CipherMode.CFB or CipherMode.CTS or CipherMode.OFB or _ => null,
412 | };
413 |
414 | ///
415 | /// Cleans up the Blowfish items.
416 | ///
417 | public void Dispose()
418 | => Dispose(true);
419 |
420 | ///
421 | /// Creates and sets a random initialization vector.
422 | ///
423 | /// The random IV.
424 | public byte[] SetRandomIV()
425 | {
426 | _randomSource.GetBytes(_initVector);
427 | return _initVector;
428 | }
429 |
430 | private static void XorBlock_private(Span block, Span iv)
431 | {
432 | for (var i = 0; i < block.Length; i++)
433 | {
434 | block[i] ^= iv[i];
435 | }
436 | }
437 |
438 | private byte[] Decrypt_ECB(byte[] ct)
439 | => Crypt_ECB(ct, true);
440 |
441 | public void SetupKey(ReadOnlySpan cipherKey)
442 | {
443 | SetupP.CopyTo(_bfP.AsSpan());
444 |
445 | // set up the S blocks
446 | SetupS0.CopyTo(_bfS0.AsSpan());
447 | SetupS1.CopyTo(_bfS1.AsSpan());
448 | SetupS2.CopyTo(_bfS2.AsSpan());
449 | SetupS3.CopyTo(_bfS3.AsSpan());
450 | if (cipherKey.Length > 56)
451 | {
452 | throw new InvalidOperationException("Key Too Long");
453 | }
454 |
455 | var j = 0;
456 | for (var i = 0; i < 18; i++)
457 | {
458 | var d = (uint) ((((((cipherKey[j % cipherKey.Length] * 256) + cipherKey[(j + 1) % cipherKey.Length]) *
459 | 256) + cipherKey[(j + 2) % cipherKey.Length]) * 256) +
460 | cipherKey[(j + 3) % cipherKey.Length]);
461 | _bfP[i] ^= d;
462 | j = (j + 4) % cipherKey.Length;
463 | }
464 |
465 | _xlPar = 0;
466 | _xrPar = 0;
467 | for (var i = 0; i < 18; i += 2)
468 | {
469 | Encipher();
470 | _bfP[i] = _xlPar;
471 | _bfP[i + 1] = _xrPar;
472 | }
473 |
474 | for (var i = 0; i < 256; i += 2)
475 | {
476 | Encipher();
477 | _bfS0[i] = _xlPar;
478 | _bfS0[i + 1] = _xrPar;
479 | }
480 |
481 | for (var i = 0; i < 256; i += 2)
482 | {
483 | Encipher();
484 | _bfS1[i] = _xlPar;
485 | _bfS1[i + 1] = _xrPar;
486 | }
487 |
488 | for (var i = 0; i < 256; i += 2)
489 | {
490 | Encipher();
491 | _bfS2[i] = _xlPar;
492 | _bfS2[i + 1] = _xrPar;
493 | }
494 |
495 | for (var i = 0; i < 256; i += 2)
496 | {
497 | Encipher();
498 | _bfS3[i] = _xlPar;
499 | _bfS3[i + 1] = _xrPar;
500 | }
501 | }
502 |
503 | public unsafe void SetupKey5(ReadOnlySpan cipherKey)
504 | {
505 | SetupP.CopyTo(_bfP.AsSpan());
506 |
507 | // set up the S blocks
508 | SetupS0.CopyTo(_bfS0.AsSpan());
509 | SetupS1.CopyTo(_bfS1.AsSpan());
510 | SetupS2.CopyTo(_bfS2.AsSpan());
511 | SetupS3.CopyTo(_bfS3.AsSpan());
512 |
513 | var j = 0;
514 | fixed (byte* pck = &cipherKey.GetPinnableReference())
515 | {
516 | uint d0 = (uint)(((pck[0] * 256 + pck[1]) * 256 + pck[2]) * 256 + pck[3]);
517 | uint d1 = (uint)(((pck[1] * 256 + pck[2]) * 256 + pck[3]) * 256 + pck[4]);
518 | uint d2 = (uint)(((pck[2] * 256 + pck[3]) * 256 + pck[4]) * 256 + pck[0]);
519 | uint d3 = (uint)(((pck[3] * 256 + pck[4]) * 256 + pck[0]) * 256 + pck[1]);
520 | uint d4 = (uint)(((pck[4] * 256 + pck[0]) * 256 + pck[1]) * 256 + pck[2]);
521 |
522 | var p = _bfP;
523 | p[0] ^= d0;
524 | p[1] ^= d4;
525 | p[2] ^= d3;
526 | p[3] ^= d2;
527 | p[4] ^= d1;
528 | p[5] ^= d0;
529 | p[6] ^= d4;
530 | p[7] ^= d3;
531 | p[8] ^= d2;
532 | p[9] ^= d1;
533 | p[10] ^= d0;
534 | p[11] ^= d4;
535 | p[12] ^= d3;
536 | p[13] ^= d2;
537 | p[14] ^= d1;
538 | p[15] ^= d0;
539 | p[16] ^= d4;
540 | p[17] ^= d3;
541 | }
542 |
543 | _xlPar = 0;
544 | _xrPar = 0;
545 | for (var i = 0; i < 18; i += 2)
546 | {
547 | Encipher();
548 | _bfP[i] = _xlPar;
549 | _bfP[i + 1] = _xrPar;
550 | }
551 |
552 | for (var i = 0; i < 256; i += 2)
553 | {
554 | Encipher();
555 | _bfS0[i] = _xlPar;
556 | _bfS0[i + 1] = _xrPar;
557 | }
558 |
559 | for (var i = 0; i < 256; i += 2)
560 | {
561 | Encipher();
562 | _bfS1[i] = _xlPar;
563 | _bfS1[i + 1] = _xrPar;
564 | }
565 |
566 | for (var i = 0; i < 256; i += 2)
567 | {
568 | Encipher();
569 | _bfS2[i] = _xlPar;
570 | _bfS2[i + 1] = _xrPar;
571 | }
572 |
573 | for (var i = 0; i < 256; i += 2)
574 | {
575 | Encipher();
576 | _bfS3[i] = _xlPar;
577 | _bfS3[i + 1] = _xrPar;
578 | }
579 | }
580 |
581 | private byte[] Crypt_ECB(byte[] text, bool decrypt)
582 | {
583 | var paddedLen = text.Length % 8 == 0 ? text.Length : text.Length + 8 - (text.Length % 8);
584 | if (paddedLen != text.Length)
585 | {
586 | Array.Resize(ref text, paddedLen);
587 | }
588 |
589 | var plainText = text.AsSpan();
590 | for (var i = 0; i < plainText.Length; i += 8)
591 | {
592 | var block = plainText.Slice(i, 8);
593 | if (decrypt)
594 | {
595 | BlockDecrypt(block);
596 | }
597 | else
598 | {
599 | BlockEncrypt(block);
600 | }
601 | }
602 |
603 | return text;
604 | }
605 |
606 | private void Crypt_CBC(Span text, bool decrypt)
607 | {
608 | byte[] preblock = null;
609 |
610 | var iv = _initVector.AsSpan();
611 |
612 | for (var i = 0; i < text.Length; i += 8)
613 | {
614 | var block = text.Slice(i, 8);
615 | if (decrypt)
616 | {
617 | preblock = block.ToArray();
618 | BlockDecrypt(block);
619 | }
620 |
621 | XorBlock_private(block, iv);
622 | if (!decrypt)
623 | {
624 | BlockEncrypt(block);
625 | iv = block;
626 | }
627 | else
628 | {
629 | // clone preblock into iv.
630 | iv = preblock.AsSpan();
631 | }
632 | }
633 | }
634 |
635 | private void BlockEncrypt(Span block)
636 | {
637 | SetBlock(block);
638 | Encipher();
639 | GetBlock(block);
640 | }
641 |
642 | private void BlockDecrypt(Span block)
643 | {
644 | SetBlock(block);
645 | Decipher();
646 | GetBlock(block);
647 | }
648 |
649 | private void SetBlock(Span block)
650 | {
651 | // split the block
652 | if (!NonStandard)
653 | {
654 | _xlPar = BinaryPrimitives.ReadUInt32BigEndian(block);
655 | _xrPar = BinaryPrimitives.ReadUInt32BigEndian(block.Slice(4));
656 | }
657 | else
658 | {
659 | _xrPar = BinaryPrimitives.ReadUInt32LittleEndian(block);
660 | _xlPar = BinaryPrimitives.ReadUInt32LittleEndian(block.Slice(4));
661 | }
662 | }
663 |
664 | private void GetBlock(Span block)
665 | {
666 | if (!NonStandard)
667 | {
668 | BinaryPrimitives.TryWriteUInt32BigEndian(block, _xlPar);
669 | BinaryPrimitives.TryWriteUInt32BigEndian(block.Slice(4), _xrPar);
670 | }
671 | else
672 | {
673 | BinaryPrimitives.TryWriteUInt32LittleEndian(block, _xrPar);
674 | BinaryPrimitives.TryWriteUInt32LittleEndian(block.Slice(4), _xlPar);
675 | }
676 | }
677 |
678 | private void Encipher()
679 | {
680 | _xlPar ^= _bfP[0];
681 | _xrPar = Round(_xlPar) ^ _bfP[1] ^ _xrPar;
682 | _xlPar = Round(_xrPar) ^ _bfP[2] ^ _xlPar;
683 | _xrPar = Round(_xlPar) ^ _bfP[3] ^ _xrPar;
684 | _xlPar = Round(_xrPar) ^ _bfP[4] ^ _xlPar;
685 | _xrPar = Round(_xlPar) ^ _bfP[5] ^ _xrPar;
686 | _xlPar = Round(_xrPar) ^ _bfP[6] ^ _xlPar;
687 | _xrPar = Round(_xlPar) ^ _bfP[7] ^ _xrPar;
688 | _xlPar = Round(_xrPar) ^ _bfP[8] ^ _xlPar;
689 | _xrPar = Round(_xlPar) ^ _bfP[9] ^ _xrPar;
690 | _xlPar = Round(_xrPar) ^ _bfP[10] ^ _xlPar;
691 | _xrPar = Round(_xlPar) ^ _bfP[11] ^ _xrPar;
692 | _xlPar = Round(_xrPar) ^ _bfP[12] ^ _xlPar;
693 | _xrPar = Round(_xlPar) ^ _bfP[13] ^ _xrPar;
694 | _xlPar = Round(_xrPar) ^ _bfP[14] ^ _xlPar;
695 | _xrPar = Round(_xlPar) ^ _bfP[15] ^ _xrPar;
696 | _xlPar = Round(_xrPar) ^ _bfP[16] ^ _xlPar;
697 | _xrPar ^= _bfP[17];
698 |
699 | // swap the blocks
700 | var swap = _xlPar;
701 | _xlPar = _xrPar;
702 | _xrPar = swap;
703 | }
704 |
705 | private void Decipher()
706 | {
707 | _xlPar ^= _bfP[17];
708 | for (uint i = 16; i > 0; i -= 2)
709 | {
710 | _xrPar = Round(_xrPar, _xlPar, i);
711 | _xlPar = Round(_xlPar, _xrPar, i - 1);
712 | }
713 |
714 | _xrPar ^= _bfP[0];
715 |
716 | // swap the blocks
717 | var swap = _xlPar;
718 | _xlPar = _xrPar;
719 | _xrPar = swap;
720 | }
721 |
722 | private uint Round(uint a, uint b, uint n) => (((_bfS0[(b >> 24) & 0xff] + _bfS1[(b >> 16) & 0xff]) ^ _bfS2[(b >> 8) & 0xff]) + _bfS3[b & 0xff]) ^ _bfP[n] ^ a;
723 |
724 | private uint Round(uint b) => ((_bfS0[(b >> 24) & 0xff] + _bfS1[(b >> 16) & 0xff]) ^ _bfS2[(b >> 8) & 0xff]) + _bfS3[b & 0xff];
725 |
726 | private void Dispose(bool disposing)
727 | {
728 | if (!IsDisposed)
729 | {
730 | if (disposing)
731 | {
732 | _randomSource.Dispose();
733 | _randomSource = null;
734 | }
735 |
736 | IsDisposed = true;
737 | }
738 | }
739 | }
--------------------------------------------------------------------------------