├── Demo ├── KeyGen.csproj.user ├── app.config ├── System.Ini │ ├── IInitializer.cs │ ├── Win32ErrorMessageAttribute.cs │ ├── AssemblyMessageAttribute.cs │ ├── ResourceAttribute.cs │ └── ModuleStringAttribute.cs ├── System.Windows.Forms │ ├── IUserControl.cs │ ├── DialogBox.cs │ ├── TextControl.cs │ ├── GenLicForm.resx │ └── PasswordForm.cs ├── System.ComponentModel │ ├── Win32FormatMessageFlags.cs │ ├── ModuleMessageFormatterConverter.cs │ ├── Win32MessageFormatterConverter.cs │ ├── AssemblyMessageFormatter.cs │ ├── ModuleMessageFormatter.cs │ └── Win32MessageFormatter.cs ├── Properties │ ├── TestAssemblyInfo.cs │ └── KeyGenAssemblyInfo.cs ├── GenLic │ └── Program.cs ├── Test.csproj ├── KeyGen.csproj ├── Test │ └── Program.cs ├── System │ └── Extensions.cs ├── System.Management.WMI │ ├── ProcessorInfo.cs │ └── NetworkAdapterConfigurationInfo.cs └── System.Resourses │ └── ResourceFile.cs ├── Source ├── Text │ ├── PrintableEncoding.cs │ ├── IPrintableEncoding.cs │ ├── Base16Encoding.cs │ ├── InternalBaseEncoding.cs │ ├── BaseEncoding.cs │ ├── Base10Encoding.cs │ ├── Base32Encoding.cs │ ├── Base64Encoding.cs │ └── CustomEncoding.cs ├── Security │ ├── Activation │ │ ├── ActivationKeyConverter.cs │ │ ├── ActivationKeyEncryptor.cs │ │ ├── ActivationKeyDecryptor.cs │ │ └── ActivationKeyBinaryParser.cs │ └── Cryptography │ │ ├── SipHashAlgorithm.cs │ │ └── ARC4CryptoTransform.cs └── IO │ └── IniFile.cs ├── LICENSE ├── ActivationKey.sln ├── Properties └── AssemblyInfo.cs ├── ActivationKey.csproj └── .gitignore /Demo/KeyGen.csproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /Demo/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Demo/System.Ini/IInitializer.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace System.Ini 4 | { 5 | public interface IInitializer 6 | { 7 | void ReadSettings(Assembly assembly = null); 8 | 9 | void WriteSettings(Assembly assembly = null); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Demo/System.Windows.Forms/IUserControl.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | 3 | namespace System.Windows.Forms 4 | { 5 | internal interface IUserControl 6 | { 7 | string DisplayName {get; set;} 8 | bool Required {get; set;} 9 | bool Complete { get; } 10 | 11 | string Text {get; set;} 12 | event EventHandler TextChanged; 13 | 14 | bool Allert(ref Collection controlNames); 15 | 16 | void Light(); 17 | 18 | void Reset(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Demo/System.ComponentModel/Win32FormatMessageFlags.cs: -------------------------------------------------------------------------------- 1 | namespace System.ComponentModel 2 | { 3 | [Serializable] 4 | [Flags] 5 | internal enum Win32FormatMessageFlags 6 | { 7 | FORMAT_MESSAGE_NONE = 0x0, 8 | FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100, 9 | FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x2000, 10 | FORMAT_MESSAGE_FROM_HMODULE = 0x800, 11 | FORMAT_MESSAGE_FROM_STRING = 0x400, 12 | FORMAT_MESSAGE_FROM_SYSTEM = 0x1000, 13 | FORMAT_MESSAGE_IGNORE_INSERTS = 0x200, 14 | FORMAT_MESSAGE_MAX_WIDTH_MASK = 0xFF 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Demo/Properties/TestAssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | [assembly: AssemblyTitle("Test")] 4 | [assembly: AssemblyDescription("")] 5 | [assembly: AssemblyConfiguration("")] 6 | [assembly: AssemblyCompany("")] 7 | [assembly: AssemblyProduct("Test")] 8 | [assembly: AssemblyCopyright("Copyright © 2024")] 9 | [assembly: AssemblyTrademark("")] 10 | [assembly: AssemblyCulture("")] 11 | [assembly: ComVisible(false)] 12 | [assembly: Guid("414850d2-031c-49eb-9ecc-098599e57f2f")] 13 | [assembly: AssemblyVersion("1.0.0.0")] 14 | [assembly: AssemblyFileVersion("1.0.0.0")] 15 | -------------------------------------------------------------------------------- /Demo/Properties/KeyGenAssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | [assembly: AssemblyTitle("Activation Key Generator 5.0 Application")] 5 | [assembly: AssemblyDescription("Activation Key Generator 5.0 Application")] 6 | [assembly: AssemblyConfiguration("")] 7 | [assembly: AssemblyCompany("NG256")] 8 | [assembly: AssemblyProduct("NG256 Activation Key Generator")] 9 | [assembly: AssemblyCopyright("© NG256 2019-2024")] 10 | [assembly: AssemblyFileVersion("5.0.0.1")] 11 | [assembly: ComVisible(false)] 12 | [assembly: Guid("77bccba3-838a-4b6e-be95-9e4ec16c46d9")] 13 | [assembly: AssemblyVersion("5.0.0.1")] 14 | -------------------------------------------------------------------------------- /Demo/System.Ini/Win32ErrorMessageAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace System.Ini 2 | { 3 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 4 | public sealed class Win32ErrorMessageAttribute : Attribute 5 | { 6 | private static readonly Win32ErrorMessageAttribute _defaultAttribute = new Win32ErrorMessageAttribute(0u); 7 | 8 | public uint MessageId {get; set;} 9 | public string[] Arguments {get; set;} 10 | 11 | public override bool Match(object obj) 12 | { 13 | Win32ErrorMessageAttribute iniEntryAttribute; 14 | if ((iniEntryAttribute = obj as Win32ErrorMessageAttribute) != null) 15 | { 16 | return iniEntryAttribute.MessageId == MessageId; 17 | } 18 | return false; 19 | } 20 | 21 | public override bool IsDefaultAttribute() 22 | { 23 | return Match(_defaultAttribute); 24 | } 25 | 26 | public Win32ErrorMessageAttribute(uint msgCode, params string[] args) 27 | { 28 | MessageId = msgCode; 29 | Arguments = args; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Demo/System.Ini/AssemblyMessageAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace System.Ini 2 | { 3 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 4 | public sealed class AssemblyMessageAttribute : Attribute 5 | { 6 | private static readonly AssemblyMessageAttribute _defaultAttribute = new AssemblyMessageAttribute("UnknownError"); 7 | 8 | public string MessageId {get; set;} 9 | public string[] Arguments {get; set;} 10 | 11 | public override bool Match(object obj) 12 | { 13 | AssemblyMessageAttribute iniEntryAttribute; 14 | if ((iniEntryAttribute = obj as AssemblyMessageAttribute) != null) 15 | { 16 | return iniEntryAttribute.MessageId == MessageId; 17 | } 18 | return false; 19 | } 20 | 21 | public override bool IsDefaultAttribute() 22 | { 23 | return Match(_defaultAttribute); 24 | } 25 | 26 | public AssemblyMessageAttribute(string msgCode, params string[] args) 27 | { 28 | MessageId = msgCode; 29 | Arguments = args; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Demo/System.Ini/ResourceAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace System.Ini 2 | { 3 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 4 | public sealed class ResourceAttribute : Attribute 5 | { 6 | private static readonly ResourceAttribute _defaultAttribute = new ResourceAttribute(); 7 | 8 | public string Name 9 | { 10 | get; 11 | set; 12 | } 13 | 14 | public object DefaultValue 15 | { 16 | get; 17 | set; 18 | } 19 | 20 | public override bool Match(object obj) 21 | { 22 | ResourceAttribute iniEntryAttribute; 23 | if ((iniEntryAttribute = obj as ResourceAttribute) != null) 24 | { 25 | return iniEntryAttribute.Name == Name; 26 | } 27 | return false; 28 | } 29 | 30 | public override bool IsDefaultAttribute() 31 | { 32 | return Match(_defaultAttribute); 33 | } 34 | 35 | public ResourceAttribute(string name = null, object defaultValue = null) 36 | { 37 | Name = name; 38 | DefaultValue = defaultValue; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Demo/System.Ini/ModuleStringAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace System.Ini 2 | { 3 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 4 | public sealed class ModuleStringAttribute : Attribute 5 | { 6 | private static readonly ModuleStringAttribute _defaultAttribute = new ModuleStringAttribute("user32.dll", 0u); 7 | 8 | public string Name {get; set;} 9 | public uint MessageId {get; set;} 10 | public string[] Arguments {get; set;} 11 | 12 | public override bool Match(object obj) 13 | { 14 | ModuleStringAttribute iniEntryAttribute; 15 | if ((iniEntryAttribute = obj as ModuleStringAttribute) != null && iniEntryAttribute.MessageId == MessageId) 16 | { 17 | return iniEntryAttribute.Name == Name; 18 | } 19 | return false; 20 | } 21 | 22 | public override bool IsDefaultAttribute() 23 | { 24 | return Match(_defaultAttribute); 25 | } 26 | 27 | public ModuleStringAttribute(string name, uint msgCode, params string[] args) 28 | { 29 | Name = name; 30 | MessageId = msgCode; 31 | Arguments = args; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Source/Text/PrintableEncoding.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: PrintableEncoding.cs 4 | 5 | • Description. 6 | 7 | Represents an enum of encoding types. Each enumeration 8 | element represents a specific encoding type. 9 | 10 | ***************************************************************/ 11 | 12 | namespace System.Text 13 | { 14 | /// 15 | /// Defines printable encoding types. 16 | /// 17 | public enum PrintableEncoding 18 | { 19 | /// 20 | /// Represents a 32 character encoding. 21 | /// 22 | Base32, 23 | 24 | /// 25 | /// Represents a 64 character encoding. 26 | /// 27 | Base64, 28 | 29 | /// 30 | /// Represents the decimal number system. 31 | /// 32 | Decimal, 33 | 34 | /// 35 | /// Represents the hexadecimal encoding. 36 | /// 37 | Hexadecimal 38 | } 39 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021-2024 ng256 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 | -------------------------------------------------------------------------------- /Demo/GenLic/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.IO; 4 | using System.Resourses; 5 | using System.Windows.Forms; 6 | 7 | namespace GenLic5 8 | { 9 | internal static class Program 10 | { 11 | [STAThread] 12 | private static void Main() 13 | { 14 | Application.EnableVisualStyles(); 15 | Application.SetCompatibleTextRenderingDefault(false); 16 | string dbPath = Path.GetFileNameWithoutExtension(PathsInfo.AppFileName) + ".db"; 17 | using (ResourceFile resourceFile = new ResourceFile(dbPath)) 18 | { 19 | resourceFile.ReadSettings(); 20 | } 21 | using (ModuleMessageFormatter user32 = new ModuleMessageFormatter("user32.dll")) 22 | { 23 | user32.ReadSettings(); 24 | } 25 | Form mainForm; 26 | using (PasswordForm pass = new PasswordForm()) 27 | { 28 | if (pass.ShowDialog() != DialogResult.OK) 29 | { 30 | return; 31 | } 32 | mainForm = new GenLicForm(pass.SecurePassword); 33 | } 34 | Application.Run(mainForm); 35 | using (ResourceFile dbFile = new ResourceFile(dbPath)) 36 | { 37 | dbFile.WriteSettings(); 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Source/Text/IPrintableEncoding.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: IPrintableEncoding.cs 4 | 5 | • Description. 6 | 7 | IBaseEncoding provides methods for converting binary data to 8 | text representation. 9 | 10 | The GetString and GetBytes methods allow you to encode and 11 | decode data, which can be useful when working with binary 12 | data that needs to be represented in a human-readable format 13 | or transmitted over pipes that only support text data. 14 | 15 | ***************************************************************/ 16 | 17 | namespace System.Text 18 | { 19 | /// 20 | /// Represents a set of methods that allow you to convert binary data into a text representation. 21 | /// This can be useful for displaying binary data in a human-readable format, 22 | /// or for transferring binary data over pipes that only support text data. 23 | /// 24 | public interface IPrintableEncoding : ICloneable 25 | { 26 | /// Decodes all the bytes in the specified byte array into a string. 27 | /// The byte array containing the sequence of bytes to decode. 28 | /// A string that contains the results of decoding the specified sequence of bytes. 29 | string GetString(byte[] bytes); 30 | 31 | /// Encodes all the characters in the specified string into a sequence of bytes. 32 | /// The string containing the characters to encode. 33 | /// A byte array containing the results of encoding the specified set of characters. 34 | byte[] GetBytes(string s); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Demo/System.ComponentModel/ModuleMessageFormatterConverter.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | 3 | namespace System.ComponentModel 4 | { 5 | internal class ModuleMessageFormatterConverter : TypeConverter 6 | { 7 | private static TypeDescriptionProvider _attributeProvider; 8 | 9 | static ModuleMessageFormatterConverter() 10 | { 11 | _attributeProvider = null; 12 | } 13 | 14 | public static void Register() 15 | { 16 | if (_attributeProvider == null) 17 | { 18 | _attributeProvider = TypeDescriptor.AddAttributes(typeof(ModuleMessageFormatter), new TypeConverterAttribute(typeof(ModuleMessageFormatterConverter))); 19 | } 20 | } 21 | 22 | public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 23 | { 24 | if (!(sourceType == typeof(string)) && !(sourceType == typeof(int))) 25 | { 26 | return base.CanConvertFrom(context, sourceType); 27 | } 28 | return true; 29 | } 30 | 31 | public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) 32 | { 33 | if (!(destinationType == typeof(string)) && !(destinationType == typeof(int))) 34 | { 35 | return base.CanConvertTo(context, destinationType); 36 | } 37 | return true; 38 | } 39 | 40 | public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) 41 | { 42 | string fileNmae; 43 | if ((fileNmae = value as string) != null) 44 | { 45 | return new ModuleMessageFormatter(fileNmae); 46 | } 47 | return base.ConvertFrom(context, culture, value); 48 | } 49 | 50 | public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 51 | { 52 | ModuleMessageFormatter formatter; 53 | if ((formatter = value as ModuleMessageFormatter) != null && destinationType == typeof(string)) 54 | { 55 | return formatter.FileName; 56 | } 57 | return base.ConvertTo(context, culture, value, destinationType); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Demo/Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {414850D2-031C-49EB-9ECC-098599E57F2F} 8 | Exe 9 | Test 10 | Test 11 | v4.0 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | none 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | {a25af6b1-f1a6-4a0e-989e-ca61c126d865} 46 | ActivationKey 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | copy "$(TargetPath)" "$(SolutionDir)Bin\" 57 | 58 | -------------------------------------------------------------------------------- /Demo/System.Windows.Forms/DialogBox.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Ini; 3 | 4 | namespace System.Windows.Forms 5 | { 6 | public class DialogBox : Form 7 | { 8 | private IContainer components; 9 | 10 | protected Button btnCancel; 11 | 12 | protected Button btnOk; 13 | 14 | [ModuleString("user32.dll", 800u)] 15 | private static string OKText { get; set; } = "&OK"; 16 | 17 | 18 | [ModuleString("user32.dll", 801u)] 19 | private static string CancelText { get; set; } = "&Cancel"; 20 | 21 | 22 | protected override void Dispose(bool disposing) 23 | { 24 | if (disposing && components != null) 25 | { 26 | components.Dispose(); 27 | } 28 | base.Dispose(disposing); 29 | } 30 | 31 | private void InitializeComponent() 32 | { 33 | btnCancel = new System.Windows.Forms.Button(); 34 | btnOk = new System.Windows.Forms.Button(); 35 | SuspendLayout(); 36 | btnCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; 37 | btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; 38 | btnCancel.Location = new System.Drawing.Point(376, 142); 39 | btnCancel.Name = "btnCancel"; 40 | btnCancel.Size = new System.Drawing.Size(75, 23); 41 | btnCancel.TabIndex = 102; 42 | btnCancel.Text = "&Cancel"; 43 | btnCancel.UseVisualStyleBackColor = true; 44 | btnOk.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; 45 | btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; 46 | btnOk.Location = new System.Drawing.Point(295, 142); 47 | btnOk.Name = "btnOk"; 48 | btnOk.Size = new System.Drawing.Size(75, 23); 49 | btnOk.TabIndex = 101; 50 | btnOk.Text = "&OK"; 51 | btnOk.UseVisualStyleBackColor = true; 52 | base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); 53 | base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 54 | base.ClientSize = new System.Drawing.Size(463, 177); 55 | base.Controls.Add(btnCancel); 56 | base.Controls.Add(btnOk); 57 | base.Name = "DialogBox"; 58 | Text = ""; 59 | ResumeLayout(false); 60 | } 61 | 62 | public DialogBox() 63 | { 64 | InitializeComponent(); 65 | btnOk.Text = OKText; 66 | btnOk.Click += Ok_Click; 67 | btnCancel.Text = CancelText; 68 | btnCancel.Click += Cancel_Click; 69 | } 70 | 71 | private void Ok_Click(object sender, EventArgs e) 72 | { 73 | base.DialogResult = DialogResult.OK; 74 | Close(); 75 | } 76 | 77 | private void Cancel_Click(object sender, EventArgs e) 78 | { 79 | base.DialogResult = DialogResult.Cancel; 80 | Close(); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Demo/System.ComponentModel/Win32MessageFormatterConverter.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | 3 | namespace System.ComponentModel 4 | { 5 | internal class Win32MessageFormatterConverter : TypeConverter 6 | { 7 | private static TypeDescriptionProvider _attributeProvider; 8 | 9 | static Win32MessageFormatterConverter() 10 | { 11 | _attributeProvider = null; 12 | } 13 | 14 | public static void Register() 15 | { 16 | if (_attributeProvider == null) 17 | { 18 | _attributeProvider = TypeDescriptor.AddAttributes(typeof(Win32MessageFormatter), new TypeConverterAttribute(typeof(Win32MessageFormatterConverter))); 19 | } 20 | } 21 | 22 | public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 23 | { 24 | if (!(sourceType == typeof(string)) && !(sourceType == typeof(int))) 25 | { 26 | return base.CanConvertFrom(context, sourceType); 27 | } 28 | return true; 29 | } 30 | 31 | public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) 32 | { 33 | if (!(destinationType == typeof(string)) && !(destinationType == typeof(int))) 34 | { 35 | return base.CanConvertTo(context, destinationType); 36 | } 37 | return true; 38 | } 39 | 40 | public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) 41 | { 42 | object obj; 43 | if ((obj = value) is int) 44 | { 45 | int lcid = (int)obj; 46 | return new Win32MessageFormatter(lcid); 47 | } 48 | CultureInfo c; 49 | if ((c = value as CultureInfo) != null) 50 | { 51 | return new Win32MessageFormatter(c); 52 | } 53 | string name; 54 | if ((name = value as string) != null) 55 | { 56 | if (int.TryParse(name, NumberStyles.Integer, culture, out var lcid)) 57 | { 58 | return new Win32MessageFormatter(lcid); 59 | } 60 | return new Win32MessageFormatter(name); 61 | } 62 | return base.ConvertFrom(context, culture, value); 63 | } 64 | 65 | public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 66 | { 67 | Win32MessageFormatter formatter; 68 | if ((formatter = value as Win32MessageFormatter) != null) 69 | { 70 | if (destinationType == typeof(int)) 71 | { 72 | return formatter.LCID; 73 | } 74 | if (destinationType == typeof(string)) 75 | { 76 | return new CultureInfo(formatter.LCID).Name; 77 | } 78 | if (destinationType == typeof(CultureInfo)) 79 | { 80 | return new CultureInfo(formatter.LCID); 81 | } 82 | } 83 | return base.ConvertTo(context, culture, value, destinationType); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Demo/System.Windows.Forms/TextControl.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using System.Drawing; 3 | 4 | namespace System.Windows.Forms 5 | { 6 | internal class TextControl : TextBox, IUserControl 7 | { 8 | private static readonly ToolTip tool = new ToolTip(); 9 | 10 | public sealed override string Text 11 | { 12 | get 13 | { 14 | return base.Text; 15 | } 16 | set 17 | { 18 | base.Text = value; 19 | } 20 | } 21 | 22 | public string DisplayName {get; set;} 23 | public string HelpText {get; set;} 24 | public bool Required {get; set;} 25 | public int MinLength {get; set;} 26 | public bool Complete 27 | { 28 | get 29 | { 30 | if (!Required) 31 | { 32 | return true; 33 | } 34 | if (MinLength <= 0) 35 | { 36 | return Text.Length > 0; 37 | } 38 | return Text.Length >= MinLength; 39 | } 40 | } 41 | 42 | public TextControl() 43 | { 44 | base.TextChanged += _text_TextChanged; 45 | base.LostFocus += TextControl_LostFocus; 46 | } 47 | 48 | public TextControl(bool required) 49 | : this() 50 | { 51 | Required = required; 52 | } 53 | 54 | public TextControl(string text) 55 | : this(false) 56 | { 57 | Text = text; 58 | } 59 | 60 | public TextControl(string text, bool required) 61 | : this(required) 62 | { 63 | Text = text; 64 | } 65 | 66 | public static implicit operator string(TextControl value) 67 | { 68 | return value.Text; 69 | } 70 | 71 | internal void _text_TextChanged(object sender, EventArgs e) 72 | { 73 | BackColor = SystemColors.Window; 74 | } 75 | 76 | private void TextControl_LostFocus(object sender, EventArgs e) 77 | { 78 | Light(); 79 | } 80 | 81 | public void Parse(string value) 82 | { 83 | Text = value; 84 | } 85 | 86 | public bool Allert(ref Collection controlNames) 87 | { 88 | if (controlNames == null) 89 | { 90 | controlNames = new Collection(); 91 | } 92 | if (Complete) 93 | { 94 | return true; 95 | } 96 | controlNames.Add(this); 97 | return false; 98 | } 99 | 100 | public void Light() 101 | { 102 | BackColor = (Complete ? SystemColors.Window : Color.LightCoral); 103 | if (!Complete && !base.DesignMode) 104 | { 105 | tool.Show(HelpText, this, 3000); 106 | } 107 | } 108 | 109 | public void Reset() 110 | { 111 | Clear(); 112 | } 113 | 114 | /*void IUserControl.TextChanged(EventHandler value) 115 | { 116 | base.TextChanged += value; 117 | } 118 | 119 | void IUserControl.TextChanged(EventHandler value) 120 | { 121 | base.TextChanged -= value; 122 | }*/ 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /Source/Security/Activation/ActivationKeyConverter.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: ActivationKeyConverter.cs 4 | 5 | • Description. 6 | 7 | ActivationKeyConverter is a converter for the ActivationKey 8 | data type. It allows you to convert objects of type 9 | ActivationKey to and from other datatypes. 10 | 11 | ***************************************************************/ 12 | 13 | using System.ComponentModel; 14 | using System.Globalization; 15 | 16 | namespace System.Security.Activation 17 | { 18 | /// 19 | /// Converts between other types. 20 | /// 21 | public sealed class ActivationKeyConverter : TypeConverter 22 | { 23 | /// 24 | public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 25 | { 26 | if (sourceType == typeof(string) || sourceType == typeof(byte[])) 27 | return true; 28 | 29 | return base.CanConvertFrom(context, sourceType); 30 | } 31 | 32 | /// 33 | public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) 34 | { 35 | if (destinationType == typeof(string) || destinationType == typeof(byte[])) 36 | return true; 37 | 38 | return base.CanConvertTo(context, destinationType); 39 | } 40 | 41 | /// 42 | public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) 43 | { 44 | switch (value) 45 | { 46 | case string str: 47 | return new ActivationKey(str); 48 | case byte[] bytes: 49 | return new ActivationKey(bytes); 50 | default: 51 | return base.ConvertFrom(context, culture, value); 52 | } 53 | } 54 | 55 | /// 56 | public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 57 | { 58 | switch (value) 59 | { 60 | case ActivationKey activationKey when destinationType == typeof(string): 61 | return activationKey.ToString(); 62 | case ActivationKey activationKey when destinationType == typeof(byte[]): 63 | return activationKey.ToBinary(); 64 | default: 65 | return base.ConvertTo(context, culture, value, destinationType); 66 | } 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /ActivationKey.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio Version 17 3 | VisualStudioVersion = 17.6.33712.159 4 | MinimumVisualStudioVersion = 10.0.40219.1 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ActivationKey", "ActivationKey.csproj", "{A25AF6B1-F1A6-4A0E-989E-CA61C126D865}" 6 | EndProject 7 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test", "Demo\Test.csproj", "{414850D2-031C-49EB-9ECC-098599E57F2F}" 8 | EndProject 9 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KeyGen", "Demo\KeyGen.csproj", "{D9034D82-3C96-4F9E-95ED-0691D6FF3ABA}" 10 | EndProject 11 | Global 12 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 13 | Debug|Any CPU = Debug|Any CPU 14 | Debug|x86 = Debug|x86 15 | Release|Any CPU = Release|Any CPU 16 | Release|x86 = Release|x86 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {A25AF6B1-F1A6-4A0E-989E-CA61C126D865}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {A25AF6B1-F1A6-4A0E-989E-CA61C126D865}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {A25AF6B1-F1A6-4A0E-989E-CA61C126D865}.Debug|x86.ActiveCfg = Debug|Any CPU 22 | {A25AF6B1-F1A6-4A0E-989E-CA61C126D865}.Debug|x86.Build.0 = Debug|Any CPU 23 | {A25AF6B1-F1A6-4A0E-989E-CA61C126D865}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {A25AF6B1-F1A6-4A0E-989E-CA61C126D865}.Release|Any CPU.Build.0 = Release|Any CPU 25 | {A25AF6B1-F1A6-4A0E-989E-CA61C126D865}.Release|x86.ActiveCfg = Release|Any CPU 26 | {A25AF6B1-F1A6-4A0E-989E-CA61C126D865}.Release|x86.Build.0 = Release|Any CPU 27 | {414850D2-031C-49EB-9ECC-098599E57F2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {414850D2-031C-49EB-9ECC-098599E57F2F}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {414850D2-031C-49EB-9ECC-098599E57F2F}.Debug|x86.ActiveCfg = Debug|Any CPU 30 | {414850D2-031C-49EB-9ECC-098599E57F2F}.Debug|x86.Build.0 = Debug|Any CPU 31 | {414850D2-031C-49EB-9ECC-098599E57F2F}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {414850D2-031C-49EB-9ECC-098599E57F2F}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {414850D2-031C-49EB-9ECC-098599E57F2F}.Release|x86.ActiveCfg = Release|Any CPU 34 | {414850D2-031C-49EB-9ECC-098599E57F2F}.Release|x86.Build.0 = Release|Any CPU 35 | {D9034D82-3C96-4F9E-95ED-0691D6FF3ABA}.Debug|Any CPU.ActiveCfg = Debug|x86 36 | {D9034D82-3C96-4F9E-95ED-0691D6FF3ABA}.Debug|Any CPU.Build.0 = Debug|x86 37 | {D9034D82-3C96-4F9E-95ED-0691D6FF3ABA}.Debug|x86.ActiveCfg = Debug|x86 38 | {D9034D82-3C96-4F9E-95ED-0691D6FF3ABA}.Debug|x86.Build.0 = Debug|x86 39 | {D9034D82-3C96-4F9E-95ED-0691D6FF3ABA}.Release|Any CPU.ActiveCfg = Release|x86 40 | {D9034D82-3C96-4F9E-95ED-0691D6FF3ABA}.Release|Any CPU.Build.0 = Release|x86 41 | {D9034D82-3C96-4F9E-95ED-0691D6FF3ABA}.Release|x86.ActiveCfg = Release|x86 42 | {D9034D82-3C96-4F9E-95ED-0691D6FF3ABA}.Release|x86.Build.0 = Release|x86 43 | EndGlobalSection 44 | GlobalSection(SolutionProperties) = preSolution 45 | HideSolutionNode = FALSE 46 | EndGlobalSection 47 | GlobalSection(ExtensibilityGlobals) = postSolution 48 | SolutionGuid = {5E058340-8179-4089-9FF6-C632081A19AE} 49 | EndGlobalSection 50 | EndGlobal 51 | -------------------------------------------------------------------------------- /Source/Text/Base16Encoding.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: Base16Encoding.cs 4 | 5 | • Description. 6 | 7 | Base16Encoding is designed to work with hexadecimal data and 8 | implements methods for encoding and decoding data. 9 | 10 | ***************************************************************/ 11 | 12 | using static System.InternalTools; 13 | 14 | namespace System.Text 15 | { 16 | internal sealed class Base16Encoding : InternalBaseEncoding 17 | { 18 | public override string EncodingName => "base-16"; 19 | 20 | public Base16Encoding() 21 | : base(0) 22 | { 23 | } 24 | 25 | public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) 26 | { 27 | Validate(chars, charIndex, charCount, bytes, byteIndex); 28 | charCount = GetCharCount(chars, charIndex, charCount, bytes, byteIndex); 29 | int startByteIndex = byteIndex; 30 | int endCharIndex = charIndex + charCount; 31 | while (charIndex < endCharIndex) 32 | { 33 | byte value = (byte)((GetValue(chars[charIndex++]) << 4) + GetValue(chars[charIndex++])); 34 | bytes[byteIndex++] = value; 35 | } 36 | 37 | return byteIndex - startByteIndex; 38 | } 39 | 40 | public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) 41 | { 42 | Validate(bytes, byteIndex, byteCount, chars, charIndex); 43 | byteCount = GetByteCount(bytes, byteIndex, byteCount, chars, charIndex); 44 | int startCharIndex = charIndex; 45 | int endByteIndex = byteIndex + byteCount; 46 | while (byteIndex < endByteIndex) 47 | { 48 | byte value = bytes[byteIndex++]; 49 | chars[charIndex++] = GetDigit(value >> 4); 50 | chars[charIndex++] = GetDigit(value & 0xF); 51 | } 52 | return charIndex - startCharIndex; 53 | } 54 | 55 | public override int GetMaxByteCount(int charCount) 56 | { 57 | return charCount >> 1; 58 | } 59 | 60 | public override int GetMaxCharCount(int byteCount) 61 | { 62 | return byteCount << 1; 63 | } 64 | 65 | private static int GetValue(char digit) 66 | { 67 | if (digit > 0x2F && digit < 0x3A) 68 | return digit - 48; 69 | if (digit > 0x40 && digit < 0x47) 70 | return digit - 55; 71 | if (digit > 0x60 && digit < 0x67) 72 | return digit - 87; 73 | throw new ArgumentOutOfRangeException(nameof(digit), digit, GetResourceString("Format_BadBase")); 74 | } 75 | 76 | private static char GetDigit(int value) 77 | { 78 | return value >= 0xA ? (char)(value + 0x37) : (char)(value + 0x30); 79 | } 80 | 81 | public override object Clone() 82 | { 83 | return new Base16Encoding(); 84 | } 85 | 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | /*********************************************************** 2 | Activation Key v. 2.1 3 | 4 | The MIT License (MIT) 5 | Copyright: © NG256 2021-2024. 6 | 7 | Permission is hereby granted, free of charge, to any person 8 | obtaining a copy of this software and associated 9 | documentation files (the "Software"), to deal in the 10 | Software without restriction, including without limitation 11 | the rights to use, copy, modify, merge, publish, distribute, 12 | sublicense, and/or sell copies of the Software, and to 13 | permit persons to whom the Software is furnished to do so, 14 | subject to the following conditions: 15 | 16 | The above copyright notice and this permission notice shall 17 | be included in all copies or substantial portions of the 18 | Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 21 | KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 22 | WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 23 | PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 24 | OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 25 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 26 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 27 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | ************************************************************/ 29 | 30 | #if COMVISIBLE 31 | using System.EnterpriseServices; 32 | #endif 33 | #if DEBUG 34 | using System.Runtime.CompilerServices; 35 | #endif 36 | using System.Reflection; 37 | using System.Runtime.InteropServices; 38 | 39 | // General information about this assembly is provided by the following set 40 | // attributes. Change the values of these attributes to change the information, 41 | // related to the assembly. 42 | [assembly: AssemblyTitle("Activation Key Library 2.1")] // Assembly name. 43 | [assembly: AssemblyDescription("Activation Key 2.1 Library")] // Assembly description. 44 | [assembly: AssemblyCompany("NG256")] // Developer. 45 | [assembly: AssemblyProduct("NG256 Activation Key")] // Product name. 46 | [assembly: AssemblyCopyright("© NG256 2021-2024")] // Copyright. 47 | [assembly: AssemblyTrademark("NG256® Activation Key®")] // Trademark. 48 | [assembly: AssemblyCulture("")] 49 | [assembly: AssemblyVersion("2.1.2412.0003")] 50 | [assembly: AssemblyFileVersion("2.1.2412.0003")] 51 | #if DEBUG 52 | [assembly: InternalsVisibleTo("Test")] 53 | [assembly: AssemblyConfiguration("Debug")] 54 | #else 55 | [assembly: AssemblyConfiguration("Release")] 56 | #endif 57 | 58 | // Setting ComVisible to False makes the types in this assembly invisible 59 | // for COM components. If you need to refer to the type in this assembly via COM, 60 | // set the ComVisible attribute to TRUE for this type. 61 | #if COMVISIBLE 62 | [assembly: ComVisible(true)] 63 | [assembly: ApplicationName("Activation Key")] // COM application name. 64 | [assembly: ApplicationID("8174d929-d3d4-4aa6-8197-56c589912c27")] 65 | #else 66 | [assembly: ComVisible(false)] 67 | #endif 68 | // The following GUID serves to identify the type library if this project will be visible to COM 69 | [assembly: Guid("138e9ccd-369e-4d83-ac84-3fccb2f7027a")] 70 | 71 | -------------------------------------------------------------------------------- /ActivationKey.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debug 5 | AnyCPU 6 | {A25AF6B1-F1A6-4A0E-989E-CA61C126D865} 7 | Library 8 | ActivationKey 9 | v4.0 10 | 11 | 2.0.2405.8 12 | 512 13 | System 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | true 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | true 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /Source/Text/InternalBaseEncoding.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: InternalBaseEncoding.cs 4 | 5 | • Description. 6 | 7 | It is an abstract class InternalBaseEncoding, which is a 8 | descendant of the Encoding class and implements the 9 | IBaseEncoding interface for creating various encodings. 10 | 11 | ***************************************************************/ 12 | 13 | namespace System.Text 14 | { 15 | internal abstract class InternalBaseEncoding : Encoding, IPrintableEncoding 16 | { 17 | protected InternalBaseEncoding(int codePage) 18 | : base(codePage) 19 | { 20 | } 21 | 22 | protected virtual void Validate(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) 23 | { 24 | if (chars == null) 25 | throw new ArgumentNullException(nameof (chars)); 26 | if (charIndex < 0) 27 | throw new ArgumentOutOfRangeException(nameof (charIndex), charIndex, InternalTools.GetResourceString("ArgumentOutOfRange_StartIndex")); 28 | if (charCount < 0) 29 | throw new ArgumentOutOfRangeException(nameof (charCount), charCount, InternalTools.GetResourceString("ArgumentOutOfRange_NegativeCount")); 30 | if (bytes == null) 31 | throw new ArgumentNullException(nameof (bytes)); 32 | if (byteIndex < 0) 33 | throw new ArgumentOutOfRangeException(nameof (byteIndex), byteIndex, InternalTools.GetResourceString("ArgumentOutOfRange_StartIndex")); 34 | } 35 | 36 | protected virtual void Validate(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) 37 | { 38 | if (bytes == null) 39 | throw new ArgumentNullException(nameof (bytes)); 40 | if (byteCount < 0) 41 | throw new ArgumentOutOfRangeException(nameof (byteCount), byteCount, InternalTools.GetResourceString("ArgumentOutOfRange_NegativeCount")); 42 | if (byteIndex < 0) 43 | throw new ArgumentOutOfRangeException(nameof (byteIndex), byteIndex, InternalTools.GetResourceString("ArgumentOutOfRange_StartIndex")); 44 | if (chars == null) 45 | throw new ArgumentNullException(nameof (chars)); 46 | if (charIndex < 0) 47 | throw new ArgumentOutOfRangeException(nameof (charIndex), charIndex, InternalTools.GetResourceString("ArgumentOutOfRange_StartIndex")); 48 | } 49 | 50 | public override int GetByteCount(char[] chars, int index, int count) 51 | { 52 | return GetMaxByteCount(chars.GetMaxCount(index, count)); 53 | } 54 | 55 | public override int GetCharCount(byte[] bytes, int index, int count) 56 | { 57 | return GetMaxCharCount(bytes.GetMaxCount(index, count)); 58 | } 59 | 60 | protected virtual int GetCharCount(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) 61 | { 62 | int maxCharCount = GetMaxCharCount(bytes.GetMaxCount(byteIndex)); 63 | return Math.Min(chars.GetMaxCount(charIndex, charCount), maxCharCount); 64 | } 65 | 66 | protected virtual int GetByteCount(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) 67 | { 68 | int maxByteCount = GetMaxByteCount(chars.GetMaxCount(charIndex)); 69 | byteCount = Math.Min(bytes.GetMaxCount(byteIndex, byteCount), maxByteCount); 70 | return byteCount; 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Source/Text/BaseEncoding.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: IniFile.cs 4 | 5 | • Description. 6 | 7 | BaseEncoding provides a convenient way to create and use 8 | various encodings that implement the IBaseEncoding 9 | interface, which can be useful in a variety of scenarios. 10 | 11 | The BaseEncoding class implements the following encodings: 12 | 13 | - Base16Encoding - Returns the hexadecimal encoding. 14 | - Base10Encoding - Returns the decimal encoding. 15 | - Base32Encoding - Returns the 32-digit encoding. 16 | - Base64Encoding - Returns the 64-character encoding. 17 | 18 | Also in the BaseEncoding class there is a GetEncoding 19 | method, which takes an alphabet string as a parameter and 20 | creates an instance of a class that implements the 21 | IBaseEncoding interface. This class is based on a passed 22 | alphabet string. 23 | 24 | ***************************************************************/ 25 | 26 | namespace System.Text 27 | { 28 | /// 29 | /// The BaseEncoding class provides static methods for creating and obtaining instances of classes that implement the IBaseEncoding interface. 30 | /// 31 | public static class BaseEncoding 32 | { 33 | /// 34 | /// Returns a hexadecimal based encoding that implements the interface. 35 | /// 36 | public static IBaseEncoding HexadecimalEncoding => (IBaseEncoding) new Base16Encoding(); 37 | 38 | /// 39 | /// Returns a decimal encoding that implements the interface. 40 | /// 41 | public static IBaseEncoding DecimalEncoding => GetEncoding("0123456789"); 42 | 43 | /// 44 | /// Returns a 32-digit based encoding that implements the interface. 45 | /// 46 | public static IBaseEncoding Base32Encoding => (IBaseEncoding) new Base32Encoding(); 47 | 48 | /// 49 | /// Returns a 64-digit based encoding that implements the interface. 50 | /// 51 | public static IBaseEncoding Base64Encoding => (IBaseEncoding) new Base64Encoding(); 52 | 53 | /// 54 | /// Creates an instance of the custom encoding class, which implements the interface, 55 | /// based on the passed alphabet string. 56 | /// 57 | /// The alphabet string on the basis of which encoding will be created. 58 | /// An instance of a class that implements the interface. 59 | /// 60 | /// The parameter is null. 61 | /// 62 | /// 63 | /// The parameter was either an empty string, contained duplicates, or contained only spaces. 64 | /// 65 | public static IBaseEncoding GetEncoding(string alphabet) => (IBaseEncoding) new CustomEncoding(alphabet); 66 | 67 | /// 68 | /// Creates an instance of encoding based on the passed . 69 | /// 70 | /// The on which the encoding will be created. 71 | /// An instance of a class that implements the interface. 72 | /// 73 | /// Thrown when the parameter does not match any of the listed values. 74 | /// 75 | public static IBaseEncoding GetEncoding(BaseEncodingType type) 76 | { 77 | switch (type) 78 | { 79 | case BaseEncodingType.Base10: 80 | return Base10Encoding; 81 | case BaseEncodingType.Base16: 82 | return Base16Encoding; 83 | case BaseEncodingType.Base32: 84 | return Base32Encoding; 85 | case BaseEncodingType.Base64: 86 | return Base64Encoding; 87 | default: 88 | throw new ArgumentOutOfRangeException(nameof (type), (object) type, InternalTools.GetResourceString("Arg_EnumIllegalVal", (object) type)); 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Source/Text/Base10Encoding.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: Base10Encoding.cs 4 | 5 | • Description. 6 | 7 | Base10Encoding is designed to work with decimal (base-10) data and 8 | implements methods for encoding and decoding data. 9 | 10 | ***************************************************************/ 11 | 12 | using static System.InternalTools; 13 | 14 | namespace System.Text 15 | { 16 | internal sealed class Base10Encoding : InternalBaseEncoding 17 | { 18 | public override string EncodingName => "base-10"; 19 | 20 | public Base10Encoding() 21 | : base(0) 22 | { 23 | } 24 | 25 | public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) 26 | { 27 | Validate(chars, charIndex, charCount, bytes, byteIndex); 28 | charCount = GetCharCount(chars, charIndex, charCount, bytes, byteIndex); 29 | int startByteIndex = byteIndex; 30 | int endCharIndex = charIndex + charCount; 31 | while (charIndex < endCharIndex) 32 | { 33 | byte value = (byte)((GetValue(chars[charIndex++]) << 4) + GetValue(chars[charIndex++])); 34 | bytes[byteIndex++] = value; 35 | } 36 | 37 | return byteIndex - startByteIndex; 38 | } 39 | 40 | static string BytesToString(byte[] bytes) 41 | { 42 | // Minimum length 1. 43 | if (bytes.Length == 0) return "0"; 44 | 45 | // length <= digits.Length. 46 | var chars = new byte[(bytes.Length * 0x00026882 + 0xFFFF) >> 16]; 47 | int length = 1; 48 | 49 | // For each byte: 50 | for (int j = 0; j != bytes.Length; ++j) 51 | { 52 | // digits = digits * 256 + data[j]. 53 | int i, carry = bytes[j]; 54 | for (i = 0; i < length || carry != 0; ++i) 55 | { 56 | int value = chars[i] * 256 + carry; 57 | carry = value / 10; 58 | value %= 10; 59 | chars[i] = (byte)value; 60 | } 61 | // digits got longer. 62 | if (i > length) length = i; 63 | } 64 | 65 | // Return string. 66 | var result = new StringBuilder(length); 67 | while (0 != length) result.Append((char)('0' + chars[--length])); 68 | return result.ToString(); 69 | } 70 | 71 | public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) 72 | { 73 | Validate(bytes, byteIndex, byteCount, chars, charIndex); 74 | byteCount = GetByteCount(bytes, byteIndex, byteCount, chars, charIndex); 75 | int startCharIndex = charIndex; 76 | int endByteIndex = byteIndex + byteCount; 77 | while (byteIndex < endByteIndex) 78 | { 79 | int i; 80 | int carry = bytes[byteIndex++]; 81 | int length = 1; 82 | for (i = 0; i < length || carry != 0; ++i) 83 | { 84 | int value = chars[i] * 256 + carry; 85 | carry = value / 10; 86 | value %= 10; 87 | chars[i + charIndex] = (char)(value + '0'); 88 | } 89 | 90 | } 91 | return charIndex - startCharIndex; 92 | } 93 | 94 | public override int GetMaxByteCount(int charCount) 95 | { 96 | return (int)Math.Ceiling(charCount * Math.Log(10, 256) / 8); 97 | } 98 | 99 | public override int GetMaxCharCount(int byteCount) 100 | { 101 | return (int)Math.Ceiling(byteCount * 8 / Math.Log(10, 256)); 102 | } 103 | 104 | private static int GetValue(char digit) 105 | { 106 | if (digit >= '0' && digit <= '9') 107 | return digit - '0'; 108 | throw new ArgumentOutOfRangeException(nameof(digit), digit, GetResourceString("Format_BadBase")); 109 | } 110 | 111 | private static char GetDigit(int value) // Corrected method name 112 | { 113 | return (char)(value + '0'); 114 | } 115 | 116 | public override object Clone() 117 | { 118 | return new Base10Encoding(); 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /Source/Text/Base32Encoding.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: Base16Encoding.cs 4 | 5 | • Description. 6 | 7 | Base32Encoding implements methods for encoding and decoding 8 | data using Base32 encoding. 9 | 10 | ***************************************************************/ 11 | 12 | using static System.InternalTools; 13 | 14 | namespace System.Text 15 | { 16 | internal sealed class Base32Encoding : InternalBaseEncoding 17 | { 18 | public override string EncodingName => "base-32"; 19 | 20 | public Base32Encoding() 21 | : base(0) 22 | { 23 | } 24 | 25 | public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) 26 | { 27 | Validate(bytes, byteIndex, byteCount, chars, charIndex); 28 | 29 | int maxCharCount = GetMaxCharCount(byteCount); 30 | byte value = 0; 31 | byte bitsCount = 5; 32 | int startCharIndex = charIndex; 33 | int endByteIndex = byteIndex + byteCount; 34 | while (byteIndex < endByteIndex) 35 | { 36 | byte currentByte = bytes[byteIndex++]; 37 | chars[charIndex++] = GetDigit((byte)(value | (uint)currentByte >> 8 - bitsCount)); 38 | if (bitsCount < 4) 39 | { 40 | chars[charIndex++] = GetDigit((byte)(currentByte >> 3 - bitsCount & 0x1F)); 41 | bitsCount += 5; 42 | } 43 | 44 | bitsCount -= 3; 45 | value = (byte)(currentByte << bitsCount & 0x1F); 46 | } 47 | 48 | if (charIndex != maxCharCount) 49 | chars[charIndex++] = GetDigit(value); 50 | 51 | return charIndex - startCharIndex; 52 | } 53 | 54 | public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) 55 | { 56 | Validate(chars, charIndex, charCount, bytes, byteIndex); 57 | charCount = GetCharCount(chars, charIndex, charCount, bytes, byteIndex); 58 | int byteCount = bytes.GetMaxCount(byteIndex); 59 | int startByteIndex = byteIndex; 60 | int endCharIndex = charIndex + charCount; 61 | uint block = 0; 62 | byte bitsCount = 8; 63 | while (charIndex < endCharIndex) 64 | { 65 | int value = GetValue(chars[charIndex++]); 66 | if (bitsCount > 5) 67 | { 68 | block |= (byte)(value << bitsCount - 5); 69 | bitsCount -= 5; 70 | } 71 | else 72 | { 73 | bytes[byteIndex++] = (byte)(block | (uint)(value >> 5 - bitsCount)); 74 | block = (byte)(value << 3 + bitsCount); 75 | bitsCount += 3; 76 | } 77 | } 78 | 79 | if (byteIndex != byteCount) 80 | bytes[byteIndex] = (byte) block; 81 | 82 | return byteIndex - startByteIndex; 83 | } 84 | 85 | private static char GetDigit(byte value) 86 | { 87 | return value < 0x1A ? (char)(value + 0x41) : (char)(value + 0x18); 88 | } 89 | 90 | private static int GetValue(char digit) 91 | { 92 | if (digit < 0x5B && digit > 0x40) return digit - 0x41; 93 | if (digit < 0x7B && digit > 0x60) return digit - 0x61; 94 | if (digit < 0x38 && digit > 0x31) return digit - 0x18; 95 | throw new ArgumentOutOfRangeException(nameof(digit), digit, GetResourceString("Format_BadBase")); 96 | } 97 | 98 | public override int GetByteCount(char[] chars, int index, int count) 99 | { 100 | return GetMaxByteCount(chars.Length - index); 101 | } 102 | 103 | public override int GetCharCount(byte[] bytes, int index, int count) 104 | { 105 | return GetMaxCharCount(bytes.Length - index); 106 | } 107 | 108 | public override int GetMaxByteCount(int charCount) 109 | { 110 | return (charCount << 2) + charCount + 0xB >> 3; 111 | } 112 | 113 | public override int GetMaxCharCount(int byteCount) 114 | { 115 | return (++byteCount << 3) / 5; 116 | } 117 | 118 | public override object Clone() 119 | { 120 | return new Base32Encoding(); 121 | } 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /Demo/KeyGen.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Debug 4 | x86 5 | {D9034D82-3C96-4F9E-95ED-0691D6FF3ABA} 6 | WinExe 7 | false 8 | KeyGen 9 | v4.0 10 | 11 | 12 | 512 13 | 14 | 15 | true 16 | full 17 | false 18 | bin\Debug\ 19 | DEBUG;TRACE 20 | prompt 21 | 4 22 | x86 23 | true 24 | 25 | 26 | none 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | x86 33 | true 34 | 35 | 36 | KeyGen 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | Form 66 | 67 | 68 | Form 69 | 70 | 71 | 72 | Form 73 | 74 | 75 | Component 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | {a25af6b1-f1a6-4a0e-989e-ca61c126d865} 86 | ActivationKey 87 | 88 | 89 | 90 | 91 | GenLicForm.cs 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | copy "$(TargetPath)" "$(SolutionDir)Bin\" 100 | 101 | -------------------------------------------------------------------------------- /Demo/System.ComponentModel/AssemblyMessageFormatter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Resources; 6 | using System.Runtime.InteropServices; 7 | 8 | namespace System.ComponentModel 9 | { 10 | [Serializable] 11 | [StructLayout(LayoutKind.Sequential, Pack = 4)] 12 | internal class AssemblyMessageFormatter 13 | { 14 | [NonSerialized] 15 | private static readonly int[] _installedLangs; 16 | 17 | [NonSerialized] 18 | private static readonly AssemblyMessageFormatter _defaultFormatter; 19 | 20 | [NonSerialized] 21 | private static readonly Assembly _mscorlib; 22 | 23 | [MarshalAs(UnmanagedType.I4)] 24 | private readonly int _lcid = CultureInfo.CurrentUICulture.LCID; 25 | 26 | [NonSerialized] 27 | private readonly Assembly _assembly = _mscorlib; 28 | 29 | [NonSerialized] 30 | private readonly CultureInfo _culture = CultureInfo.CurrentUICulture; 31 | 32 | public int LCID => _lcid; 33 | 34 | public static AssemblyMessageFormatter DefaultFormatter => _defaultFormatter; 35 | 36 | static AssemblyMessageFormatter() 37 | { 38 | _defaultFormatter = new AssemblyMessageFormatter(); 39 | _mscorlib = Assembly.GetAssembly(typeof(object)); 40 | CultureInfo[] installedCultures = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures); 41 | CultureInfo[] specificCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures); 42 | List installedLangs = new List(installedCultures.Length); 43 | CultureInfo[] array = specificCultures; 44 | foreach (CultureInfo culture in array) 45 | { 46 | if (installedCultures.Contains(culture)) 47 | { 48 | installedLangs.Add(culture.LCID); 49 | } 50 | } 51 | _installedLangs = installedLangs.ToArray(); 52 | } 53 | 54 | public AssemblyMessageFormatter(Assembly assembly = null) 55 | { 56 | if (assembly != null) 57 | { 58 | _assembly = assembly; 59 | } 60 | } 61 | 62 | public AssemblyMessageFormatter(int lcid, Assembly assembly = null) 63 | : this(assembly) 64 | { 65 | if (_installedLangs.Contains(lcid)) 66 | { 67 | _culture = new CultureInfo(lcid); 68 | _lcid = lcid; 69 | } 70 | } 71 | 72 | public AssemblyMessageFormatter(CultureInfo culture, Assembly assembly = null) 73 | : this(assembly) 74 | { 75 | if (culture != null && _installedLangs.Contains(culture.LCID)) 76 | { 77 | _culture = culture; 78 | _lcid = culture.LCID; 79 | } 80 | } 81 | 82 | public AssemblyMessageFormatter(TextInfo info, Assembly assembly = null) 83 | : this(assembly) 84 | { 85 | if (info != null && _installedLangs.Contains(info.LCID)) 86 | { 87 | _culture = new CultureInfo(info.LCID); 88 | _lcid = info.LCID; 89 | } 90 | } 91 | 92 | public AssemblyMessageFormatter(string name, Assembly assembly = null) 93 | : this(assembly) 94 | { 95 | try 96 | { 97 | CultureInfo culture = CultureInfo.GetCultureInfo(name); 98 | if (_installedLangs.Contains(culture.LCID)) 99 | { 100 | _lcid = culture.LCID; 101 | } 102 | } 103 | catch 104 | { 105 | _lcid = CultureInfo.CurrentUICulture.LCID; 106 | } 107 | } 108 | 109 | private static string GetDescription(Enum enumElement) 110 | { 111 | MemberInfo[] memInfo = enumElement.GetType().GetMember(enumElement.ToString()); 112 | if (memInfo != null && memInfo.Length != 0) 113 | { 114 | object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); 115 | if (attrs != null && attrs.Length != 0) 116 | { 117 | return ((DescriptionAttribute)attrs[0]).Description; 118 | } 119 | } 120 | return enumElement.ToString(); 121 | } 122 | 123 | public static string GetMessage(string messageId, CultureInfo targetUICulture = null, Assembly assembly = null) 124 | { 125 | try 126 | { 127 | if (targetUICulture == null) 128 | { 129 | targetUICulture = CultureInfo.CurrentUICulture; 130 | } 131 | if (assembly == null) 132 | { 133 | assembly = _mscorlib; 134 | } 135 | return new ResourceManager(assembly.GetName().Name, assembly).GetResourceSet(targetUICulture, true, true)?.GetString(messageId); 136 | } 137 | catch 138 | { 139 | return null; 140 | } 141 | } 142 | 143 | public string GetMessage(string messageId) 144 | { 145 | return GetMessage(messageId, new CultureInfo(_lcid), _assembly); 146 | } 147 | 148 | public string FormatMessage(string messageId, params object[] arguments) 149 | { 150 | return string.Format(_culture, GetMessage(messageId), arguments); 151 | } 152 | 153 | public Exception CreateException(Exception innerException, string messageId, params object[] arguments) 154 | { 155 | return new Exception(FormatMessage(messageId, arguments), innerException); 156 | } 157 | 158 | public Exception CreateException(string messageId, params object[] arguments) 159 | { 160 | return new Exception(FormatMessage(messageId, arguments)); 161 | } 162 | 163 | public override string ToString() 164 | { 165 | string name = CultureInfo.GetCultureInfo(_lcid).DisplayName; 166 | if (!string.IsNullOrEmpty(name)) 167 | { 168 | return name; 169 | } 170 | return _lcid.ToString(); 171 | } 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /Demo/Test/Program.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Security.Activation; 3 | using System.Security.Cryptography; 4 | using System; 5 | using System.Linq; 6 | using System.Net.NetworkInformation; 7 | using System.Text; 8 | 9 | internal static class Program 10 | { 11 | 12 | // Custom encoding example with numbers, latine and cyrilic characters 13 | private static string Base128 = "0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnmЙЦУКЕЁНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮйцукеёнгшщзхъфывапролджэячсмитьбю"; 14 | 15 | // Input data 16 | private static byte[] HelloWorld = { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21 }; 17 | 18 | private static void Main(string[] args) 19 | { 20 | byte[] macAddr = 21 | ( 22 | from netInterface in NetworkInterface.GetAllNetworkInterfaces() 23 | where netInterface.OperationalStatus == OperationalStatus.Up 24 | select netInterface.GetPhysicalAddress().GetAddressBytes() 25 | ).FirstOrDefault(); 26 | 27 | // Pass one: using the default encryptor without data. 28 | Console.WriteLine(); 29 | Console.WriteLine("Default cryptography without data:"); 30 | using (ActivationKey key = ActivationKey.CreateEncryptor(macAddr).Generate()) 31 | { 32 | using (ActivationKeyDecryptor decryptor = key.CreateDecryptor(macAddr)) 33 | { 34 | if (decryptor.Success && decryptor.Data.Length != 0) 35 | { 36 | using (TextReader reader = decryptor.GetTextReader(null)) 37 | { 38 | Console.WriteLine("The key content is: " + reader.ReadToEnd()); 39 | } 40 | } 41 | Console.WriteLine("Base10: \t" + key.ToString(PrintableEncoding.Decimal)); 42 | Console.WriteLine("Base16: \t" + key.ToString(PrintableEncoding.Hexadecimal)); 43 | Console.WriteLine("Base32: \t" + key); 44 | Console.WriteLine("Base64: \t" + key.ToString(PrintableEncoding.Base64)); 45 | Console.WriteLine("Base128:\t" + key.ToString(ActivationKeyTextParser.CreateEncoding(Base128))); 46 | ActivationKey.DefaultManager.SaveToFile(key, "key1.bin", true); 47 | ActivationKey.DefaultManager.SaveToFile(key, "key1.txt"); 48 | } 49 | } 50 | 51 | // Pass two: using the default encryptor with data. 52 | Console.WriteLine(); 53 | Console.WriteLine("Default cryptography with data:"); 54 | object[] objArray1 = { HelloWorld }; 55 | using (ActivationKey key = ActivationKey.CreateEncryptor(new object[0]).Generate(objArray1)) 56 | { 57 | using (ActivationKeyDecryptor decryptor = key.CreateDecryptor(new object[0])) 58 | { 59 | if (decryptor.Success && (decryptor.Data.Length != 0)) 60 | { 61 | using (TextReader reader = decryptor.GetTextReader(null)) 62 | { 63 | Console.WriteLine("The key content is: " + reader.ReadToEnd()); 64 | } 65 | } 66 | Console.WriteLine("Base10: \t" + key.ToString(PrintableEncoding.Decimal)); 67 | Console.WriteLine("Base16: \t" + key.ToString(PrintableEncoding.Hexadecimal)); 68 | Console.WriteLine("Base32: \t" + key); 69 | Console.WriteLine("Base64: \t" + key.ToString(PrintableEncoding.Base64)); 70 | Console.WriteLine("Base128:\t" + key.ToString(ActivationKeyTextParser.CreateEncoding(Base128))); 71 | ActivationKey.DefaultManager.SaveToFile(key, "key2.bin", true); 72 | ActivationKey.DefaultManager.SaveToFile(key, "key2.txt"); 73 | } 74 | } 75 | 76 | // Pass three: using the AES encryptor and MD5 hash algorithm with data. 77 | Console.WriteLine(); 78 | Console.WriteLine("Custom cryptography (AES+MD5) with data:"); 79 | object[] objArray2 = { HelloWorld }; 80 | using (ActivationKey key = ActivationKey.CreateEncryptor(new object[0]).Generate(objArray2)) 81 | { 82 | using (ActivationKeyDecryptor decryptor = key.CreateDecryptor(new object[0])) 83 | { 84 | if (decryptor.Success && (decryptor.Data.Length != 0)) 85 | { 86 | using (TextReader reader = decryptor.GetTextReader(null)) 87 | { 88 | Console.WriteLine("The key content is: " + reader.ReadToEnd()); 89 | } 90 | } 91 | Console.WriteLine("Base10: \t" + key.ToString(PrintableEncoding.Decimal)); 92 | Console.WriteLine("Base16: \t" + key.ToString(PrintableEncoding.Hexadecimal)); 93 | Console.WriteLine("Base32: \t" + key); 94 | Console.WriteLine("Base64: \t" + key.ToString(PrintableEncoding.Base64)); 95 | Console.WriteLine("Base128:\t" + key.ToString(ActivationKeyTextParser.CreateEncoding(Base128))); 96 | ActivationKey.DefaultManager.SaveToFile(key, "key3.bin", true); 97 | ActivationKey.DefaultManager.SaveToFile(key, "key3.txt", false); 98 | } 99 | } 100 | Console.ReadKey(); 101 | } 102 | } 103 | 104 | 105 | -------------------------------------------------------------------------------- /Demo/System/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.ComponentModel; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace System 7 | { 8 | public static class Extensions 9 | { 10 | public static string GetMessages(this Exception e) 11 | { 12 | string result = $"{e.Message} in {e.TargetSite}\n"; 13 | if (e.InnerException != null) 14 | { 15 | result += e.InnerException.GetMessages(); 16 | } 17 | return result; 18 | } 19 | 20 | public static IEnumerable> GetProperties(this object obj) 21 | { 22 | return from p in obj.GetType().GetProperties() 23 | let key = p.Name 24 | let result = p.GetValue(obj, null) 25 | select new KeyValuePair(key, result); 26 | } 27 | 28 | public static IEnumerable> GetProperties(this object obj, Func selector = null) where TAttr : Attribute 29 | { 30 | Type type = obj.GetType(); 31 | if (!typeof(TAttr).IsSubclassOf(typeof(Attribute))) 32 | { 33 | throw new InvalidOperationException(); 34 | } 35 | return from p in type.GetProperties() 36 | from a in p.GetCustomAttributes(false) 37 | where a is TAttr 38 | let key = selector?.Invoke((TAttr)a) ?? p.Name 39 | let result = p.GetValue(obj, null) 40 | select new KeyValuePair(key, result); 41 | } 42 | 43 | public static IEnumerable> GetProperties(this object obj, Func selector = null) where TAttr : Attribute 44 | { 45 | return from p in obj.GetType().GetProperties() 46 | from a in p.GetCustomAttributes(false) 47 | let result = p.GetValue(obj, null) 48 | where result is TResult && a is TAttr 49 | let key = selector?.Invoke((TAttr)a) ?? p.Name 50 | select new KeyValuePair(key, (TResult)result); 51 | } 52 | 53 | public static IEnumerable> GetProperties(this object obj, Func selector = null) where TAttr : Attribute 54 | { 55 | return from p in obj.GetType().GetProperties() 56 | from a in p.GetCustomAttributes(false) 57 | let result = p.GetValue(obj, null) 58 | where result is TResult && a is TAttr 59 | let key = selector((TAttr)a) 60 | select new KeyValuePair(key, (TResult)result); 61 | } 62 | 63 | public static IEnumerable> GetProperties(this object obj) where TAttr : Attribute 64 | { 65 | return from p in obj.GetType().GetProperties() 66 | from a in p.GetCustomAttributes(false) 67 | where a is TAttr 68 | let result = p.GetValue(obj, null) 69 | select new KeyValuePair((TAttr)a, result); 70 | } 71 | 72 | public static IEnumerable> GetProperties(this object obj) where TAttr : Attribute 73 | { 74 | return from p in obj.GetType().GetProperties() 75 | from a in p.GetCustomAttributes(false) 76 | let result = p.GetValue(obj, null) 77 | where result is TResult && a is TAttr 78 | select new KeyValuePair((TAttr)a, (TResult)result); 79 | } 80 | 81 | public static IEnumerable> GetProperties(this object obj, params Type[] types) 82 | { 83 | return from p in obj.GetType().GetProperties() 84 | from a in p.GetCustomAttributes(false) 85 | let result = p.GetValue(obj, null) 86 | where types.Any((Type t) => t.IsInstanceOfType(a)) 87 | select new KeyValuePair((Attribute)a, result); 88 | } 89 | 90 | internal static void SetPropertyValue(this PropertyInfo property, T value) 91 | { 92 | if (value != null) 93 | { 94 | property?.SetValue(null, value, null); 95 | } 96 | } 97 | 98 | internal static void SetPropertyValue(this PropertyInfo property, object value) 99 | { 100 | if (value != null) 101 | { 102 | property?.SetValue(null, value, null); 103 | } 104 | } 105 | 106 | internal static T GetPropertyValue(this PropertyInfo property) 107 | { 108 | if (!(property == null)) 109 | { 110 | return (T)property.GetValue(null, null); 111 | } 112 | return default(T); 113 | } 114 | 115 | internal static object GetPropertyValue(this PropertyInfo property) 116 | { 117 | if (!(property == null)) 118 | { 119 | return property.GetValue(null, null); 120 | } 121 | return null; 122 | } 123 | 124 | internal static TypeConverter GetPropertyConverter(this PropertyInfo property, bool createDefault = false) 125 | { 126 | Type propertyType = property.GetType(); 127 | TypeConverterAttribute propertyConverter; 128 | if ((propertyConverter = property.GetCustomAttributes(typeof(TypeConverterAttribute), false).FirstOrDefault() as TypeConverterAttribute) != null) 129 | { 130 | Type converterType = Type.GetType(propertyConverter.ConverterTypeName); 131 | TypeConverter converter; 132 | if (converterType != null && (converter = Activator.CreateInstance(converterType) as TypeConverter) != null) 133 | { 134 | return converter; 135 | } 136 | } 137 | TypeConverter typeConverter = TypeDescriptor.GetConverter(propertyType); 138 | if (!createDefault) 139 | { 140 | return null; 141 | } 142 | return typeConverter; 143 | } 144 | 145 | public static bool ImplementsInterface(this Type type, Type interfaceType) 146 | { 147 | if (type == null || (!type.IsClass && !type.IsValueType)) 148 | { 149 | throw new ArgumentException(null, "type"); 150 | } 151 | if (interfaceType == null || !interfaceType.IsInterface) 152 | { 153 | throw new ArgumentException(null, "interfaceType"); 154 | } 155 | return type.GetInterfaces().Any((Type i) => i == interfaceType); 156 | } 157 | 158 | public static bool ImplementsInterface(this Type type) where T : class 159 | { 160 | return type.ImplementsInterface(typeof(T)); 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /Source/Text/Base64Encoding.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: Base64Encoding.cs 4 | 5 | • Description. 6 | 7 | Base64Encoding implements methods for encoding and decoding 8 | data using Base64 encoding. To make the text easier to read, 9 | the '+' and '/' symbols were replaced with '#' and '$', and 10 | the trailing symbol '=' were removed. 11 | 12 | ***************************************************************/ 13 | 14 | using static System.InternalTools; 15 | 16 | namespace System.Text 17 | { 18 | internal sealed class Base64Encoding : InternalBaseEncoding 19 | { 20 | public override string EncodingName => "base-64"; 21 | 22 | public Base64Encoding() : base(0) 23 | { 24 | } 25 | 26 | public override byte[] GetBytes(string s) 27 | { 28 | return base.GetBytes(s.Trim('=')); 29 | } 30 | 31 | public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) 32 | { 33 | Validate(bytes, byteIndex, byteCount, chars, charIndex); 34 | 35 | int mod = byteCount % 3; 36 | int startCharIndex = charIndex; 37 | int endByteIndex = byteIndex + (byteCount - mod); 38 | 39 | while (byteIndex < endByteIndex) 40 | { 41 | chars[charIndex] = GetDigit((bytes[byteIndex] & 0xFC) >> 2); 42 | chars[charIndex + 1] = GetDigit((bytes[byteIndex] & 0x03) << 4 | (bytes[byteIndex + 1] & 0xF0) >> 4); 43 | chars[charIndex + 2] = GetDigit((bytes[byteIndex + 0x1] & 0xF) << 2 | (bytes[byteIndex + 2] & 0xC0) >> 6); 44 | chars[charIndex + 3] = GetDigit(bytes[byteIndex + 0x2] & 0x3F); 45 | byteIndex += 3; 46 | charIndex += 4; 47 | } 48 | 49 | switch (mod) 50 | { 51 | case 1: 52 | chars[charIndex] = GetDigit((bytes[endByteIndex] & 0xFC) >> 2); 53 | chars[charIndex + 1] = GetDigit((bytes[endByteIndex] & 0x3) << 4); 54 | charIndex += 2; 55 | break; 56 | case 2: 57 | chars[charIndex] = GetDigit((bytes[endByteIndex] & 0xFC) >> 2); 58 | chars[charIndex + 1] = GetDigit((bytes[endByteIndex] & 0x3) << 4 | (bytes[endByteIndex + 0x1] & 0xF0) >> 4); 59 | chars[charIndex + 2] = GetDigit((bytes[endByteIndex + 1] & 0xF) << 2); 60 | charIndex += 3; 61 | break; 62 | } 63 | 64 | return charIndex - startCharIndex; 65 | } 66 | 67 | public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) 68 | { 69 | Validate(chars, charIndex, charCount, bytes, byteIndex); 70 | 71 | int mod = GetMaxByteCount(charCount) % 3; 72 | int startByteIndex = byteIndex; 73 | int endCharIndex = charIndex + charCount; 74 | uint block = byte.MaxValue; 75 | 76 | while (charIndex < endCharIndex) 77 | { 78 | uint value = (uint) GetValue(chars[charIndex++]); 79 | block = block << 6 | value; 80 | 81 | if ((block & 0x80000000U) != 0) 82 | { 83 | bytes[byteIndex] = (byte)(block >> 16); 84 | bytes[byteIndex + 1] = (byte)(block >> 8); 85 | bytes[byteIndex + 2] = (byte)block; 86 | 87 | byteIndex += 3; 88 | block = 0xFF; 89 | } 90 | } 91 | 92 | switch (mod) 93 | { 94 | case 1: 95 | bytes[byteIndex] = (byte)(block >> 4); 96 | byteIndex += 1; 97 | break; 98 | case 2: 99 | bytes[byteIndex] = (byte)(block >> 10); 100 | bytes[byteIndex + 1] = (byte)(block >> 2); 101 | byteIndex += 2; 102 | break; 103 | } 104 | 105 | return byteIndex - startByteIndex; 106 | } 107 | 108 | public char GetDigit(int value) 109 | { 110 | if (value < 0x1A) return (char)(value + 0x41); 111 | if (value < 0x34) return (char)(value + 0x47); 112 | if (value < 0x3E) return (char)(value - 0x04); 113 | if (value == 0x3E) return (char)0x23; 114 | if (value == 0x3F) return (char)0x24; 115 | return (char)0x3D; 116 | } 117 | 118 | private int GetValue(char digit) 119 | { 120 | if (digit < 0x5B && digit > 0x40) return digit - 0x41; 121 | if (digit < 0x7B && digit > 0x60) return digit - 0x47; 122 | if (digit < 0x3A && digit > 0x2F) return digit + 0x04; 123 | if (digit == 0x23) return 0x3E; 124 | if (digit == 0x24) return 0x3F; 125 | throw new ArgumentOutOfRangeException(nameof(digit), digit, GetResourceString("Format_BadBase")); 126 | } 127 | 128 | public override int GetByteCount(char[] chars, int index, int count) 129 | { 130 | return GetMaxByteCount(chars.Length - index); 131 | } 132 | 133 | public override int GetCharCount(byte[] bytes, int index, int count) 134 | { 135 | return GetMaxCharCount(bytes.Length - index); 136 | } 137 | 138 | 139 | public override int GetMaxByteCount(int charCount) 140 | { 141 | return (charCount * 3) >> 2; 142 | } 143 | 144 | public override int GetMaxCharCount(int byteCount) 145 | { 146 | return ((byteCount << 2) | 2) / 3; 147 | } 148 | 149 | public override object Clone() 150 | { 151 | return new Base64Encoding(); 152 | } 153 | } 154 | } -------------------------------------------------------------------------------- /Demo/System.Windows.Forms/GenLicForm.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 | -------------------------------------------------------------------------------- /Demo/System.Management.WMI/ProcessorInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace System.Management.WMI 4 | { 5 | public class ProcessorInfo 6 | { 7 | public ushort AddressWidth {get; set;} 8 | public ushort Architecture {get; set;} 9 | public ushort Availability {get; set;} 10 | public string Caption {get; set;} 11 | public object ConfigManagerErrorCode {get; set;} 12 | public object ConfigManagerUserConfig {get; set;} 13 | public ushort CpuStatus {get; set;} 14 | public string CreationClassName {get; set;} 15 | public uint CurrentClockSpeed {get; set;} 16 | public ushort CurrentVoltage {get; set;} 17 | public ushort DataWidth {get; set;} 18 | public string Description {get; set;} 19 | public string DeviceID {get; set;} 20 | public object ErrorCleared {get; set;} 21 | public object ErrorDescription {get; set;} 22 | public uint ExtClock {get; set;} 23 | public ushort Family {get; set;} 24 | public object InstallDate {get; set;} 25 | public uint L2CacheSize {get; set;} 26 | public object L2CacheSpeed {get; set;} 27 | public uint L3CacheSize {get; set;} 28 | public uint L3CacheSpeed {get; set;} 29 | public object LastErrorCode {get; set;} 30 | public ushort Level {get; set;} 31 | public ushort LoadPercentage {get; set;} 32 | public string Manufacturer {get; set;} 33 | public uint MaxClockSpeed {get; set;} 34 | public string Name {get; set;} 35 | public uint NumberOfCores {get; set;} 36 | public uint NumberOfLogicalProcessors {get; set;} 37 | public object OtherFamilyDescription {get; set;} 38 | public object PNPDeviceID {get; set;} 39 | public object PowerManagementCapabilities {get; set;} 40 | public bool PowerManagementSupported {get; set;} 41 | public string ProcessorId {get; set;} 42 | public ushort ProcessorType {get; set;} 43 | public ushort Revision {get; set;} 44 | public string Role {get; set;} 45 | public string SocketDesignation {get; set;} 46 | public string Status {get; set;} 47 | public ushort StatusInfo {get; set;} 48 | public object Stepping {get; set;} 49 | public string SystemCreationClassName {get; set;} 50 | public string SystemName {get; set;} 51 | public object UniqueId {get; set;} 52 | public ushort UpgradeMethod {get; set;} 53 | public string Version {get; set;} 54 | public object VoltageCaps {get; set;} 55 | private ProcessorInfo() 56 | { 57 | } 58 | 59 | private static T GetPropertyValue(ManagementObject wmi, string propertyName) 60 | { 61 | try 62 | { 63 | return (T)(wmi.GetPropertyValue(propertyName) ?? ((object)default(T))); 64 | } 65 | catch 66 | { 67 | return default(T); 68 | } 69 | } 70 | 71 | public static ProcessorInfo[] GetProcessorInfo() 72 | { 73 | ManagementClass managementClass = new ManagementClass(new ManagementPath("Win32_Processor")); 74 | List list = new List(); 75 | foreach (ManagementObject item in managementClass.GetInstances()) 76 | { 77 | list.Add(new ProcessorInfo 78 | { 79 | AddressWidth = GetPropertyValue(item, "AddressWidth"), 80 | Architecture = GetPropertyValue(item, "Architecture"), 81 | Availability = GetPropertyValue(item, "Availability"), 82 | Caption = GetPropertyValue(item, "Caption"), 83 | ConfigManagerErrorCode = GetPropertyValue(item, "ConfigManagerErrorCode"), 84 | ConfigManagerUserConfig = GetPropertyValue(item, "ConfigManagerUserConfig"), 85 | CpuStatus = GetPropertyValue(item, "CpuStatus"), 86 | CreationClassName = GetPropertyValue(item, "CreationClassName"), 87 | CurrentClockSpeed = GetPropertyValue(item, "CurrentClockSpeed"), 88 | CurrentVoltage = GetPropertyValue(item, "CurrentVoltage"), 89 | DataWidth = GetPropertyValue(item, "DataWidth"), 90 | Description = GetPropertyValue(item, "Description"), 91 | DeviceID = GetPropertyValue(item, "DeviceID"), 92 | ErrorCleared = GetPropertyValue(item, "ErrorCleared"), 93 | ErrorDescription = GetPropertyValue(item, "ErrorDescription"), 94 | ExtClock = GetPropertyValue(item, "ExtClock"), 95 | Family = GetPropertyValue(item, "Family"), 96 | InstallDate = GetPropertyValue(item, "InstallDate"), 97 | L2CacheSize = GetPropertyValue(item, "L2CacheSize"), 98 | L2CacheSpeed = GetPropertyValue(item, "L2CacheSpeed"), 99 | L3CacheSize = GetPropertyValue(item, "L3CacheSize"), 100 | L3CacheSpeed = GetPropertyValue(item, "L3CacheSpeed"), 101 | LastErrorCode = GetPropertyValue(item, "LastErrorCode"), 102 | Level = GetPropertyValue(item, "Level"), 103 | LoadPercentage = GetPropertyValue(item, "LoadPercentage"), 104 | Manufacturer = GetPropertyValue(item, "Manufacturer"), 105 | MaxClockSpeed = GetPropertyValue(item, "MaxClockSpeed"), 106 | Name = GetPropertyValue(item, "Name"), 107 | NumberOfCores = GetPropertyValue(item, "NumberOfCores"), 108 | NumberOfLogicalProcessors = GetPropertyValue(item, "NumberOfLogicalProcessors"), 109 | OtherFamilyDescription = GetPropertyValue(item, "OtherFamilyDescription"), 110 | PNPDeviceID = GetPropertyValue(item, "PNPDeviceID"), 111 | PowerManagementCapabilities = GetPropertyValue(item, "PowerManagementCapabilities"), 112 | PowerManagementSupported = GetPropertyValue(item, "PowerManagementSupported"), 113 | ProcessorId = GetPropertyValue(item, "ProcessorId"), 114 | ProcessorType = GetPropertyValue(item, "ProcessorType"), 115 | Revision = GetPropertyValue(item, "Revision"), 116 | Role = GetPropertyValue(item, "Role"), 117 | SocketDesignation = GetPropertyValue(item, "SocketDesignation"), 118 | Status = GetPropertyValue(item, "Status"), 119 | StatusInfo = GetPropertyValue(item, "StatusInfo"), 120 | Stepping = GetPropertyValue(item, "Stepping"), 121 | SystemCreationClassName = GetPropertyValue(item, "SystemCreationClassName"), 122 | SystemName = GetPropertyValue(item, "SystemName"), 123 | UniqueId = GetPropertyValue(item, "UniqueId"), 124 | UpgradeMethod = GetPropertyValue(item, "UpgradeMethod"), 125 | Version = GetPropertyValue(item, "Version"), 126 | VoltageCaps = GetPropertyValue(item, "VoltageCaps") 127 | }); 128 | item.Dispose(); 129 | } 130 | return list.ToArray(); 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /Source/Security/Activation/ActivationKeyEncryptor.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: ActivationKeyEncryptor.cs 4 | 5 | • Description. 6 | ActivationKeyEncryptor can be used to protect data 7 | associated with the activation of software or services. It 8 | allows you to generate unique activation keys that can be 9 | used to authenticate and bind to a user-defined software and 10 | hardware environment. 11 | 12 | The code can be used to create a software activation system 13 | or other products that require key activation verification. 14 | 15 | ***************************************************************/ 16 | 17 | using System.Security.Cryptography; 18 | using static System.InternalTools; 19 | 20 | namespace System.Security.Activation 21 | { 22 | /// 23 | /// Implements functionality for generation of activation keys. 24 | /// Data can be encrypted using various encryption and hashing algorithms. 25 | /// 26 | public sealed class ActivationKeyEncryptor : IDisposable 27 | { 28 | private ICryptoTransform _encryptor; 29 | private HashAlgorithm _hasher; 30 | private byte[] _seed; 31 | 32 | /// 33 | /// Returns an instance of the using the default encryption algorithm. 34 | /// 35 | public static ActivationKeyEncryptor DefaultEncryptor => new ActivationKeyEncryptor(); 36 | 37 | /// 38 | /// Initializes a new instance of the using default cryptographic algorithm. 39 | /// 40 | /// 41 | /// Environment binding parameters used to generate the key. 42 | /// These parameters can be used to create a unique activation key that can be used to authenticate a user or device. 43 | /// 44 | public ActivationKeyEncryptor(params object[] environment) 45 | { 46 | byte[] key = Serialize(environment); 47 | byte[] seed = GenerateRandom(sizeof(uint)); 48 | _encryptor = new ARC4CryptoTransform(key, seed); 49 | _hasher = new SipHashAlgorithm(seed); 50 | _seed = seed; 51 | } 52 | 53 | /// 54 | /// Initializes a new instance of the using specified cryptographic algorithm. 55 | /// 56 | /// 57 | /// Symmetric encryption algorithm. 58 | /// 59 | /// 60 | /// Hash algorithm. 61 | /// 62 | /// 63 | /// Environment binding parameters used to generate the key. 64 | /// These parameters can be used to create a unique activation key that can be used to authenticate a user or device. 65 | /// 66 | /// If one of the arguments 67 | /// ( or ) is null. 68 | /// 69 | public ActivationKeyEncryptor(SymmetricAlgorithm symmetricAlgorithm, HashAlgorithm hashAlgorithm, 70 | params object[] environment) 71 | { 72 | if (symmetricAlgorithm == null) 73 | throw new ArgumentNullException(nameof(symmetricAlgorithm), 74 | GetResourceString("ArgumentNull_WithParamName", nameof(symmetricAlgorithm))); 75 | if (hashAlgorithm == null) 76 | throw new ArgumentNullException(nameof(hashAlgorithm), 77 | GetResourceString("ArgumentNull_WithParamName", nameof(hashAlgorithm))); 78 | 79 | byte[] seed = symmetricAlgorithm.IV; 80 | _hasher = hashAlgorithm; 81 | _seed = seed; 82 | using (PasswordDeriveBytes deriveBytes = new PasswordDeriveBytes(Serialize(environment), seed)) 83 | { 84 | _encryptor = 85 | symmetricAlgorithm.CreateEncryptor(deriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8), seed); 86 | } 87 | } 88 | 89 | /// 90 | /// Generates an based on the transferred data without a time limit for use. 91 | /// 92 | /// 93 | /// Data that will be stored in the key and can be retrieved when the key is verified. 94 | /// 95 | /// 96 | /// The instance received by the current object. 97 | /// 98 | public ActivationKey Generate(params object[] data) 99 | { 100 | if (_encryptor == null || _hasher == null) 101 | throw new ObjectDisposedException(nameof(ActivationKeyEncryptor), 102 | GetResourceString("ObjectDisposed_Generic")); 103 | 104 | ActivationKey activationKey = Generate(DateTime.MaxValue.Date, data); 105 | return activationKey; 106 | } 107 | 108 | /// 109 | /// Generates an based on the data and expiration date. 110 | /// 111 | /// 112 | /// The key expiration date. 113 | /// 114 | /// 115 | /// Data that will be included in the activation key. 116 | /// 117 | /// 118 | /// Created activation key. 119 | /// 120 | public ActivationKey Generate(DateTime expirationDate, params object[] data) 121 | { 122 | byte[] serializedData = Serialize(expirationDate, data); 123 | byte[] encryptedData = _encryptor.TransformFinalBlock(serializedData, 0, serializedData.Length); 124 | byte[] seed = _seed.ArrayClone(); 125 | byte[] hash = _hasher.ComputeHash(Serialize(serializedData, seed)); 126 | 127 | ActivationKey activationKey = new ActivationKey(encryptedData, hash, seed); 128 | return activationKey; 129 | } 130 | 131 | /// 132 | public void Dispose() 133 | { 134 | _encryptor?.Dispose(); 135 | _hasher?.Dispose(); 136 | _seed.Clear(); 137 | _encryptor = null; 138 | _hasher = null; 139 | _seed = null; 140 | } 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /Source/IO/IniFile.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************** 2 | 3 | • File: IniFile.cs 4 | 5 | • Description. 6 | 7 | IniFile is a regular expression based INI file content analyzer. 8 | This implementation only supports reading keys, since data is 9 | usually entered into ini files manually using any text editor. 10 | 11 | ********************************************************************/ 12 | 13 | using System.Collections.Generic; 14 | using System.Text; 15 | using System.Text.RegularExpressions; 16 | 17 | namespace System.IO 18 | { 19 | internal class IniFile 20 | { 21 | private const string COMMENT_PATTERN = @"(?:(?<=;|#)(?:[ \t]*))(?.+)(?<=\S)"; 22 | private const string SECTION_PATTERN = @"(?:[ \t]*)(?<=\[)(?:[ \t]*)(?
\w+)(?:[ \t]*?)(?=\])"; 23 | private const string ENTRY_PATTERN = @"(?(?=\S)(?\w+)(?:[ \t]*)(?==)=(?<==)(?:[ \t]*)(?.*)(?<=\S))"; 24 | private const StringComparison CMP = StringComparison.InvariantCultureIgnoreCase; 25 | private static readonly Regex _regex = new Regex($"{COMMENT_PATTERN}|{SECTION_PATTERN}|{ENTRY_PATTERN}", 26 | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); 27 | private readonly MatchCollection _matches; 28 | 29 | public IniFile(TextReader reader) 30 | { 31 | _matches = _regex.Matches(reader.ReadToEnd()); 32 | } 33 | 34 | public IniFile(Stream stream, Encoding encoding) 35 | { 36 | using (StreamReader reader = new StreamReader(stream, encoding)) 37 | { 38 | _matches = _regex.Matches(reader.ReadToEnd()); 39 | } 40 | } 41 | 42 | public IniFile(string fileName, Encoding encoding = null) 43 | { 44 | string content = File.ReadAllText(fileName, encoding ?? Encoding.UTF8); 45 | _matches = _regex.Matches(content); 46 | } 47 | 48 | private bool CheckSection(Match match, string section, ref string currentSection) 49 | { 50 | Group sectionGroup = match.Groups["section"]; 51 | if (sectionGroup.Success) 52 | { 53 | currentSection = sectionGroup.Value; 54 | } 55 | 56 | return currentSection.Equals(section, CMP); 57 | } 58 | 59 | // Returns a single entry specified by section and key, 60 | // or a default value if no entry is found. 61 | public string GetEntry(string section, string key, string defaultValue = null) 62 | { 63 | if (key == null) key = string.Empty; 64 | if (section == null) section = string.Empty; 65 | string currentSection = string.Empty; 66 | for (var i = 0; i < _matches.Count; i++) 67 | { 68 | var match = _matches[i]; 69 | if (!CheckSection(match, section, ref currentSection)) 70 | { 71 | continue; 72 | } 73 | 74 | Group keyGroup = match.Groups["key"]; 75 | Group valueGroup = match.Groups["value"]; 76 | if (keyGroup.Success && keyGroup.Value.Equals(key, CMP)) 77 | { 78 | return valueGroup.Value; 79 | } 80 | } 81 | 82 | return defaultValue ?? string.Empty; 83 | } 84 | 85 | // Returns all entries contained in the section. 86 | // If no entry is found, an empty enumerator will be returned. 87 | public IEnumerable GetEntries(string section) 88 | { 89 | IList entries = new List(); 90 | string currentSection = string.Empty; 91 | for (var i = 0; i < _matches.Count; i++) 92 | { 93 | var match = _matches[i]; 94 | if (!CheckSection(match, section, ref currentSection)) 95 | { 96 | continue; 97 | } 98 | 99 | Group keyGroup = match.Groups["key"]; 100 | Group valueGroup = match.Groups["value"]; 101 | if (keyGroup.Success) 102 | { 103 | entries.Add(valueGroup.Value); 104 | } 105 | } 106 | 107 | return entries; 108 | } 109 | 110 | // Returns all entries matching the specified key contained in the section. 111 | // If no entry is found, an empty enumerator will be returned. 112 | public IEnumerable GetEntries(string section, string key) 113 | { 114 | IList entries = new List(); 115 | string currentSection = string.Empty; 116 | for (var i = 0; i < _matches.Count; i++) 117 | { 118 | var match = _matches[i]; 119 | if (!CheckSection(match, section, ref currentSection)) 120 | { 121 | continue; 122 | } 123 | 124 | Group keyGroup = match.Groups["key"]; 125 | Group valueGroup = match.Groups["value"]; 126 | if (keyGroup.Success && keyGroup.Value.Equals(key, CMP)) 127 | { 128 | entries.Add(valueGroup.Value); 129 | } 130 | } 131 | 132 | return entries; 133 | } 134 | 135 | public static string GetEntry(string fileName, string section, string key, string defaultValue = null) 136 | { 137 | return new IniFile(fileName).GetEntry(section, key, defaultValue ?? string.Empty); 138 | } 139 | 140 | public static string GetEntry(string fileName, Encoding encoding, string section, string key, string defaultValue = null) 141 | { 142 | return new IniFile(fileName, encoding).GetEntry(section, key, defaultValue ?? string.Empty); 143 | } 144 | 145 | public static IEnumerable GetEntries(string fileName, string section, string key = null) 146 | { 147 | IniFile iniFile = new IniFile(fileName); 148 | return key.IsNullOrEmpty() 149 | ? iniFile.GetEntries(section) 150 | : iniFile.GetEntries(section, key); 151 | } 152 | 153 | public static IEnumerable GetEntries(string fileName, Encoding encoding, string section, string key = null) 154 | { 155 | IniFile iniFile = new IniFile(fileName, encoding); 156 | return key.IsNullOrEmpty() 157 | ? iniFile.GetEntries(section) 158 | : iniFile.GetEntries(section, key); 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /Demo/System.ComponentModel/ModuleMessageFormatter.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using System.Ini; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Runtime.InteropServices; 6 | using System.Text; 7 | 8 | namespace System.ComponentModel 9 | { 10 | [Serializable] 11 | [TypeConverter(typeof(ModuleMessageFormatterConverter))] 12 | internal class ModuleMessageFormatter : Win32MessageFormatter 13 | { 14 | private const string DEFAULT = "user32.dll"; 15 | 16 | [NonSerialized] 17 | private string _moduleName = "user32.dll"; 18 | 19 | [NonSerialized] 20 | private IntPtr _handle; 21 | 22 | [NonSerialized] 23 | private bool _disposed; 24 | 25 | [NonSerialized] 26 | private static readonly ModuleMessageFormatter _defaultFormatter = new ModuleMessageFormatter(); 27 | 28 | private static readonly Encoding TextEncoding = Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage); 29 | 30 | public string FileName => _moduleName; 31 | 32 | public new static ModuleMessageFormatter DefaultFormatter => _defaultFormatter; 33 | 34 | private ModuleMessageFormatter() 35 | { 36 | } 37 | 38 | public ModuleMessageFormatter(string moduleName) 39 | { 40 | _moduleName = moduleName; 41 | _handle = LoadLibrary(moduleName); 42 | } 43 | 44 | [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)] 45 | private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName); 46 | 47 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 48 | private static extern int LoadString(IntPtr hInstance, uint uID, [Out] StringBuilder lpBuffer, int nBufferMax); 49 | 50 | [DllImport("kernel32.dll", SetLastError = true)] 51 | private static extern int GetLastError(); 52 | 53 | [DllImport("kernel32.dll", SetLastError = true)] 54 | private static extern bool FreeLibrary(IntPtr hInstance); 55 | 56 | public override void Dispose() 57 | { 58 | if (!_disposed && _handle != IntPtr.Zero) 59 | { 60 | FreeLibrary(_handle); 61 | _disposed = true; 62 | } 63 | base.Dispose(); 64 | GC.SuppressFinalize(this); 65 | } 66 | 67 | internal static string LoadString(uint id, string fileName) 68 | { 69 | IntPtr handle = IntPtr.Zero; 70 | StringBuilder lpBuffer = new StringBuilder(1024); 71 | try 72 | { 73 | handle = LoadLibrary(fileName); 74 | FreeLibrary(handle); 75 | int result; 76 | if (LoadString(handle, id, lpBuffer, 1024) == 0 && (result = GetLastError()) > 0) 77 | { 78 | throw new Win32Exception(result); 79 | } 80 | } 81 | finally 82 | { 83 | if (handle != IntPtr.Zero) 84 | { 85 | FreeLibrary(handle); 86 | } 87 | } 88 | return lpBuffer.ToString(); 89 | } 90 | 91 | internal string LoadString(uint id) 92 | { 93 | if (_disposed) 94 | { 95 | throw new ObjectDisposedException(_moduleName); 96 | } 97 | StringBuilder lpBuffer = new StringBuilder(1024); 98 | int result; 99 | if (LoadString(_handle, id, lpBuffer, 1024) == 0 && (result = GetLastError()) > 0) 100 | { 101 | throw new Win32Exception(result); 102 | } 103 | return lpBuffer.ToString(); 104 | } 105 | 106 | public override string ToString() 107 | { 108 | return _moduleName; 109 | } 110 | 111 | public override string FormatMessage(string moduleName, uint messageId, params string[] arguments) 112 | { 113 | string messgae = LoadString(messageId, moduleName); 114 | return base.FormatMessage(messgae, arguments); 115 | } 116 | 117 | public override string FormatMessage(string moduleName, uint messageId, bool ignoreNewLine, params string[] arguments) 118 | { 119 | string messgae = LoadString(messageId, moduleName); 120 | return base.FormatMessage(messgae, ignoreNewLine, arguments); 121 | } 122 | 123 | public override string FormatMessage(uint messageId, params string[] arguments) 124 | { 125 | string messgae = LoadString(messageId); 126 | return base.FormatMessage(messgae, arguments); 127 | } 128 | 129 | public override string FormatMessage(uint messageId, bool ignoreNewLine, params string[] arguments) 130 | { 131 | string messgae = LoadString(messageId); 132 | return base.FormatMessage(messgae, ignoreNewLine, arguments); 133 | } 134 | 135 | public override string FormatMessage(uint messageId) 136 | { 137 | string messgae = LoadString(messageId); 138 | return base.FormatMessage(messgae); 139 | } 140 | 141 | public override string FormatMessage(uint messageId, bool ignoreNewLine) 142 | { 143 | string messgae = LoadString(messageId); 144 | return base.FormatMessage(messgae, ignoreNewLine); 145 | } 146 | 147 | [Obsolete] 148 | public override string FormatMessage(uint messageId, Win32FormatMessageFlags flags, string source, params string[] arguments) 149 | { 150 | return FormatMessage(messageId, arguments); 151 | } 152 | 153 | [Obsolete] 154 | public override string FormatMessage(uint messageId, Win32FormatMessageFlags flags, string source, bool ignoreNewLine, params string[] arguments) 155 | { 156 | return FormatMessage(messageId, ignoreNewLine, arguments); 157 | } 158 | 159 | public Exception GetException(uint messageId, params string[] parameters) 160 | { 161 | return new Exception(FormatMessage(messageId, parameters)); 162 | } 163 | 164 | public Exception GetException(uint messageId, bool ignoreNewLine, params string[] parameters) 165 | { 166 | return new Exception(FormatMessage(messageId, parameters)); 167 | } 168 | 169 | public override void ReadSettings(Assembly assembly = null) 170 | { 171 | if (assembly == null) 172 | { 173 | assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly(); 174 | } 175 | Type[] types = assembly.GetTypes(); 176 | for (int i = 0; i < types.Length; i++) 177 | { 178 | PropertyInfo[] properties = types[i].GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); 179 | foreach (PropertyInfo property in properties) 180 | { 181 | ModuleStringAttribute moduleString; 182 | if (!property.CanWrite || (moduleString = property.GetCustomAttributes(typeof(ModuleStringAttribute), false).FirstOrDefault() as ModuleStringAttribute) == null || moduleString.Name != _moduleName) 183 | { 184 | continue; 185 | } 186 | uint msgId = moduleString.MessageId; 187 | string[] args = moduleString.Arguments; 188 | try 189 | { 190 | if (property.PropertyType == typeof(string)) 191 | { 192 | object newPropertyValue = FormatMessage(msgId, args); 193 | property.SetPropertyValue(newPropertyValue); 194 | } 195 | } 196 | catch (Exception) 197 | { 198 | } 199 | } 200 | } 201 | } 202 | 203 | [Obsolete] 204 | public override void WriteSettings(Assembly assembly = null) 205 | { 206 | try 207 | { 208 | throw new NotImplementedException(); 209 | } 210 | catch (Exception) 211 | { 212 | } 213 | } 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /Source/Security/Cryptography/SipHashAlgorithm.cs: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | • File: SipHashAlgorithm.cs 4 | 5 | • Description. 6 | 7 | SipHashAlgorithm provides the ability to create cryptographic 8 | hash functions based on a modified SipHash algorithm. 9 | 10 | The default hash algorithm choice is SipHash, which works 11 | very well for short input data. In this implementation, the 12 | length of the resulting hash is 32 bits, which is sufficient 13 | for the purposes of this project. 14 | 15 | 16 | ****************************************************************/ 17 | 18 | using static System.InternalTools; 19 | 20 | namespace System.Security.Cryptography 21 | { 22 | // Provides the ability to create cryptographic hash functions based on the SipHash algorithm. 23 | // This allows the class to be used to check the integrity of the activation key data. 24 | internal sealed class SipHashAlgorithm : HashAlgorithm 25 | { 26 | // Returns the default hash generator. 27 | public static SipHashAlgorithm DefaultHash => new SipHashAlgorithm(); 28 | 29 | // An array of four uint elements that are used to store intermediate values when calculating the hash function. 30 | private uint[] _buffer = { 0x736F6D65, 0x646F7261, 0x1F160A00, 0x100A1603 }; 31 | 32 | // The constructor initializes the elements of the _buffer array using the seed parameter. 33 | private uint _seed; 34 | 35 | // Sets the hash size to the size of an integer. 36 | private SipHashAlgorithm() 37 | { 38 | HashSizeValue = 32; 39 | } 40 | 41 | // Accepts a seed parameter. The constructor initializes the elements of the _buffer array using the seed parameter. 42 | // Seed is parameter that is used to initialize the initial state of the algorithm 43 | public SipHashAlgorithm(uint seed = 0) : this() 44 | { 45 | _seed = seed; 46 | Initialize(); 47 | } 48 | 49 | // Takes a bytes array and uses it to initialize the elements of the _buffer array. 50 | public unsafe SipHashAlgorithm(byte[] iv) : this() 51 | { 52 | if (iv == null) 53 | throw new ArgumentNullException(nameof(iv), GetResourceString("ArgumentNull_Key")); 54 | if (iv.Length < 4) 55 | throw new ArgumentException(GetResourceString("Cryptography_InvalidIVSize"), nameof(iv)); 56 | 57 | _seed = ConvertTo(iv); 58 | Initialize(); 59 | } 60 | 61 | // Initializes the elements of the _buffer array. 62 | public override void Initialize() 63 | { 64 | _buffer[0] = 0x736F6D65 ^ _seed; 65 | _buffer[1] = 0x646F7261 ^ _seed; 66 | _buffer[2] = 0x1F160A00 ^ _buffer[0]; 67 | _buffer[3] = 0x100A1603 ^ _buffer[1]; 68 | } 69 | 70 | // Returns a hash value obtained from a byte array using the SipHash algorithm. 71 | public int GetInt32(byte[] bytes) 72 | { 73 | return ConvertTo(ComputeHash(bytes), 0); 74 | } 75 | 76 | // Returns a hash value obtained from a byte array using the SipHash algorithm. 77 | private uint GetUInt32(byte[] bytes) 78 | { 79 | return ConvertTo(ComputeHash(bytes), 0); 80 | } 81 | 82 | // Rearranges the elements of the _buffer array. The method is used in the SipRound method to shuffle values. 83 | private void Rotate() 84 | { 85 | _buffer[0] += _buffer[1] ^ _buffer[2] ^ _buffer[3]; 86 | uint swap = _buffer[0]; 87 | _buffer[0] = _buffer[1]; 88 | _buffer[1] = _buffer[2]; 89 | _buffer[2] = _buffer[3]; 90 | _buffer[3] = swap; 91 | } 92 | 93 | // Performs one round of calculations in the SipHash algorithm. 94 | private void SipRound() 95 | { 96 | _buffer[0] += _buffer[1]; 97 | _buffer[1] <<= 13; 98 | _buffer[1] ^= _buffer[0]; 99 | _buffer[0] <<= 32; 100 | 101 | _buffer[2] += _buffer[3]; 102 | _buffer[3] <<= 16; 103 | _buffer[3] ^= _buffer[2]; 104 | 105 | _buffer[0] += _buffer[3]; 106 | _buffer[3] <<= 21; 107 | _buffer[3] ^= _buffer[0]; 108 | 109 | _buffer[2] += _buffer[1]; 110 | _buffer[1] <<= 17; 111 | _buffer[1] ^= _buffer[2]; 112 | _buffer[2] <<= 32; 113 | 114 | Rotate(); 115 | Rotate(); 116 | Rotate(); 117 | } 118 | 119 | // Calculates a hash value from a byte array using the SipHash algorithm. 120 | protected override unsafe void HashCore(byte[] array, int ibStart, int cbSize) 121 | { 122 | uint lenght = (uint)cbSize; 123 | uint b = ((uint)lenght) << 24; 124 | 125 | if (lenght > 0) 126 | { 127 | fixed (byte* bytes = &array[ibStart]) 128 | { 129 | byte* @byte = bytes; 130 | uint tailCount = lenght & 7; 131 | byte* ptrSeed = @byte + lenght - tailCount; 132 | 133 | while (@byte < ptrSeed) 134 | { 135 | _buffer[0] ^= (uint)@byte[0]; 136 | _buffer[1] ^= (uint)@byte[1] << 8; 137 | _buffer[2] ^= (uint)@byte[2] << 16; 138 | _buffer[3] ^= (uint)@byte[3] << 24; 139 | 140 | SipRound(); 141 | SipRound(); 142 | 143 | @byte += 4; 144 | } 145 | 146 | for (int i = 0; i < tailCount; ++i) 147 | { 148 | _buffer[3] ^= b; 149 | b |= (uint)ptrSeed[i] << (8 * i); 150 | _buffer[0] ^= b; 151 | 152 | } 153 | } 154 | } 155 | 156 | _buffer[3] ^= b; 157 | 158 | SipRound(); 159 | SipRound(); 160 | 161 | _buffer[0] ^= b; 162 | _buffer[2] ^= 0xff; 163 | 164 | SipRound(); 165 | SipRound(); 166 | SipRound(); 167 | SipRound(); 168 | } 169 | 170 | // Returns the final hash value. 171 | protected override unsafe byte[] HashFinal() 172 | { 173 | byte[] hashValue = new byte[4] {0, 0, 0, 0}; 174 | fixed (uint* buffer = hashValue) 175 | { 176 | for (var i = 0; i < _buffer.Length; i++) 177 | { 178 | *buffer ^= _buffer[i]; 179 | } 180 | } 181 | Initialize(); 182 | return hashValue; 183 | } 184 | 185 | // Releases resources used by the class. 186 | protected override void Dispose(bool disposing) 187 | { 188 | if (!disposing) 189 | { 190 | return; 191 | } 192 | 193 | _buffer.Clear(); 194 | _buffer = null; 195 | _seed = 0; 196 | base.Dispose(true); 197 | } 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /.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 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd 364 | -------------------------------------------------------------------------------- /Demo/System.Windows.Forms/PasswordForm.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Ini; 3 | using System.Runtime.InteropServices; 4 | using System.Security; 5 | using System.Text; 6 | 7 | namespace System.Windows.Forms 8 | { 9 | public class PasswordForm : DialogBox 10 | { 11 | private const char PASSWORD_CHAR = '•'; 12 | 13 | private readonly SecureString _secureString = new SecureString(); 14 | 15 | private IContainer components; 16 | 17 | protected Label lblPass; 18 | 19 | protected TextBox txtPassword; 20 | 21 | [ModuleString("user32.dll", 800u)] 22 | private static string OKText {get; set; } = "&OK"; 23 | 24 | [ModuleString("user32.dll", 801u)] 25 | private static string CancelText {get; set; } = "&Cancel"; 26 | 27 | public SecureString SecurePassword => _secureString; 28 | 29 | public string Password => ToString(_secureString); 30 | 31 | [DefaultValue("Please enter password:")] 32 | [Localizable(true)] 33 | [Browsable(false)] 34 | [EditorBrowsable(EditorBrowsableState.Never)] 35 | public string LabelText 36 | { 37 | get 38 | { 39 | return lblPass.Text; 40 | } 41 | set 42 | { 43 | lblPass.Text = value; 44 | } 45 | } 46 | 47 | private void InitializeComponent() 48 | { 49 | lblPass = new System.Windows.Forms.Label(); 50 | txtPassword = new System.Windows.Forms.TextBox(); 51 | SuspendLayout(); 52 | btnOk.Location = new System.Drawing.Point(171, 61); 53 | btnOk.Click += new System.EventHandler(btnOk_Click); 54 | btnCancel.Location = new System.Drawing.Point(252, 61); 55 | btnCancel.Click += new System.EventHandler(btnCancel_Click); 56 | lblPass.AutoSize = true; 57 | lblPass.Location = new System.Drawing.Point(13, 13); 58 | lblPass.Name = "lblPass"; 59 | lblPass.Size = new System.Drawing.Size(91, 13); 60 | lblPass.TabIndex = 0; 61 | lblPass.Text = "Please enter password:"; 62 | txtPassword.Location = new System.Drawing.Point(13, 30); 63 | txtPassword.MaxLength = 16; 64 | txtPassword.Name = "txtPassword"; 65 | txtPassword.PasswordChar = '•'; 66 | txtPassword.Size = new System.Drawing.Size(314, 20); 67 | txtPassword.TabIndex = 1; 68 | txtPassword.KeyPress += new System.Windows.Forms.KeyPressEventHandler(InputBox_KeyPress); 69 | txtPassword.KeyDown += new System.Windows.Forms.KeyEventHandler(InputBox_KeyDown); 70 | txtPassword.ReadOnly = true; 71 | txtPassword.AcceptsReturn = true; 72 | base.AcceptButton = btnOk; 73 | base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); 74 | base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 75 | base.CancelButton = btnCancel; 76 | base.ClientSize = new System.Drawing.Size(339, 96); 77 | base.Controls.Add(txtPassword); 78 | base.Controls.Add(lblPass); 79 | base.Controls.Add(btnCancel); 80 | base.Controls.Add(btnOk); 81 | base.ControlBox = true; 82 | base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; 83 | base.MaximizeBox = false; 84 | base.MinimizeBox = false; 85 | base.Name = "PasswordForm"; 86 | base.ShowIcon = false; 87 | base.ShowInTaskbar = false; 88 | base.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; 89 | base.TopMost = true; 90 | ResumeLayout(false); 91 | PerformLayout(); 92 | base.Load += new System.EventHandler(OnLoad); 93 | base.MouseLeave += new System.EventHandler(OnMouseLeave); 94 | base.MouseEnter += new System.EventHandler(OnMouseEnter); 95 | btnOk.MouseEnter += new System.EventHandler(OnMouseEnter); 96 | btnCancel.MouseEnter += new System.EventHandler(OnMouseEnter); 97 | txtPassword.MouseEnter += new System.EventHandler(OnMouseEnter); 98 | } 99 | 100 | private void OnLoad(object sender, EventArgs e) 101 | { 102 | OnMouseLeave(this, EventArgs.Empty); 103 | } 104 | 105 | public PasswordForm() 106 | { 107 | InitializeComponent(); 108 | lblPass.Text = "Enter password:"; 109 | txtPassword.Select(); 110 | } 111 | 112 | private static string ToString(SecureString secureString) 113 | { 114 | IntPtr stringPointer = Marshal.SecureStringToBSTR(secureString); 115 | try 116 | { 117 | return Marshal.PtrToStringBSTR(stringPointer); 118 | } 119 | finally 120 | { 121 | Marshal.ZeroFreeBSTR(stringPointer); 122 | } 123 | } 124 | 125 | private unsafe static byte[] ToByteArray(SecureString secureString, Encoding encoding = null) 126 | { 127 | if (secureString == null) 128 | { 129 | throw new ArgumentNullException("secureString"); 130 | } 131 | if (encoding == null) 132 | { 133 | encoding = Encoding.UTF8; 134 | } 135 | int maxLength = encoding.GetMaxByteCount(secureString.Length); 136 | IntPtr bytes = Marshal.AllocHGlobal(maxLength); 137 | IntPtr str = Marshal.SecureStringToBSTR(secureString); 138 | try 139 | { 140 | char* chars = (char*)str.ToPointer(); 141 | byte* bptr = (byte*)bytes.ToPointer(); 142 | int len = encoding.GetBytes(chars, secureString.Length, bptr, maxLength); 143 | byte[] _bytes = new byte[len]; 144 | for (int i = 0; i < len; i++) 145 | { 146 | _bytes[i] = *bptr; 147 | bptr++; 148 | } 149 | return _bytes; 150 | } 151 | finally 152 | { 153 | Marshal.FreeHGlobal(bytes); 154 | Marshal.ZeroFreeBSTR(str); 155 | } 156 | } 157 | 158 | private void OnMouseLeave(object sender, EventArgs e) 159 | { 160 | base.Opacity = 0.99; 161 | } 162 | 163 | private void OnMouseEnter(object sender, EventArgs e) 164 | { 165 | base.Opacity = 1.0; 166 | } 167 | 168 | private void btnOk_Click(object sender, EventArgs e) 169 | { 170 | base.DialogResult = DialogResult.OK; 171 | Close(); 172 | } 173 | 174 | private void btnCancel_Click(object sender, EventArgs e) 175 | { 176 | _secureString.Clear(); 177 | txtPassword.Clear(); 178 | } 179 | 180 | protected override void Dispose(bool disposing) 181 | { 182 | if (disposing && components != null) 183 | { 184 | components.Dispose(); 185 | } 186 | base.Dispose(disposing); 187 | } 188 | 189 | private void InputBox_KeyPress(object sender, KeyPressEventArgs e) 190 | { 191 | if (e.KeyChar == '\b') 192 | { 193 | ProcessBackspace(); 194 | } 195 | else 196 | { 197 | ProcessNewCharacter(e.KeyChar); 198 | } 199 | e.Handled = true; 200 | } 201 | 202 | private void ProcessNewCharacter(char character) 203 | { 204 | if (txtPassword.SelectionLength > 0) 205 | { 206 | RemoveSelectedCharacters(); 207 | } 208 | _secureString.InsertAt(txtPassword.SelectionStart, character); 209 | ResetDisplayCharacters(txtPassword.SelectionStart + 1); 210 | } 211 | 212 | private void RemoveSelectedCharacters() 213 | { 214 | for (int i = 0; i < txtPassword.SelectionLength; i++) 215 | { 216 | _secureString.RemoveAt(txtPassword.SelectionStart); 217 | } 218 | } 219 | 220 | private void ResetDisplayCharacters(int caretPosition) 221 | { 222 | txtPassword.Text = new string('•', _secureString.Length); 223 | txtPassword.SelectionStart = caretPosition; 224 | } 225 | 226 | private void ProcessBackspace() 227 | { 228 | if (txtPassword.SelectionLength > 0) 229 | { 230 | RemoveSelectedCharacters(); 231 | ResetDisplayCharacters(txtPassword.SelectionStart); 232 | } 233 | else if (txtPassword.SelectionStart > 0) 234 | { 235 | _secureString.RemoveAt(txtPassword.SelectionStart - 1); 236 | ResetDisplayCharacters(txtPassword.SelectionStart - 1); 237 | } 238 | } 239 | 240 | private void InputBox_KeyDown(object sender, KeyEventArgs e) 241 | { 242 | if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back) 243 | { 244 | ProcessDelete(); 245 | e.Handled = true; 246 | } 247 | else if (IsIgnorableKey(e.KeyCode)) 248 | { 249 | e.Handled = true; 250 | } 251 | } 252 | 253 | private static bool IsIgnorableKey(Keys key) 254 | { 255 | if (key != Keys.Escape) 256 | { 257 | return key == Keys.Return; 258 | } 259 | return true; 260 | } 261 | 262 | private void ProcessDelete() 263 | { 264 | if (txtPassword.SelectionLength > 0) 265 | { 266 | RemoveSelectedCharacters(); 267 | } 268 | else if (txtPassword.SelectionStart < txtPassword.Text.Length) 269 | { 270 | _secureString.RemoveAt(txtPassword.SelectionStart); 271 | } 272 | ResetDisplayCharacters(txtPassword.SelectionStart); 273 | } 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /Demo/System.Management.WMI/NetworkAdapterConfigurationInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace System.Management.WMI 4 | { 5 | public class NetworkAdapterConfigurationInfo 6 | { 7 | public object ArpAlwaysSourceRoute {get; set;} 8 | public object ArpUseEtherSNAP {get; set;} 9 | public string Caption {get; set;} 10 | public string DatabasePath {get; set;} 11 | public object DeadGWDetectEnabled {get; set;} 12 | public string[] DefaultIPGateway {get; set;} 13 | public object DefaultTOS {get; set;} 14 | public object DefaultTTL {get; set;} 15 | public string Description {get; set;} 16 | public bool DHCPEnabled {get; set;} 17 | public object DHCPLeaseExpires {get; set;} 18 | public object DHCPLeaseObtained {get; set;} 19 | public object DHCPServer {get; set;} 20 | public object DNSDomain {get; set;} 21 | public string[] DNSDomainSuffixSearchOrder {get; set;} 22 | public bool DNSEnabledForWINSResolution {get; set;} 23 | public string DNSHostName {get; set;} 24 | public string[] DNSServerSearchOrder {get; set;} 25 | public bool DomainDNSRegistrationEnabled {get; set;} 26 | public object ForwardBufferMemory {get; set;} 27 | public bool FullDNSRegistrationEnabled {get; set;} 28 | public ushort[] GatewayCostMetric {get; set;} 29 | public object IGMPLevel {get; set;} 30 | public uint Index {get; set;} 31 | public uint InterfaceIndex {get; set;} 32 | public string[] IPAddress {get; set;} 33 | public uint IPConnectionMetric {get; set;} 34 | public bool IPEnabled {get; set;} 35 | public bool IPFilterSecurityEnabled {get; set;} 36 | public object IPPortSecurityEnabled {get; set;} 37 | public string[] IPSecPermitIPProtocols {get; set;} 38 | public string[] IPSecPermitTCPPorts {get; set;} 39 | public string[] IPSecPermitUDPPorts {get; set;} 40 | public string[] IPSubnet {get; set;} 41 | public object IPUseZeroBroadcast {get; set;} 42 | public object IPXAddress {get; set;} 43 | public object IPXEnabled {get; set;} 44 | public object IPXFrameType {get; set;} 45 | public object IPXMediaType {get; set;} 46 | public object IPXNetworkNumber {get; set;} 47 | public object IPXVirtualNetNumber {get; set;} 48 | public object KeepAliveInterval {get; set;} 49 | public object KeepAliveTime {get; set;} 50 | public string MACAddress {get; set;} 51 | public object MTU {get; set;} 52 | public object NumForwardPackets {get; set;} 53 | public object PMTUBHDetectEnabled {get; set;} 54 | public object PMTUDiscoveryEnabled {get; set;} 55 | public string ServiceName {get; set;} 56 | public string SettingID {get; set;} 57 | public uint TcpipNetbiosOptions {get; set;} 58 | public object TcpMaxConnectRetransmissions {get; set;} 59 | public object TcpMaxDataRetransmissions {get; set;} 60 | public object TcpNumConnections {get; set;} 61 | public object TcpUseRFC1122UrgentPointer {get; set;} 62 | public object TcpWindowSize {get; set;} 63 | public bool WINSEnableLMHostsLookup {get; set;} 64 | public object WINSHostLookupFile {get; set;} 65 | public object WINSPrimaryServer {get; set;} 66 | public string WINSScopeID {get; set;} 67 | public object WINSSecondaryServer {get; set;} 68 | private NetworkAdapterConfigurationInfo() 69 | { 70 | } 71 | 72 | private static T GetPropertyValue(ManagementObject wmi, string propertyName) 73 | { 74 | try 75 | { 76 | return (T)(wmi.GetPropertyValue(propertyName) ?? ((object)default(T))); 77 | } 78 | catch 79 | { 80 | return default(T); 81 | } 82 | } 83 | 84 | public static NetworkAdapterConfigurationInfo[] GetNetworkAdapterConfigurationInfo() 85 | { 86 | ManagementClass managementClass = new ManagementClass(new ManagementPath("Win32_NetworkAdapterConfiguration")); 87 | List list = new List(); 88 | foreach (ManagementObject item in managementClass.GetInstances()) 89 | { 90 | list.Add(new NetworkAdapterConfigurationInfo 91 | { 92 | ArpAlwaysSourceRoute = GetPropertyValue(item, "ArpAlwaysSourceRoute"), 93 | ArpUseEtherSNAP = GetPropertyValue(item, "ArpUseEtherSNAP"), 94 | Caption = GetPropertyValue(item, "Caption"), 95 | DatabasePath = GetPropertyValue(item, "DatabasePath"), 96 | DeadGWDetectEnabled = GetPropertyValue(item, "DeadGWDetectEnabled"), 97 | DefaultIPGateway = GetPropertyValue(item, "DefaultIPGateway"), 98 | DefaultTOS = GetPropertyValue(item, "DefaultTOS"), 99 | DefaultTTL = GetPropertyValue(item, "DefaultTTL"), 100 | Description = GetPropertyValue(item, "Description"), 101 | DHCPEnabled = GetPropertyValue(item, "DHCPEnabled"), 102 | DHCPLeaseExpires = GetPropertyValue(item, "DHCPLeaseExpires"), 103 | DHCPLeaseObtained = GetPropertyValue(item, "DHCPLeaseObtained"), 104 | DHCPServer = GetPropertyValue(item, "DHCPServer"), 105 | DNSDomain = GetPropertyValue(item, "DNSDomain"), 106 | DNSDomainSuffixSearchOrder = GetPropertyValue(item, "DNSDomainSuffixSearchOrder"), 107 | DNSEnabledForWINSResolution = GetPropertyValue(item, "DNSEnabledForWINSResolution"), 108 | DNSHostName = GetPropertyValue(item, "DNSHostName"), 109 | DNSServerSearchOrder = GetPropertyValue(item, "DNSServerSearchOrder"), 110 | DomainDNSRegistrationEnabled = GetPropertyValue(item, "DomainDNSRegistrationEnabled"), 111 | ForwardBufferMemory = GetPropertyValue(item, "ForwardBufferMemory"), 112 | FullDNSRegistrationEnabled = GetPropertyValue(item, "FullDNSRegistrationEnabled"), 113 | GatewayCostMetric = GetPropertyValue(item, "GatewayCostMetric"), 114 | IGMPLevel = GetPropertyValue(item, "IGMPLevel"), 115 | Index = GetPropertyValue(item, "Index"), 116 | InterfaceIndex = GetPropertyValue(item, "InterfaceIndex"), 117 | IPAddress = GetPropertyValue(item, "IPAddress"), 118 | IPConnectionMetric = GetPropertyValue(item, "IPConnectionMetric"), 119 | IPEnabled = GetPropertyValue(item, "IPEnabled"), 120 | IPFilterSecurityEnabled = GetPropertyValue(item, "IPFilterSecurityEnabled"), 121 | IPPortSecurityEnabled = GetPropertyValue(item, "IPPortSecurityEnabled"), 122 | IPSecPermitIPProtocols = GetPropertyValue(item, "IPSecPermitIPProtocols"), 123 | IPSecPermitTCPPorts = GetPropertyValue(item, "IPSecPermitTCPPorts"), 124 | IPSecPermitUDPPorts = GetPropertyValue(item, "IPSecPermitUDPPorts"), 125 | IPSubnet = GetPropertyValue(item, "IPSubnet"), 126 | IPUseZeroBroadcast = GetPropertyValue(item, "IPUseZeroBroadcast"), 127 | IPXAddress = GetPropertyValue(item, "IPXAddress"), 128 | IPXEnabled = GetPropertyValue(item, "IPXEnabled"), 129 | IPXFrameType = GetPropertyValue(item, "IPXFrameType"), 130 | IPXMediaType = GetPropertyValue(item, "IPXMediaType"), 131 | IPXNetworkNumber = GetPropertyValue(item, "IPXNetworkNumber"), 132 | IPXVirtualNetNumber = GetPropertyValue(item, "IPXVirtualNetNumber"), 133 | KeepAliveInterval = GetPropertyValue(item, "KeepAliveInterval"), 134 | KeepAliveTime = GetPropertyValue(item, "KeepAliveTime"), 135 | MACAddress = GetPropertyValue(item, "MACAddress"), 136 | MTU = GetPropertyValue(item, "MTU"), 137 | NumForwardPackets = GetPropertyValue(item, "NumForwardPackets"), 138 | PMTUBHDetectEnabled = GetPropertyValue(item, "PMTUBHDetectEnabled"), 139 | PMTUDiscoveryEnabled = GetPropertyValue(item, "PMTUDiscoveryEnabled"), 140 | ServiceName = GetPropertyValue(item, "ServiceName"), 141 | SettingID = GetPropertyValue(item, "SettingID"), 142 | TcpipNetbiosOptions = GetPropertyValue(item, "TcpipNetbiosOptions"), 143 | TcpMaxConnectRetransmissions = GetPropertyValue(item, "TcpMaxConnectRetransmissions"), 144 | TcpMaxDataRetransmissions = GetPropertyValue(item, "TcpMaxDataRetransmissions"), 145 | TcpNumConnections = GetPropertyValue(item, "TcpNumConnections"), 146 | TcpUseRFC1122UrgentPointer = GetPropertyValue(item, "TcpUseRFC1122UrgentPointer"), 147 | TcpWindowSize = GetPropertyValue(item, "TcpWindowSize"), 148 | WINSEnableLMHostsLookup = GetPropertyValue(item, "WINSEnableLMHostsLookup"), 149 | WINSHostLookupFile = GetPropertyValue(item, "WINSHostLookupFile"), 150 | WINSPrimaryServer = GetPropertyValue(item, "WINSPrimaryServer"), 151 | WINSScopeID = GetPropertyValue(item, "WINSScopeID"), 152 | WINSSecondaryServer = GetPropertyValue(item, "WINSSecondaryServer") 153 | }); 154 | item.Dispose(); 155 | } 156 | return list.ToArray(); 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /Source/Security/Activation/ActivationKeyDecryptor.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: ActivationKeyDecryptor.cs 4 | 5 | • Description. 6 | 7 | ActivationKeyDecryptor is a class that is used to check the 8 | activation of a key and decrypt the data contained in it, 9 | using various encryption and hashing algorithms, as well as 10 | binding to user-defined hardware and software environment 11 | variables. 12 | 13 | The code can be used to create a software activation system 14 | or other products that require key activation verification. 15 | 16 | ***************************************************************/ 17 | 18 | using System.Diagnostics; 19 | using System.IO; 20 | using System.Security.Cryptography; 21 | using System.Text; 22 | using static System.InternalTools; 23 | 24 | namespace System.Security.Activation 25 | { 26 | /// 27 | /// Used to verify the activation key and decrypt the data contained in it. 28 | /// Data can be encrypted using various encryption and hashing algorithms. 29 | /// 30 | public sealed class ActivationKeyDecryptor : IDisposable 31 | { 32 | private byte[] _data = null; 33 | 34 | /// 35 | /// Returns a byte array containing the decrypted data. 36 | /// 37 | public byte[] Data => _data?.ArrayClone(); 38 | 39 | /// 40 | /// Returns true if the data was successfully decrypted. 41 | /// False means the key failed verification. 42 | /// 43 | public bool Success => _data != null; 44 | 45 | 46 | /// 47 | /// Returns the activation key expiration date. 48 | /// 49 | public DateTime ExpirationDate { get; private set; } = DateTime.MinValue.Date; 50 | 51 | // Decrypts the data contained in the activation key 52 | // using the specified encryption and hashing algorithm. 53 | private unsafe void InternalDecrypt(ICryptoTransform transform, HashAlgorithm hashAlgorithm, 54 | ActivationKey activationKey) 55 | { 56 | if (activationKey.InvalidState) 57 | return; 58 | 59 | byte[] data = activationKey.Data; 60 | byte[] decryptedData = transform.TransformFinalBlock(data, 0, data.Length); 61 | byte[] seed = activationKey.Seed; 62 | byte[] hash = hashAlgorithm.ComputeHash(Serialize(decryptedData, seed)); 63 | 64 | if (decryptedData.Length < sizeof(DateTime)) // The data block is too short for DateTime. 65 | return; 66 | 67 | ExpirationDate = ConvertTo(decryptedData); 68 | if (ExpirationDate.Date >= DateTime.Today.Date && hash.ArrayEquals(activationKey.Hash)) 69 | _data = decryptedData.ArrayClone(sizeof(DateTime)); 70 | } 71 | 72 | // The invisible constructor. 73 | internal ActivationKeyDecryptor() 74 | { 75 | } 76 | 77 | /// 78 | /// Initializes a new instance of the , 79 | /// which is used to decrypt the data contained in the . 80 | /// 81 | /// 82 | /// The activation key to be verified. 83 | /// 84 | /// 85 | /// Environment binding parameters used to generate the key. 86 | /// These parameters can be used to create a unique activation key 87 | /// that can be used to authenticate a user or device. 88 | /// 89 | /// 90 | /// Trows if argument is null. 91 | /// 92 | public ActivationKeyDecryptor(ActivationKey activationKey, params object[] environment) 93 | { 94 | if (activationKey == null) 95 | throw new ArgumentNullException(nameof(activationKey), 96 | GetResourceString("ArgumentNull_WithParamName", nameof(activationKey))); 97 | 98 | try 99 | { 100 | byte[] seed = activationKey.Seed; 101 | using (ICryptoTransform decryptor = new ARC4CryptoTransform(Serialize(environment), seed)) 102 | using (HashAlgorithm hasher = new SipHashAlgorithm(seed)) 103 | { 104 | InternalDecrypt(decryptor, hasher, activationKey); 105 | } 106 | } 107 | catch (Exception e) 108 | { 109 | _data = null; 110 | #if DEBUG 111 | if (Debug.Listeners.Count > 0) 112 | { 113 | Debug.WriteLine(DateTime.Now); 114 | Debug.WriteLine(e, "Exception"); 115 | } 116 | #endif 117 | } 118 | } 119 | 120 | /// 121 | /// Initializes a new instance of the , 122 | /// 123 | /// 124 | /// Symmetric encryption algorithm. 125 | /// 126 | /// 127 | /// Hash algorithm. 128 | /// 129 | /// 130 | /// The activation key to be verified. 131 | /// 132 | /// 133 | /// Environment binding parameters used to generate the key. 134 | /// These parameters can be used to create a unique activation key 135 | /// that can be used to authenticate a user or device. 136 | /// 137 | /// If one of the arguments (, 138 | /// or ) is null. 139 | /// 140 | public ActivationKeyDecryptor(SymmetricAlgorithm symmetricAlgorithm, HashAlgorithm hashAlgorithm, 141 | ActivationKey activationKey, params object[] environment) 142 | { 143 | if (symmetricAlgorithm == null) 144 | throw new ArgumentNullException(nameof(symmetricAlgorithm), 145 | GetResourceString("ArgumentNull_WithParamName", nameof(symmetricAlgorithm))); 146 | if (hashAlgorithm == null) 147 | throw new ArgumentNullException(nameof(hashAlgorithm), 148 | GetResourceString("ArgumentNull_WithParamName", nameof(hashAlgorithm))); 149 | if (activationKey == null) 150 | throw new ArgumentNullException(nameof(activationKey), 151 | GetResourceString("ArgumentNull_WithParamName", nameof(activationKey))); 152 | 153 | try 154 | { 155 | byte[] seed = activationKey.Seed; 156 | using (PasswordDeriveBytes deriveBytes = new PasswordDeriveBytes(Serialize(environment), seed)) 157 | using (ICryptoTransform decryptor = 158 | symmetricAlgorithm.CreateDecryptor(deriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8), seed)) 159 | { 160 | InternalDecrypt(decryptor, hashAlgorithm, activationKey); 161 | } 162 | } 163 | catch (Exception e) 164 | { 165 | _data = null; 166 | #if DEBUG 167 | if (Debug.Listeners.Count > 0) 168 | { 169 | Debug.WriteLine(DateTime.Now); 170 | Debug.WriteLine(e, "Exception"); 171 | } 172 | #endif 173 | } 174 | } 175 | 176 | /// 177 | /// Returns a object that can be used 178 | /// to read the decrypted data stored to the activation key. 179 | /// 180 | /// 181 | /// A object for reading the decrypted data. 182 | /// 183 | /// 184 | /// Key verification failed, the key did not contain encrypted data, or the key has expired. 185 | /// 186 | public BinaryReader GetBinaryReader() 187 | { 188 | if (_data.IsNullOrEmpty()) 189 | throw new InvalidOperationException(GetResourceString("Arg_InvalidOperationException")); 190 | 191 | BinaryReader binaryReader = new BinaryReader(new MemoryStream(Data, false)); 192 | return binaryReader; 193 | } 194 | 195 | /// 196 | /// Returns a object that can be used 197 | /// to read the decrypted data stored to the activation key. 198 | /// 199 | /// 200 | /// The encoding applied to the contents of the decrypted data. 201 | /// 202 | /// 203 | /// A object for reading the decrypted data. 204 | /// 205 | /// 206 | /// Key verification failed, the key did not contain encrypted data, or the key has expired. 207 | /// 208 | public TextReader GetTextReader(Encoding encoding = null) 209 | { 210 | if (_data.IsNullOrEmpty()) 211 | throw new InvalidOperationException(GetResourceString("Arg_InvalidOperationException")); 212 | 213 | TextReader textReader = new StreamReader(new MemoryStream(Data, false), encoding ?? Encoding.UTF8); 214 | return textReader; 215 | } 216 | 217 | /// 218 | public void Dispose() 219 | { 220 | _data.Clear(); 221 | _data = null; 222 | } 223 | } 224 | } -------------------------------------------------------------------------------- /Source/Security/Cryptography/ARC4CryptoTransform.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: ARC4CryptoTransform.cs 4 | 5 | • Description. 6 | 7 | ARC4CryptoTransform implements and provides methods for 8 | encrypting and decrypting data using a modified RC4 9 | algorithm. Used by default to generate activation keys. 10 | 11 | Despite the known vulnerabilities of RC4, such as leaking 12 | key information and the possibility of attacking weak keys, 13 | it is sufficient for the purposes of this project, since the 14 | length of the encrypted data, as a rule, does not exceed a 15 | few bytes. To improve cryptographic strength, an 16 | initialization vector and skipping the first 512 bytes were 17 | implemented. 18 | 19 | ***************************************************************/ 20 | 21 | using static System.InternalTools; 22 | 23 | namespace System.Security.Cryptography 24 | { 25 | // Implements a modified version of the RC4+ encryption algorithm. 26 | internal sealed unsafe class ARC4CryptoTransform : ICryptoTransform 27 | { 28 | // Internal state arrays for RC4. 29 | private byte[] _s1 = new byte[256]; 30 | private byte[] _s2 = new byte[256]; 31 | 32 | // Indices for both state arrays. 33 | private int _x1, _y1, _x2, _y2; 34 | private bool _disposed = false; 35 | 36 | // Size of the input data block in bits. 37 | public int InputBlockSize => 1; 38 | 39 | // Size of the output data block in bits. 40 | public int OutputBlockSize => 1; 41 | 42 | // Indicates whether multiple data blocks can be converted. 43 | public bool CanTransformMultipleBlocks => true; 44 | 45 | // Indicates whether the transformation can be reused. 46 | public bool CanReuseTransform => false; 47 | 48 | public ARC4CryptoTransform(byte[] key, byte[] iv) 49 | { 50 | if (key == null) 51 | throw new ArgumentNullException(nameof(key), GetResourceString("ArgumentNull_Array")); 52 | if (iv == null) 53 | throw new ArgumentNullException(nameof(iv), GetResourceString("ArgumentNull_Array")); 54 | if (iv.Length < 4) 55 | throw new ArgumentException(GetResourceString("Cryptography_InvalidIVSize"), nameof(iv)); 56 | 57 | byte* ivPtr = stackalloc byte[iv.Length]; 58 | for (int i = 0; i < iv.Length; i++) 59 | { 60 | ivPtr[i] = iv[i]; 61 | } 62 | 63 | // Perform Linear Congruential Random (LCR) generating and Key Scheduling Algorithm (KSA) on both state arrays. 64 | fixed (byte* s1Ptr = _s1, s2Ptr = _s2, keyPtr = key) 65 | { 66 | /***** Apply the LCR operation. *****/ 67 | LCR(s1Ptr, ivPtr); 68 | 69 | // Shift the IV for the second state array. 70 | for (int i = 0; i < 4; i++) 71 | ivPtr[i] = (byte)((ivPtr[i] + 128) & 0xFF); 72 | 73 | // Rotate the IV for further modification. 74 | byte swap = ivPtr[0]; 75 | for (int i = 0; i < 3; i++) 76 | ivPtr[i] = ivPtr[i + 1]; 77 | ivPtr[3] = swap; 78 | LCR(s2Ptr, ivPtr); 79 | 80 | /***** Apply the KSA operation. *****/ 81 | int keyLength = key.Length; 82 | KSA(s1Ptr, keyPtr, keyLength, ref _x1, ref _y1); 83 | KSA(s2Ptr, keyPtr, keyLength, ref _x2, ref _y2); 84 | } 85 | 86 | // Initialize indices for the state arrays. 87 | _x1 = _y1 = _x2 = _y2 = 0; 88 | } 89 | 90 | public ARC4CryptoTransform(byte[] key, int seed) : this(key, BitConverter.GetBytes(seed)) 91 | { 92 | } 93 | 94 | public ARC4CryptoTransform(byte[] key, uint seed) : this(key, BitConverter.GetBytes(seed)) 95 | { 96 | } 97 | 98 | // Swap state array values. 99 | private static void Swap(byte* array, int x, int y) 100 | { 101 | if (x != y) 102 | { 103 | array[x] ^= array[y]; 104 | array[y] ^= array[x]; 105 | array[x] ^= array[y]; 106 | } 107 | } 108 | 109 | // The Linear Congruential Generator (LCR) operation used in RC4. 110 | private static void LCR(byte* sblock, byte* iv) 111 | { 112 | // Extract the initialization vector (IV) values. 113 | int r = iv[0]; // Nolinear transformation value. 114 | int x = iv[1]; // First value. 115 | int a = ((iv[2] & 0x3F) << 2) | 1; // Multiplier. 116 | int c = ((iv[3] & 0x7F) << 1) | 1; // Increment. 117 | int s = (byte)(((iv[2] & 0xC0) >> 5) | ((iv[3] & 0x80) >> 7)); // Shift. 118 | 119 | // Apply the Linear Congruential Transformation. 120 | for (int i = 0; i < 256; i++) 121 | { 122 | int b = (x = (a * x + c) & 0xFF) ^ r; 123 | sblock[i] = (byte)((b << s) | (b >> (8 - s))); 124 | } 125 | } 126 | 127 | // The Key Scheduling Algorithm (KSA) used in RC4 to initialize the state array. 128 | private static void KSA(byte* sblock, byte* key, int keyLength, ref int x, ref int y) 129 | { 130 | if (keyLength < 1) 131 | return; 132 | 133 | for (int i = 0, j = 0; i < 256; i++) 134 | { 135 | j = (j + sblock[i] + key[i % keyLength]) % 256; 136 | Swap(sblock, i, j); 137 | } 138 | 139 | // Skip the first 256 bytes to reduce correlation with the key. 140 | PRGA(sblock, ref x, ref y, 256); 141 | } 142 | 143 | // Performs PRGA operation. 144 | private static void PRGA(byte* sblock, ref int x, ref int y) 145 | { 146 | // Perform the swapping of state array values. 147 | x = (x + 1) & 0xFF; 148 | y = (y + sblock[x]) & 0xFF; 149 | Swap(sblock, x, y); 150 | } 151 | 152 | private static void PRGA(byte* sblock, ref int x, ref int y, int n) 153 | { 154 | for (int i = 0; i < n; i++) 155 | { 156 | x = (x + 1) & 0xFF; 157 | y = (y + sblock[x]) & 0xFF; 158 | Swap(sblock, x, y); 159 | } 160 | } 161 | 162 | // Converts a block of data using the RC4 algorithm. 163 | public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, 164 | int outputOffset) 165 | { 166 | CheckDisposed(); 167 | CheckBufer(inputBuffer, inputOffset, inputCount); 168 | CheckBufer(outputBuffer, outputOffset); 169 | 170 | fixed (byte* s1Ptr = _s1, s2Ptr = _s2) 171 | { 172 | for (int i = 0; i < inputCount; i++) 173 | { 174 | // Generate an intermediate key bytes using PRGA operation. 175 | PRGA(s1Ptr, ref _x1, ref _y1); 176 | byte k1 = s1Ptr[(s1Ptr[_x1] + s1Ptr[_y1]) & 0xFF]; 177 | PRGA(s2Ptr, ref _x2, ref _y2); 178 | byte k2 = s2Ptr[(s2Ptr[_x2] + s2Ptr[_y2]) & 0xFF]; 179 | 180 | // Combine the two key bytes using additional nonlinear transformations. 181 | byte k = (byte)((k1 + k2) ^ ((k1 << 5) | (k2 >> 3))); 182 | 183 | // XOR the key byte with the input to produce the output. 184 | outputBuffer[outputOffset + i] = (byte)(inputBuffer[inputOffset + i] ^ k); 185 | } 186 | } 187 | 188 | return inputCount; 189 | } 190 | 191 | // Converts the last block of data using the RC4 algorithm. 192 | public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) 193 | { 194 | CheckDisposed(); 195 | CheckBufer(inputBuffer, inputOffset, inputCount); 196 | 197 | byte[] finalBlock = new byte[inputCount]; 198 | TransformBlock(inputBuffer, inputOffset, inputCount, finalBlock, 0); 199 | return finalBlock; 200 | } 201 | 202 | private void CheckBufer(byte[] buffer, int offset) 203 | { 204 | if (buffer == null) 205 | throw new ArgumentNullException(nameof(buffer), GetResourceString("ArgumentNull_Buffer")); 206 | if (offset < 0) 207 | throw new ArgumentOutOfRangeException(nameof(offset), offset, 208 | GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); 209 | if (offset > buffer.Length) 210 | throw new ArgumentOutOfRangeException(nameof(offset), offset, 211 | GetResourceString("Argument_InvalidValue")); 212 | } 213 | 214 | private void CheckBufer(byte[] buffer, int offset, int count) 215 | { 216 | CheckBufer(buffer, offset); 217 | if (count < 0) 218 | throw new ArgumentOutOfRangeException(nameof(count), offset, 219 | GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); 220 | if (count > buffer.Length) 221 | throw new ArgumentOutOfRangeException(nameof(count), count, GetResourceString("Argument_InvalidValue")); 222 | if (buffer.Length - count < offset) 223 | throw new ArgumentException(GetResourceString("Argument_InvalidOffLen")); 224 | } 225 | 226 | private void CheckDisposed() 227 | { 228 | if (_disposed) 229 | throw new ObjectDisposedException(nameof(ARC4CryptoTransform), GetResourceString("ObjectDisposed_Generic")); 230 | } 231 | 232 | // Releases resources used by the class. 233 | public void Dispose() 234 | { 235 | _s1.Clear(); 236 | _s2.Clear(); 237 | 238 | _s1 = null; 239 | _s2 = null; 240 | 241 | _x1 = _y1 = _x2 = _y2 = 0; 242 | 243 | _disposed = true; 244 | } 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /Source/Text/CustomEncoding.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************** 2 | 3 | • File: CustomEncoding.cs 4 | 5 | • Description. 6 | 7 | The CustomEncoding class provides an implementation of 8 | various encodings of binary data to text using custom 9 | characters. 10 | 11 | It is used to convert binary data to text representation and 12 | vice versa. The class uses a custom alphabet, which is 13 | specified when the instance is created. 14 | 15 | This code is based on https://github.com/KvanTTT/BaseNcoding 16 | distributed under Apache-2.0 license 17 | http://www.apache.org/licenses/LICENSE-2.0 18 | 19 | 20 | ******************************************************************/ 21 | 22 | using System.Linq; 23 | using static System.InternalTools; 24 | 25 | namespace System.Text 26 | { 27 | 28 | // Represents the implementation of various encodings of binary data to text using user-specified characters. 29 | internal sealed class CustomEncoding : IPrintableEncoding 30 | { 31 | private const uint MAX_BITS_COUNT = 32; 32 | private readonly int _blockSize; 33 | private readonly int _blockCharsCount; 34 | private readonly char[] _encodingTable; 35 | private readonly int[] _decodingTable; 36 | private readonly ulong[] _powN; 37 | 38 | public CustomEncoding(string alphabet) 39 | { 40 | if (alphabet == null) 41 | throw new ArgumentNullException(nameof(alphabet), GetResourceString("ArgumentNull_String")); 42 | if (alphabet.IsNullOrWhiteSpace()) 43 | throw new ArgumentException(GetResourceString("Format_EmptyInputString"), nameof(alphabet)); 44 | _encodingTable = alphabet.ToCharArray(); 45 | if (!alphabet.IsPrintableCharacters() || _encodingTable.ContainsDuplicates()) 46 | throw new ArgumentException(GetResourceString("Format_InvalidString"), nameof(alphabet)); 47 | 48 | uint charsCount = (uint)alphabet.Length; 49 | uint x = charsCount; 50 | int bitsPerChar = 0; 51 | while ((x >>= 1) != 0) 52 | bitsPerChar++; 53 | int lcm = bitsPerChar; 54 | for (int i = 8, j = i; i != 0; lcm = j) 55 | { 56 | i = lcm % i; 57 | } 58 | 59 | _blockSize = (bitsPerChar / lcm) * 8; 60 | _blockCharsCount = _blockSize / bitsPerChar; 61 | 62 | _decodingTable = new int[_encodingTable.Max() + 1]; 63 | 64 | for (int i = 0; i < _decodingTable.Length; i++) 65 | { 66 | _decodingTable[i] = -1; 67 | } 68 | 69 | for (int i = 0; i < charsCount; i++) 70 | { 71 | _decodingTable[_encodingTable[i]] = i; 72 | } 73 | 74 | int optimalBitsCount = 0; 75 | uint charsCountInBits = 0; 76 | 77 | int logBaseN = 0; 78 | for (uint i = charsCount; (i /= 2) != 0; logBaseN++) ; 79 | 80 | double charsCountLog = Math.Log(2, charsCount); 81 | double maxRatio = 0; 82 | 83 | for (int i = logBaseN; i <= MAX_BITS_COUNT; i++) 84 | { 85 | uint j = (uint)Math.Ceiling(i * charsCountLog); 86 | double ratio = (double)i / j; 87 | if (ratio > maxRatio) 88 | { 89 | maxRatio = ratio; 90 | optimalBitsCount = i; 91 | charsCountInBits = j; 92 | } 93 | } 94 | 95 | _blockSize = optimalBitsCount; 96 | _blockCharsCount = (int)charsCountInBits; 97 | _powN = new ulong[_blockCharsCount]; 98 | ulong pow = 1; 99 | for (int i = 0; i < _blockCharsCount - 1; i++) 100 | { 101 | _powN[_blockCharsCount - 1 - i] = pow; 102 | pow *= charsCount; 103 | } 104 | 105 | _powN[0] = pow; 106 | } 107 | 108 | public string GetString(byte[] data) 109 | { 110 | 111 | if (data == null || data.Length == 0) 112 | { 113 | return ""; 114 | } 115 | 116 | int mainBitsLength = data.Length * 8 / _blockSize * _blockSize; 117 | int tailBitsLength = data.Length * 8 - mainBitsLength; 118 | int mainCharsCount = mainBitsLength * _blockCharsCount / _blockSize; 119 | int tailCharsCount = (tailBitsLength * _blockCharsCount + _blockSize - 1) / _blockSize; 120 | int totalCharsCount = mainCharsCount + tailCharsCount; 121 | int iterationCount = mainCharsCount / _blockCharsCount; 122 | 123 | var result = new char[totalCharsCount]; 124 | 125 | for (int ind = 0; ind < iterationCount; ind++) 126 | { 127 | int charInd = ind * _blockCharsCount; 128 | int bitInd = ind * _blockSize; 129 | ulong bits = ReadValue(data, bitInd, _blockSize); 130 | EncodeBlock(result, charInd, _blockCharsCount, bits); 131 | } 132 | 133 | if (tailBitsLength != 0) 134 | { 135 | ulong bits = ReadValue(data, mainBitsLength, tailBitsLength); 136 | EncodeBlock(result, mainCharsCount, tailCharsCount, bits); 137 | } 138 | 139 | return new string(result); 140 | } 141 | 142 | public byte[] GetBytes(string str) 143 | { 144 | if (str.IsNullOrEmpty()) 145 | { 146 | return new byte[0]; 147 | } 148 | 149 | int totalBitsLength = ((str.Length - 1) * _blockSize / _blockCharsCount + 8) / 8 * 8; 150 | int mainBitsLength = totalBitsLength / _blockSize * _blockSize; 151 | int tailBitsLength = totalBitsLength - mainBitsLength; 152 | int mainCharsCount = mainBitsLength * _blockCharsCount / _blockSize; 153 | int tailCharsCount = (tailBitsLength * _blockCharsCount + _blockSize - 1) / _blockSize; 154 | ulong tailBits = DecodeBlock(str, mainCharsCount, tailCharsCount); 155 | if (tailBits >> tailBitsLength != 0) 156 | { 157 | totalBitsLength += 8; 158 | mainBitsLength = totalBitsLength / _blockSize * _blockSize; 159 | tailBitsLength = totalBitsLength - mainBitsLength; 160 | mainCharsCount = mainBitsLength * _blockCharsCount / _blockSize; 161 | tailCharsCount = (tailBitsLength * _blockCharsCount + _blockSize - 1) / _blockSize; 162 | } 163 | 164 | int iterationCount = mainCharsCount / _blockCharsCount; 165 | byte[] result = new byte[totalBitsLength / 8]; 166 | 167 | for (int ind = 0; ind < iterationCount; ind++) 168 | { 169 | int charInd = ind * _blockCharsCount; 170 | int bitInd = ind * _blockSize; 171 | ulong block = DecodeBlock(str, charInd, _blockCharsCount); 172 | WriteValue(result, block, bitInd, _blockSize); 173 | } 174 | 175 | if (tailCharsCount != 0) 176 | { 177 | ulong block = DecodeBlock(str, mainCharsCount, tailCharsCount); 178 | WriteValue(result, block, mainBitsLength, tailBitsLength); 179 | } 180 | 181 | return result; 182 | } 183 | 184 | private static ulong ReadValue(byte[] data, int bitIndex, int bitsCount) 185 | { 186 | ulong result = 0; 187 | 188 | int currentBytePos = Math.DivRem(bitIndex, 8, out int currentBitInBytePos); 189 | 190 | int xLength = Math.Min(bitsCount, 8 - currentBitInBytePos); 191 | if (xLength != 0) 192 | { 193 | result = ((ulong)data[currentBytePos] << 0x38 + currentBitInBytePos) >> 0x40 - xLength << 194 | bitsCount - xLength; 195 | 196 | currentBytePos += Math.DivRem(currentBitInBytePos + xLength, 8, out currentBitInBytePos); 197 | 198 | int x2Length = bitsCount - xLength; 199 | if (x2Length > 8) 200 | { 201 | x2Length = 8; 202 | } 203 | 204 | while (x2Length > 0) 205 | { 206 | xLength += x2Length; 207 | result |= (ulong)data[currentBytePos] >> 8 - x2Length << bitsCount - xLength; 208 | 209 | currentBytePos += Math.DivRem(currentBitInBytePos + x2Length, 8, out currentBitInBytePos); 210 | 211 | x2Length = bitsCount - xLength; 212 | if (x2Length > 8) 213 | { 214 | x2Length = 8; 215 | } 216 | } 217 | } 218 | 219 | return result; 220 | } 221 | 222 | private static void WriteValue(byte[] data, ulong value, int bitIndex, int bitsCount) 223 | { 224 | unchecked 225 | { 226 | int currentBytePos = Math.DivRem(bitIndex, 8, out int currentBitInBytePos); 227 | 228 | int xLength = Math.Min(bitsCount, 8 - currentBitInBytePos); 229 | if (xLength != 0) 230 | { 231 | byte x1 = (byte)(value << 0x40 - bitsCount >> 0x38 + currentBitInBytePos); 232 | data[currentBytePos] |= x1; 233 | 234 | currentBytePos += Math.DivRem(currentBitInBytePos + xLength, 8, out currentBitInBytePos); 235 | 236 | int x2Length = bitsCount - xLength; 237 | if (x2Length > 8) 238 | { 239 | x2Length = 8; 240 | } 241 | 242 | while (x2Length > 0) 243 | { 244 | xLength += x2Length; 245 | byte x2 = (byte)(value >> bitsCount - xLength << 8 - x2Length); 246 | data[currentBytePos] |= x2; 247 | 248 | currentBytePos += Math.DivRem(currentBitInBytePos + x2Length, 8, out currentBitInBytePos); 249 | 250 | x2Length = bitsCount - xLength; 251 | if (x2Length > 8) 252 | { 253 | x2Length = 8; 254 | } 255 | } 256 | } 257 | } 258 | } 259 | 260 | private void EncodeBlock(char[] chars, int charIndex, int charCount, ulong block) 261 | { 262 | uint baseEncoding = (uint)_encodingTable.Length; 263 | int startCharIndex = charIndex; 264 | int endCharIndex = startCharIndex + charCount; 265 | while(charIndex < endCharIndex) 266 | { 267 | ulong blockCount = block / baseEncoding; 268 | ulong digit = block - blockCount * baseEncoding; 269 | block = blockCount; 270 | chars[charIndex++] = _encodingTable[(int)digit]; 271 | } 272 | } 273 | 274 | private ulong DecodeBlock(string data, int charIndex, int charCount) 275 | { 276 | ulong result = 0; 277 | for (int i = 0; i < charCount; i++) 278 | { 279 | result += (ulong)_decodingTable[data[charIndex + i]] * 280 | _powN[_blockCharsCount - 1 - i]; 281 | } 282 | 283 | return result; 284 | } 285 | 286 | public object Clone() 287 | { 288 | return new CustomEncoding(new string(_encodingTable)); 289 | } 290 | } 291 | } 292 | -------------------------------------------------------------------------------- /Demo/System.ComponentModel/Win32MessageFormatter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Globalization; 3 | using System.Ini; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Runtime.InteropServices; 7 | using System.Text; 8 | 9 | namespace System.ComponentModel 10 | { 11 | [Serializable] 12 | [StructLayout(LayoutKind.Sequential, Pack = 4)] 13 | [TypeConverter(typeof(Win32MessageFormatterConverter))] 14 | internal class Win32MessageFormatter : IInitializer, IDisposable 15 | { 16 | protected const int BUFF_SIZE = 1024; 17 | 18 | [NonSerialized] 19 | private static readonly int[] _installedLangs; 20 | 21 | [NonSerialized] 22 | private static readonly Win32MessageFormatter _defaultFormatter; 23 | 24 | [MarshalAs(UnmanagedType.I4)] 25 | private readonly int _lcid; 26 | 27 | public int LCID => _lcid; 28 | 29 | public static Win32MessageFormatter DefaultFormatter => _defaultFormatter; 30 | 31 | public virtual void Dispose() 32 | { 33 | } 34 | 35 | static Win32MessageFormatter() 36 | { 37 | _defaultFormatter = new Win32MessageFormatter(); 38 | CultureInfo[] installedCultures = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures); 39 | CultureInfo[] specificCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures); 40 | List installedLangs = new List(installedCultures.Length); 41 | CultureInfo[] array = specificCultures; 42 | foreach (CultureInfo culture in array) 43 | { 44 | if (installedCultures.Contains(culture)) 45 | { 46 | installedLangs.Add(culture.LCID); 47 | } 48 | } 49 | _installedLangs = installedLangs.ToArray(); 50 | } 51 | 52 | public Win32MessageFormatter() 53 | { 54 | _lcid = CultureInfo.CurrentCulture.LCID; 55 | } 56 | 57 | public Win32MessageFormatter(int lcid) 58 | : this() 59 | { 60 | if (_installedLangs.Contains(lcid)) 61 | { 62 | _lcid = lcid; 63 | } 64 | } 65 | 66 | public Win32MessageFormatter(CultureInfo culture) 67 | : this() 68 | { 69 | if (culture != null && _installedLangs.Contains(culture.LCID)) 70 | { 71 | _lcid = culture.LCID; 72 | } 73 | } 74 | 75 | public Win32MessageFormatter(TextInfo info) 76 | : this() 77 | { 78 | if (info != null && _installedLangs.Contains(info.LCID)) 79 | { 80 | _lcid = info.LCID; 81 | } 82 | } 83 | 84 | public Win32MessageFormatter(string name) 85 | { 86 | try 87 | { 88 | CultureInfo culture = CultureInfo.GetCultureInfo(name); 89 | if (_installedLangs.Contains(culture.LCID)) 90 | { 91 | _lcid = culture.LCID; 92 | } 93 | } 94 | catch 95 | { 96 | _lcid = CultureInfo.CurrentCulture.LCID; 97 | } 98 | } 99 | 100 | [DllImport("kernel32.dll", SetLastError = true)] 101 | private static extern IntPtr GetModuleHandle([MarshalAs(UnmanagedType.LPStr)] string lpModuleName); 102 | 103 | [DllImport("kernel32.dll", SetLastError = true)] 104 | [return: MarshalAs(UnmanagedType.I4)] 105 | private static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, [Out] StringBuilder lpBuffer, int nSize, string[] arguments); 106 | 107 | public virtual string FormatMessage(uint messageId, Win32FormatMessageFlags flags, string source, params string[] arguments) 108 | { 109 | if (string.IsNullOrEmpty(source)) 110 | { 111 | flags &= ~Win32FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING; 112 | flags &= ~Win32FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE; 113 | } 114 | if (arguments.Length == 0) 115 | { 116 | flags &= ~Win32FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY; 117 | } 118 | StringBuilder buffer = new StringBuilder(1024); 119 | IntPtr formatPtr = (string.IsNullOrEmpty(source) ? IntPtr.Zero : Marshal.StringToHGlobalAnsi(source)); 120 | int length = FormatMessage((int)flags, formatPtr, messageId, _lcid, buffer, 1024, arguments); 121 | if (length <= 0) 122 | { 123 | return string.Empty; 124 | } 125 | return buffer.ToString(0, length); 126 | } 127 | 128 | public virtual string FormatMessage(uint messageId, Win32FormatMessageFlags flags, string source, bool ignoreNewLine, params string[] arguments) 129 | { 130 | flags = ((!ignoreNewLine) ? (flags & ~Win32FormatMessageFlags.FORMAT_MESSAGE_MAX_WIDTH_MASK) : (flags | Win32FormatMessageFlags.FORMAT_MESSAGE_MAX_WIDTH_MASK)); 131 | if (string.IsNullOrEmpty(source)) 132 | { 133 | flags &= ~Win32FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING; 134 | flags &= ~Win32FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE; 135 | } 136 | if (arguments.Length == 0) 137 | { 138 | flags &= ~Win32FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY; 139 | } 140 | StringBuilder buffer = new StringBuilder(1024); 141 | IntPtr formatPtr = (string.IsNullOrEmpty(source) ? IntPtr.Zero : Marshal.StringToHGlobalAnsi(source)); 142 | int length = FormatMessage((int)flags, formatPtr, messageId, _lcid, buffer, 1024, arguments); 143 | if (length <= 0) 144 | { 145 | return string.Empty; 146 | } 147 | return buffer.ToString(0, length); 148 | } 149 | 150 | public virtual string FormatMessage(uint messageId, params string[] arguments) 151 | { 152 | StringBuilder buffer = new StringBuilder(1024); 153 | int length = FormatMessage(0x1000 | ((arguments.Length != 0) ? 8192 : 512), IntPtr.Zero, messageId, _lcid, buffer, 1024, arguments); 154 | if (length <= 0) 155 | { 156 | return string.Empty; 157 | } 158 | return buffer.ToString(0, length); 159 | } 160 | 161 | public virtual string FormatMessage(uint messageId, bool ignoreNewLine, params string[] arguments) 162 | { 163 | StringBuilder buffer = new StringBuilder(1024); 164 | Win32FormatMessageFlags flags = Win32FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM; 165 | flags |= ((arguments.Length != 0) ? Win32FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY : Win32FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS); 166 | if (ignoreNewLine) 167 | { 168 | flags |= Win32FormatMessageFlags.FORMAT_MESSAGE_MAX_WIDTH_MASK; 169 | } 170 | int length = FormatMessage((int)flags, IntPtr.Zero, messageId, _lcid, buffer, 1024, arguments); 171 | if (length <= 0) 172 | { 173 | return string.Empty; 174 | } 175 | return buffer.ToString(0, length); 176 | } 177 | 178 | public virtual string FormatMessage(uint messageId) 179 | { 180 | StringBuilder buffer = new StringBuilder(1024); 181 | int length = FormatMessage(4608, IntPtr.Zero, messageId, _lcid, buffer, 1024, null); 182 | if (length <= 0) 183 | { 184 | return string.Empty; 185 | } 186 | return buffer.ToString(0, length); 187 | } 188 | 189 | public virtual string FormatMessage(uint messageId, bool ignoreNewLine) 190 | { 191 | StringBuilder buffer = new StringBuilder(1024); 192 | Win32FormatMessageFlags flags = Win32FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM | Win32FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS; 193 | if (ignoreNewLine) 194 | { 195 | flags |= Win32FormatMessageFlags.FORMAT_MESSAGE_MAX_WIDTH_MASK; 196 | } 197 | int length = FormatMessage((int)flags, IntPtr.Zero, messageId, _lcid, buffer, 1024, null); 198 | if (length <= 0) 199 | { 200 | return string.Empty; 201 | } 202 | return buffer.ToString(0, length); 203 | } 204 | 205 | public virtual string FormatMessage(string moduleName, uint messageId, params string[] arguments) 206 | { 207 | StringBuilder buffer = new StringBuilder(1024); 208 | IntPtr modulePtr = (string.IsNullOrEmpty(moduleName) ? IntPtr.Zero : GetModuleHandle(moduleName)); 209 | int length = FormatMessage(0x800 | ((arguments.Length != 0) ? 8192 : 512), modulePtr, messageId, _lcid, buffer, 1024, arguments); 210 | if (length <= 0) 211 | { 212 | return string.Empty; 213 | } 214 | return buffer.ToString(0, length); 215 | } 216 | 217 | public virtual string FormatMessage(string moduleName, uint messageId, bool ignoreNewLine, params string[] arguments) 218 | { 219 | StringBuilder buffer = new StringBuilder(1024); 220 | IntPtr modulePtr = (string.IsNullOrEmpty(moduleName) ? IntPtr.Zero : GetModuleHandle(moduleName)); 221 | Win32FormatMessageFlags flags = Win32FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE; 222 | flags |= ((arguments.Length != 0) ? Win32FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY : Win32FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS); 223 | if (ignoreNewLine) 224 | { 225 | flags |= Win32FormatMessageFlags.FORMAT_MESSAGE_MAX_WIDTH_MASK; 226 | } 227 | int length = FormatMessage((int)flags, modulePtr, messageId, _lcid, buffer, 1024, arguments); 228 | if (length <= 0) 229 | { 230 | return string.Empty; 231 | } 232 | return buffer.ToString(0, length); 233 | } 234 | 235 | public virtual string FormatMessage(string message, params string[] arguments) 236 | { 237 | StringBuilder buffer = new StringBuilder(1024); 238 | IntPtr formatPtr = (string.IsNullOrEmpty(message) ? IntPtr.Zero : Marshal.StringToHGlobalAnsi(message)); 239 | int length = FormatMessage(0x400 | ((arguments.Length != 0) ? 8192 : 512), formatPtr, 0u, _lcid, buffer, 1024, arguments); 240 | message = buffer.ToString(0, length); 241 | return message; 242 | } 243 | 244 | public virtual string FormatMessage(string message, bool ignoreNewLine, params string[] arguments) 245 | { 246 | StringBuilder buffer = new StringBuilder(1024); 247 | IntPtr formatPtr = (string.IsNullOrEmpty(message) ? IntPtr.Zero : Marshal.StringToHGlobalAnsi(message)); 248 | Win32FormatMessageFlags flags = Win32FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING; 249 | flags |= ((arguments.Length != 0) ? Win32FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY : Win32FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS); 250 | if (ignoreNewLine) 251 | { 252 | flags |= Win32FormatMessageFlags.FORMAT_MESSAGE_MAX_WIDTH_MASK; 253 | } 254 | int length = FormatMessage((int)flags, formatPtr, 0u, _lcid, buffer, 1024, arguments); 255 | message = buffer.ToString(0, length); 256 | return message; 257 | } 258 | 259 | public Win32Exception GetWin32Exception(uint msgCode, params string[] parameters) 260 | { 261 | string message = FormatMessage(msgCode, parameters); 262 | return new Win32Exception((int)msgCode, message); 263 | } 264 | 265 | public override string ToString() 266 | { 267 | string name = CultureInfo.GetCultureInfo(_lcid).DisplayName; 268 | if (!string.IsNullOrEmpty(name)) 269 | { 270 | return name; 271 | } 272 | return _lcid.ToString(); 273 | } 274 | 275 | public virtual void ReadSettings(Assembly assembly = null) 276 | { 277 | if (assembly == null) 278 | { 279 | assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly(); 280 | } 281 | Type[] types = assembly.GetTypes(); 282 | for (int i = 0; i < types.Length; i++) 283 | { 284 | PropertyInfo[] properties = types[i].GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); 285 | foreach (PropertyInfo property in properties) 286 | { 287 | Win32ErrorMessageAttribute win32Message; 288 | if (!property.CanWrite || (win32Message = property.GetCustomAttributes(typeof(Win32ErrorMessageAttribute), false).FirstOrDefault() as Win32ErrorMessageAttribute) == null) 289 | { 290 | continue; 291 | } 292 | uint msgId = win32Message.MessageId; 293 | string[] args = win32Message.Arguments; 294 | try 295 | { 296 | if (property.PropertyType == typeof(string)) 297 | { 298 | object newPropertyValue = FormatMessage(msgId, args); 299 | property.SetPropertyValue(newPropertyValue); 300 | } 301 | } 302 | catch (Exception) 303 | { 304 | } 305 | } 306 | } 307 | } 308 | 309 | [Obsolete] 310 | public virtual void WriteSettings(Assembly assembly = null) 311 | { 312 | try 313 | { 314 | throw new NotImplementedException(); 315 | } 316 | catch (Exception) 317 | { 318 | } 319 | } 320 | } 321 | } 322 | -------------------------------------------------------------------------------- /Source/Security/Activation/ActivationKeyBinaryParser.cs: -------------------------------------------------------------------------------- 1 | /*************************************************************** 2 | 3 | • File: ActivationKeyBinaryParser.cs 4 | 5 | • Description. 6 | 7 | ActivationKeyBinaryParser is a parser of binary data 8 | containing activation keys, which can be represented as a 9 | sequence of bytes with the required header. 10 | 11 | The class provides methods for parsing activation keys as 12 | well as for creating instances of the ActivationKey class, 13 | which is a data structure containing information about the 14 | activation key. 15 | 16 | ***************************************************************/ 17 | 18 | using System.IO; 19 | using static System.InternalTools; 20 | 21 | namespace System.Security.Activation 22 | { 23 | /// 24 | /// Represents a parser that provides tools for analyzing binary data with activation keys 25 | /// which can be represented as bytes sequence with required header. 26 | /// 27 | public class ActivationKeyBinaryParser : ICloneable 28 | { 29 | // A constant representing the default header "aK" of the activation key file. You can replace it with your own value. 30 | internal const ushort BinaryHeader = 0x4B61; 31 | 32 | internal static readonly ActivationKeyBinaryParser InternalParser = new ActivationKeyBinaryParser(); 33 | private ushort _header = BinaryHeader; 34 | 35 | /// 36 | /// The header of the activation key binary file, which is used to verify the file format. 37 | /// 38 | public ushort Header 39 | { 40 | get => _header; 41 | internal set => _header = value; 42 | } 43 | 44 | /// 45 | /// Returns the default instance of the . 46 | /// 47 | public static ActivationKeyBinaryParser DefaultParser => (ActivationKeyBinaryParser)InternalParser.Clone(); 48 | 49 | /// 50 | /// Initializes a new instance of using the default parameters. 51 | /// 52 | public ActivationKeyBinaryParser() 53 | { 54 | } 55 | 56 | /// 57 | /// Initializes a new instance of using the specified parameters. 58 | /// 59 | /// The header of the activation key file, which is used to verify the file format. 60 | /// 61 | /// 62 | public ActivationKeyBinaryParser(ushort header) 63 | { 64 | _header = header; 65 | } 66 | 67 | // Parses the stream and fill the activation key data. 68 | internal void InternalParse(ActivationKey activationKey, BinaryReader reader) 69 | { 70 | Stream stream = reader.BaseStream; 71 | try 72 | { 73 | ushort header = reader.ReadUInt16(); 74 | if (header != _header) 75 | throw new InvalidDataException(GetResourceString("Serialization_BinaryHeader", stream)); 76 | int dataLength = reader.ReadInt32(); 77 | int hashLength = reader.ReadInt32(); 78 | int tailLength = reader.ReadInt32(); 79 | activationKey.Data = reader.ReadBytes(dataLength); 80 | activationKey.Hash = reader.ReadBytes(hashLength); 81 | activationKey.Seed = reader.ReadBytes(tailLength); 82 | } 83 | catch (Exception e) 84 | { 85 | throw new InvalidDataException(GetResourceString("Serialization_InvalidFormat", stream.Position), e); 86 | } 87 | } 88 | 89 | // Parses the activation key binary file and populates the ActivationKey object with data from the file. 90 | internal void InternalParse(ActivationKey activationKey, byte[] bytes) 91 | { 92 | using (MemoryStream stream = new MemoryStream(bytes)) 93 | using (BinaryReader reader = new BinaryReader(stream)) 94 | { 95 | InternalParse(activationKey, reader); 96 | } 97 | } 98 | 99 | /// 100 | /// Parses key activation data from a reader. 101 | /// 102 | /// 103 | /// A reader from the stream containing key activation data. 104 | /// 105 | /// 106 | /// An instance of instance containing the parsed data. 107 | /// 108 | /// 109 | /// Thrown if is null. 110 | /// 111 | public ActivationKey Parse(BinaryReader reader) 112 | { 113 | if (reader == null) 114 | throw new ArgumentNullException(nameof(reader)); 115 | 116 | ActivationKey activationKey = new ActivationKey(); 117 | InternalParse(activationKey, reader); 118 | return activationKey; 119 | } 120 | 121 | /// 122 | /// Parses key activation data from a stream. 123 | /// 124 | /// 125 | /// A stream containing key activation data. 126 | /// 127 | /// 128 | /// An instance of instance containing the parsed data. 129 | /// 130 | /// 131 | /// Thrown if is null. 132 | /// 133 | /// 134 | /// Thrown when the stream is not readable or contains no data. 135 | /// 136 | public ActivationKey Parse(Stream stream) 137 | { 138 | if (stream == null) 139 | throw new ArgumentNullException(nameof(stream), GetResourceString("ArgumentNull_Stream")); 140 | if (!stream.CanRead) 141 | throw new ArgumentException(GetResourceString("Argument_StreamNotReadable")); 142 | if (stream.Length == 0) 143 | throw new ArgumentException(GetResourceString("Serialization_Stream")); 144 | 145 | 146 | using (BinaryReader reader = new BinaryReader(stream)) 147 | { 148 | ActivationKey activationKey = Parse(reader); 149 | return activationKey; 150 | } 151 | } 152 | 153 | /// 154 | /// Parses key activation data from a byte array. 155 | /// 156 | /// 157 | /// A byte array containing key activation data. 158 | /// 159 | /// 160 | /// An instance of instance containing the parsed data. 161 | /// 162 | /// 163 | /// Thrown if array is null or empty. 164 | /// 165 | public ActivationKey Parse(byte[] bytes) 166 | { 167 | if (bytes.IsNullOrEmpty()) 168 | throw new ArgumentException(GetResourceString("Arg_EmptyOrNullArray"), nameof(bytes)); 169 | 170 | ActivationKey activationKey = new ActivationKey(); 171 | InternalParse(activationKey, bytes); 172 | return activationKey; 173 | } 174 | 175 | // Returns the length of the data that will be written to the stream when the ActivationKey object is serialized. 176 | private int GetLength(ActivationKey activationKey) 177 | { 178 | return sizeof(ushort) 179 | + sizeof(int) * 3 180 | + activationKey.Data.Length 181 | + activationKey.Hash.Length 182 | + activationKey.Seed.Length; 183 | } 184 | 185 | /// 186 | /// Writes key activation data to the stream. 187 | /// 188 | /// 189 | /// An instance of to serialize. 190 | /// 191 | /// 192 | /// Serialization stream writer. 193 | /// 194 | /// 195 | /// Thrown if one of arguments is null. 196 | /// 197 | public void Write(ActivationKey activationKey, BinaryWriter writer) 198 | { 199 | if (activationKey == null) 200 | throw new ArgumentNullException(nameof(activationKey), 201 | GetResourceString("ArgumentNull_WithParamName", nameof(activationKey))); 202 | if (writer == null) 203 | throw new ArgumentNullException(nameof(writer), 204 | GetResourceString("ArgumentNull_WithParamName", nameof(writer))); 205 | 206 | writer.Write(BinaryHeader); 207 | writer.Write(activationKey.Data.Length); 208 | writer.Write(activationKey.Hash.Length); 209 | writer.Write(activationKey.Seed.Length); 210 | writer.Write(activationKey.Data); 211 | writer.Write(activationKey.Hash); 212 | writer.Write(activationKey.Seed); 213 | } 214 | 215 | /// 216 | /// Writes key activation data to the stream. 217 | /// 218 | /// 219 | /// An instance of to serialize. 220 | /// 221 | /// 222 | /// Serialization stream. 223 | /// 224 | /// 225 | /// Thrown if one of arguments is null. 226 | /// 227 | /// 228 | /// Thrown if output stream is not writable. 229 | /// 230 | public void Write(ActivationKey activationKey, Stream stream) 231 | { 232 | if (activationKey == null) 233 | throw new ArgumentNullException(nameof(activationKey), 234 | GetResourceString("ArgumentNull_WithParamName", nameof(activationKey))); 235 | if (stream == null) 236 | throw new ArgumentNullException(nameof(stream), GetResourceString("ArgumentNull_Stream")); 237 | if (!stream.CanWrite) 238 | throw new ArgumentException(GetResourceString("Argument_StreamNotWritable")); 239 | 240 | 241 | using (BinaryWriter writer = new BinaryWriter(stream)) 242 | { 243 | Write(activationKey, writer); 244 | } 245 | } 246 | 247 | /// 248 | /// Converts the object to a byte array. 249 | /// 250 | /// 251 | /// An instance of to convert. 252 | /// 253 | /// 254 | /// Byte array representing the object. 255 | /// 256 | /// 257 | /// Thrown if activation key is null. 258 | /// 259 | public byte[] GetBytes(ActivationKey activationKey) 260 | { 261 | if (activationKey == null) 262 | throw new ArgumentNullException(nameof(activationKey), 263 | GetResourceString("ArgumentNull_WithParamName", nameof(activationKey))); 264 | if (activationKey.InvalidState) 265 | throw new InvalidOperationException("Arg_InvalidOperationException"); 266 | 267 | using (MemoryStream stream = new MemoryStream(GetLength(activationKey))) 268 | { 269 | Write(activationKey, stream); 270 | byte[] bytes = stream.ToArray(); 271 | return bytes; 272 | } 273 | } 274 | 275 | /// 276 | public object Clone() 277 | { 278 | return new ActivationKeyBinaryParser(_header); 279 | } 280 | } 281 | } -------------------------------------------------------------------------------- /Demo/System.Resourses/ResourceFile.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.ComponentModel; 3 | using System.Globalization; 4 | using System.Ini; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Reflection; 8 | using System.Resources; 9 | 10 | namespace System.Resourses 11 | { 12 | public class ResourceFile : ResourceSet, IInitializer, IResourceReader, IEnumerable, IDisposable, IResourceWriter 13 | { 14 | private const ulong MagicBytes = 7498353358uL; 15 | 16 | [NonSerialized] 17 | protected IResourceWriter Writer; 18 | 19 | protected ResourceFile() 20 | { 21 | } 22 | 23 | private bool SafeGenerate(string fileName) 24 | { 25 | try 26 | { 27 | if (File.Exists(fileName)) 28 | { 29 | using (Stream stream = File.OpenRead(fileName)) 30 | { 31 | using (BinaryReader reader = new BinaryReader(stream)) 32 | { 33 | if (stream.Length > 8 && reader.ReadUInt64() == 7498353358L) 34 | { 35 | return true; 36 | } 37 | } 38 | } 39 | } 40 | File.Delete(fileName); 41 | using (ResourceWriter writer = new ResourceWriter(fileName)) 42 | { 43 | writer.Generate(); 44 | } 45 | } 46 | catch 47 | { 48 | return false; 49 | } 50 | return true; 51 | } 52 | 53 | private bool SafeGenerate(Stream stream) 54 | { 55 | try 56 | { 57 | using (BinaryReader reader = new BinaryReader(stream)) 58 | { 59 | if (stream.Length > 8 && reader.ReadUInt64() == 7498353358L) 60 | { 61 | return true; 62 | } 63 | } 64 | stream.Seek(0L, SeekOrigin.Begin); 65 | using (ResourceWriter writer = new ResourceWriter(stream)) 66 | { 67 | writer.Generate(); 68 | } 69 | } 70 | catch 71 | { 72 | return false; 73 | } 74 | return true; 75 | } 76 | 77 | public ResourceFile(string fileName, bool readOnly = false) 78 | { 79 | if (fileName == null) 80 | { 81 | throw new ArgumentNullException("fileName", AssemblyMessageFormatter.DefaultFormatter.GetMessage("ArgumentNull_FileName")); 82 | } 83 | if (fileName == string.Empty) 84 | { 85 | throw new ArgumentNullException("fileName", AssemblyMessageFormatter.DefaultFormatter.GetMessage("Argument_EmptyFileName")); 86 | } 87 | if (!SafeGenerate(fileName)) 88 | { 89 | throw new FileNotFoundException(AssemblyMessageFormatter.DefaultFormatter.FormatMessage("IO.FileNotFound_FileName", fileName), fileName); 90 | } 91 | Reader = new ResourceReader(fileName); 92 | ReadResources(); 93 | if (!readOnly) 94 | { 95 | Writer = new ResourceWriter(File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); 96 | } 97 | } 98 | 99 | public ResourceFile(Stream stream, bool readOnly = false) 100 | { 101 | if (stream == null) 102 | { 103 | throw new ArgumentNullException("stream"); 104 | } 105 | if (!stream.CanRead) 106 | { 107 | throw new InvalidOperationException(AssemblyMessageFormatter.DefaultFormatter.GetMessage("Argument_StreamNotReadable")); 108 | } 109 | if (!stream.CanWrite) 110 | { 111 | throw new InvalidOperationException(AssemblyMessageFormatter.DefaultFormatter.GetMessage("Argument_StreamNotWritable")); 112 | } 113 | if (!SafeGenerate(stream)) 114 | { 115 | throw new FileNotFoundException(AssemblyMessageFormatter.DefaultFormatter.GetMessage("BadImageFormat_ResourcesHeaderCorrupted")); 116 | } 117 | Reader = new ResourceReader(stream); 118 | ReadResources(); 119 | if (!readOnly) 120 | { 121 | Writer = new ResourceWriter(stream); 122 | } 123 | } 124 | 125 | public ResourceFile(ResourceReader reader, out Stream stream, bool readOnly = false) 126 | { 127 | stream = null; 128 | Reader = reader ?? throw new ArgumentNullException("reader"); 129 | ReadResources(); 130 | if (!readOnly) 131 | { 132 | stream = new MemoryStream(8096); 133 | Writer = new ResourceWriter(stream); 134 | } 135 | } 136 | 137 | private object InternalReadObject(Type type, string name, bool ignoreCase = false, object defaultValue = null, TypeConverter converter = null, CultureInfo culture = null) 138 | { 139 | if (type == null) 140 | { 141 | return null; 142 | } 143 | if (converter == null) 144 | { 145 | converter = TypeDescriptor.GetConverter(type); 146 | } 147 | if (culture == null) 148 | { 149 | culture = CultureInfo.InvariantCulture; 150 | } 151 | Type defaultValueType = defaultValue?.GetType(); 152 | IConvertible def; 153 | if ((def = defaultValue as IConvertible) != null) 154 | { 155 | if (type == typeof(string)) 156 | { 157 | defaultValue = def.ToString(culture); 158 | } 159 | else if (type == typeof(int)) 160 | { 161 | defaultValue = def.ToInt32(culture); 162 | } 163 | else if (type == typeof(double)) 164 | { 165 | defaultValue = def.ToDouble(culture); 166 | } 167 | else if (type == typeof(bool)) 168 | { 169 | defaultValue = def.ToBoolean(culture); 170 | } 171 | else if (type == typeof(byte)) 172 | { 173 | defaultValue = def.ToByte(culture); 174 | } 175 | else if (type == typeof(char)) 176 | { 177 | defaultValue = def.ToChar(culture); 178 | } 179 | else if (type == typeof(sbyte)) 180 | { 181 | defaultValue = def.ToSByte(culture); 182 | } 183 | else if (type == typeof(short)) 184 | { 185 | defaultValue = def.ToInt16(culture); 186 | } 187 | else if (type == typeof(ushort)) 188 | { 189 | defaultValue = def.ToUInt16(culture); 190 | } 191 | else if (type == typeof(uint)) 192 | { 193 | defaultValue = def.ToUInt32(culture); 194 | } 195 | else if (type == typeof(long)) 196 | { 197 | defaultValue = def.ToInt64(culture); 198 | } 199 | else if (type == typeof(ulong)) 200 | { 201 | defaultValue = def.ToUInt64(culture); 202 | } 203 | else if (type == typeof(float)) 204 | { 205 | defaultValue = def.ToSingle(culture); 206 | } 207 | else if (type == typeof(decimal)) 208 | { 209 | defaultValue = def.ToDecimal(culture); 210 | } 211 | } 212 | else if (defaultValueType == null) 213 | { 214 | defaultValue = (type.IsValueType ? Activator.CreateInstance(type) : null); 215 | } 216 | else if (!defaultValueType.IsAssignableFrom(type) && !defaultValueType.IsSubclassOf(type)) 217 | { 218 | defaultValue = ((!converter.CanConvertFrom(defaultValueType)) ? (type.IsValueType ? Activator.CreateInstance(type) : null) : converter.ConvertFrom(null, culture, defaultValue)); 219 | } 220 | object value; 221 | try 222 | { 223 | value = GetObject(name, ignoreCase); 224 | } 225 | catch (Exception) 226 | { 227 | return defaultValue; 228 | } 229 | if (value == null) 230 | { 231 | return defaultValue; 232 | } 233 | Type valueType = value.GetType(); 234 | if (valueType == type) 235 | { 236 | return value; 237 | } 238 | if (!converter.CanConvertFrom(valueType)) 239 | { 240 | return defaultValue; 241 | } 242 | return converter.ConvertFrom(null, culture, value); 243 | } 244 | 245 | private void InternalWriteObject(Type type, string name, object value = null, TypeConverter converter = null, CultureInfo culture = null) 246 | { 247 | if (name == null || value == null || type == null) 248 | { 249 | return; 250 | } 251 | Type type2 = value.GetType(); 252 | if (converter == null) 253 | { 254 | converter = TypeDescriptor.GetConverter(type); 255 | } 256 | if (culture == null) 257 | { 258 | culture = CultureInfo.InvariantCulture; 259 | } 260 | IConvertible conv; 261 | if (type2 == type) 262 | { 263 | AddResource(name, value); 264 | } 265 | else if ((conv = value as IConvertible) != null) 266 | { 267 | if (type == typeof(string)) 268 | { 269 | value = conv.ToString(culture); 270 | } 271 | else if (type == typeof(int)) 272 | { 273 | value = conv.ToInt32(culture); 274 | } 275 | else if (type == typeof(double)) 276 | { 277 | value = conv.ToDouble(culture); 278 | } 279 | else if (type == typeof(bool)) 280 | { 281 | value = conv.ToBoolean(culture); 282 | } 283 | else if (type == typeof(byte)) 284 | { 285 | value = conv.ToByte(culture); 286 | } 287 | else if (type == typeof(char)) 288 | { 289 | value = conv.ToChar(culture); 290 | } 291 | else if (type == typeof(sbyte)) 292 | { 293 | value = conv.ToSByte(culture); 294 | } 295 | else if (type == typeof(short)) 296 | { 297 | value = conv.ToInt16(culture); 298 | } 299 | else if (type == typeof(ushort)) 300 | { 301 | value = conv.ToUInt16(culture); 302 | } 303 | else if (type == typeof(uint)) 304 | { 305 | value = conv.ToUInt32(culture); 306 | } 307 | else if (type == typeof(long)) 308 | { 309 | value = conv.ToInt64(culture); 310 | } 311 | else if (type == typeof(ulong)) 312 | { 313 | value = conv.ToUInt64(culture); 314 | } 315 | else if (type == typeof(float)) 316 | { 317 | value = conv.ToSingle(culture); 318 | } 319 | else if (type == typeof(decimal)) 320 | { 321 | value = conv.ToDecimal(culture); 322 | } 323 | AddResource(name, value); 324 | } 325 | else if (converter.CanConvertTo(type)) 326 | { 327 | AddResource(name, converter.ConvertTo(null, culture, value, type)); 328 | } 329 | } 330 | 331 | protected override void Dispose(bool disposing) 332 | { 333 | if (disposing) 334 | { 335 | IResourceWriter writer = Writer; 336 | Writer = null; 337 | writer?.Close(); 338 | Table?.Clear(); 339 | } 340 | Writer = null; 341 | base.Dispose(disposing); 342 | } 343 | 344 | protected override void ReadResources() 345 | { 346 | base.ReadResources(); 347 | Reader?.Close(); 348 | } 349 | 350 | protected void UpdateTable(object name, object value) 351 | { 352 | if (Table.Contains(name)) 353 | { 354 | Table[name] = value; 355 | } 356 | else 357 | { 358 | Table.Add(name, value); 359 | } 360 | } 361 | 362 | public T GetValue(string name, T defaultValue = default(T), bool ignoreCase = false) 363 | { 364 | try 365 | { 366 | T obj; 367 | return ((obj = (T)GetObject(name, ignoreCase)) != null) ? obj : defaultValue; 368 | } 369 | catch 370 | { 371 | return defaultValue; 372 | } 373 | } 374 | 375 | public string GetString(string name, string defaultValue = null, bool ignoreCase = false) 376 | { 377 | try 378 | { 379 | return GetString(name, ignoreCase); 380 | } 381 | catch 382 | { 383 | return defaultValue; 384 | } 385 | } 386 | 387 | public void AddResource(string name, T value) 388 | { 389 | AddResource(name, value); 390 | } 391 | 392 | public virtual void AddResource(string name, string value) 393 | { 394 | UpdateTable(name, value); 395 | Writer.AddResource(name, value); 396 | } 397 | 398 | public virtual void AddResource(string name, object value) 399 | { 400 | UpdateTable(name, value); 401 | Writer.AddResource(name, value); 402 | } 403 | 404 | public virtual void AddResource(string name, byte[] value) 405 | { 406 | UpdateTable(name, value); 407 | Writer.AddResource(name, value); 408 | } 409 | 410 | public virtual void Generate() 411 | { 412 | Writer.Generate(); 413 | } 414 | 415 | public virtual void ReadSettings(Assembly assembly = null) 416 | { 417 | if (assembly == null) 418 | { 419 | assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly(); 420 | } 421 | Type[] types = assembly.GetTypes(); 422 | for (int i = 0; i < types.Length; i++) 423 | { 424 | PropertyInfo[] properties = types[i].GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); 425 | foreach (PropertyInfo property in properties) 426 | { 427 | ResourceAttribute assemblyMessage; 428 | if (property.CanWrite && (assemblyMessage = property.GetCustomAttributes(typeof(ResourceAttribute), false).FirstOrDefault() as ResourceAttribute) != null) 429 | { 430 | string name = assemblyMessage.Name ?? property.Name; 431 | object defaultValue = assemblyMessage.DefaultValue; 432 | try 433 | { 434 | Type propertyType = property.PropertyType; 435 | TypeConverter converter = property.GetPropertyConverter(); 436 | object newPropertyValue = InternalReadObject(propertyType, name, true, defaultValue, converter); 437 | property.SetPropertyValue(newPropertyValue); 438 | } 439 | catch (Exception) 440 | { 441 | } 442 | } 443 | } 444 | } 445 | } 446 | 447 | public virtual void WriteSettings(Assembly assembly = null) 448 | { 449 | if (Writer == null) 450 | { 451 | return; 452 | } 453 | if (assembly == null) 454 | { 455 | assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly(); 456 | } 457 | Type[] types = assembly.GetTypes(); 458 | for (int i = 0; i < types.Length; i++) 459 | { 460 | PropertyInfo[] properties = types[i].GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); 461 | foreach (PropertyInfo property in properties) 462 | { 463 | ResourceAttribute assemblyMessage; 464 | if (!property.CanWrite || (assemblyMessage = property.GetCustomAttributes(typeof(ResourceAttribute), false).FirstOrDefault() as ResourceAttribute) == null) 465 | { 466 | continue; 467 | } 468 | string name = assemblyMessage.Name ?? property.Name; 469 | try 470 | { 471 | Type propertyType = property.PropertyType; 472 | TypeConverter converter = property.GetPropertyConverter(); 473 | object value = property.GetPropertyValue(); 474 | string str; 475 | if ((str = value as string) != null) 476 | { 477 | Writer.AddResource(name, str); 478 | } 479 | else 480 | { 481 | InternalWriteObject(propertyType, name, value, converter); 482 | } 483 | } 484 | catch (Exception) 485 | { 486 | } 487 | } 488 | } 489 | Writer.Generate(); 490 | } 491 | } 492 | } 493 | --------------------------------------------------------------------------------