Add Original SDK

This commit is contained in:
2026-05-06 07:47:36 +02:00
parent 2915e04380
commit 0ed627517a
674 changed files with 89334 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,58 @@
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]

View File

@@ -0,0 +1,548 @@
// !! We strongly recommend that you read the "readme.txt" file in the sample code folder.
// !! It contains important instructions on how to use the sample code
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices; // so we can marshal our structures in dapf.cs
namespace dapfTest
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox machineIDText;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox expdayText;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox expmonthText;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox expyearText;
private GroupBox groupBox2;
private Label label9;
private TextBox maxDaysText;
private Button demoSoftwareKey;
public string AppName = "dapfTest";
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.dapfFile = new System.Windows.Forms.TextBox();
this.programDongle = new System.Windows.Forms.Button();
this.programDongleMod = new System.Windows.Forms.Button();
this.lockSoftware = new System.Windows.Forms.Button();
this.tempSoftwareKey = new System.Windows.Forms.Button();
this.encryptShellData = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.expyearText = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.expmonthText = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.expdayText = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.machineIDText = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label9 = new System.Windows.Forms.Label();
this.maxDaysText = new System.Windows.Forms.TextBox();
this.demoSoftwareKey = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(416, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Full path of dapf file:";
//
// dapfFile
//
this.dapfFile.Location = new System.Drawing.Point(16, 40);
this.dapfFile.Name = "dapfFile";
this.dapfFile.Size = new System.Drawing.Size(344, 20);
this.dapfFile.TabIndex = 1;
//
// programDongle
//
this.programDongle.Location = new System.Drawing.Point(84, 88);
this.programDongle.Name = "programDongle";
this.programDongle.Size = new System.Drawing.Size(208, 23);
this.programDongle.TabIndex = 2;
this.programDongle.Text = "Program Dongle";
this.programDongle.Click += new System.EventHandler(this.programDongle_Click);
//
// programDongleMod
//
this.programDongleMod.Location = new System.Drawing.Point(84, 128);
this.programDongleMod.Name = "programDongleMod";
this.programDongleMod.Size = new System.Drawing.Size(208, 23);
this.programDongleMod.TabIndex = 3;
this.programDongleMod.Text = "Program Dongle with modification";
this.programDongleMod.Click += new System.EventHandler(this.programDongleMod_Click);
//
// lockSoftware
//
this.lockSoftware.Location = new System.Drawing.Point(84, 168);
this.lockSoftware.Name = "lockSoftware";
this.lockSoftware.Size = new System.Drawing.Size(208, 23);
this.lockSoftware.TabIndex = 4;
this.lockSoftware.Text = "Lock Software";
this.lockSoftware.Click += new System.EventHandler(this.lockSoftware_Click);
//
// tempSoftwareKey
//
this.tempSoftwareKey.Location = new System.Drawing.Point(64, 88);
this.tempSoftwareKey.Name = "tempSoftwareKey";
this.tempSoftwareKey.Size = new System.Drawing.Size(208, 23);
this.tempSoftwareKey.TabIndex = 5;
this.tempSoftwareKey.Text = "Create Software Key";
//
// encryptShellData
//
this.encryptShellData.Location = new System.Drawing.Point(84, 208);
this.encryptShellData.Name = "encryptShellData";
this.encryptShellData.Size = new System.Drawing.Size(208, 23);
this.encryptShellData.TabIndex = 6;
this.encryptShellData.Text = "Encrypt Shell Data Files";
this.encryptShellData.Click += new System.EventHandler(this.encryptShellData_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.expyearText);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.expmonthText);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.expdayText);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.machineIDText);
this.groupBox1.Controls.Add(this.tempSoftwareKey);
this.groupBox1.Location = new System.Drawing.Point(16, 256);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(336, 128);
this.groupBox1.TabIndex = 7;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Temporary Software Key";
//
// expyearText
//
this.expyearText.Location = new System.Drawing.Point(240, 56);
this.expyearText.Name = "expyearText";
this.expyearText.Size = new System.Drawing.Size(32, 20);
this.expyearText.TabIndex = 13;
this.expyearText.Text = "yyyy";
//
// label5
//
this.label5.Location = new System.Drawing.Point(224, 56);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(8, 20);
this.label5.TabIndex = 12;
this.label5.Text = "/";
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// expmonthText
//
this.expmonthText.Location = new System.Drawing.Point(184, 56);
this.expmonthText.Name = "expmonthText";
this.expmonthText.Size = new System.Drawing.Size(32, 20);
this.expmonthText.TabIndex = 11;
this.expmonthText.Text = "mm";
//
// label4
//
this.label4.Location = new System.Drawing.Point(168, 56);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(8, 20);
this.label4.TabIndex = 10;
this.label4.Text = "/";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// expdayText
//
this.expdayText.Location = new System.Drawing.Point(128, 56);
this.expdayText.Name = "expdayText";
this.expdayText.Size = new System.Drawing.Size(32, 20);
this.expdayText.TabIndex = 9;
this.expdayText.Text = "dd";
//
// label3
//
this.label3.Location = new System.Drawing.Point(24, 56);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(100, 20);
this.label3.TabIndex = 8;
this.label3.Text = "Expiry Date:";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label2
//
this.label2.Location = new System.Drawing.Point(24, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(100, 20);
this.label2.TabIndex = 7;
this.label2.Text = "Machine ID:";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// machineIDText
//
this.machineIDText.Location = new System.Drawing.Point(128, 24);
this.machineIDText.Name = "machineIDText";
this.machineIDText.Size = new System.Drawing.Size(184, 20);
this.machineIDText.TabIndex = 6;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.label9);
this.groupBox2.Controls.Add(this.maxDaysText);
this.groupBox2.Controls.Add(this.demoSoftwareKey);
this.groupBox2.Location = new System.Drawing.Point(19, 400);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(336, 99);
this.groupBox2.TabIndex = 14;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Demo Software Key";
//
// label9
//
this.label9.Location = new System.Drawing.Point(24, 24);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(100, 20);
this.label9.TabIndex = 7;
this.label9.Text = "Max Days:";
this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// maxDaysText
//
this.maxDaysText.Location = new System.Drawing.Point(128, 24);
this.maxDaysText.Name = "maxDaysText";
this.maxDaysText.Size = new System.Drawing.Size(184, 20);
this.maxDaysText.TabIndex = 6;
//
// demoSoftwareKey
//
this.demoSoftwareKey.Location = new System.Drawing.Point(61, 59);
this.demoSoftwareKey.Name = "demoSoftwareKey";
this.demoSoftwareKey.Size = new System.Drawing.Size(208, 23);
this.demoSoftwareKey.TabIndex = 5;
this.demoSoftwareKey.Text = "Create Demo Template";
this.demoSoftwareKey.Click += new System.EventHandler(this.demoSoftwareKey_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(376, 523);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.encryptShellData);
this.Controls.Add(this.lockSoftware);
this.Controls.Add(this.programDongleMod);
this.Controls.Add(this.programDongle);
this.Controls.Add(this.dapfFile);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox dapfFile;
private System.Windows.Forms.Button programDongle;
private System.Windows.Forms.Button programDongleMod;
private System.Windows.Forms.Button lockSoftware;
private System.Windows.Forms.Button tempSoftwareKey;
private System.Windows.Forms.Button encryptShellData;
/* The sample code contains 5 functions. You will not need to use all these functions in your code.
Just use which ever functions are most appropriate and customise in your own way. The sample code
is just a guide.
There are two methods to loading a DAPF file. These are shown in the first two functions
programDongle_Click and programDongleMod_Click:
programDongle_Click: we load the DAPF file from disk and get a handle and use it "as is" using the API
call LoadDAPFFromFile. You can make some limited changes to overwrite the default
behaviour by using API flags.
programDongleMod_Click: we load the DAPF file from disk and load into structures. We can then modify the
DAPF settings by modifying this structure. This method uses the API calls
ReadDAPFEx and LoadDAPF.
The other functions use the first method (as it is simpler) but you can use the second method instead if
you prefer.
Note - an alternative to using the programDongleMod_Click technique is to modify the DAPF file on disk
and then use the programDongle_Click technique. To modify a binary DAPF you would use the binary structures
that are defined in dapf.h. To modify JSON DAPF you would need to use a JSON parser.
lockSoftware_Click : locks software (protect it) to a dongle as specified by the DAPF file.
encryptShellData_Click: encrypts the shell data files specified in the DAPF file (this is used with encrypting
data file if you use the Shell Method with "Data File Encryption" enabled).
tempSoftwareKey_Click: creates a Temporary Software Key based on the DAPF file and settings the user has entered.
demoSoftwareKey_Click: creates a Demo Software Key Template based on the DAPF file and settings the user has entered.
*/
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
// load a DAPF file from disk and program the dongle as specified by the DAPF file
private void programDongle_Click(object sender, System.EventArgs e)
{
IntPtr dapfHandle;
int err_code;
uint dongle_number;
// load DAPF from File into memory
dapfHandle = DinkeyAdd.LoadDAPFFromFile(dapfFile.Text, out err_code);
if (dapfHandle == IntPtr.Zero)
{
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// program dongle as specified by the DAPF file
err_code = DinkeyAdd.AddProtection(dapfHandle, DinkeyAdd.ACTION_PROGRAM_DONGLE, 0, 0, out dongle_number);
// Unload DAPF from memory
DinkeyAdd.UnloadDAPF(ref dapfHandle);
// display message (error or success)
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// load a DAPF file from disk, modify it in memory and then program the dongle
private void programDongleMod_Click(object sender, System.EventArgs e)
{
IntPtr dapfHandle;
int dummy1, dummy2, err_code;
uint dongle_number;
DINKEYINFO DinkeyInfo;
LICENCEINFO[] LicenceInfo;
FILEINFO[] FileInfo;
ALGORITHM[] Algorithms;
DATAFILEENC[] DataFileEnc;
// in this case we need to read the DAPF into our structures, so that the DAPF values can be modified
err_code = DinkeyAdd.ReadDAPFEx(dapfFile.Text, out DinkeyInfo, out LicenceInfo, out FileInfo, out Algorithms, out DataFileEnc, out dummy1, out dummy2);
if (err_code != 0)
{
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// patch new values
LicenceInfo[0].Features = 12345;
LicenceInfo[0].Execs = 100;
LicenceInfo[0].LicenceName = "fred";
// get DAPF handle
dapfHandle = DinkeyAdd.LoadDAPF(DinkeyInfo, LicenceInfo, FileInfo, Algorithms, DataFileEnc, out err_code);
if (dapfHandle == IntPtr.Zero)
{
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// program dongle
err_code = DinkeyAdd.AddProtection(dapfHandle, DinkeyAdd.ACTION_PROGRAM_DONGLE, 0, 0, out dongle_number);
// Unload DAPF from memory
DinkeyAdd.UnloadDAPF(ref dapfHandle);
// display message (error or success)
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// load a DAPF file from disk and protect the files specified
// (in practice it is better to protect the files one at a time and output messages as you go along, similar to DinkeyAdd.exe)
// In this example we specify the flag to overwrite any existing output file that might exist.
private void lockSoftware_Click(object sender, System.EventArgs e)
{
IntPtr dapfHandle;
int err_code;
uint dummy;
// load DAPF from File into memory
dapfHandle = DinkeyAdd.LoadDAPFFromFile(dapfFile.Text, out err_code);
if (dapfHandle == IntPtr.Zero)
{
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// protect all the files listed in the DAPF file
err_code = DinkeyAdd.AddProtection(dapfHandle, DinkeyAdd.ACTION_PROTECT_SOFTWARE, -1, DinkeyAdd.FLAGS_OVERWRITE_OUTPUT, out dummy);
// Unload DAPF from memory
DinkeyAdd.UnloadDAPF(ref dapfHandle);
// display message (error or success)
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// load a DAPF file from disk and encrypt the shell data files specified
// (in practice it is better to encrypt the files one at a time and output messages as you go along, similar to DinkeyAdd.exe)
// In this example we specify the flag to overwrite any existing output file that might exist.
private void encryptShellData_Click(object sender, System.EventArgs e)
{
IntPtr dapfHandle;
int err_code;
// load DAPF from File into memory
dapfHandle = DinkeyAdd.LoadDAPFFromFile(dapfFile.Text, out err_code);
if (dapfHandle == IntPtr.Zero)
{
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// encrypt all the shell data files listed in the DAPF file
err_code = DinkeyAdd.EncryptShellDataFiles(dapfHandle, -1, DinkeyAdd.FLAGS_OVERWRITE_OUTPUT);
// Unload DAPF from memory
DinkeyAdd.UnloadDAPF(ref dapfHandle);
// display message (error or success)
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// load a DAPF file from disk and create a Temporary Software Key using the info that the user entered
private void tempSoftwareKey_Click(object sender, System.EventArgs e)
{
IntPtr dapfHandle;
int err_code;
TEMP_SWKEY_INFO swkey_info = new TEMP_SWKEY_INFO();
// load DAPF from File into memory
dapfHandle = DinkeyAdd.LoadDAPFFromFile(dapfFile.Text, out err_code);
if (dapfHandle == IntPtr.Zero)
{
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// fill out the SWKEY structure from the values the user entered
swkey_info.size = Marshal.SizeOf(typeof(TEMP_SWKEY_INFO));
swkey_info.machineID = Convert.ToUInt32(machineIDText.Text, 16);
swkey_info.expiry_day = Convert.ToInt32(expdayText.Text, 10);
swkey_info.expiry_month = Convert.ToInt32(expmonthText.Text, 10);
swkey_info.expiry_year = Convert.ToInt32(expyearText.Text, 10);
// !!!! in this case we just choose Pro Plus. You could load the DAPF file into structures and see which model is selected.
// If there is more than one model selected you can ask the customer to choose which model they want.
swkey_info.dongle_model = DinkeyAdd.SWKEY_MODEL_PRO_PLUS;
swkey_info.dongle_number = 0;
// attempt to create the Temporary Software Key
err_code = DinkeyAdd.CreateTempSoftwareKey(dapfHandle, swkey_info, 0);
// Unload DAPF from memory
DinkeyAdd.UnloadDAPF(ref dapfHandle);
// display message (error or success)
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
private void demoSoftwareKey_Click(object sender, EventArgs e)
{
IntPtr dapfHandle;
int err_code;
DEMO_SWKEY_INFO swkey_info = new DEMO_SWKEY_INFO();
// load DAPF from File into memory
dapfHandle = DinkeyAdd.LoadDAPFFromFile(dapfFile.Text, out err_code);
if (dapfHandle == IntPtr.Zero)
{
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// fill out the SWKEY structure from the values the user entered
swkey_info.size = Marshal.SizeOf(typeof(DEMO_SWKEY_INFO));
swkey_info.max_days = Convert.ToInt32(maxDaysText.Text, 10);
// !!!! in this case we just choose the default model (assuming you only selected one in the DAPF file).
// If you want to specify more than one model then OR the flags together. e.g. DinkeyAdd.SWKEY_BITMAP_PRO_LITE | DinkeyAdd.SWKEY_BITMAP_PRO_PLUS
swkey_info.models = DinkeyAdd.SWKEY_BITMAP_DEFAULT;
// attempt to create the Temporary Software Key
err_code = DinkeyAdd.CreateDemoSoftwareKeyTemplate(dapfHandle, swkey_info, 0);
// Unload DAPF from memory
DinkeyAdd.UnloadDAPF(ref dapfHandle);
// display message (error or success)
MessageBox.Show(DinkeyAdd.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,50 @@
dapfTest - sample code to call DinkeyAdd Module in C#
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is written in Visual Studio 2002 but will work in more recent
versions of Visual Studio (they will upgrade the Project to the latest version.
If prompted you should also upgrade the .NET framework the project requires).
For users of Visual Studio 2005 or higher, the default setting to projects is to
compile for the Target Platform "Any". This means that on 32-bit Windows, your
code will run as 32-bit code (and needs to call DinkeyAdd32.dll) and under 64-bit
Windows your code will run as 64-bit code (and needs to call DinkeyAdd64.dll).
The sample code works this out automatically. If you select the target platform as "x86"
then it will always be 32-bit and so you only need to use DinkeyAdd32.dll. If you
select "x64" then your code will be 64-bit and you only need to use DinkeyAdd64.dll.
The main source files in the project are:
dapf.cs - the source file contains declarations of our API. We automatically
work out whether your code is running in 32-bit or 64-bit and load
the appropriate DinkeyAdd module.
Form1.cs - this is the sample code giving an example on how you can call our API.
It contains 5 functions. Just use which ever functions are most appropriate
and customise in your own way.
The best approach is to compile the sample code and see how it works and then to take
the appropriate code and apply it to your own project. You should include the dapf.cs
file in your project and use/modify which ever functions from Form1.cs you feel are
appropriate. The dapf.cs file should not be modified.
The sample code is just a guide. As none of the parameters are security sensitive then
there is no need to implement strong security in calling DinkeyAdd.
Make sure you remember to do the following when creating your own project:
1) Insert the following namespaces in your code file:
using System.Runtime.InteropServices;
2) Insert the dapf.cs file in your project.
3) You need to put DinkeyAdd32.dll and/or DinkeyAdd64.dll into the folder that
contains dapfTest. Otherwise the System.DllNotFoundException error will appear
when you run dapfTest.
Notes on Debugging 64-bit Code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you use the 64-bit module (DinkeyAdd64.dll) the anti-debug code is so strong
that if you are debugging your code, after calling our API then it will crash with
an SEH exception. There are no debug modules for DinkeyAdd so you will have to find
other ways of debugging your code (for example taking out the call altogether).

View File

@@ -0,0 +1,552 @@
// !! this file should not be modified
// DAPF file is in the following format:
// DINKEYINFO
// LICENCEINFO (however many are needed)
// FILEINFO (however many are needed)
// ALGORITHM (however many are needed)
// DATAFILEENC (however many are needed)
using System;
using System.Runtime.InteropServices; // so we can marshal the structures as a block of memory
using System.Text; // for StringBuilder class for GetLastMessage API
// *********** define structures that make up the DAPF file *******************
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct DINKEYINFO
{
public byte Header1; // should be set to "DAPF"
public byte Header2;
public byte Header3;
public byte Header4;
public int Version; // version of this structure. Currently 9.
public int SelectedModels; // BIT0 = Dinkey Pro Lite, BIT1 = Dinkey Pro Plus, BIT2 = Dinkey Pro Net etc...
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=12)]
public string ProdCode;
public int PerLicence; // 1 = per licence, 0 = per product (default)
public int MaxNetUsers; // product net users, unlimited = -1, no entry = -2
public int RangeSettings; // 0 = any number, 1 = dongle in computer, 2 = range
public uint RangeMin;
public uint RangeMax;
public int NumLicences; // number of LICENCEINFO structures in this DAPF file
public int NumProgs; // number of FILEINFO structures in this DAPF file
public int NumAlgs;
public int DataSizeType; // 1 = set the zero data size, 0 = use file to initialise data area
public int ZeroDataSize; // size of the data area area in bytes
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string DataFile; // path to data file (0 = no data file)
public int DataAreaSize; // file size in bytes, -1 = file not found
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ShellSuccessMsg; // Shell Method messages...
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ShellNoDongleMsg;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ShellExpiryDateMsg;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ShellExpiryExecsMsg;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ShellWarnDateMsg;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ShellWarnExecsMsg;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ShellNetUserLimitMsg;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ShellOtherErrorMsg;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ShellBackgroundMsg;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string NetNoServerMsg;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=12)]
public byte[] rwalg; // coded form of rw algorithm (0 = no algorithm)
public int SecOptions; // BIT0: DRIS encryption, BIT1: Data encryption, BIT2: Data enc with alg, BIT3: only secure update codes
public byte SecDRISEncKey1; // DRIS encryption parameters
public byte SecDRISEncKey2;
public byte SecDRISEncKey3;
public byte Ignored1; // this byte is ignored
public byte SecDataEncKey1; // API Data encryption parameters
public byte SecDataEncKey2;
public byte SecDataEncKey3;
public byte Ignored2; // this byte is ignored
public int ProtectionType; // 0 = software + dongle, 1 = dongle only, 2 = program only
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=12)]
public string DataEncKeyProdCode; // Alternative Product Code used to generate internal encryption keys. Normally set to 0.
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string Notes; // user-defined notes
public int LockDongle; // 0 = don't lock (default), 1 = lock dongle to user's computer
public int Reserved1; // must be 0
public int Reserved2; // must be 0
public int AdvancedOptions; // BIT0 = do not allow usb-over-network for non-Net dongles, BIT1 = do not check for Software Key at Runtime.
public int NumDataFileEnc; // Number of data files in our encryption list
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct LICENCEINFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string LicenceName;
public int MaxDays; // -1 = no limit
public int ExpiryDay; // -1 = no limit, 0 = no change
public int ExpiryMonth;
public int ExpiryYear;
public int Execs; // -1 = no limit
public int ExecsWarn; // 0 = no warning (just for Shell method)
public int DaysWarn; // 0 = no warning (just for Shell method)
public uint Features;
public int LicenceNetUsers; // unlimited = -1 (-2 = not needed (this is for display only))
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct FILEINFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string InputName; // input file (full path)
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string OutputName; // output file/folder
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string CallingProg; // calling program name
public int LicenceIndex; // index (of licence) in the LicenceInfo structure (1-based index. 0 = no selection)
public int Method; // 0-api, 1-shell, 2-shell & api
public int ShellFlags; // same bit flag values as in dris. i.e. 1 = DEC_ONE_EXEC, 4 = START_NET_USER
public int BackGround; // 0=no background, 1=1min, 2=5min, 3=10min, 4=30min, 5=60min
public int OtherShellOptions; // BIT0 = Shell Data Encryption is enabled, BIT1: Extra Anti-Debug is disabled, BIT2: Extra Anti-Piracy is disabled
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string EncFileList; // files (or file types) that the Shell-protected program will treat as encrypted (separated by ':')
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string ExceptList; // files (or file types) that are exceptions to the above list (separated by ':')
public int ExtraAntiPiracy; // 0 = off, 1=min, 10=max
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct ALGORITHM
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=12)]
public byte[] alg;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct DATAFILEENC
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string InputName; // file name, wild cards are allowed
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string OutputName; // file name (or folder name if input is a wildcard)
}
// this structure is used for creating temporary software keys
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct TEMP_SWKEY_INFO
{
public int size; // size of this structure (must be initialised)
public uint machineID; // machine ID in (hex) integer form
public int expiry_day; // expiry date of the Software Key
public int expiry_month;
public int expiry_year;
public int dongle_model; // model of the Software Key. See constant values below
public uint dongle_number; // dongle number of the Software Key. 0 = default (random)
}
// this structure is used for creating demo software key templates
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct DEMO_SWKEY_INFO
{
public int size; // size of this structure (must be initialised)
public int max_days; // max days demo swkey installation is valid (0-60)
public int models; // bitmap of valid dongle models. See constant values below. 0 = default (only use if only one model is selected in DINKEYINFO)
}
// ********************** API functions ************************
// we declare classes for all the API functions for each bitness
// Loads DAPF from disk and returns handle
class LoadDAPFFromFile32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr LoadDAPFFromFile(string dapf_file, out int err_code);
}
class LoadDAPFFromFile64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr LoadDAPFFromFile(string dapf_file, out int err_code);
}
// Loads DAPF from disk into structures supplied (so we can modify DAPF in memory)
class ReadDAPFEx32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern int ReadDAPFEx(string dapf_file, out DINKEYINFO DinkeyInfo, byte[] licence_bytes, byte[] fileinfo_bytes, byte[] alg_bytes, byte[] datafile_bytes, out int dapf_version, out int dapf_format);
}
class ReadDAPFEx64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern int ReadDAPFEx(string dapf_file, out DINKEYINFO DinkeyInfo, byte[] licence_bytes, byte[] fileinfo_bytes, byte[] alg_bytes, byte[] datafile_bytes, out int dapf_version, out int dapf_format);
}
// Loads DAPF from structures and returns a handle
class LoadDAPF32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr LoadDAPF(ref DINKEYINFO DinkeyInfo, byte[] licence_bytes, byte[] fileinfo_bytes, byte[] alg_bytes, byte[] datafile_bytes, out int ret_code);
}
class LoadDAPF64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr LoadDAPF(ref DINKEYINFO DinkeyInfo, byte[] licence_bytes, byte[] fileinfo_bytes, byte[] alg_bytes, byte[] datafile_bytes, out int ret_code);
}
// saves the DAPF file to disk
class WriteDAPFEx32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern int WriteDAPFEx(IntPtr dapf_handle, string dapf_file, int dapf_format, int dapf_version, int flags);
}
class WriteDAPFEx64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern int WriteDAPFEx(IntPtr dapf_handle, string dapf_file, int dapf_format, int dapf_version, int flags);
}
// unloads the DAPF file
class UnloadDAPF32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern void UnloadDAPF(ref IntPtr dapf_handle);
}
class UnloadDAPF64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern void UnloadDAPF(ref IntPtr dapf_handle);
}
class AddProtection32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern int AddProtection(IntPtr dapf_handle, int action, int file_num, int flags, out uint dongle_number);
}
class AddProtection64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern int AddProtection(IntPtr dapf_handle, int action, int file_num, int flags, out uint dongle_number);
}
class CreateTempSoftwareKey32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern int CreateTempSoftwareKey(IntPtr dapf_handle, ref TEMP_SWKEY_INFO swkey_info, int flags);
}
class CreateTempSoftwareKey64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern int CreateTempSoftwareKey(IntPtr dapf_handle, ref TEMP_SWKEY_INFO swkey_info, int flags);
}
class CreateDemoSoftwareKeyTemplate32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern int CreateDemoSoftwareKeyTemplate(IntPtr dapf_handle, ref DEMO_SWKEY_INFO swkey_info, int flags);
}
class CreateDemoSoftwareKeyTemplate64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern int CreateDemoSoftwareKeyTemplate(IntPtr dapf_handle, ref DEMO_SWKEY_INFO swkey_info, int flags);
}
class EncryptShellDataFiles32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern int EncryptShellDataFiles(IntPtr dapf_handle, int file_num, int flags);
}
class EncryptShellDataFiles64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern int EncryptShellDataFiles(IntPtr dapf_handle, int file_num, int flags);
}
class GetLastMessage32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern void GetLastMessage(StringBuilder message, int buffer_size, out int message_length);
}
class GetLastMessage64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern void GetLastMessage(StringBuilder message, int buffer_size, out int message_length);
}
class GetLastExtendedError32
{
[DllImport("DinkeyAdd32.dll", CharSet = CharSet.Ansi)]
public static extern int GetLastExtendedError();
}
class GetLastExtendedError64
{
[DllImport("DinkeyAdd64.dll", CharSet = CharSet.Ansi)]
public static extern int GetLastExtendedError();
}
// ********************* DinkeyAdd class **********************
class DinkeyAdd
{
// constants
public const int DAPF_VERSION = 9; // current DAPF version
// WriteDAPFEx API flags
public const int FLAGS_LOSE_FEATURES = 1; // means that you can save the DAPF file to an earlier version even if it means losing some new features that have been currently set
// AddProtection API action values
public const int ACTION_USE_DAPF_SETTINGS = 0; // means you just ignore the action value and use the default dapf settings
public const int ACTION_PROGRAM_DONGLE = 1; // program the dongle only
public const int ACTION_PROTECT_SOFTWARE = 2; // protect a software file (index indicated by separate parameter)
public const int ACTION_PROGRAM_AND_PROTECT = 3; // program the dongle and protect software
// AddProtection API flags values
public const int FLAGS_OVERWRITE_OUTPUT = 1; // overwrite the output file if it already exists (default is to give an error)
// SoftwareKey API flags
public const int FLAGS_OVERWRITE_SWKEY = 1; // overwrite an existing swkey with the new one
public const int FLAGS_EXPIRY_DONTCARE = 2; // create the Software Key even though the expiry date (or max days) is less than the expiry date of the key itself.
// constants for dapf_format in ReadDAPFEx and WriteDAPFEx functions
public const int DAPF_FORMAT_BINARY = 1;
public const int DAPF_FORMAT_JSON = 2;
public const int DAPF_FORMAT_JSON_MIN = 3; // this value is only used with WriteDAPEx. ReadDAPFEx cannot return this value.
// constants for values for model in the TEMP_SWKEY_INFO structure
public const int SWKEY_MODEL_PRO_LITE = 0;
public const int SWKEY_MODEL_PRO_PLUS = 1;
public const int SWKEY_MODEL_PRO_NET = 2;
public const int SWKEY_MODEL_FD_LITE = 3;
public const int SWKEY_MODEL_FD_PLUS = 4;
public const int SWKEY_MODEL_FD_NET = 5;
// constants for models bitmap in the DEMO_SWKEY_INFO structure
public const int SWKEY_BITMAP_DEFAULT = 0; // use default value set in DINKEYINFO.SelectedModels
public const int SWKEY_BITMAP_PRO_LITE = 1; // BIT0
public const int SWKEY_BITMAP_PRO_PLUS = 2; // BIT1
public const int SWKEY_BITMAP_PRO_NET = 4; // BIT2
public const int SWKEY_BITMAP_FD_LITE = 8; // BIT3
public const int SWKEY_BITMAP_FD_PLUS = 16; // BIT4
public const int SWKEY_BITMAP_FD_NET = 32; // BIT5
// private constants
private const int MAX_LICENCES = 255; // max number of licences in a DAPF file
private const int MAX_FILE_INFO = 1000; // theoretically unlimited but in practice it is easier if we limit it
private const int MAX_USER_ALGS = 20; // max number of user algs in DAPF file
private const int MAX_DATA_ENCS = 255; // max number of Shell data encryption files in DAPF file
// **** main API
// We only want to load the correct DLL for the bit-ness of the computer. The other DLL may not exist.
// if the appropriate DLL does not exist in the same directory as this test program you will receive a DllNotFoundException
public static IntPtr LoadDAPFFromFile(string dapf_file, out int err_code)
{
if (IntPtr.Size == 4)
return LoadDAPFFromFile32.LoadDAPFFromFile(dapf_file, out err_code);
return LoadDAPFFromFile64.LoadDAPFFromFile(dapf_file, out err_code);
}
// we have to do some marshalling of arrays of bytes into arrays of structures
public static int ReadDAPFEx(string dapf_file, out DINKEYINFO DinkeyInfo, out LICENCEINFO[] LicenceInfo, out FILEINFO[] FileInfo, out ALGORITHM[] Algorithms, out DATAFILEENC[] DataFileEnc, out int dapf_version, out int dapf_format)
{
int ret_code, i;
byte[] licence_bytes = new byte[MAX_LICENCES * Marshal.SizeOf(typeof(LICENCEINFO))];
byte[] licence_bytes_one_struct = new byte[Marshal.SizeOf(typeof(LICENCEINFO))];
byte[] fileinfo_bytes = new byte[MAX_FILE_INFO * Marshal.SizeOf(typeof(FILEINFO))];
byte[] fileinfo_bytes_one_struct = new byte[Marshal.SizeOf(typeof(FILEINFO))];
byte[] alg_bytes = new byte[MAX_USER_ALGS * Marshal.SizeOf(typeof(ALGORITHM))];
byte[] alg_bytes_one_struct = new byte[Marshal.SizeOf(typeof(ALGORITHM))];
byte[] datafile_bytes = new byte[MAX_DATA_ENCS * Marshal.SizeOf(typeof(DATAFILEENC))];
byte[] datafile_bytes_one_struct = new byte[Marshal.SizeOf(typeof(DATAFILEENC))];
GCHandle MyGC;
DinkeyInfo = new DINKEYINFO();
LicenceInfo = null;
FileInfo = null;
Algorithms = null;
DataFileEnc = null;
if (IntPtr.Size == 4)
ret_code = ReadDAPFEx32.ReadDAPFEx(dapf_file, out DinkeyInfo, licence_bytes, fileinfo_bytes, alg_bytes, datafile_bytes, out dapf_version, out dapf_format);
else
ret_code = ReadDAPFEx64.ReadDAPFEx(dapf_file, out DinkeyInfo, licence_bytes, fileinfo_bytes, alg_bytes, datafile_bytes, out dapf_version, out dapf_format);
if (ret_code != 0)
return ret_code;
// convert byte array to an array of structs
LicenceInfo = new LICENCEINFO[DinkeyInfo.NumLicences];
for (i=0; i<DinkeyInfo.NumLicences; i++)
{
Array.Copy(licence_bytes, i*Marshal.SizeOf(typeof(LICENCEINFO)), licence_bytes_one_struct, 0, Marshal.SizeOf(typeof(LICENCEINFO)));
MyGC = GCHandle.Alloc(licence_bytes_one_struct, GCHandleType.Pinned);
LicenceInfo[i] = (LICENCEINFO)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(LICENCEINFO));
MyGC.Free();
}
FileInfo = new FILEINFO[DinkeyInfo.NumProgs];
for (i=0; i<DinkeyInfo.NumProgs; i++)
{
Array.Copy(fileinfo_bytes, i*Marshal.SizeOf(typeof(FILEINFO)), fileinfo_bytes_one_struct, 0, Marshal.SizeOf(typeof(FILEINFO)));
MyGC = GCHandle.Alloc(fileinfo_bytes_one_struct, GCHandleType.Pinned);
FileInfo[i] = (FILEINFO)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(FILEINFO));
MyGC.Free();
}
Algorithms = new ALGORITHM[DinkeyInfo.NumAlgs];
for (i=0; i<DinkeyInfo.NumAlgs; i++)
{
Array.Copy(alg_bytes, i*Marshal.SizeOf(typeof(ALGORITHM)), alg_bytes_one_struct, 0, Marshal.SizeOf(typeof(ALGORITHM)));
MyGC = GCHandle.Alloc(alg_bytes_one_struct, GCHandleType.Pinned);
Algorithms[i] = (ALGORITHM)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(ALGORITHM));
MyGC.Free();
}
DataFileEnc = new DATAFILEENC[DinkeyInfo.NumDataFileEnc];
for (i=0; i<DinkeyInfo.NumDataFileEnc; i++)
{
Array.Copy(datafile_bytes, i*Marshal.SizeOf(typeof(DATAFILEENC)), datafile_bytes_one_struct, 0, Marshal.SizeOf(typeof(DATAFILEENC)));
MyGC = GCHandle.Alloc(datafile_bytes_one_struct, GCHandleType.Pinned);
DataFileEnc[i] = (DATAFILEENC)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(DATAFILEENC));
MyGC.Free();
}
return ret_code;
}
// we have to do some marshalling of an array of structures into an array of bytes
public static IntPtr LoadDAPF(DINKEYINFO DinkeyInfo, LICENCEINFO[] LicenceInfo, FILEINFO[] FileInfo, ALGORITHM[] Algorithms, DATAFILEENC[] DataFileEnc, out int ret_code)
{
int i;
byte[] licence_bytes = new byte[MAX_LICENCES * Marshal.SizeOf(typeof(LICENCEINFO))];
byte[] licence_bytes_one_struct = new byte[Marshal.SizeOf(typeof(LICENCEINFO))];
byte[] fileinfo_bytes = new byte[MAX_FILE_INFO * Marshal.SizeOf(typeof(FILEINFO))];
byte[] fileinfo_bytes_one_struct = new byte[Marshal.SizeOf(typeof(FILEINFO))];
byte[] alg_bytes = new byte[MAX_USER_ALGS * Marshal.SizeOf(typeof(ALGORITHM))];
byte[] alg_bytes_one_struct = new byte[Marshal.SizeOf(typeof(ALGORITHM))];
byte[] datafile_bytes = new byte[MAX_DATA_ENCS * Marshal.SizeOf(typeof(DATAFILEENC))];
byte[] datafile_bytes_one_struct = new byte[Marshal.SizeOf(typeof(DATAFILEENC))];
GCHandle MyGC;
// convert array of structs to a byte array
for (i=0; i<DinkeyInfo.NumLicences; i++)
{
MyGC = GCHandle.Alloc(licence_bytes_one_struct, GCHandleType.Pinned);
Marshal.StructureToPtr(LicenceInfo[i], MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
Array.Copy(licence_bytes_one_struct, 0, licence_bytes, i*Marshal.SizeOf(typeof(LICENCEINFO)), Marshal.SizeOf(typeof(LICENCEINFO)));
}
for (i=0; i<DinkeyInfo.NumProgs; i++)
{
MyGC = GCHandle.Alloc(fileinfo_bytes_one_struct, GCHandleType.Pinned);
Marshal.StructureToPtr(FileInfo[i], MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
Array.Copy(fileinfo_bytes_one_struct, 0, fileinfo_bytes, i*Marshal.SizeOf(typeof(FILEINFO)), Marshal.SizeOf(typeof(FILEINFO)));
}
for (i=0; i<DinkeyInfo.NumAlgs; i++)
{
MyGC = GCHandle.Alloc(alg_bytes_one_struct, GCHandleType.Pinned);
Marshal.StructureToPtr(Algorithms[i], MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
Array.Copy(alg_bytes_one_struct, 0, alg_bytes, i*Marshal.SizeOf(typeof(ALGORITHM)), Marshal.SizeOf(typeof(ALGORITHM)));
}
for (i=0; i<DinkeyInfo.NumDataFileEnc; i++)
{
MyGC = GCHandle.Alloc(datafile_bytes_one_struct, GCHandleType.Pinned);
Marshal.StructureToPtr(DataFileEnc[i], MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
Array.Copy(datafile_bytes_one_struct, 0, datafile_bytes, i*Marshal.SizeOf(typeof(DATAFILEENC)), Marshal.SizeOf(typeof(DATAFILEENC)));
}
if (IntPtr.Size == 4)
return LoadDAPF32.LoadDAPF(ref DinkeyInfo, licence_bytes, fileinfo_bytes, alg_bytes, datafile_bytes, out ret_code);
return LoadDAPF64.LoadDAPF(ref DinkeyInfo, licence_bytes, fileinfo_bytes, alg_bytes, datafile_bytes, out ret_code);
}
public static int WriteDAPFEx(IntPtr dapf_handle, string dapf_file, int dapf_format, int dapf_version, int flags)
{
if (IntPtr.Size == 4)
return WriteDAPFEx32.WriteDAPFEx(dapf_handle, dapf_file, dapf_format, dapf_version, flags);
return WriteDAPFEx64.WriteDAPFEx(dapf_handle, dapf_file, dapf_format, dapf_version, flags);
}
public static void UnloadDAPF(ref IntPtr dapf_handle)
{
if (IntPtr.Size == 4)
UnloadDAPF32.UnloadDAPF(ref dapf_handle);
else
UnloadDAPF64.UnloadDAPF(ref dapf_handle);
return;
}
public static int AddProtection(IntPtr dapf_handle, int action, int file_num, int flags, out uint dongle_number)
{
if (IntPtr.Size == 4)
return AddProtection32.AddProtection(dapf_handle, action, file_num, flags, out dongle_number);
return AddProtection64.AddProtection(dapf_handle, action, file_num, flags, out dongle_number);
}
public static int CreateTempSoftwareKey(IntPtr dapf_handle, TEMP_SWKEY_INFO swkey_info, int flags)
{
if (IntPtr.Size == 4)
return CreateTempSoftwareKey32.CreateTempSoftwareKey(dapf_handle, ref swkey_info, flags);
return CreateTempSoftwareKey64.CreateTempSoftwareKey(dapf_handle, ref swkey_info, flags);
}
public static int CreateDemoSoftwareKeyTemplate(IntPtr dapf_handle, DEMO_SWKEY_INFO swkey_info, int flags)
{
if (IntPtr.Size == 4)
return CreateDemoSoftwareKeyTemplate32.CreateDemoSoftwareKeyTemplate(dapf_handle, ref swkey_info, flags);
return CreateDemoSoftwareKeyTemplate64.CreateDemoSoftwareKeyTemplate(dapf_handle, ref swkey_info, flags);
}
public static int EncryptShellDataFiles(IntPtr dapf_handle, int file_num, int flags)
{
if (IntPtr.Size == 4)
return EncryptShellDataFiles32.EncryptShellDataFiles(dapf_handle, file_num, flags);
return EncryptShellDataFiles64.EncryptShellDataFiles(dapf_handle, file_num, flags);
}
// do a bit of work here to make the function easier to use for C#
public static string GetLastMessage()
{
int length, dummy;
StringBuilder message;
if (IntPtr.Size == 4)
{
GetLastMessage32.GetLastMessage(null, 0, out length);
message = new StringBuilder(length);
GetLastMessage32.GetLastMessage(message, length, out dummy);
}
else
{
GetLastMessage64.GetLastMessage(null, 0, out length);
message = new StringBuilder(length);
GetLastMessage64.GetLastMessage(message, length, out dummy);
}
return message.ToString();
}
public static int GetLastExtendedError()
{
if (IntPtr.Size == 4)
return GetLastExtendedError32.GetLastExtendedError();
return GetLastExtendedError64.GetLastExtendedError();
}
}

View File

@@ -0,0 +1,121 @@
<VisualStudioProject>
<CSHARP
ProjectType = "Local"
ProductVersion = "7.0.9466"
SchemaVersion = "1.0"
ProjectGuid = "{6535AF22-2AF4-4401-BFE2-889CD40C8F2F}"
>
<Build>
<Settings
ApplicationIcon = "App.ico"
AssemblyKeyContainerName = ""
AssemblyName = "dapfTest"
AssemblyOriginatorKeyFile = ""
DefaultClientScript = "JScript"
DefaultHTMLPageLayout = "Grid"
DefaultTargetSchema = "IE50"
DelaySign = "false"
OutputType = "WinExe"
RootNamespace = "dapfTest"
StartupObject = ""
>
<Config
Name = "Debug"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "DEBUG;TRACE"
DocumentationFile = ""
DebugSymbols = "true"
FileAlignment = "4096"
IncrementalBuild = "true"
Optimize = "false"
OutputPath = "bin\Debug\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
<Config
Name = "Release"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "TRACE"
DocumentationFile = ""
DebugSymbols = "false"
FileAlignment = "4096"
IncrementalBuild = "false"
Optimize = "true"
OutputPath = "bin\Release\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
</Settings>
<References>
<Reference
Name = "System"
AssemblyName = "System"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.dll"
/>
<Reference
Name = "System.Data"
AssemblyName = "System.Data"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.Data.dll"
/>
<Reference
Name = "System.Drawing"
AssemblyName = "System.Drawing"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.Drawing.dll"
/>
<Reference
Name = "System.Windows.Forms"
AssemblyName = "System.Windows.Forms"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.Windows.Forms.dll"
/>
<Reference
Name = "System.XML"
AssemblyName = "System.Xml"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.XML.dll"
/>
</References>
</Build>
<Files>
<Include>
<File
RelPath = "App.ico"
BuildAction = "Content"
/>
<File
RelPath = "AssemblyInfo.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "dapf.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "Form1.cs"
SubType = "Form"
BuildAction = "Compile"
/>
<File
RelPath = "Form1.resx"
DependentUpon = "Form1.cs"
BuildAction = "EmbeddedResource"
/>
<File
RelPath = "readme.txt"
BuildAction = "Content"
/>
</Include>
</Files>
</CSHARP>
</VisualStudioProject>

View File

@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 7.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dapfTest", "dapfTest.csproj", "{6535AF22-2AF4-4401-BFE2-889CD40C8F2F}"
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
ConfigName.0 = Debug
ConfigName.1 = Release
EndGlobalSection
GlobalSection(ProjectDependencies) = postSolution
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{6535AF22-2AF4-4401-BFE2-889CD40C8F2F}.Debug.ActiveCfg = Debug|.NET
{6535AF22-2AF4-4401-BFE2-889CD40C8F2F}.Debug.Build.0 = Debug|.NET
{6535AF22-2AF4-4401-BFE2-889CD40C8F2F}.Release.ActiveCfg = Release|.NET
{6535AF22-2AF4-4401-BFE2-889CD40C8F2F}.Release.Build.0 = Release|.NET
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,58 @@
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]

View File

@@ -0,0 +1,128 @@
<VisualStudioProject>
<CSHARP
ProjectType = "Local"
ProductVersion = "7.10.3077"
SchemaVersion = "2.0"
ProjectGuid = "{1B4F9D4B-2045-4A7D-9007-1FBDB9E30F2C}"
>
<Build>
<Settings
ApplicationIcon = "App.ico"
AssemblyKeyContainerName = ""
AssemblyName = "ChangeTest"
AssemblyOriginatorKeyFile = ""
DefaultClientScript = "JScript"
DefaultHTMLPageLayout = "Grid"
DefaultTargetSchema = "IE50"
DelaySign = "false"
OutputType = "WinExe"
PreBuildEvent = ""
PostBuildEvent = ""
RootNamespace = "ChangeTest"
RunPostBuildEvent = "OnBuildSuccess"
StartupObject = ""
>
<Config
Name = "Debug"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "DEBUG;TRACE"
DocumentationFile = ""
DebugSymbols = "true"
FileAlignment = "4096"
IncrementalBuild = "true"
NoStdLib = "false"
NoWarn = ""
Optimize = "false"
OutputPath = "bin\Debug\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
<Config
Name = "Release"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "TRACE"
DocumentationFile = ""
DebugSymbols = "false"
FileAlignment = "4096"
IncrementalBuild = "false"
NoStdLib = "false"
NoWarn = ""
Optimize = "true"
OutputPath = "bin\Release\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
</Settings>
<References>
<Reference
Name = "System"
AssemblyName = "System"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.dll"
/>
<Reference
Name = "System.Data"
AssemblyName = "System.Data"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.Data.dll"
/>
<Reference
Name = "System.Drawing"
AssemblyName = "System.Drawing"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.Drawing.dll"
/>
<Reference
Name = "System.Windows.Forms"
AssemblyName = "System.Windows.Forms"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.Windows.Forms.dll"
/>
<Reference
Name = "System.XML"
AssemblyName = "System.Xml"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.XML.dll"
/>
</References>
</Build>
<Files>
<Include>
<File
RelPath = "App.ico"
BuildAction = "Content"
/>
<File
RelPath = "AssemblyInfo.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "DinkeyChange.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "Form1.cs"
SubType = "Form"
BuildAction = "Compile"
/>
<File
RelPath = "Form1.resx"
DependentUpon = "Form1.cs"
BuildAction = "EmbeddedResource"
/>
<File
RelPath = "readme.txt"
BuildAction = "Content"
/>
</Include>
</Files>
</CSHARP>
</VisualStudioProject>

View File

@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChangeTest", "ChangeTest.csproj", "{1B4F9D4B-2045-4A7D-9007-1FBDB9E30F2C}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{1B4F9D4B-2045-4A7D-9007-1FBDB9E30F2C}.Debug.ActiveCfg = Debug|.NET
{1B4F9D4B-2045-4A7D-9007-1FBDB9E30F2C}.Debug.Build.0 = Debug|.NET
{1B4F9D4B-2045-4A7D-9007-1FBDB9E30F2C}.Release.ActiveCfg = Release|.NET
{1B4F9D4B-2045-4A7D-9007-1FBDB9E30F2C}.Release.Build.0 = Release|.NET
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,203 @@
// !! this file should not be modified
using System;
using System.Runtime.InteropServices; // so we can import DLL functions
using System.Text; // so we can extract prodcode from array
// classes to load the correct 32-bit/64-bit DinkeyChange.dll functions - used by DinkeyChange class
// loads DCGetInfo from the 32-bit DinkeyChange.dll
class DCGetInfo32
{
[DllImport("DinkeyChange.dll", CharSet = CharSet.Ansi)]
public static extern int DCGetInfo(int type_mask, int model_mask, string prodcode_mask, int array_length, out int num_found, int[] type, int[] model, byte[] prodcode, uint[] dongle_number, int[] update_number);
}
// loads DCGetInfo from the 64-bit DinkeyChange64.dll
class DCGetInfo64
{
[DllImport("DinkeyChange64.dll", CharSet = CharSet.Ansi)]
public static extern int DCGetInfo(int type_mask, int model_mask, string prodcode_mask, int array_length, out int num_found, int[] type, int[] model, byte[] prodcode, uint[] dongle_number, int[] update_number);
}
// loads DCGetDiagnosticInfo from the 32-bit DinkeyChange.dll
class DCGetDiagnosticInfo32
{
[DllImport("DinkeyChange.dll", CharSet = CharSet.Ansi)]
public static extern int DCGetDiagnosticInfo(string filename);
}
// loads DCGetDiagnosticInfo from the 64-bit DinkeyChange64.dll
class DCGetDiagnosticInfo64
{
[DllImport("DinkeyChange64.dll", CharSet = CharSet.Ansi)]
public static extern int DCGetDiagnosticInfo(string filename);
}
// loads DCDoUpdateCodeString from the 32-bit DinkeyChange.dll
class DCDoUpdateCodeString32
{
[DllImport("DinkeyChange.dll", CharSet = CharSet.Ansi)]
public static extern int DCDoUpdateCodeString(string update_code_string, out int confirmation_code, out int extended_error);
}
// loads DCDoUpdateCodeString from the 64-bit DinkeyChange64.dll
class DCDoUpdateCodeString64
{
[DllImport("DinkeyChange64.dll", CharSet = CharSet.Ansi)]
public static extern int DCDoUpdateCodeString(string update_code_string, out int confirmation_code, out int extended_error);
}
// loads DCDoUpdateCodeFromFile from the 32-bit DinkeyChange.dll
class DCDoUpdateCodeFromFile32
{
[DllImport("DinkeyChange.dll", CharSet = CharSet.Ansi)]
public static extern int DCDoUpdateCodeFromFile(string update_code_file, out int confirmation_code, out int extended_error);
}
// loads DCDoUpdateCodeFromFile from the 64-bit DinkeyChange64.dll
class DCDoUpdateCodeFromFile64
{
[DllImport("DinkeyChange64.dll", CharSet = CharSet.Ansi)]
public static extern int DCDoUpdateCodeFromFile(string update_code_file, out int confirmation_code, out int extended_error);
}
// loads DCRestoreDinkeyFDLite from the 32-bit DinkeyChange.dll
class DCRestoreDinkeyFDLite32
{
[DllImport("DinkeyChange.dll", CharSet = CharSet.Ansi)]
public static extern int DCRestoreDinkeyFDLite();
}
// loads DCRestoreDinkeyFDLite from the 64-bit DinkeyChange64.dll
class DCRestoreDinkeyFDLite64
{
[DllImport("DinkeyChange64.dll", CharSet = CharSet.Ansi)]
public static extern int DCRestoreDinkeyFDLite();
}
// loads DCGetMachineID from the 32-bit DinkeyChange.dll
class DCGetMachineID32
{
[DllImport("DinkeyChange.dll", CharSet = CharSet.Ansi)]
public static extern int DCGetMachineID(out uint machineID, out int extended_error);
}
// loads DCGetMachineID from the 64-bit DinkeyChange64.dll
class DCGetMachineID64
{
[DllImport("DinkeyChange64.dll", CharSet = CharSet.Ansi)]
public static extern int DCGetMachineID(out uint machineID, out int extended_error);
}
// loads DCDownloadTempSoftwareKey from the 32-bit DinkeyChange.dll
class DCDownloadTempSoftwareKey32
{
[DllImport("DinkeyChange.dll", CharSet = CharSet.Ansi)]
public static extern int DCDownloadTempSoftwareKey(uint machineID, out int extended_error);
}
// loads DCDownloadTempSoftwareKey from the 64-bit DinkeyChange64.dll
class DCDownloadTempSoftwareKey64
{
[DllImport("DinkeyChange64.dll", CharSet = CharSet.Ansi)]
public static extern int DCDownloadTempSoftwareKey(uint machineID, out int extended_error);
}
// loads DCDownloadDemoSoftwareKey from the 32-bit DinkeyChange.dll
class DCDownloadDemoSoftwareKey32
{
[DllImport("DinkeyChange.dll", CharSet = CharSet.Ansi)]
public static extern int DCDownloadDemoSoftwareKey(uint machineID, string prodcode, int model, out int extended_error);
}
// loads DCDownloadDemoSoftwareKey from the 64-bit DinkeyChange64.dll
class DCDownloadDemoSoftwareKey64
{
[DllImport("DinkeyChange64.dll", CharSet = CharSet.Ansi)]
public static extern int DCDownloadDemoSoftwareKey(uint machineID, string prodcode, int model, out int extended_error);
}
class DinkeyChange
{
// **** main API
// We only want to load the correct DLL for the bit-ness of the computer. The other DLL may not exist.
// if the appropriate DLL does not exist in the same directory as this test program you will receive a DllNotFoundException
// detects whether running 32-bit code or 64-bit code and loads appropriate Dll.
public static int DCGetInfo(int type_mask, int model_mask, string prodcode_mask, int array_length, out int num_found, int[] type, int[] model, byte[] prodcode, uint[] dongle_number, int[] update_number)
{
if (IntPtr.Size == 4)
return DCGetInfo32.DCGetInfo(type_mask, model_mask, prodcode_mask, array_length, out num_found, type, model, prodcode, dongle_number, update_number);
return DCGetInfo64.DCGetInfo(type_mask, model_mask, prodcode_mask, array_length, out num_found, type, model, prodcode, dongle_number, update_number);
}
public static int DCGetDiagnosticInfo(string filename)
{
if (IntPtr.Size == 4)
return DCGetDiagnosticInfo32.DCGetDiagnosticInfo(filename);
return DCGetDiagnosticInfo64.DCGetDiagnosticInfo(filename);
}
public static int DCDoUpdateCodeString(string update_code_string, out int confirmation_code, out int extended_error)
{
if (IntPtr.Size == 4)
return DCDoUpdateCodeString32.DCDoUpdateCodeString(update_code_string, out confirmation_code, out extended_error);
return DCDoUpdateCodeString64.DCDoUpdateCodeString(update_code_string, out confirmation_code, out extended_error);
}
public static int DCDoUpdateCodeFromFile(string update_code_string, out int confirmation_code, out int extended_error)
{
if (IntPtr.Size == 4)
return DCDoUpdateCodeFromFile32.DCDoUpdateCodeFromFile(update_code_string, out confirmation_code, out extended_error);
return DCDoUpdateCodeFromFile64.DCDoUpdateCodeFromFile(update_code_string, out confirmation_code, out extended_error);
}
public static int DCRestoreDinkeyFDLite()
{
if (IntPtr.Size == 4)
return DCRestoreDinkeyFDLite32.DCRestoreDinkeyFDLite();
return DCRestoreDinkeyFDLite64.DCRestoreDinkeyFDLite();
}
public static int DCGetMachineID(out uint machineID, out int extended_error)
{
if (IntPtr.Size == 4)
return DCGetMachineID32.DCGetMachineID(out machineID, out extended_error);
return DCGetMachineID64.DCGetMachineID(out machineID, out extended_error);
}
public static int DCDownloadTempSoftwareKey(uint machineID, out int extended_error)
{
if (IntPtr.Size == 4)
return DCDownloadTempSoftwareKey32.DCDownloadTempSoftwareKey(machineID, out extended_error);
return DCDownloadTempSoftwareKey64.DCDownloadTempSoftwareKey(machineID, out extended_error);
}
public static int DCDownloadDemoSoftwareKey(uint machineID, string prodcode, int model, out int extended_error)
{
if (IntPtr.Size == 4)
return DCDownloadDemoSoftwareKey32.DCDownloadDemoSoftwareKey(machineID, prodcode, model, out extended_error);
return DCDownloadDemoSoftwareKey64.DCDownloadDemoSoftwareKey(machineID, prodcode, model, out extended_error);
}
// **** general purpose routines
// routine to extract product code string from array of product codes
public static string GetProductCode(byte[] prodcode, int index)
{
int i;
StringBuilder sb = new StringBuilder(8);
for (i=index*9; i<(index+1)*9; i++)
{
if (prodcode[i] == 0)
return sb.ToString();
else
sb.Append((char)prodcode[i]);
}
return sb.ToString();
}
}

View File

@@ -0,0 +1,581 @@
// !! We strongly recommend that you read the "readme.txt" file in the sample code folder.
// !! It contains important instructions on how to use the sample code
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace ChangeTest
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button get_dongle_info;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox diag_filename;
private System.Windows.Forms.Button write_diag_file;
private System.Windows.Forms.Button do_update_code_string;
private System.Windows.Forms.TextBox update_code_string;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button do_update_code_file;
private System.Windows.Forms.TextBox update_code_file;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button restore_fd_lite;
private System.Windows.Forms.Button get_machine_id;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox swkey_prod_code;
private System.Windows.Forms.Button download_temp_swkey;
private System.Windows.Forms.Button download_demo_swkey;
private System.Windows.Forms.TextBox machine_id;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
// maximum number of USB devices that can be attached to a machine at any time
public const int MAX_USB_DEVICES = 128;
public const int MAX_PRODCODE_LEN = 9; // including terminating null
public string AppName = "ChangeTest";
// mask values
public const int TYPE_MASK_PRO = 1;
public const int TYPE_MASK_FD = 2;
public const int TYPE_MASK_ALL = (TYPE_MASK_PRO | TYPE_MASK_FD);
public const int MODEL_MASK_LITE = 1;
public const int MODEL_MASK_PLUS = 2;
public const int MODEL_MASK_NET = 4;
public const int MODEL_MASK_ALL = (MODEL_MASK_LITE | MODEL_MASK_PLUS | MODEL_MASK_NET);
public const int MODEL_MASK_DEFAULT = (MODEL_MASK_PLUS | MODEL_MASK_NET);
// type values for DCGetInfo (returned in the array)
public const int TYPE_PRO = 1;
public const int TYPE_FD = 2;
// model values for DCGetInfo (returned in the array)
public const int MODEL_LITE = 1;
public const int MODEL_PLUS = 2;
public const int MODEL_NET5 = 4;
public const int MODEL_NETU = 7;
// model values for DCDownloadDemoSoftwareKey
public const int SWKEY_MODEL_DEFAULT = -1; // NB this assumes that the Demo Software Key Template was created with only one valid dongle model
public const int SWKEY_MODEL_PRO_LITE = 0;
public const int SWKEY_MODEL_PRO_PLUS = 1;
public const int SWKEY_MODEL_PRO_NET = 2;
public const int SWKEY_MODEL_FD_LITE = 3;
public const int SWKEY_MODEL_FD_PLUS = 4;
public const int SWKEY_MODEL_FD_NET = 5;
private void InitializeComponent()
{
this.get_dongle_info = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.diag_filename = new System.Windows.Forms.TextBox();
this.write_diag_file = new System.Windows.Forms.Button();
this.do_update_code_string = new System.Windows.Forms.Button();
this.update_code_string = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.do_update_code_file = new System.Windows.Forms.Button();
this.update_code_file = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.restore_fd_lite = new System.Windows.Forms.Button();
this.get_machine_id = new System.Windows.Forms.Button();
this.machine_id = new System.Windows.Forms.TextBox();
this.download_temp_swkey = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.swkey_prod_code = new System.Windows.Forms.TextBox();
this.download_demo_swkey = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// get_dongle_info
//
this.get_dongle_info.Location = new System.Drawing.Point(48, 24);
this.get_dongle_info.Name = "get_dongle_info";
this.get_dongle_info.Size = new System.Drawing.Size(224, 24);
this.get_dongle_info.TabIndex = 0;
this.get_dongle_info.Text = "Get Dongle Information";
this.get_dongle_info.Click += new System.EventHandler(this.get_dongle_info_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 72);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(280, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Enter diagnostic filename:";
//
// diag_filename
//
this.diag_filename.Location = new System.Drawing.Point(16, 88);
this.diag_filename.Name = "diag_filename";
this.diag_filename.Size = new System.Drawing.Size(288, 20);
this.diag_filename.TabIndex = 2;
this.diag_filename.Text = "";
//
// write_diag_file
//
this.write_diag_file.Location = new System.Drawing.Point(48, 120);
this.write_diag_file.Name = "write_diag_file";
this.write_diag_file.Size = new System.Drawing.Size(224, 24);
this.write_diag_file.TabIndex = 3;
this.write_diag_file.Text = "Write Diagnostics to File";
this.write_diag_file.Click += new System.EventHandler(this.write_diag_file_Click);
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 168);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(280, 16);
this.label2.TabIndex = 4;
this.label2.Text = "Enter short Update Code here:";
//
// update_code_string
//
this.update_code_string.Location = new System.Drawing.Point(16, 184);
this.update_code_string.Name = "update_code_string";
this.update_code_string.Size = new System.Drawing.Size(288, 20);
this.update_code_string.TabIndex = 5;
this.update_code_string.Text = "";
//
// do_update_code_string
//
this.do_update_code_string.Location = new System.Drawing.Point(48, 216);
this.do_update_code_string.Name = "do_update_code_string";
this.do_update_code_string.Size = new System.Drawing.Size(224, 24);
this.do_update_code_string.TabIndex = 6;
this.do_update_code_string.Text = "Make Changes";
this.do_update_code_string.Click += new System.EventHandler(this.do_update_code_string_Click);
//
// do_update_code_file
//
this.do_update_code_file.Location = new System.Drawing.Point(48, 312);
this.do_update_code_file.Name = "do_update_code_file";
this.do_update_code_file.Size = new System.Drawing.Size(224, 24);
this.do_update_code_file.TabIndex = 9;
this.do_update_code_file.Text = "Make Changes";
this.do_update_code_file.Click += new System.EventHandler(this.do_update_code_file_Click);
//
// update_code_file
//
this.update_code_file.Location = new System.Drawing.Point(16, 280);
this.update_code_file.Name = "update_code_file";
this.update_code_file.Size = new System.Drawing.Size(288, 20);
this.update_code_file.TabIndex = 8;
this.update_code_file.Text = "";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 264);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(280, 16);
this.label3.TabIndex = 7;
this.label3.Text = "Enter path to Update Code file:";
//
// restore_fd_lite
//
this.restore_fd_lite.Location = new System.Drawing.Point(48, 368);
this.restore_fd_lite.Name = "restore_fd_lite";
this.restore_fd_lite.Size = new System.Drawing.Size(224, 24);
this.restore_fd_lite.TabIndex = 10;
this.restore_fd_lite.Text = "Restore Dinkey FD Lite";
this.restore_fd_lite.Click += new System.EventHandler(this.restore_fd_lite_Click);
//
// get_machine_id
//
this.get_machine_id.Location = new System.Drawing.Point(16, 424);
this.get_machine_id.Name = "get_machine_id";
this.get_machine_id.Size = new System.Drawing.Size(144, 24);
this.get_machine_id.TabIndex = 11;
this.get_machine_id.Text = "Get Machine ID";
this.get_machine_id.Click += new System.EventHandler(this.get_machine_id_Click);
//
// machine_id
//
this.machine_id.Location = new System.Drawing.Point(168, 424);
this.machine_id.Name = "machine_id";
this.machine_id.Size = new System.Drawing.Size(136, 20);
this.machine_id.TabIndex = 12;
this.machine_id.Text = "";
//
// download_temp_swkey
//
this.download_temp_swkey.Location = new System.Drawing.Point(48, 480);
this.download_temp_swkey.Name = "download_temp_swkey";
this.download_temp_swkey.Size = new System.Drawing.Size(224, 24);
this.download_temp_swkey.TabIndex = 13;
this.download_temp_swkey.Text = "Download Temporary Software Key";
this.download_temp_swkey.Click += new System.EventHandler(this.download_temp_swkey_Click);
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 528);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(280, 16);
this.label4.TabIndex = 14;
this.label4.Text = "Demo Software Key Product Code:";
//
// swkey_prod_code
//
this.swkey_prod_code.Location = new System.Drawing.Point(16, 544);
this.swkey_prod_code.Name = "swkey_prod_code";
this.swkey_prod_code.Size = new System.Drawing.Size(288, 20);
this.swkey_prod_code.TabIndex = 15;
this.swkey_prod_code.Text = "";
//
// download_demo_swkey
//
this.download_demo_swkey.Location = new System.Drawing.Point(48, 576);
this.download_demo_swkey.Name = "download_demo_swkey";
this.download_demo_swkey.Size = new System.Drawing.Size(224, 24);
this.download_demo_swkey.TabIndex = 16;
this.download_demo_swkey.Text = "Download Demo Software Key";
this.download_demo_swkey.Click += new System.EventHandler(this.download_demo_swkey_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(320, 624);
this.Controls.Add(this.download_demo_swkey);
this.Controls.Add(this.swkey_prod_code);
this.Controls.Add(this.label4);
this.Controls.Add(this.machine_id);
this.Controls.Add(this.download_temp_swkey);
this.Controls.Add(this.get_machine_id);
this.Controls.Add(this.restore_fd_lite);
this.Controls.Add(this.do_update_code_file);
this.Controls.Add(this.update_code_file);
this.Controls.Add(this.label3);
this.Controls.Add(this.do_update_code_string);
this.Controls.Add(this.update_code_string);
this.Controls.Add(this.label2);
this.Controls.Add(this.write_diag_file);
this.Controls.Add(this.diag_filename);
this.Controls.Add(this.label1);
this.Controls.Add(this.get_dongle_info);
this.Name = "Form1";
this.Text = "ChangeTest";
this.ResumeLayout(false);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
// routine to get & display information for all dongles attached
private void get_dongle_info_Click(object sender, System.EventArgs e)
{
int ret_code, i, num_found;
string DisplayString = null;
string Type, Model, ProdCodeString;
// return arrays of dongle details filedin by DCGetInfo
int[] type = new int[MAX_USB_DEVICES];
int[] model = new int[MAX_USB_DEVICES];
byte[] prodcode = new Byte[MAX_USB_DEVICES*MAX_PRODCODE_LEN];
uint[] dongle_number = new uint[MAX_USB_DEVICES];
int[] update_number = new int[MAX_USB_DEVICES];
// find dongle information for all dongle types, Plus & Net models, for all product codes
// NB In practice you will probably want to set the prodcode_mask to the value of your product code
ret_code = DinkeyChange.DCGetInfo(TYPE_MASK_ALL, MODEL_MASK_DEFAULT, null, MAX_USB_DEVICES, out num_found, type, model, prodcode, dongle_number, update_number);
// check error code and display error if an error occurs
if (ret_code == 401)
{
MessageBox.Show("No dongles detected matching the search criteria specified", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else if (ret_code != 0)
{
DisplayString = "An error occurred getting dongle information. Error: " + String.Format("{0:D}", ret_code);
MessageBox.Show(DisplayString, AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// display info for dongle(s) detected
for (i=0; i<num_found; i++)
{
// get type of dongle
if (type[i] == TYPE_PRO)
Type = "Pro";
else
Type = "FD";
// get model of dongle
if (model[i] == MODEL_LITE)
Model = "Lite";
else if (model[i] == MODEL_PLUS)
Model = "Plus";
else
Model = "Net";
ProdCodeString = DinkeyChange.GetProductCode(prodcode, i);
DisplayString += String.Format("{0}. Dinkey {1} {2} with dongle number: {3}, product code: {4}, update number: {5}", i+1, Type, Model, dongle_number[i], ProdCodeString, update_number[i]);
DisplayString += Environment.NewLine;
}
MessageBox.Show(DisplayString, "Dongle Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// Write Dongle Diagnostics to file
private void write_diag_file_Click(object sender, System.EventArgs e)
{
int ret_code;
// NB this could take a while if the data area is very large
ret_code = DinkeyChange.DCGetDiagnosticInfo(diag_filename.Text);
// check error code and display error if an error occurs
if (ret_code == 754)
{
MessageBox.Show("Could not create the diagnostic file. Please check that the path exists: " + diag_filename.Text, AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else if (ret_code != 0)
{
MessageBox.Show(String.Format("Error {0} writing diagnostic information", ret_code), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// display success
MessageBox.Show("Diagnostic file written successfully.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// Update dongle using short code typed-in
private void do_update_code_string_Click(object sender, System.EventArgs e)
{
int ret_code, confirmation_code, extended_error;
// make changes
ret_code = DinkeyChange.DCDoUpdateCodeString(update_code_string.Text, out confirmation_code, out extended_error);
// check error code and display error if an error occurs
if (ret_code != 0)
{
DisplayError(ret_code, extended_error);
return;
}
MessageBox.Show(String.Format("Dongle updated successfully!\nConfirmation code is : {0:X4}", confirmation_code), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void do_update_code_file_Click(object sender, System.EventArgs e)
{
int ret_code, confirmation_code, extended_error;
// make changes
ret_code = DinkeyChange.DCDoUpdateCodeFromFile(update_code_file.Text, out confirmation_code, out extended_error);
// check error code and display error if an error occurs
if (ret_code != 0)
{
DisplayError(ret_code, extended_error);
return;
}
MessageBox.Show(String.Format("Dongle updated successfully!\nConfirmation code is : {0:X4}", confirmation_code), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// attempt to restore a Dinkey FD Lite dongle
private void restore_fd_lite_Click(object sender, System.EventArgs e)
{
int ret_code;
ret_code = DinkeyChange.DCRestoreDinkeyFDLite();
// check error code and display error if an error occurs
if (ret_code != 0)
{
DisplayError(ret_code, 0);
return;
}
MessageBox.Show("Dinkey FD Lite restored successfully.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void get_machine_id_Click(object sender, System.EventArgs e)
{
int ret_code, extended_error;
uint machineID;
ret_code = DinkeyChange.DCGetMachineID(out machineID, out extended_error);
// check error code and display error if an error occurs
if (ret_code != 0)
{
DisplayError(ret_code, extended_error);
return;
}
// display the machine ID in the text box
machine_id.Text = String.Format("{0:X8}", machineID);
}
private void download_temp_swkey_Click(object sender, System.EventArgs e)
{
int ret_code, extended_error;
uint machineID;
// first get the machine ID...
ret_code = DinkeyChange.DCGetMachineID(out machineID, out extended_error);
// check error code and display error if an error occurs
if (ret_code != 0)
{
DisplayError(ret_code, extended_error);
return;
}
// ... and then try to download the temporary software key
ret_code = DinkeyChange.DCDownloadTempSoftwareKey(machineID, out extended_error);
// check error code and display error if an error occurs
if (ret_code != 0)
{
DisplayError(ret_code, extended_error);
return;
}
MessageBox.Show("Temporary Software Key downloaded successfully.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void download_demo_swkey_Click(object sender, System.EventArgs e)
{
int ret_code, extended_error;
uint machineID;
// first get the machine ID...
ret_code = DinkeyChange.DCGetMachineID(out machineID, out extended_error);
// check error code and display error if an error occurs
if (ret_code != 0)
{
DisplayError(ret_code, extended_error);
return;
}
// try to download the demo software key
// (NB we are assuming only one dongle model is set in the Demo Software Template.
// If multiple models are set you will also need to specify the exact model)
ret_code = DinkeyChange.DCDownloadDemoSoftwareKey(machineID, swkey_prod_code.Text, SWKEY_MODEL_DEFAULT, out extended_error);
// check error code and display error if an error occurs
if (ret_code != 0)
{
DisplayError(ret_code, extended_error);
return;
}
MessageBox.Show("Demo Software Key downloaded successfully.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// displays messages for the most common errors. You will want to change this for your code
void DisplayError(int ret_code, int extended_error)
{
switch (ret_code)
{
case 401:
MessageBox.Show("Error! No dongles detected that meet the search criteria!", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 409:
MessageBox.Show("Error! The dongle detected has not been programmed by DinkeyAdd.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 758:
MessageBox.Show("Error! Cannot open the Update Code file specified.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 759:
MessageBox.Show("Error! The file specified is not a valid Update Code file.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 762:
case 763:
case 764:
MessageBox.Show("Error! Update Code is not in a correct format / update code file is corrupt.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 765:
MessageBox.Show("Error! The Update Code does not match any dongle attached to your machine.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 766:
MessageBox.Show("Error! The update number for this Update Code is too high. You need to first enter an update code that was previously sent to you.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 767:
MessageBox.Show("Error! You have already entered this Update Code.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 1905:
MessageBox.Show("Error! There is no Software Key available for download.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 1907:
MessageBox.Show("Error! The Temporary Software Key has expired. Cannot download it.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 1910:
MessageBox.Show("Error! The Software Key has already been downloaded.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 1921:
MessageBox.Show("Error! You specified the 'default model' but there is more than one model available. You need to specify a specific dongle model.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 1922:
MessageBox.Show("Error! The model you requested is not available.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 1923:
MessageBox.Show("Error! The Demo Software Key Template has been disabled.", AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 1924:
MessageBox(NULL, "Error! You have run out of Demo Software Key activations. You need to order some more.", g_szAppName, MB_OK);
break;
default:
MessageBox.Show(String.Format("An error occurred updating the dongle.\nError: {0}, Extended Error: {1}", ret_code, extended_error), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
}
return;
}
}
}

View File

@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="$this.Name">
<value>Form1</value>
</data>
</root>

View File

@@ -0,0 +1,64 @@
ChangeTest - sample code to call DinkeyChange Module in C#
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is written in Visual Studio 2003 but will work in more recent versions of
Visual Studio (they will upgrade the Project to the latest version. If prompted you
should also upgrade the .NET framework the project requires).
For users of Visual Studio 2005 or higher, the default setting to projects is to compile
for the Target Platform "Any". This means that on 32-bit Windows, your code will run as
32-bit code (and needs to call DinkeyChange.dll) and under 64-bit Windows your code will
run as 64-bit code (and needs to call DinkeyChange64.dll). The sample code works this out
automatically. If you select the target platform as "x86" then it will always be 32-bit
and so you only need to use DinkeyChange.dll. If you select "x64" then your code will be
64-bit and you only need to use DinkeyChange64.dll.
The main source files in the project are:
DinkeyChange.cs - the source file contains declarations of our API. We automatically
work out whether your code is running in 32-bit or 64-bit and load the
appropriate DinkeyChange module.
Form1.cs - this is the sample code giving an example on how you can call our API.
It contains 7 functions. Just use which ever functions are most appropriate
and customise in your own way.
The best approach is to compile the sample code and see how it works and then to take the
appropriate code and apply it to your own project. You should include the DinkeyChange.cs
file in your project and use/modify which ever functions from Form1.cs you feel are
appropriate. The DinkeyChange.cs file should not be modified.
The sample code is just a guide. As none of the parameters are security sensitive then
there is no need to implement strong security in calling DinkeyChange.
Make sure you remember to do the following when creating your own project:
1) Insert the DinkeyChange.cs file in your project.
2) You need to put DinkeyChange.dll and/or DinkeyChange64.dll into the folder that
contains your EXE file. Otherwise the System.DllNotFoundException error will appear
when you run ChangeTest.
You can rename DinkeyChange.dll (DinkeyChange64.dll) to a name of your choice. In this
case you will need to modify the dll names specified in the DinkeyChange.cs file.
Notes on Debugging 64-bit Code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you use the 64-bit module (DinkeyChange64.dll) the anti-debug code is so strong that
if you are debugging your code, after calling our API then it will crash with an SEH
exception. If you want to be able to debug your code then you can setup your project so
that your code calls the debug module (DinkeyChange64Debug.dll) in your "debug" build and
the standard module (DinkeyChange64.dll) in your release build. In this case you will
need to modify the declarations of our API in DinkeyChange.cs. This is an example for
DCDoUpdateCodeFromFile64:
class DCDoUpdateCodeFromFile64
{
#if DEBUG ' debug module
[DllImport("DinkeyChange64Debug.dll", CharSet = CharSet.Ansi)]
public static extern int DCDoUpdateCodeFromFile(string update_code_file, out int confirmation_code, out int extended_error);
#else ' standard module
[DllImport("DinkeyChange64.dll", CharSet = CharSet.Ansi)]
public static extern int DCDoUpdateCodeFromFile(string update_code_file, out int confirmation_code, out int extended_error);
#endif
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,58 @@
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]

View File

@@ -0,0 +1,214 @@
// !! We strongly recommend that you read the "readme.txt" file in the sample code folder.
// !! It contains important instructions on how to use the sample code
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO; // for file I/O
using System.Runtime.InteropServices; // so we can marshal our structures in drpf.cs
namespace drpfTest
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox drpfFile;
private System.Windows.Forms.Button updatecode;
private System.Windows.Forms.Button updatecodeMod;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public string AppName = "drpfTest";
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.drpfFile = new System.Windows.Forms.TextBox();
this.updatecode = new System.Windows.Forms.Button();
this.updatecodeMod = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(440, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Full path of drpf file:";
//
// drpfFile
//
this.drpfFile.Location = new System.Drawing.Point(16, 40);
this.drpfFile.Name = "drpfFile";
this.drpfFile.Size = new System.Drawing.Size(424, 20);
this.drpfFile.TabIndex = 1;
this.drpfFile.Text = "";
//
// updatecode
//
this.updatecode.Location = new System.Drawing.Point(96, 88);
this.updatecode.Name = "updatecode";
this.updatecode.Size = new System.Drawing.Size(264, 23);
this.updatecode.TabIndex = 2;
this.updatecode.Text = "Generate Update Code";
this.updatecode.Click += new System.EventHandler(this.updatecode_Click);
//
// updatecodeMod
//
this.updatecodeMod.Location = new System.Drawing.Point(96, 128);
this.updatecodeMod.Name = "updatecodeMod";
this.updatecodeMod.Size = new System.Drawing.Size(264, 23);
this.updatecodeMod.TabIndex = 3;
this.updatecodeMod.Text = "Generate Update Code with modifications ";
this.updatecodeMod.Click += new System.EventHandler(this.updatecodeMod_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(456, 174);
this.Controls.Add(this.updatecodeMod);
this.Controls.Add(this.updatecode);
this.Controls.Add(this.drpfFile);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
/* The sample code contains 2 functions. Use which ever functions are most appropriate and customise
in your own way. The sample code is just a guide.
There are two methods to loading a DRPF file. These are shown in the these two functions
updatecode_Click and updatecodeMod_Click:
updatecode_Click: we load the DRPF file from disk and get a handle and use it "as is" using the API
call LoadDRPFFromFile. You can make some limited changes to overwrite the default
behaviour by using API flags.
updatecodeMod_Click: we load the DRPF file from disk and load into structures. We can then modify the
DRPF settings by modifying this structure. This method uses the API calls
ReadDRPFEx and LoadDRPF.
*/
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void updatecode_Click(object sender, System.EventArgs e)
{
IntPtr drpfHandle;
int err_code;
UPDATE_CODE_OUTPUTS Outputs = new UPDATE_CODE_OUTPUTS();
// load DRPF from File into memory
drpfHandle = DinkeyRemote.LoadDRPFFromFile(drpfFile.Text, out err_code);
if (drpfHandle == IntPtr.Zero)
{
MessageBox.Show(DinkeyRemote.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// generate update code as specified by the DRPF file
err_code = DinkeyRemote.GenerateUpdateCode(drpfHandle, 0, 0, null, null, out Outputs);
// Unload DRPF from memory
DinkeyRemote.UnloadDRPF(ref drpfHandle);
// display message (error or success)
MessageBox.Show(DinkeyRemote.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void updatecodeMod_Click(object sender, System.EventArgs e)
{
IntPtr drpfHandle;
int dummy1, dummy2, err_code;
REMOTEINFO RemoteInfo;
LICENCEINFO[] LicenceInfo;
ALGCHANGE[] AlgChanges;
DATACHANGE[] DataChanges;
UPDATE_CODE_OUTPUTS Outputs = new UPDATE_CODE_OUTPUTS();
// in this case we need to read the DRPF into our structures, so that the DRPF values can be modified
err_code = DinkeyRemote.ReadDRPFEx(drpfFile.Text, out RemoteInfo, out LicenceInfo, out AlgChanges, out DataChanges, out dummy1, out dummy2);
if (err_code != 0)
{
MessageBox.Show(DinkeyRemote.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// patch new values in the RemoteInfo, LicenceInfo, AlgChanges, DataChanges structures
LicenceInfo[0].FeaturesFlag = 1; // so that the features value below will be recognised
LicenceInfo[0].Features = 12345;
LicenceInfo[0].AddSetExecs = 1; // so the executions will be added to existing
LicenceInfo[0].Execs = 100;
// get DRPF handle
drpfHandle = DinkeyRemote.LoadDRPF(RemoteInfo, LicenceInfo, AlgChanges, DataChanges, out err_code);
if (drpfHandle == IntPtr.Zero)
{
MessageBox.Show(DinkeyRemote.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// generate update code as specified by the modified DRPF file
err_code = DinkeyRemote.GenerateUpdateCode(drpfHandle, 0, 0, null, null, out Outputs);
// Unload DRPF from memory
DinkeyRemote.UnloadDRPF(ref drpfHandle);
// display message (error or success)
MessageBox.Show(DinkeyRemote.GetLastMessage(), AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
}

View File

@@ -0,0 +1,166 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used forserialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="label1.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="label1.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="label1.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="drpfFile.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="drpfFile.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="drpfFile.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="updatecode.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="updatecode.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="updatecode.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="updatecodeMod.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="updatecodeMod.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="updatecodeMod.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="$this.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.Name">
<value>Form1</value>
</data>
<data name="$this.Language" type="System.Globalization.CultureInfo, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>(Default)</value>
</data>
<data name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.Localizable" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.GridSize" type="System.Drawing.Size, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>8, 8</value>
</data>
<data name="$this.DrawGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</data>
<data name="$this.TrayHeight" type="System.Int32, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>80</value>
</data>
<data name="$this.SnapToGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</data>
<data name="$this.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
</root>

View File

@@ -0,0 +1,50 @@
drpfTest - sample code to call DinkeyRemote Module in C#
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is written in Visual Studio 2002 but will work in more recent
versions of Visual Studio (they will upgrade the Project to the latest version.
If prompted you should also upgrade the .NET framework the project requires).
For users of Visual Studio 2005 or higher, the default setting to projects is to
compile for the Target Platform "Any". This means that on 32-bit Windows, your
code will run as 32-bit code (and needs to call DinkeyRemote32.dll) and under 64-bit
Windows your code will run as 64-bit code (and needs to call DinkeyRemote64.dll).
The sample code works this out automatically. If you select the target platform as "x86"
then it will always be 32-bit and so you only need to use DinkeyRemote32.dll. If you
select "x64" then your code will be 64-bit and you only need to use DinkeyRemote64.dll.
The main source files in the project are:
drpf.cs - the source file contains declarations of our API. We automatically
work out whether your code is running in 32-bit or 64-bit and load
the appropriate DinkeyRemote module.
Form1.cs - this is the sample code giving an example on how you can call our API.
It contains 2 functions. Just use the function most appropriate for you
and customise in your own way.
The best approach is to compile the sample code and see how it works and then to take
the appropriate code and apply it to your own project. You should include the drpf.cs
file in your project and use/modify which ever functions from Form1.cs you feel are
appropriate. The drpf.cs file should not be modified.
The sample code is just a guide. As none of the parameters are security sensitive then
there is no need to implement strong security in calling DinkeyRemote.
Make sure you remember to do the following when creating your own project:
1) Insert the following namespaces in your code file:
using System.Runtime.InteropServices;
2) Insert the drpf.cs file in your project.
3) You need to put DinkeyRemote32.dll and/or DinkeyRemote64.dll into the folder that
contains drpfTest. Otherwise the System.DllNotFoundException error will appear
when you run drpfTest.
Notes on Debugging 64-bit Code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you use the 64-bit module (DinkeyRemote64.dll) the anti-debug code is so strong
that if you are debugging your code, after calling our API then it will crash with
an SEH exception. There are no debug modules for DinkeyRemote so you will have to
find other ways of debugging your code (for example taking out the call altogether).

View File

@@ -0,0 +1,385 @@
// !! this file should not be modified
// DRPF file is in the following format:
// REMOTEINFO
// LICENCEINFO (however many are needed)
// ALGCHANGE (however many are needed)
// DATACHANGE (however many are needed) - may refer to external files.
// Remember: you only need to specify a value if you want to change it. Otherwise you
// specify the default "no change" setting. For most entries this is indicated by 0.
// However, for MaxNetUsers and LicenceNetUsers it is "-2" because 0 is a valid value to change to.
using System;
using System.Runtime.InteropServices; // so we can marshal the structures as a block of memory
using System.Text; // for StringBuilder class for GetLastMessage API
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct REMOTEINFO
{
public byte Header1; // Should be set to "DRPF" = DinkeyRemote Parameter File
public byte Header2;
public byte Header3;
public byte Header4;
public int Version; // version of this structure - currently 2
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=12)]
public string ProdCode; // Product Code
public uint DongleNumber;
public int UpdateNumber;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string Notes; // user-defined notes
public int NumLicences;
public int NumAlgs; // number of algs to set (incl r/w alg)
public int NumDataChanges; // number of data change blocks specified
public int DataAreaSize; // -1 = increase as necessary. specifies the new size of the data area
public int PerLicence; // 0 = no change, 1 = per licence net users, 2 = per product net users
public int MaxNetUsers; // product net users, unlimited = -1, no change = -2
public int LastUsedDay; // Day = 0 (only) -> no change
public int LastUsedMonth;
public int LastUsedYear;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=12)]
public string DataEncKeyProdCode;
public int ChangeCodeType; // 0 = no change, bit0 = only accept secure codes, bit1 = accept secure & short codes
public int CodeType; // type of code to generate. 0 = secure code, 1 = short code
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string OutputFileName; // name of file to output code to. Null (default) -> UpdateCode.ducf
public int LockDongle; // 1 = lock dongle to user's computer
public int ResetDongleLock; // 1 = reset the dongle lock so that the dongle can be locked to a new machine
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct LICENCEINFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string LicenceName; // name of the licence
public int Action; // 0 = change, 1 = delete, 2 = add
public int AddSetExecs; // 0 = no change to execs, 1 = add, 2 = set
public int Execs; // -1 = no limit
public int ExecsWarn; // 0 = remove warning, -1 = no change
public int ExpiryDay; // -1 = no limit, 0 = no change
public int ExpiryMonth;
public int ExpiryYear;
public int AddSetMaxDays; // 0 = no change, 1 = add, 2 = set
public int MaxDays; // -1 = no limit
public int DaysWarn; // 0 = remove warning, -1 = no change
public int FeaturesFlag; // 0 = don't change features, 1 = change features
public uint Features; // all values OK
public int LicenceNetUsers; // unlimited = -1, no change = -2
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct ALGCHANGE
{
public int alg_number; // number of algorithm to set (0 = r/w algorithm)
[MarshalAs(UnmanagedType.ByValArray, SizeConst=12)]
public byte[] alg; // algorithm
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct DATACHANGE
{
public int type; // 1 = file, 2 = hex data, 3 = ascii, 4 = ascii null-term string
public int offset; // offset in dongle data memory to write data
public int length; // length of data to change
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)]
public byte[] data; // data to write OR name of data file depending on which method set
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct UPDATE_CODE_OUTPUTS
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=128*3)]
public string ShortCode; // the update code (for short update codes only)
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string UpdateCodeFile; // the output ducf that contains the update code
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=8)]
public string ConfirmationCode; // the confirmation code
}
// ********************** API functions ************************
// we declare classes for all the API functions for each bitness
// Loads DRPF from disk and returns handle
class LoadDRPFFromFile32
{
[DllImport("DinkeyRemote32.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr LoadDRPFFromFile(string drpf_file, out int err_code);
}
class LoadDRPFFromFile64
{
[DllImport("DinkeyRemote64.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr LoadDRPFFromFile(string drpf_file, out int err_code);
}
// Loads DRPF from disk into structures supplied (so we can modify DRPF in memory)
class ReadDRPFEx32
{
[DllImport("DinkeyRemote32.dll", CharSet = CharSet.Ansi)]
public static extern int ReadDRPFEx(string drpf_file, out REMOTEINFO RemoteInfo, byte[] licence_bytes, byte[] algchange_bytes, byte[] datachange_bytes, out int drpf_version, out int drpf_format);
}
class ReadDRPFEx64
{
[DllImport("DinkeyRemote64.dll", CharSet = CharSet.Ansi)]
public static extern int ReadDRPFEx(string drpf_file, out REMOTEINFO RemoteInfo, byte[] licence_bytes, byte[] algchange_bytes, byte[] datachange_bytes, out int drpf_version, out int drpf_format);
}
// Loads DRPF from structures and returns a handle
class LoadDRPF32
{
[DllImport("DinkeyRemote32.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr LoadDRPF(ref REMOTEINFO RemoteInfo, byte[] licence_bytes, byte[] algchange_bytes, byte[] datachange_bytes, out int ret_code);
}
class LoadDRPF64
{
[DllImport("DinkeyRemote64.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr LoadDRPF(ref REMOTEINFO RemoteInfo, byte[] licence_bytes, byte[] algchange_bytes, byte[] datachange_bytes, out int ret_code);
}
// saves the DRPF file to disk
class WriteDRPFEx32
{
[DllImport("DinkeyRemote32.dll", CharSet = CharSet.Ansi)]
public static extern int WriteDRPFEx(IntPtr drpf_handle, string drpf_file, int drpf_format, int drpf_version, int flags);
}
class WriteDRPFEx64
{
[DllImport("DinkeyRemote64.dll", CharSet = CharSet.Ansi)]
public static extern int WriteDRPFEx(IntPtr drpf_handle, string drpf_file, int drpf_format, int drpf_version, int flags);
}
// unloads the DRPF file
class UnloadDRPF32
{
[DllImport("DinkeyRemote32.dll", CharSet = CharSet.Ansi)]
public static extern void UnloadDRPF(ref IntPtr drpf_handle);
}
class UnloadDRPF64
{
[DllImport("DinkeyRemote64.dll", CharSet = CharSet.Ansi)]
public static extern void UnloadDRPF(ref IntPtr drpf_handle);
}
class GenerateUpdateCode32
{
[DllImport("DinkeyRemote32.dll", CharSet = CharSet.Ansi)]
public static extern int GenerateUpdateCode(IntPtr drpf_handle, uint dongle_number, int update_number, string ducf_file, string logfile, out UPDATE_CODE_OUTPUTS Outputs);
}
class GenerateUpdateCode64
{
[DllImport("DinkeyRemote64.dll", CharSet = CharSet.Ansi)]
public static extern int GenerateUpdateCode(IntPtr drpf_handle, uint dongle_number, int update_number, string ducf_file, string logfile, out UPDATE_CODE_OUTPUTS Outputs);
}
class GetLastMessage32
{
[DllImport("DinkeyRemote32.dll", CharSet = CharSet.Ansi)]
public static extern void GetLastMessage(StringBuilder message, int buffer_size, out int message_length);
}
class GetLastMessage64
{
[DllImport("DinkeyRemote64.dll", CharSet = CharSet.Ansi)]
public static extern void GetLastMessage(StringBuilder message, int buffer_size, out int message_length);
}
class GetLastExtendedError32
{
[DllImport("DinkeyRemote32.dll", CharSet = CharSet.Ansi)]
public static extern int GetLastExtendedError();
}
class GetLastExtendedError64
{
[DllImport("DinkeyRemote64.dll", CharSet = CharSet.Ansi)]
public static extern int GetLastExtendedError();
}
// ********************* DinkeyRemote class **********************
class DinkeyRemote
{
// constants
public const int DRPF_VERSION = 2; // current DRPF version
// WriteDRPFEx API flags
public const int FLAGS_LOSE_FEATURES = 1; // means that you can save the DRPF file to an earlier version even if it means losing some new features that have been currently set
// constants for drpf_format in ReadDRPFEx and WriteDRPFEx functions
public const int DRPF_FORMAT_BINARY = 1;
public const int DRPF_FORMAT_JSON = 2;
public const int DRPF_FORMAT_JSON_MIN = 3; // this value is only used with WriteDRPFEx. ReadDRPFEx cannot return this value.
// private constants
private const int MAX_LICENCES = 255; // max number of licence changes in a DRPF file (theoretically unlimited but easier if we limit it)
private const int MAX_ALG_CHANGES = 21; // max number of alg changes in DRPF file
private const int MAX_DATA_CHANGES = 127; // max number of data area changes in DRPF file
// **** main API
// We only want to load the correct DLL for the bit-ness of the computer. The other DLL may not exist.
// if the appropriate DLL does not exist in the same directory as this test program you will receive a DllNotFoundException
public static IntPtr LoadDRPFFromFile(string drpf_file, out int err_code)
{
if (IntPtr.Size == 4)
return LoadDRPFFromFile32.LoadDRPFFromFile(drpf_file, out err_code);
return LoadDRPFFromFile64.LoadDRPFFromFile(drpf_file, out err_code);
}
// we have to do some marshalling of arrays of bytes into arrays of structures
public static int ReadDRPFEx(string drpf_file, out REMOTEINFO RemoteInfo, out LICENCEINFO[] LicenceInfo, out ALGCHANGE[] AlgChanges, out DATACHANGE[] DataChanges, out int drpf_version, out int drpf_format)
{
int ret_code, i;
byte[] licence_bytes = new byte[MAX_LICENCES * Marshal.SizeOf(typeof(LICENCEINFO))];
byte[] licence_bytes_one_struct = new byte[Marshal.SizeOf(typeof(LICENCEINFO))];
byte[] algchange_bytes = new byte[MAX_ALG_CHANGES * Marshal.SizeOf(typeof(ALGCHANGE))];
byte[] algchange_bytes_one_struct = new byte[Marshal.SizeOf(typeof(ALGCHANGE))];
byte[] datachange_bytes = new byte[MAX_DATA_CHANGES * Marshal.SizeOf(typeof(DATACHANGE))];
byte[] datachange_bytes_one_struct = new byte[Marshal.SizeOf(typeof(DATACHANGE))];
GCHandle MyGC;
RemoteInfo = new REMOTEINFO();
LicenceInfo = null;
AlgChanges = null;
DataChanges = null;
if (IntPtr.Size == 4)
ret_code = ReadDRPFEx32.ReadDRPFEx(drpf_file, out RemoteInfo, licence_bytes, algchange_bytes, datachange_bytes, out drpf_version, out drpf_format);
else
ret_code = ReadDRPFEx64.ReadDRPFEx(drpf_file, out RemoteInfo, licence_bytes, algchange_bytes, datachange_bytes, out drpf_version, out drpf_format);
if (ret_code != 0)
return ret_code;
// convert byte array to an array of structs
LicenceInfo = new LICENCEINFO[RemoteInfo.NumLicences];
for (i=0; i<RemoteInfo.NumLicences; i++)
{
Array.Copy(licence_bytes, i*Marshal.SizeOf(typeof(LICENCEINFO)), licence_bytes_one_struct, 0, Marshal.SizeOf(typeof(LICENCEINFO)));
MyGC = GCHandle.Alloc(licence_bytes_one_struct, GCHandleType.Pinned);
LicenceInfo[i] = (LICENCEINFO)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(LICENCEINFO));
MyGC.Free();
}
AlgChanges = new ALGCHANGE[RemoteInfo.NumAlgs];
for (i=0; i<RemoteInfo.NumAlgs; i++)
{
Array.Copy(algchange_bytes, i*Marshal.SizeOf(typeof(ALGCHANGE)), algchange_bytes_one_struct, 0, Marshal.SizeOf(typeof(ALGCHANGE)));
MyGC = GCHandle.Alloc(algchange_bytes_one_struct, GCHandleType.Pinned);
AlgChanges[i] = (ALGCHANGE)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(ALGCHANGE));
MyGC.Free();
}
DataChanges = new DATACHANGE[RemoteInfo.NumDataChanges];
for (i=0; i<RemoteInfo.NumDataChanges; i++)
{
Array.Copy(datachange_bytes, i*Marshal.SizeOf(typeof(DATACHANGE)), datachange_bytes_one_struct, 0, Marshal.SizeOf(typeof(DATACHANGE)));
MyGC = GCHandle.Alloc(datachange_bytes_one_struct, GCHandleType.Pinned);
DataChanges[i] = (DATACHANGE)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(DATACHANGE));
MyGC.Free();
}
return ret_code;
}
// we have to do some marshalling of an array of structures into an array of bytes
public static IntPtr LoadDRPF(REMOTEINFO RemoteInfo, LICENCEINFO[] LicenceInfo, ALGCHANGE[] AlgChanges, DATACHANGE[] DataChanges, out int ret_code)
{
int i;
byte[] licence_bytes = new byte[MAX_LICENCES * Marshal.SizeOf(typeof(LICENCEINFO))];
byte[] licence_bytes_one_struct = new byte[Marshal.SizeOf(typeof(LICENCEINFO))];
byte[] algchange_bytes = new byte[MAX_ALG_CHANGES * Marshal.SizeOf(typeof(ALGCHANGE))];
byte[] algchange_bytes_one_struct = new byte[Marshal.SizeOf(typeof(ALGCHANGE))];
byte[] datachange_bytes = new byte[MAX_DATA_CHANGES * Marshal.SizeOf(typeof(DATACHANGE))];
byte[] datachange_bytes_one_struct = new byte[Marshal.SizeOf(typeof(DATACHANGE))];
GCHandle MyGC;
// convert array of structs to a byte array
for (i=0; i<RemoteInfo.NumLicences; i++)
{
MyGC = GCHandle.Alloc(licence_bytes_one_struct, GCHandleType.Pinned);
Marshal.StructureToPtr(LicenceInfo[i], MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
Array.Copy(licence_bytes_one_struct, 0, licence_bytes, i*Marshal.SizeOf(typeof(LICENCEINFO)), Marshal.SizeOf(typeof(LICENCEINFO)));
}
for (i=0; i<RemoteInfo.NumAlgs; i++)
{
MyGC = GCHandle.Alloc(algchange_bytes_one_struct, GCHandleType.Pinned);
Marshal.StructureToPtr(AlgChanges[i], MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
Array.Copy(algchange_bytes_one_struct, 0, algchange_bytes, i*Marshal.SizeOf(typeof(ALGCHANGE)), Marshal.SizeOf(typeof(ALGCHANGE)));
}
for (i=0; i<RemoteInfo.NumDataChanges; i++)
{
MyGC = GCHandle.Alloc(datachange_bytes_one_struct, GCHandleType.Pinned);
Marshal.StructureToPtr(DataChanges[i], MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
Array.Copy(datachange_bytes_one_struct, 0, datachange_bytes, i*Marshal.SizeOf(typeof(DATACHANGE)), Marshal.SizeOf(typeof(DATACHANGE)));
}
if (IntPtr.Size == 4)
return LoadDRPF32.LoadDRPF(ref RemoteInfo, licence_bytes, algchange_bytes, datachange_bytes, out ret_code);
return LoadDRPF64.LoadDRPF(ref RemoteInfo, licence_bytes, algchange_bytes, datachange_bytes, out ret_code);
}
// we have to do some marshalling of an array of structures into an array of bytes
public static int WriteDRPFEx(IntPtr drpf_handle, string drpf_file, int drpf_format, int drpf_version, int flags)
{
if (IntPtr.Size == 4)
return WriteDRPFEx32.WriteDRPFEx(drpf_handle, drpf_file, drpf_format, drpf_version, flags);
return WriteDRPFEx64.WriteDRPFEx(drpf_handle, drpf_file, drpf_format, drpf_version, flags);
}
public static void UnloadDRPF(ref IntPtr drpf_handle)
{
if (IntPtr.Size == 4)
UnloadDRPF32.UnloadDRPF(ref drpf_handle);
else
UnloadDRPF64.UnloadDRPF(ref drpf_handle);
return;
}
public static int GenerateUpdateCode(IntPtr drpf_handle, uint dongle_number, int update_number, string ducf_file, string logfile, out UPDATE_CODE_OUTPUTS Outputs)
{
if (IntPtr.Size == 4)
return GenerateUpdateCode32.GenerateUpdateCode(drpf_handle, dongle_number, update_number, ducf_file, logfile, out Outputs);
return GenerateUpdateCode64.GenerateUpdateCode(drpf_handle, dongle_number, update_number, ducf_file, logfile, out Outputs);
}
// do a bit of work here to make the function easier to use for C#
public static string GetLastMessage()
{
int length, dummy;
StringBuilder message;
if (IntPtr.Size == 4)
{
GetLastMessage32.GetLastMessage(null, 0, out length);
message = new StringBuilder(length);
GetLastMessage32.GetLastMessage(message, length, out dummy);
}
else
{
GetLastMessage64.GetLastMessage(null, 0, out length);
message = new StringBuilder(length);
GetLastMessage64.GetLastMessage(message, length, out dummy);
}
return message.ToString();
}
public static int GetLastExtendedError()
{
if (IntPtr.Size == 4)
return GetLastExtendedError32.GetLastExtendedError();
return GetLastExtendedError64.GetLastExtendedError();
}
}

View File

@@ -0,0 +1,121 @@
<VisualStudioProject>
<CSHARP
ProjectType = "Local"
ProductVersion = "7.0.9466"
SchemaVersion = "1.0"
ProjectGuid = "{7C474B2E-28FA-4821-8FF0-FD2181A0B242}"
>
<Build>
<Settings
ApplicationIcon = "App.ico"
AssemblyKeyContainerName = ""
AssemblyName = "drpfTest"
AssemblyOriginatorKeyFile = ""
DefaultClientScript = "JScript"
DefaultHTMLPageLayout = "Grid"
DefaultTargetSchema = "IE50"
DelaySign = "false"
OutputType = "WinExe"
RootNamespace = "drpfTest"
StartupObject = ""
>
<Config
Name = "Debug"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "DEBUG;TRACE"
DocumentationFile = ""
DebugSymbols = "true"
FileAlignment = "4096"
IncrementalBuild = "true"
Optimize = "false"
OutputPath = "bin\Debug\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
<Config
Name = "Release"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "TRACE"
DocumentationFile = ""
DebugSymbols = "false"
FileAlignment = "4096"
IncrementalBuild = "false"
Optimize = "true"
OutputPath = "bin\Release\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
</Settings>
<References>
<Reference
Name = "System"
AssemblyName = "System"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.dll"
/>
<Reference
Name = "System.Data"
AssemblyName = "System.Data"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.Data.dll"
/>
<Reference
Name = "System.Drawing"
AssemblyName = "System.Drawing"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.Drawing.dll"
/>
<Reference
Name = "System.Windows.Forms"
AssemblyName = "System.Windows.Forms"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.Windows.Forms.dll"
/>
<Reference
Name = "System.XML"
AssemblyName = "System.Xml"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\System.XML.dll"
/>
</References>
</Build>
<Files>
<Include>
<File
RelPath = "App.ico"
BuildAction = "Content"
/>
<File
RelPath = "AssemblyInfo.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "drpf.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "Form1.cs"
SubType = "Form"
BuildAction = "Compile"
/>
<File
RelPath = "Form1.resx"
DependentUpon = "Form1.cs"
BuildAction = "EmbeddedResource"
/>
<File
RelPath = "readme.txt"
BuildAction = "Content"
/>
</Include>
</Files>
</CSHARP>
</VisualStudioProject>

View File

@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 7.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "drpfTest", "drpfTest.csproj", "{7C474B2E-28FA-4821-8FF0-FD2181A0B242}"
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
ConfigName.0 = Debug
ConfigName.1 = Release
EndGlobalSection
GlobalSection(ProjectDependencies) = postSolution
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{7C474B2E-28FA-4821-8FF0-FD2181A0B242}.Debug.ActiveCfg = Debug|.NET
{7C474B2E-28FA-4821-8FF0-FD2181A0B242}.Debug.Build.0 = Debug|.NET
{7C474B2E-28FA-4821-8FF0-FD2181A0B242}.Release.ActiveCfg = Release|.NET
{7C474B2E-28FA-4821-8FF0-FD2181A0B242}.Release.Build.0 = Release|.NET
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,58 @@
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]

View File

@@ -0,0 +1,120 @@
<VisualStudioProject>
<CSHARP
ProjectType = "Local"
ProductVersion = "7.0.9466"
SchemaVersion = "1.0"
ProjectGuid = "{8199C796-57A5-4EA6-B0E0-41022918FCC2}"
>
<Build>
<Settings
ApplicationIcon = "App.ico"
AssemblyKeyContainerName = ""
AssemblyName = "DllTest"
AssemblyOriginatorKeyFile = ""
DefaultClientScript = "JScript"
DefaultHTMLPageLayout = "Grid"
DefaultTargetSchema = "IE50"
DelaySign = "false"
OutputType = "WinExe"
RootNamespace = "DllTest"
StartupObject = ""
>
<Config
Name = "Debug"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "DEBUG;TRACE"
DocumentationFile = ""
DebugSymbols = "true"
FileAlignment = "4096"
IncrementalBuild = "true"
Optimize = "false"
OutputPath = "bin\Debug\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
<Config
Name = "Release"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "TRACE"
DocumentationFile = ""
DebugSymbols = "false"
FileAlignment = "4096"
IncrementalBuild = "false"
Optimize = "true"
OutputPath = "bin\Release\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
</Settings>
<References>
<Reference
Name = "System"
AssemblyName = "System"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.dll"
/>
<Reference
Name = "System.Data"
AssemblyName = "System.Data"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.Data.dll"
/>
<Reference
Name = "System.Drawing"
AssemblyName = "System.Drawing"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.Drawing.dll"
/>
<Reference
Name = "System.Windows.Forms"
AssemblyName = "System.Windows.Forms"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.Windows.Forms.dll"
/>
<Reference
Name = "System.XML"
AssemblyName = "System.Xml"
HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.0.3705\System.XML.dll"
/>
</References>
</Build>
<Files>
<Include>
<File
RelPath = "App.ico"
BuildAction = "Content"
/>
<File
RelPath = "AssemblyInfo.cs"
BuildAction = "Compile"
/>
<File
RelPath = "dris.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "Form1.cs"
SubType = "Form"
BuildAction = "Compile"
/>
<File
RelPath = "Form1.resx"
DependentUpon = "Form1.cs"
BuildAction = "EmbeddedResource"
/>
<File
RelPath = "readme.txt"
BuildAction = "Content"
/>
</Include>
</Files>
</CSHARP>
</VisualStudioProject>

View File

@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 7.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DllTest", "DllTest.csproj", "{8199C796-57A5-4EA6-B0E0-41022918FCC2}"
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
ConfigName.0 = Debug
ConfigName.1 = Release
EndGlobalSection
GlobalSection(ProjectDependencies) = postSolution
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{8199C796-57A5-4EA6-B0E0-41022918FCC2}.Debug.ActiveCfg = Debug|.NET
{8199C796-57A5-4EA6-B0E0-41022918FCC2}.Debug.Build.0 = Debug|.NET
{8199C796-57A5-4EA6-B0E0-41022918FCC2}.Release.ActiveCfg = Release|.NET
{8199C796-57A5-4EA6-B0E0-41022918FCC2}.Release.Build.0 = Release|.NET
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,874 @@
// !! We strongly recommend that you read the "readme.txt" file in the sample code folder.
// !! It contains important instructions on how to use the sample code
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace DllTest
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(72, 72);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(160, 40);
this.label1.TabIndex = 0;
this.label1.Text = "It Worked!";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(296, 205);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label1});
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
public const int MY_SDSN = 10101; // !!!! change this value to be the value of your SDSN (demo = 10101)
public const string MY_PRODCODE = "DEMO"; // !!!! change this value to match the Product Code in the dongle
/// <summary>
/// The main entry point for the application.
/// </summary>
/* The sample code contains 11 functions. You will not need to use all these
functions in your code. Just use which ever functions are most appropriate
and customise in your own way. The sample code is just a guide. You should
implement the protection in a stronger way using the techniques described in
the "Increasing your Protection" chapter of the manual.
ProtCheck // a standard protection check
ProtCheckWithAlg // a protection check & executing an Algorithm
WriteBytes // a protection check & write data to the dongle
ReadBytes // a protection check & read data from the dongle
EncryptUserData // a protection check & encrypting data and then decrypting the data
// these functions are the same as the functions listed above but encrypting all parameters passed to our API
ProtCheckEnc // a standard protection check
ProtCheckWithAlgEnc // a protection check & executing an Algorithm
WriteBytesEnc // a protection check & write data to the dongle
ReadBytesEnc // a protection check & read data from the dongle
EncryptUserDataEnc // a protection check & encrypting data and then decrypting the data
// this function displays the current network users
DisplayNetUsers
If you are using Dinkey Lite then you can only use 4 functions:
ProtCheck, ProtCheckWithAlg, ProtCheckEnc, ProtCheckWithAlgEnc
*/
[STAThread]
static void Main()
{
// call the function(s) of your choice here
// in this example I have chosen a standard protection check
if (ProtCheck() != 0)
return; // check fails - exit program
Application.Run(new Form1());
}
// ************************* our 10 functions follow *************************
// **************************** ProtCheck *********************************
// standard protection check
public static int ProtCheck()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.PROTECTION_CHECK; // standard protection check
dris.flags = 0; // no extra flags, but you may want to specify some if you want to start a network user or decrement execs,...
ret_code = DinkeyPro.DDProtCheck(dris, null);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
if (dris.prodcode != MY_PRODCODE)
{
MessageBox.Show("Incorrect Product Code! Please modify your source code so that MY_PRODCODE is set to be the Product Code in the dongle.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// if you are using a network dongle and you want to list the network users then use this function:
// DisplayNetUsers(dris);
return 0;
}
// **************************** ProtCheckWithAlg ****************************
// !!!! You should replace this function with the one generated by the
// "generate source code" button in Algorithm tab for DinkeyAdd (if you have specified an algorithm)
// or from DinkeyLook if you are using a Dinkey Lite dongle.
private static int MyAlgorithm(int a, int b, int c, int d, int e, int f, int g, int h)
{
return a + b + c + d + e + f + g + h;
}
// NB for this to work you must program at least "user algorithm" into the dongle
// NB We have used a very simple algorithm here (in the MyAlgorithm function). You must patch this with the
// sample code generated by DinkeyAdd for the algorithm that you are using. For Dinkey Lite copy the sample code from DinkeyLook
public static int ProtCheckWithAlg()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.EXECUTE_ALGORITHM; // standard protection check & execute algorithm
dris.flags = 0; // no extra flags, but you may want to specify some if you want to start a network user or decrement execs,...
dris.alg_number = 1; // execute algorithm 1 (you do not need to specify this field if you are only using Lite models).
// you should remove these entries if you are using Dinkey Lite so that algorithm arguments are random
dris.var_a = 1; // sample values
dris.var_b = 2;
dris.var_c = 3;
dris.var_d = 4;
dris.var_e = 5;
dris.var_f = 6;
dris.var_g = 7;
dris.var_h = 8;
ret_code = DinkeyPro.DDProtCheck(dris, null);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// if you want you can check the algorithm answer - however if algorithm is from your code then best to just use the answer in your code
// !!!! Make sure you have replaced the MyAlgorithm routine with the algorithm you have specified in DinkeyAdd
if (MyAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h) != dris.alg_answer)
{
MessageBox.Show("Dinkey protection error!\nYou have not patched your algorithm in the MyAlgorithm routine", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
return 0;
}
// ************************** WriteBytes ******************************
// This writes the Data 0,1,2,3,4,5,6,7,8,9 to the dongle data area at offset 7
// In order for this function to work you will need to have a data area in your dongle that is at least 18 bytes long.
// if you want to write a string then you need to convert it to a byte array first:
// encoding.GetBytes(your_string, 0, your_string.Length, data, 0) where encoding is of ASCIIEncoding type.
public static int WriteBytes()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] DataToWrite = {0,1,2,3,4,5,6,7,8,9};
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.WRITE_DATA_AREA; // standard protection check & write data to dongle
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_offset = 7;
dris.rw_length = DataToWrite.GetLength(0);
ret_code = DinkeyPro.DDProtCheck(dris, DataToWrite);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
return 0;
}
// ************************ ReadBytes ************************************
// This reads 10 bytes of data from offset 7 in the dongle data area
// In order for this function to work you will need to have a data area in your dongle that is at least 18 bytes long.
// if you want to read a string then you need to convert it from a byte array (via an array of char)
// CharArray = encoding.GetChars(data); where CharArray is of type char[] and encoding is of type ASCIIEncoding
// your_string = new String(CharArray, 0, your_string_length);
public static int ReadBytes()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] DataToRead = new byte[10];
string DisplayString;
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.READ_DATA_AREA; // standard protection check & read data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_offset = 7;
dris.rw_length = DataToRead.GetLength(0);
ret_code = DinkeyPro.DDProtCheck(dris, DataToRead);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
DisplayString = "Dinkey Dongle data area, offset 7: " + String.Format("{0:D2} {1:D2} {2:D2} {3:D2} {4:D2} {5:D2} {6:D2} {7:D2} {8:D2} {9:D2}",
DataToRead[0], DataToRead[1], DataToRead[2], DataToRead[3], DataToRead[4], DataToRead[5], DataToRead[6], DataToRead[7], DataToRead[8], DataToRead[9]);
MessageBox.Show(DisplayString, "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return 0;
}
// ************************** EncryptUserData ************************************
// This function will do a protection check and ask the dongle to encrypt some data using encryption key 1
// It will then do another protection check & decrypt the data
// if you want to encrypt of decrypt string then see comment for WriteBytes and ReadBytes
public static int EncryptUserData()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] Data = {0,1,2,3,4,5,6,7,8,9};
string DisplayString;
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.ENCRYPT_USER_DATA; // standard protection check & encrypt data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT;
dris.rw_length = Data.GetLength(0);
dris.data_crypt_key_num = 1;
ret_code = DinkeyPro.DDProtCheck(dris, Data);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// ... could add code to check other elements of the DRIS, e.g. ret_code, sdsn, ...
// Now decrypt the same data to get the original values
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.DECRYPT_USER_DATA; // standard protection check & read data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_length = Data.GetLength(0);
dris.data_crypt_key_num = 1;
ret_code = DinkeyPro.DDProtCheck(dris, Data);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
DisplayString = "decrypted data is: " + String.Format("{0:D2} {1:D2} {2:D2} {3:D2} {4:D2} {5:D2} {6:D2} {7:D2} {8:D2} {9:D2}",
Data[0], Data[1], Data[2], Data[3], Data[4], Data[5], Data[6], Data[7], Data[8], Data[9]);
MessageBox.Show(DisplayString, "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return 0;
}
// !!!!!!!!!!! all the functions listed below encrypt all parameters to our API !!!!!!!!!!!!!!!!!!!!!
// In order for them to work properly you need to choose "Encrypt DRIS" and "Encrypt Data passed to API"
// in the Extra Security tab of DinkeyAdd. In this example, for Data Encryption I use the r/w algorithm
// but the code can be modified easily to use the 3 encryption parameters.
// !!!! please overwrite this function with the one generated by DinkeyAdd for R/W Algorithm
private static int MyRWAlgorithm(int a, int b, int c, int d, int e, int f, int g, int h)
{
return a ^ b ^ c ^ d ^ e ^ f;
}
// !!!! please overwrite this function with the one generated by DinkeyAdd
private static void CryptDRIS(DRIS dris)
{
int i, j, k;
byte[] bigseed = new byte[256];
byte[] S = new byte[256];
byte temp, t;
byte[] dris_bytes = new byte[Marshal.SizeOf(dris)];
dris.DrisToByteArray(dris, dris_bytes); // convert DRIS to byte array so we can encrypt it
for (i=0; i<256; i+=8)
{
dris.Set4Bytes(bigseed, i, dris.seed1);
dris.Set4Bytes(bigseed, i+4, dris.seed2);
}
for (i=0; i<256; i++)
S[i] = (byte)i;
for (i=0, j=0; i<256; i++)
{
j = (j + S[i] + bigseed[i] + 123) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
}
for (i=0, j=0, k=16; k<Marshal.SizeOf(dris); k++)
{
i = (i + 1) % 256;
j = (j + S[i] + 212) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
t = (byte)(S[i] + S[j] + 97);
dris_bytes[k] ^= S[t];
}
dris.ByteArrayToDris(dris_bytes, dris); // convert it back again
return;
}
// !!!! please overwrite this function with the one generated by DinkeyAdd
private static void CryptApiData(DRIS dris, byte[] data, int length, int alg_answer)
{
int i, j, k;
byte[] bigseed = new byte[256];
byte[] S = new byte[256];
byte temp, t;
for (i=0; i<256; i+=8)
{
dris.Set4Bytes(bigseed, i, dris.seed1);
dris.Set4Bytes(bigseed, i+4, dris.seed2);
}
for (i=0; i<256; i++)
S[i] = (byte)i;
for (i=0, j=0; i<256; i++)
{
j = (j + S[i] + bigseed[i] + (alg_answer & 0xff)) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
}
for (i=0, j=0, k=0; k<length; k++)
{
i = (i + 1) % 256;
j = (j + S[i] + ((alg_answer >> 8) & 0xff)) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
t = (byte)(S[i] + S[j] + ((alg_answer >> 16) & 0xff));
data[k] ^= S[t];
}
return;
}
// **************************** ProtCheckEnc ******************************
// We encrypt the DRIS passed to the API. Patch the CryptDRIS function in this file from source code generated by DinkeyAdd.
public static int ProtCheckEnc()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.PROTECTION_CHECK; // standard protection check
dris.flags = 0; // no extra flags, but you may want to specify some if you want to start a network user or decrement execs,...
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, null);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
if (dris.prodcode != MY_PRODCODE)
{
MessageBox.Show("Incorrect Product Code! Please modify your source code so that MY_PRODCODE is set to be the Product Code in the dongle.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
return 0;
}
// **************************** ProtCheckWithAlgEnc *************************
// NB for this to work you must program at least "user algorithm" into the dongle
// NB We have used a very simple algorithm here (in the MyAlgorithm function). You must patch this with the
// sample code generated by DinkeyAdd for the algorithm that you are using. For Dinkey Lite copy source from DinkeyLook.
// We encrypt the DRIS passed to the API. Patch the CryptDRIS function in this file from source code generated by DinkeyAdd.
public static int ProtCheckWithAlgEnc()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.EXECUTE_ALGORITHM; // standard protection check & execute algorithm
dris.flags = 0; // no extra flags, but you may want to specify some if you want to start a network user or decrement execs,...
dris.alg_number = 1; // execute algorithm 1 (you do not need to specify this field if you are only using Lite models).
// you should remove these entries if you are using Dinkey Lite so that algorithm arguments are random
dris.var_a = 1; // sample values
dris.var_b = 2;
dris.var_c = 3;
dris.var_d = 4;
dris.var_e = 5;
dris.var_f = 6;
dris.var_g = 7;
dris.var_h = 8;
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, null);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// if you want you can check the algorithm answer - however if algorithm is from your code then best to just use the answer in your code
// !!!! Make sure you have replaced the MyAlgorithm routine with the algorithm you have specified in DinkeyAdd
if (MyAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h) != dris.alg_answer)
{
MessageBox.Show("Dinkey protection error!\nYou have not patched your algorithm in the MyAlgorithm routine", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
return 0;
}
// ************************** WriteBytesEnc ***************************
// This writes the Data 0,1,2,3,4,5,6,7,8,9 to the dongle data area at offset 7
// In order for this function to work you will need to have a data area in your dongle that is at least 18 bytes long.
// We encrypt the DRIS and Data passed to the API. Patch the CryptDRIS and CryptApiData functions in this file from source code generated by DinkeyAdd.
// if you want to write strings then see comment for WriteBytes
public static int WriteBytesEnc()
{
int ret_code, alg_ans;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] DataToWrite = {0,1,2,3,4,5,6,7,8,9};
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.WRITE_DATA_AREA; // standard protection check & write data to dongle
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_offset = 7;
dris.rw_length = DataToWrite.GetLength(0);
// calculate r/w algorithm answer - NB need to replace MyRWAlgorithm code with code for r/w algorithm
alg_ans = MyRWAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h);
// encrypt data we want to write.
CryptApiData(dris, DataToWrite, DataToWrite.GetLength(0), alg_ans);
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, DataToWrite);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
return 0;
}
// ************************ ReadBytesEnc *********************************
// This reads 10 bytes of data from offset 7 in the dongle data area
// In order for this function to work you will need to have a data area in your dongle that is at least 18 bytes long.
// We encrypt the DRIS and Data passed to the API. Patch the CryptDRIS and CryptApiData functions in this file from source code generated by DinkeyAdd.
// if you want to read strings then see comment for ReadBytes
public static int ReadBytesEnc()
{
int ret_code, alg_ans;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] DataRead = new byte[10];
string DisplayString;
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.READ_DATA_AREA; // standard protection check & read data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_offset = 7;
dris.rw_length = DataRead.GetLength(0);
// calculate r/w algorithm answer - NB need to replace MyRWAlgorithm code with code for r/w algorithm
alg_ans = MyRWAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h);
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, DataRead);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// decrypt data that was read.
CryptApiData(dris, DataRead, DataRead.GetLength(0), alg_ans);
DisplayString = "Dinkey Dongle data area, offset 7: " + String.Format("{0:D2} {1:D2} {2:D2} {3:D2} {4:D2} {5:D2} {6:D2} {7:D2} {8:D2} {9:D2}",
DataRead[0], DataRead[1], DataRead[2], DataRead[3], DataRead[4], DataRead[5], DataRead[6], DataRead[7], DataRead[8], DataRead[9]);
MessageBox.Show(DisplayString, "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return 0;
}
// ************************** EncryptUserDataEnc *********************************
// This function will do a protection check and ask the dongle to encrypt some data using encryption key 1
// It will then do another protection & decrypt the data
// We encrypt the DRIS and Data passed to/from the API. Patch the CryptDRIS and CryptApiData functions in this file from source code generated by DinkeyAdd.
// if you want to encrypt of decrypt strings then see comment for WriteBytes and ReadBytes
public static int EncryptUserDataEnc()
{
int ret_code, alg_ans;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
DRIS dris2 = new DRIS(); // initialise the DRIS with random values & set the header
byte[] Data = {0,1,2,3,4,5,6,7,8,9};
string DisplayString;
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.ENCRYPT_USER_DATA; // standard protection check & encrypt data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT;
dris.rw_length = Data.GetLength(0);
dris.data_crypt_key_num = 1;
// calculate r/w algorithm answer - NB need to replace MyRWAlgorithm code with code for r/w algorithm
alg_ans = MyRWAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h);
// encrypt data we pass to our API.
CryptApiData(dris, Data, Data.GetLength(0), alg_ans);
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, Data);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// ... could add code to check other elements of the DRIS, e.g. ret_code, sdsn, ...
// NB use another dris so that we can ensure elements are initialised to different random numbers
dris2.size = Marshal.SizeOf(dris2);
dris2.function = DRIS.DECRYPT_USER_DATA; // standard protection check & read data
dris2.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris2.rw_length = Data.GetLength(0);
dris2.data_crypt_key_num = 1;
CryptDRIS(dris2); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris2, Data);
CryptDRIS(dris2); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris2.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris2.sdsn != MY_SDSN)
{
MessageBox.Show("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
// later on in your program you can check the return code again
if (dris2.ret_code != 0)
{
MessageBox.Show("Dinkey Dongle protection error", "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
alg_ans = MyRWAlgorithm(dris2.var_a, dris2.var_b, dris2.var_c, dris2.var_d, dris2.var_e, dris2.var_f, dris2.var_g, dris2.var_h);
// decrypt data that was passed to us by the API.
CryptApiData(dris2, Data, Data.GetLength(0), alg_ans);
DisplayString = "decrypted data is: " + String.Format("{0:D2} {1:D2} {2:D2} {3:D2} {4:D2} {5:D2} {6:D2} {7:D2} {8:D2} {9:D2}",
Data[0], Data[1], Data[2], Data[3], Data[4], Data[5], Data[6], Data[7], Data[8], Data[9]);
MessageBox.Show(DisplayString, "DllSample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return 0;
}
// *********************** DisplayNetUsers *******************************
// This function displays the current network users (for DinkeyNet only).
// The DDProtCheck function must be called before this function is called.
// (Normally you would use DinkeyServer to view the network users but this enables you to do it from the client if you want)
public static int DisplayNetUsers(DRIS dris)
{
string DisplayString;
int num_net_users, extended_error, ret_code, i, max_net_users;
NU_INFO[] nu_info;
if (dris.net_users == -1)
max_net_users = 100; // if unlimited network users are allowed then display up to 100 users (for example)
else
max_net_users = dris.net_users;
if (max_net_users == 0) // no network users are allowed, so nothing to do!
return 0;
if (dris.model < 3) {
MessageBox.Show("A network dongle has not been detected. Therefore you cannot display the network users.", "Net Users", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return -1;
}
ret_code = DinkeyPro.DDGetNetUserList(null, out num_net_users, out nu_info, max_net_users, out extended_error);
if (ret_code != 0)
{
MessageBox.Show(String.Format("Error {0}/{1} finding network user information.", ret_code, extended_error), "Net Users", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
DisplayString = String.Format("number of net users: {0}", num_net_users) + Environment.NewLine;
for (i=0; i<num_net_users; i++)
{
DisplayString += String.Format("{0}. licence: {1}, user: {2}, computer: {3}, ip address: {4}", i+1,
nu_info[i].licenceName, nu_info[i].userName, nu_info[i].computerName, nu_info[i].ipAddress);
DisplayString += Environment.NewLine;
}
MessageBox.Show(DisplayString, "Net Users", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return ret_code;
}
// to display common errors that occur - !!!! you will want to change these messages
public static void DisplayError(int ret_code, int ext_err)
{
string DisplayString;
switch(ret_code)
{
case 401:
MessageBox.Show("Error! No dongles detected!", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 403:
MessageBox.Show("Error! A dongle was detected but it was a different type to the one specified in DinkeyAdd.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 404:
MessageBox.Show("Error! A dongle was detected but it was a different model to those specified in DinkeyAdd.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 409:
MessageBox.Show("Error! The dongle detected has not been programmed by DinkeyAdd.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 410:
MessageBox.Show("Error! A dongle was detected but it has a different Product Code to the one specified in DinkeyAdd.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 411:
MessageBox.Show("Error! The dongle detected does not contain the licence associated with this program.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 413:
MessageBox.Show("Error! This program has not been protected by DinkeyAdd. For guidance please read the DinkeyAdd chapter of the Dinkey manual.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 417:
MessageBox.Show("Error! One or more of the parameters set in the DRIS is incorrect.\nIt could also be caused if you are encrypting the DRIS in your code but did not specify DRIS encryption in DinkeyAdd - or vice versa.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 423:
MessageBox.Show("Error! The number of network users has been exceeded.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 435:
MessageBox.Show("Error! DinkeyServer has not been detected on the network.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
case 922:
MessageBox.Show("Error! The Software Key has expired.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
// internal error - cannot load DLL
case -1:
MessageBox.Show("Error! Cannot call protection check because DLL is not loaded.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
default:
DisplayString = "An error occurred checking the dongle. Error: " + String.Format("{0:D}", ret_code) + "\nExtended Error: " + String.Format("{0:D}", ext_err);
MessageBox.Show(DisplayString, "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
}
return;
}
}
}

View File

@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="$this.Name">
<value>Form1</value>
</data>
</root>

View File

@@ -0,0 +1,287 @@
// !! this file should not be modified
using System;
using System.Runtime.InteropServices; // so we can marshal the DRIS as a block of memory
using System.Text; // so we can extract / set strings in the DRIS
using System.Windows.Forms; // for MessageBox
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public class DRIS
{
// the first 4 fields are never encrypted
public byte header1; // should be set to "DRIS"
public byte header2;
public byte header3;
public byte header4;
// inputs
public int size; // size of this structure
public int seed1; // seed for data/dris encryption
public int seed2; // as above
// (maybe encrypted from now on)
public int function; // specify only one function
public int flags; // options for the function selected. To use more than one OR them together: OPTION1 | OPTION2...
public uint execs_decrement; // amount by which to dec execs if we use flag: DEC_MANY_EXECS
public int data_crypt_key_num; // number of the key (1-3) that the dongle uses to encrypt or decrypt user data
public int rw_offset; // offset in the dongle data area to read or write data
public int rw_length; // length of data are to read/write/encrypt/decrypt
public IntPtr DoNotUse; // do not use the rw_data_ptr element use the "Data" argument of the DDProtCheck function
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] // NB access this field by using alg_licence_name (see below)
private byte[] _alt_licence_name = null; // protection check for different licence instead of this one
public int var_a; // variable values for user algorithm
public int var_b;
public int var_c;
public int var_d;
public int var_e;
public int var_f;
public int var_g;
public int var_h;
public int alg_number; // the number of the user algorithm that you want to execute
// outputs
public int ret_code; // return code from the protection check
public int ext_err; // extended error
public int type; // type of dongle detected. 1 = Pro, 2 = FD
public int model; // model of dongle detected. 1 = Lite, 2 = Plus, 4 = Net 5, 7 = Net Unlimited
public int sdsn; // Software Developer's Serial Number
[MarshalAs(UnmanagedType.ByValArray, SizeConst=12)] // NB access this field by using prodcode (see below)
private byte[] _prodcode = null; // product code (null-terminated)
public uint dongle_number;
public int update_number;
public uint data_area_size; // size of the data area in the dongle detected
public int max_alg_num; // number of algorithms in the dongle detected
public int execs; // executions left: -1 indicates 'no limit'
public int exp_day; // expiry day: -1 indicates 'no limit'
public int exp_month; // expiry month: -1 indicates 'no limit'
public int exp_year; // expiry year: -1 indicates 'no limit'
public uint features; // features value
public int net_users; // maximum number of network users for the dongle detected: -1 indicates 'mo limit'
public int alg_answer; // answer to the user algorithm executed with the given variable values
public uint fd_capacity; // capacity of the data area in FD dongle. Currently fixed at ~10MB but may change in the future.
[MarshalAs(UnmanagedType.ByValArray, SizeConst=128)] // NB access this field by using fd_drive (see below)
private byte[] _fd_drive = null; // fd drive letter (null-terminated)
public int swkey_type; // 0 = no swkey detected, 1 = temporary software key, 2 = demo software key
public int swkey_exp_day; // software key expiry date (if software key detected)
public int swkey_exp_month;
public int swkey_exp_year;
// NB we have to do it this way because we cannot encrypt strings correctly unless they are byte arrays
public string prodcode
{
get
{
StringBuilder sb = new StringBuilder(12);
foreach (byte b in _prodcode)
{
if (b == 0)
return sb.ToString();
else
sb.Append((char)b);
}
return sb.ToString();
}
}
public string fd_drive
{
get
{
StringBuilder sb = new StringBuilder(128);
foreach (byte b in _fd_drive)
{
if (b == 0)
return sb.ToString();
else
sb.Append((char)b);
}
return sb.ToString();
}
}
// NB we have to do it this way because we cannot encrypt strings correctly unless they are byte arrays
public string alt_licence_name
{
set
{
int i;
StringBuilder sb = new StringBuilder(value, 256);
for (i=0; i<sb.Length; i++)
{
_alt_licence_name[i] = (byte)sb[i];
}
_alt_licence_name[i] = 0; // null terminate
}
}
// sets 4 bytes from an integer at the specified offset in a data array
public void Set4Bytes(byte[] data, int offset, int value)
{
data[offset] = (byte)(value & 0xff);
data[offset+1] = (byte)((value >> 8) & 0xff);
data[offset+2] = (byte)((value >> 16) & 0xff);
data[offset+3] = (byte)((value >> 24) & 0xff);
return;
}
// converts to DRIS structure to a byte array (so we can do encryption)
public void DrisToByteArray(DRIS dris, byte[] data)
{
GCHandle MyGC = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.StructureToPtr(dris, MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
return;
}
// converts a byte array to the DRIS structure (so we can do encryption)
public void ByteArrayToDris(byte[] data, DRIS dris)
{
GCHandle MyGC = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), dris);
MyGC.Free();
return;
}
// to make a new instance of this class, initialise every element to a random value and then set the header
public DRIS()
{
Random rnd = new Random();
Byte[] temp = new Byte[Marshal.SizeOf(this)];
rnd.NextBytes(temp);
ByteArrayToDris(temp, this);
this.header1 = (byte)'D';
this.header2 = (byte)'R';
this.header3 = (byte)'I';
this.header4 = (byte)'S';
}
// functions - must specify only one
public const int PROTECTION_CHECK = 1; // checks for dongle, check program params...
public const int EXECUTE_ALGORITHM = 2; // protection check + calculate answer for specified algorithm with specified inputs
public const int WRITE_DATA_AREA = 3; // protection check + writes dongle data area
public const int READ_DATA_AREA = 4; // protection check + reads dongle data area
public const int ENCRYPT_USER_DATA = 5; // protection check + the dongle will encrypt user data
public const int DECRYPT_USER_DATA = 6; // protection check + the dongle will decrypt user data
public const int FAST_PRESENCE_CHECK = 7; // checks for the presence of the correct dongle only with minimal security, no flags allowed.
public const int STOP_NET_USER = 8; // stops a network user (a protection check is NOT performed)
// flags - can specify as many as you like
public const int DEC_ONE_EXEC = 1; // decrement execs by 1
public const int DEC_MANY_EXECS = 2; // decrement execs by number specified in execs_decrement
public const int START_NET_USER = 4; // starts a network user
public const int USE_FUNCTION_ARGUMENT = 16; // use the extra argument in the function for pointers
public const int CHECK_LOCAL_FIRST = 32; // always look in local ports before looking in network ports
public const int CHECK_NETWORK_FIRST = 64; // always look on the network before looking in local ports
public const int USE_ALT_LICENCE_NAME = 128; // use name specified in alt_licence_name instead of the default one
public const int DONT_SET_MAXDAYS_EXPIRY = 256; // if the max days expiry date has not been calculated then do not do it this time
public const int MATCH_DONGLE_NUMBER = 512; // restrict the search to match the dongle number specified in the DRIS
public const int DONT_RETURN_FD_DRIVE = 1024; // if an FD dongle has been detected then don't return the flash drive/mount name in the DRIS
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct NU_INFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string licenceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=50)]
public string userName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string computerName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=16)]
public string ipAddress;
}
// 32-bit protection check (loads 32-bit DLL)
class DDProtCheck32
{
[DllImport("dpwin32.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// 64-bit protection check (loads 64-bit DLL)
class DDProtCheck64
{
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// 32-bit get network user info (loads 32-bit DLL)
class DDGetNetUserList32
{
[DllImport("dpwin32.dll", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// 64-bit get network user info (loads 64-bit DLL)
class DDGetNetUserList64
{
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// call our API - we only want to load the correct DLL for the bit-ness of the computer. The other DLL may not exist.
class DinkeyPro
{
// calls the DDProtCheck function in the appropriate DLL
public static int DDProtCheck(DRIS dris, byte[] data)
{
int ret_code = -1;
if (IntPtr.Size == 4)
{
try
{
ret_code = DDProtCheck32.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dpwin32.dll. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else {
try
{
ret_code = DDProtCheck64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dpwin64.dll. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
return ret_code;
}
public static int DDGetNetUserList(string licence_name, out int num_net_users, out NU_INFO[] nu_info, int num_info_structs, out int extended_error)
{
int ret_code = -1;
int i;
extended_error = num_net_users = 0;
byte[] nu_info_bytes = new byte[num_info_structs * Marshal.SizeOf(typeof(NU_INFO))];
byte[] nu_info_one_struct = new byte[Marshal.SizeOf(typeof(NU_INFO))];
GCHandle MyGC;
nu_info = null;
// call the function and get info as a byte array
if (IntPtr.Size == 4)
ret_code = DDGetNetUserList32.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
else
ret_code = DDGetNetUserList64.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
if (ret_code != 0)
return ret_code;
// convert byte array to an array of structs
nu_info = new NU_INFO[num_net_users];
for (i=0; i<num_net_users; i++)
{
Array.Copy(nu_info_bytes, i*Marshal.SizeOf(typeof(NU_INFO)), nu_info_one_struct, 0, Marshal.SizeOf(typeof(NU_INFO)));
MyGC = GCHandle.Alloc(nu_info_one_struct, GCHandleType.Pinned);
nu_info[i] = (NU_INFO)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(NU_INFO));
MyGC.Free();
}
return 0;
}
}

View File

@@ -0,0 +1,353 @@
// !! this file should not be modified
using System;
using System.Runtime.InteropServices; // so we can marshal the DRIS as a block of memory
using System.Text; // so we can extract / set strings in the DRIS
using System.Windows.Forms; // for MessageBox
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public class DRIS
{
// the first 4 fields are never encrypted
public byte header1; // should be set to "DRIS"
public byte header2;
public byte header3;
public byte header4;
// inputs
public int size; // size of this structure
public int seed1; // seed for data/dris encryption
public int seed2; // as above
// (maybe encrypted from now on)
public int function; // specify only one function
public int flags; // options for the function selected. To use more than one OR them together: OPTION1 | OPTION2...
public uint execs_decrement; // amount by which to dec execs if we use flag: DEC_MANY_EXECS
public int data_crypt_key_num; // number of the key (1-3) that the dongle uses to encrypt or decrypt user data
public int rw_offset; // offset in the dongle data area to read or write data
public int rw_length; // length of data are to read/write/encrypt/decrypt
public IntPtr DoNotUse; // do not use the rw_data_ptr element use the "Data" argument of the DDProtCheck function
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] // NB access this field by using alg_licence_name (see below)
private byte[] _alt_licence_name = null; // protection check for different licence instead of this one
public int var_a; // variable values for user algorithm
public int var_b;
public int var_c;
public int var_d;
public int var_e;
public int var_f;
public int var_g;
public int var_h;
public int alg_number; // the number of the user algorithm that you want to execute
// outputs
public int ret_code; // return code from the protection check
public int ext_err; // extended error
public int type; // type of dongle detected. 1 = Pro, 2 = FD
public int model; // model of dongle detected. 1 = Lite, 2 = Plus, 4 = Net 5, 7 = Net Unlimited
public int sdsn; // Software Developer's Serial Number
[MarshalAs(UnmanagedType.ByValArray, SizeConst=12)] // NB access this field by using prodcode (see below)
private byte[] _prodcode = null; // product code (null-terminated)
public uint dongle_number;
public int update_number;
public uint data_area_size; // size of the data area in the dongle detected
public int max_alg_num; // number of algorithms in the dongle detected
public int execs; // executions left: -1 indicates 'no limit'
public int exp_day; // expiry day: -1 indicates 'no limit'
public int exp_month; // expiry month: -1 indicates 'no limit'
public int exp_year; // expiry year: -1 indicates 'no limit'
public uint features; // features value
public int net_users; // maximum number of network users for the dongle detected: -1 indicates 'mo limit'
public int alg_answer; // answer to the user algorithm executed with the given variable values
public uint fd_capacity; // capacity of the data area in FD dongle. Currently fixed at ~10MB but may change in the future.
[MarshalAs(UnmanagedType.ByValArray, SizeConst=128)] // NB access this field by using fd_drive (see below)
private byte[] _fd_drive = null; // fd drive letter (null-terminated)
public int swkey_type; // 0 = no swkey detected, 1 = temporary software key, 2 = demo software key
public int swkey_exp_day; // software key expiry date (if software key detected)
public int swkey_exp_month;
public int swkey_exp_year;
// NB we have to do it this way because we cannot encrypt strings correctly unless they are byte arrays
public string prodcode
{
get
{
StringBuilder sb = new StringBuilder(12);
foreach (byte b in _prodcode)
{
if (b == 0)
return sb.ToString();
else
sb.Append((char)b);
}
return sb.ToString();
}
}
public string fd_drive
{
get
{
StringBuilder sb = new StringBuilder(128);
foreach (byte b in _fd_drive)
{
if (b == 0)
return sb.ToString();
else
sb.Append((char)b);
}
return sb.ToString();
}
}
// NB we have to do it this way because we cannot encrypt strings correctly unless they are byte arrays
public string alt_licence_name
{
set
{
int i;
StringBuilder sb = new StringBuilder(value, 256);
for (i=0; i<sb.Length; i++)
{
_alt_licence_name[i] = (byte)sb[i];
}
_alt_licence_name[i] = 0; // null terminate
}
}
// sets 4 bytes from an integer at the specified offset in a data array
public void Set4Bytes(byte[] data, int offset, int value)
{
data[offset] = (byte)(value & 0xff);
data[offset+1] = (byte)((value >> 8) & 0xff);
data[offset+2] = (byte)((value >> 16) & 0xff);
data[offset+3] = (byte)((value >> 24) & 0xff);
return;
}
// converts to DRIS structure to a byte array (so we can do encryption)
public void DrisToByteArray(DRIS dris, byte[] data)
{
GCHandle MyGC = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.StructureToPtr(dris, MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
return;
}
// converts a byte array to the DRIS structure (so we can do encryption)
public void ByteArrayToDris(byte[] data, DRIS dris)
{
GCHandle MyGC = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), dris);
MyGC.Free();
return;
}
// to make a new instance of this class, initialise every element to a random value and then set the header
public DRIS()
{
Random rnd = new Random();
Byte[] temp = new Byte[Marshal.SizeOf(this)];
rnd.NextBytes(temp);
ByteArrayToDris(temp, this);
this.header1 = (byte)'D';
this.header2 = (byte)'R';
this.header3 = (byte)'I';
this.header4 = (byte)'S';
}
// functions - must specify only one
public const int PROTECTION_CHECK = 1; // checks for dongle, check program params...
public const int EXECUTE_ALGORITHM = 2; // protection check + calculate answer for specified algorithm with specified inputs
public const int WRITE_DATA_AREA = 3; // protection check + writes dongle data area
public const int READ_DATA_AREA = 4; // protection check + reads dongle data area
public const int ENCRYPT_USER_DATA = 5; // protection check + the dongle will encrypt user data
public const int DECRYPT_USER_DATA = 6; // protection check + the dongle will decrypt user data
public const int FAST_PRESENCE_CHECK = 7; // checks for the presence of the correct dongle only with minimal security, no flags allowed.
public const int STOP_NET_USER = 8; // stops a network user (a protection check is NOT performed)
// flags - can specify as many as you like
public const int DEC_ONE_EXEC = 1; // decrement execs by 1
public const int DEC_MANY_EXECS = 2; // decrement execs by number specified in execs_decrement
public const int START_NET_USER = 4; // starts a network user
public const int USE_FUNCTION_ARGUMENT = 16; // use the extra argument in the function for pointers
public const int CHECK_LOCAL_FIRST = 32; // always look in local ports before looking in network ports
public const int CHECK_NETWORK_FIRST = 64; // always look on the network before looking in local ports
public const int USE_ALT_LICENCE_NAME = 128; // use name specified in alt_licence_name instead of the default one
public const int DONT_SET_MAXDAYS_EXPIRY = 256; // if the max days expiry date has not been calculated then do not do it this time
public const int MATCH_DONGLE_NUMBER = 512; // restrict the search to match the dongle number specified in the DRIS
public const int DONT_RETURN_FD_DRIVE = 1024; // if an FD dongle has been detected then don't return the flash drive/mount name in the DRIS
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct NU_INFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string licenceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=50)]
public string userName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string computerName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=16)]
public string ipAddress;
}
// DDProtCheck
// Windows 32-bit protection check (loads 32-bit DLL)
class DDProtCheckWin32
{
[DllImport("dpwin32.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// Windows 64-bit protection check (loads 64-bit DLL)
class DDProtCheckWin64
{
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// Linux 64-bit protection check (loads 64-bit so) (NB only 64-bit Linux is supported by .NET Core)
class DDProtCheckLin64
{
[DllImport("dplin64.so", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// Mac 64-bit protection check (loads 64-bit dylib) (NB only 64-bit Mac code is supported by .NET Core) (NB we found that the release module dpmac64.dylib crashed)
class DDProtCheckMac64
{
[DllImport("dpmac64debug.dylib", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// DDGetNetUserList
// Windows 32-bit get network user info (loads 32-bit DLL)
class DDGetNetUserListWin32
{
[DllImport("dpwin32.dll", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// Windows 64-bit get network user info (loads 64-bit DLL)
class DDGetNetUserListWin64
{
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// Linux 64-bit get network user info (loads 64-bit DLL)
class DDGetNetUserListLin64
{
[DllImport("dplin64.so", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// call our API - we only want to load the correct DLL for the OS and bit-ness of the computer. The other DLLs may not exist.
class DinkeyPro
{
// calls the DDProtCheck function in the appropriate DLL
public static int DDProtCheck(DRIS dris, byte[] data)
{
int ret_code = -1;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // method valid from .NET Core 1.0 and .NET framework 4.7
{
if (Environment.Is64BitProcess) // method valid from .NET Core 2.0 and .NET framework 4.0
{
try
{
ret_code = DDProtCheckWin64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dpwin64.dll. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
try
{
ret_code = DDProtCheckWin32.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dpwin32.dll. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
try
{
ret_code = DDProtCheckLin64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dplin64.so. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
try
{
ret_code = DDProtCheckMac64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dpmac64debug.dylib. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
MessageBox.Show("Error! Dinkey Pro/FD not supported on this OS.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
return ret_code;
}
public static int DDGetNetUserList(string licence_name, out int num_net_users, out NU_INFO[] nu_info, int num_info_structs, out int extended_error)
{
int ret_code = -1;
int i;
extended_error = num_net_users = 0;
byte[] nu_info_bytes = new byte[num_info_structs * Marshal.SizeOf(typeof(NU_INFO))];
byte[] nu_info_one_struct = new byte[Marshal.SizeOf(typeof(NU_INFO))];
GCHandle MyGC;
nu_info = null;
// call the function and get info as a byte array
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
if (Environment.Is64BitProcess)
ret_code = DDGetNetUserListWin64.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
else
ret_code = DDGetNetUserListWin32.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
ret_code = DDGetNetUserListLin64.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
MessageBox.Show("Error! This function is not supported in the Mac debug module.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
if (ret_code != 0)
return ret_code;
// convert byte array to an array of structs
nu_info = new NU_INFO[num_net_users];
for (i=0; i<num_net_users; i++)
{
Array.Copy(nu_info_bytes, i*Marshal.SizeOf(typeof(NU_INFO)), nu_info_one_struct, 0, Marshal.SizeOf(typeof(NU_INFO)));
MyGC = GCHandle.Alloc(nu_info_one_struct, GCHandleType.Pinned);
nu_info[i] = (NU_INFO)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(NU_INFO));
MyGC.Free();
}
return 0;
}
}

View File

@@ -0,0 +1,422 @@
// !! this file should not be modified
using System;
using System.Runtime.InteropServices; // so we can marshal the DRIS as a block of memory
using System.Text; // so we can extract / set strings in the DRIS
using System.Windows.Forms; // for MessageBox
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public class DRIS
{
// the first 4 fields are never encrypted
public byte header1; // should be set to "DRIS"
public byte header2;
public byte header3;
public byte header4;
// inputs
public int size; // size of this structure
public int seed1; // seed for data/dris encryption
public int seed2; // as above
// (maybe encrypted from now on)
public int function; // specify only one function
public int flags; // options for the function selected. To use more than one OR them together: OPTION1 | OPTION2...
public uint execs_decrement; // amount by which to dec execs if we use flag: DEC_MANY_EXECS
public int data_crypt_key_num; // number of the key (1-3) that the dongle uses to encrypt or decrypt user data
public int rw_offset; // offset in the dongle data area to read or write data
public int rw_length; // length of data are to read/write/encrypt/decrypt
public IntPtr DoNotUse; // do not use the rw_data_ptr element use the "Data" argument of the DDProtCheck function
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] // NB access this field by using alg_licence_name (see below)
private byte[] _alt_licence_name = null; // protection check for different licence instead of this one
public int var_a; // variable values for user algorithm
public int var_b;
public int var_c;
public int var_d;
public int var_e;
public int var_f;
public int var_g;
public int var_h;
public int alg_number; // the number of the user algorithm that you want to execute
// outputs
public int ret_code; // return code from the protection check
public int ext_err; // extended error
public int type; // type of dongle detected. 1 = Pro, 2 = FD
public int model; // model of dongle detected. 1 = Lite, 2 = Plus, 4 = Net 5, 7 = Net Unlimited
public int sdsn; // Software Developer's Serial Number
[MarshalAs(UnmanagedType.ByValArray, SizeConst=12)] // NB access this field by using prodcode (see below)
private byte[] _prodcode = null; // product code (null-terminated)
public uint dongle_number;
public int update_number;
public uint data_area_size; // size of the data area in the dongle detected
public int max_alg_num; // number of algorithms in the dongle detected
public int execs; // executions left: -1 indicates 'no limit'
public int exp_day; // expiry day: -1 indicates 'no limit'
public int exp_month; // expiry month: -1 indicates 'no limit'
public int exp_year; // expiry year: -1 indicates 'no limit'
public uint features; // features value
public int net_users; // maximum number of network users for the dongle detected: -1 indicates 'mo limit'
public int alg_answer; // answer to the user algorithm executed with the given variable values
public uint fd_capacity; // capacity of the data area in FD dongle. Currently fixed at ~10MB but may change in the future.
[MarshalAs(UnmanagedType.ByValArray, SizeConst=128)] // NB access this field by using fd_drive (see below)
private byte[] _fd_drive = null; // fd drive letter (null-terminated)
public int swkey_type; // 0 = no swkey detected, 1 = temporary software key, 2 = demo software key
public int swkey_exp_day; // software key expiry date (if software key detected)
public int swkey_exp_month;
public int swkey_exp_year;
// NB we have to do it this way because we cannot encrypt strings correctly unless they are byte arrays
public string prodcode
{
get
{
StringBuilder sb = new StringBuilder(12);
foreach (byte b in _prodcode)
{
if (b == 0)
return sb.ToString();
else
sb.Append((char)b);
}
return sb.ToString();
}
}
public string fd_drive
{
get
{
StringBuilder sb = new StringBuilder(128);
foreach (byte b in _fd_drive)
{
if (b == 0)
return sb.ToString();
else
sb.Append((char)b);
}
return sb.ToString();
}
}
// NB we have to do it this way because we cannot encrypt strings correctly unless they are byte arrays
public string alt_licence_name
{
set
{
int i;
StringBuilder sb = new StringBuilder(value, 256);
for (i=0; i<sb.Length; i++)
{
_alt_licence_name[i] = (byte)sb[i];
}
_alt_licence_name[i] = 0; // null terminate
}
}
// sets 4 bytes from an integer at the specified offset in a data array
public void Set4Bytes(byte[] data, int offset, int value)
{
data[offset] = (byte)(value & 0xff);
data[offset+1] = (byte)((value >> 8) & 0xff);
data[offset+2] = (byte)((value >> 16) & 0xff);
data[offset+3] = (byte)((value >> 24) & 0xff);
return;
}
// converts to DRIS structure to a byte array (so we can do encryption)
public void DrisToByteArray(DRIS dris, byte[] data)
{
GCHandle MyGC = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.StructureToPtr(dris, MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
return;
}
// converts a byte array to the DRIS structure (so we can do encryption)
public void ByteArrayToDris(byte[] data, DRIS dris)
{
GCHandle MyGC = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), dris);
MyGC.Free();
return;
}
// to make a new instance of this class, initialise every element to a random value and then set the header
public DRIS()
{
Random rnd = new Random();
Byte[] temp = new Byte[Marshal.SizeOf(this)];
rnd.NextBytes(temp);
ByteArrayToDris(temp, this);
this.header1 = (byte)'D';
this.header2 = (byte)'R';
this.header3 = (byte)'I';
this.header4 = (byte)'S';
}
// functions - must specify only one
public const int PROTECTION_CHECK = 1; // checks for dongle, check program params...
public const int EXECUTE_ALGORITHM = 2; // protection check + calculate answer for specified algorithm with specified inputs
public const int WRITE_DATA_AREA = 3; // protection check + writes dongle data area
public const int READ_DATA_AREA = 4; // protection check + reads dongle data area
public const int ENCRYPT_USER_DATA = 5; // protection check + the dongle will encrypt user data
public const int DECRYPT_USER_DATA = 6; // protection check + the dongle will decrypt user data
public const int FAST_PRESENCE_CHECK = 7; // checks for the presence of the correct dongle only with minimal security, no flags allowed.
public const int STOP_NET_USER = 8; // stops a network user (a protection check is NOT performed)
// flags - can specify as many as you like
public const int DEC_ONE_EXEC = 1; // decrement execs by 1
public const int DEC_MANY_EXECS = 2; // decrement execs by number specified in execs_decrement
public const int START_NET_USER = 4; // starts a network user
public const int USE_FUNCTION_ARGUMENT = 16; // use the extra argument in the function for pointers
public const int CHECK_LOCAL_FIRST = 32; // always look in local ports before looking in network ports
public const int CHECK_NETWORK_FIRST = 64; // always look on the network before looking in local ports
public const int USE_ALT_LICENCE_NAME = 128; // use name specified in alt_licence_name instead of the default one
public const int DONT_SET_MAXDAYS_EXPIRY = 256; // if the max days expiry date has not been calculated then do not do it this time
public const int MATCH_DONGLE_NUMBER = 512; // restrict the search to match the dongle number specified in the DRIS
public const int DONT_RETURN_FD_DRIVE = 1024; // if an FD dongle has been detected then don't return the flash drive/mount name in the DRIS
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct NU_INFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string licenceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=50)]
public string userName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string computerName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=16)]
public string ipAddress;
}
// DDProtCheck
// Windows 32-bit protection check (loads 32-bit DLL)
class DDProtCheckWin32
{
[DllImport("dpwin32.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// Windows 64-bit protection check (loads 64-bit DLL)
class DDProtCheckWin64
{
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// Linux 32-bit protection check (loads 32-bit so)
class DDProtCheckLin32
{
[DllImport("dplin32.so", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// Linux 64-bit protection check (loads 64-bit so)
class DDProtCheckLin64
{
[DllImport("dplin64.so", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// Mac 32-bit protection check (loads 32-bit dylib)
class DDProtCheckMac32
{
[DllImport("dpmac32.dylib", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// Mac 64-bit protection check (loads 64-bit dylib)
class DDProtCheckMac64
{
[DllImport("dpmac64.dylib", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
}
// DDGetNetUserList
// Windows 32-bit get network user info (loads 32-bit DLL)
class DDGetNetUserListWin32
{
[DllImport("dpwin32.dll", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// Windows 64-bit get network user info (loads 64-bit DLL)
class DDGetNetUserListWin64
{
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// Linux 32-bit get network user info (loads 32-bit so)
class DDGetNetUserListLin32
{
[DllImport("dplin32.so", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// Linux 64-bit get network user info (loads 64-bit so)
class DDGetNetUserListLin64
{
[DllImport("dplin64.so", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// Mac 32-bit get network user info (loads 32-bit dylib)
class DDGetNetUserListMac32
{
[DllImport("dpmac32.dylib", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// Mac 64-bit get network user info (loads 64-bit dylib)
class DDGetNetUserListMac64
{
[DllImport("dpmac64.dylib", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// call our API - we only want to load the correct DLL for the OS and bit-ness of the computer. The other DLLs may not exist.
class DinkeyPro
{
// calls the DDProtCheck function in the appropriate DLL
public static int DDProtCheck(DRIS dris, byte[] data)
{
int ret_code = -1;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // method valid from .NET Core 1.0 and .NET framework 4.7
{
if (Environment.Is64BitProcess) // method valid from .NET Core 2.0 and .NET framework 4.0
{
try
{
ret_code = DDProtCheckWin64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dpwin64.dll. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
try
{
ret_code = DDProtCheckWin32.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dpwin32.dll. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
if (Environment.Is64BitProcess)
{
try
{
ret_code = DDProtCheckLin64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dplin64.do. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
try
{
ret_code = DDProtCheckLin32.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dplin32.so. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
if (Environment.Is64BitProcess)
{
try
{
ret_code = DDProtCheckMac64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dpmac64.dylib. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
try
{
ret_code = DDProtCheckMac32.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
MessageBox.Show("Error! Cannot find dpmac32.dylib. This should be in the same folder as DllTest.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
else
{
MessageBox.Show("Error! Dinkey Pro/FD not supported on this OS.", "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
return ret_code;
}
public static int DDGetNetUserList(string licence_name, out int num_net_users, out NU_INFO[] nu_info, int num_info_structs, out int extended_error)
{
int ret_code = -1;
int i;
extended_error = num_net_users = 0;
byte[] nu_info_bytes = new byte[num_info_structs * Marshal.SizeOf(typeof(NU_INFO))];
byte[] nu_info_one_struct = new byte[Marshal.SizeOf(typeof(NU_INFO))];
GCHandle MyGC;
nu_info = null;
// call the function and get info as a byte array
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
if (Environment.Is64BitProcess)
ret_code = DDGetNetUserListWin64.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
else
ret_code = DDGetNetUserListWin32.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
if (Environment.Is64BitProcess)
ret_code = DDGetNetUserListLin64.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
else
ret_code = DDGetNetUserListLin32.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
if (Environment.Is64BitProcess)
ret_code = DDGetNetUserListMac64.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
else
ret_code = DDGetNetUserListMac32.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
}
if (ret_code != 0)
return ret_code;
// convert byte array to an array of structs
nu_info = new NU_INFO[num_net_users];
for (i=0; i<num_net_users; i++)
{
Array.Copy(nu_info_bytes, i*Marshal.SizeOf(typeof(NU_INFO)), nu_info_one_struct, 0, Marshal.SizeOf(typeof(NU_INFO)));
MyGC = GCHandle.Alloc(nu_info_one_struct, GCHandleType.Pinned);
nu_info[i] = (NU_INFO)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(NU_INFO));
MyGC.Free();
}
return 0;
}
}

View File

@@ -0,0 +1,169 @@
DllTest - sample code to call Runtime module in C# using VS 2002 and higher
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is written in Visual Studio 2002 but will work in more recent versions of Visual Studio
(they will upgrade the Project to the latest version. If prompted you should also upgrade the .NET
framework the project requires). If you are using .NET Core then please read the notes at the bottom
of this file. If you are using VS 2022 (or higher) then you will receive warnings when compiling this
code - use the VS 2022 project instead.
The main source files in the project are:
File name Description
Form1.cs main source code file for C#
dris.cs contains the DRIS structure and low-level functions to manipulate it.
The best approach is to compile the sample code and see how it works and then to take the appropriate code
and apply it to your own project. You should include the dris.cs file in your project and use/modify which
ever functions from form1.cs you feel are appropriate. The dris.cs file should not be modified.
The sample code contains 11 functions. You will not need to use all these functions in your code. Just use
which ever functions are most appropriate and customise in your own way. The sample code is just a guide.
You should implement the protection in a stronger way using the techniques described in the
"Increasing your Protection" chapter of the manual.
Code marked with !!!! are places where you should customise the sample code so that it will work properly:
* Change the MY_SDSN value to the value of your SDSN
* Change the MY_PRODCODE value to the Product Code in the dongle
* Change the MyAlgorithm code (if you call a user algorithm)
* Change the CryptDRIS code (if you encrypt the DRIS)
* Change the CryptApiData (if you encrypt Data you send to our API)
* Change the MyRWAlgorithm code (if encrypt Data you send to our API using the R/W algorithm)
You will also probably want to replace our error messages with your own. However, you should still
display or log any error codes returned by the protection check otherwise you will not be able to
identify the cause of the error. (You can look up error codes in our knowledge base: microcosm.com/kb).
For users of Visual Studio 2005 or higher, the default setting for projects is to compile for the Target
Platform "Any". This means that on 32-bit Windows, your code will run as 32-bit code (and needs to call
dpwin32.dll) and under 64-bit Windows your code will run as 64-bit code (and needs to call dpwin64.dll).
The sample code works this out automatically. If you select the target platform as "x86" then it will
always be 32-bit and so you only need to use dpwin32.dll. If you select "x64" then your code will be
64-bit and you only need to use dpwin64.dll.
Note - as you are using the API method in this sample you should protect dpwin32.dll and/or dpwin64.dll
and not your program. Because your program is linked to the DLL it is protected. You can also protect
your program with the Shell Method should you wish.
Note - if you are compiling for the Platform target "Any" (and therefore need to protect both dpwin32.dll
and dpwin64.dll) then you will probably want to protect these modules to the same licence so that they share
a common set of protection parameters.
Make sure you remember to do the following:
1) Insert the following namespaces in your code file:
using System.Runtime.InteropServices;
using System.Text;
2) Insert the dris.cs file in your project.
2) You need to output the protected dpwin32.dll (dpwin64.dll) to the folder that contains your assemblies.
Otherwise the System.DllNotFoundException error will appear when you run DllTest.
If you wish you can rename dpwin32.dll (dpwin64.dll) to a name of your choice. In this case you will need to
modify the dll name in the dris.cs file.
Note - CSharp is an interpreted language and so it is easier to decompile than other languages. You can
improve security if you use an obfuscator to obfuscate your code. Or - even better - you could use the
Shell Method to protect your assemblies. This encrypts your code (making it impossible to decompile).
Notes on Debugging 64-bit Code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you use the 64-bit runtime module (dpwin64.dll) to protect your software the anti-debug code is so
strong that if you are debugging your code, after the call DDProtCheck then it will crash with an SEH
exception. If you want to be able to debug your code then you can setup your project so that your code calls
the debug module (dpwin64debug.dll) in your "debug" build and the standard module (dpwin64.dll) in your
release build. You can do this by modifying the declaration of DDProtCheck64 in dris.cs like this:
class DDProtCheck64
{
#if DEBUG ' debug module
[DllImport("dpwin64debug.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
#else ' standard module
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[] data);
#endif
}
Note - the debug module has the following restrictions:
1) It will not correctly start a network user (network dongles only). However, other than that the protection
check will function correctly and return success.
2) You will not be able to encrypt the DRIS. (If you do encrypt the DRIS in your release build then you
should make sure that CryptDRIS does not get called in your debug build).
3) The protection check will take slightly longer than normal.
4) The DDGetNetUserList function will return error 428 (not implemented).
5) A temporary subprocess is created which may be (falsely) detected as malicious by anti-virus programs.
This behaviour does not occur in 32-bit code, so if you are using dpwin32.dll then you can debug your code.
Important Note for UWP app Developers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Universal Windows Platform (UWP) application (previously called Windows Store Apps or Metro Apps) are not
compatible with Lite or Plus dongles because the restrictions imposed by these applications. However, you
can protect these Apps with network dongles (because the restrictive access is performed by the non-UWP
DinkeyServer process). If you do this you will need to enable the "Private Networks (Client and Server)"
Capability in your package manifest.
.NET Core / .NET 5+
~~~~~~~~~~~~~~~~~~~
The sample code provided also works with .NET Core. However, .NET Core also supports Linux and macOS as well
as other platforms. If you want to support these OS then please replace dris.cs with dris_dotnetcore.cs.
The files are very similar but dris_dotnetcore.cs will load the relevant native runtime module (dpwin32.dll
under 32-bit Windows; dpwin64.dll under 64-bit Windows; dplin64.so under Linux OS; dpmac64debug.dylib under
macOS - unfortunately the release module is not compatible with the .NET Core framework so you have to use
the debug one. This also means that our solution is not compatible with ARM-based macOS - because the debug
modules do not exist).
If you are using .NET Core version earlier than 3.0 then Windows.Forms are not supported and you will have to
replace the MessageBox.Show lines with Console.WriteLine.
The Shell Method is compatible with .NET Core Console, Windows.Forms and WPF applications. It is supported
under Windows and Linux but not macOS. It is only supported for .NET Core version 3.0 or higher. If you are
using the Shell Method then you should protect your compiled dll and not the "appHost" (this is a native
executable which is just a stub program that loads the assemblies in your dll). Also do not use "dotnet run"
to launch your application - it will run the unprotected version. Either launch the executable or run using
"dotnet <program.dll>".
If you publish a "single-file executable" file then although this file can be protected we do not recommend
it because it is not secure. (The single-file executable just comprises a stub loader with your compiled
assemblies and configuration files appended to the end of the executable. These files are just considered as
data appended to the executable file in a custom format and therefore are not protected. When you shell
protect your executable you are just protecting the loader but not your assemblies). Instead you need to
build your code and then add protection before publishing. You should protect your assemblies in the obj
directory (and in the platform type you specified) e.g. obj/Release/net5.0/win-x64, because the publish
process takes your assemblies from this location when it builds the single-file executable. You will also
need to distribute all the extra files that DinkeyAdd generates. e.g. <file>.dp64.dll.
If you publish using the ReadytoRun compilation this will not work because it includes mixtures of .NET
assemblies and native code and the .NET Shell Method does not support that.
Mono
~~~~
The sample code provided also works with Mono. However, Mono also supports Linux and macOS, and so if you want
to support those OS then please replace dris.cs with dris_mono.cs. Note, dris_mono.cs is very similar to
dris_dotnetcore.cs (see above) but with Mono, 32-bit Linux and 32-bit Mac are also supported and you don't
need to use the debug modules (for release) under macOS.
Visual Studio Installer Projects Extension
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use this extension to create a project in your solution that will create an installation program / msi
file. Please note that after your application has been built you need to protect it with DinkeyAdd before you
can invoke the installer project. You can do this manually by building your application project (not the entire
solution); then adding protection to your application using DinkeyAdd; then building your installer project.
Or you can automate this by executing DinkeyAddCmd as a post-build step. For example:
"c:\program files (x86)\Dinkey Pro 7.6.0\DinkeyAdd\DinkeyAddCmd.exe" c:\adir\mydapf.dapfj /a2
Note - if you specify "primary output" in your installer project then it will take the files from
obj\Release\net5.0 (for example), rather than bin\Release\net5.0. So, you need to add protection to your files
in this folder.
Note - if you use the API Method you will also need to include the protected runtime modules that you use
(e.g. dpwin64.dll). If you use the Shell Method you will also need to include in your installer project all
of the output files mentioned by DinkeyAdd. e.g. <application_name>.dp64.dll

View File

@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DllTest", "DllTest.csproj", "{EDCD7B70-034F-417C-B7C0-E86583C2FC5C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{EDCD7B70-034F-417C-B7C0-E86583C2FC5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EDCD7B70-034F-417C-B7C0-E86583C2FC5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EDCD7B70-034F-417C-B7C0-E86583C2FC5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EDCD7B70-034F-417C-B7C0-E86583C2FC5C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {02BA6556-AD6D-40BD-A7EE-65BEE2095E5C}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,808 @@
// See https://aka.ms/new-console-template for more information
using System;
using System.Runtime.InteropServices;
namespace DllTest
{
public class Program
{
public const int MY_SDSN = 10101; // !!!! change this value to be the value of your SDSN (demo = 10101)
public const string MY_PRODCODE = "DEMO"; // !!!! change this value to match the Product Code in the dongle
/* The sample code contains 11 functions. You will not need to use all these
functions in your code. Just use which ever functions are most appropriate
and customise in your own way. The sample code is just a guide. You should
implement the protection in a stronger way using the techniques described in
the "Increasing your Protection" chapter of the manual.
ProtCheck // a standard protection check
ProtCheckWithAlg // a protection check & executing an Algorithm
WriteBytes // a protection check & write data to the dongle
ReadBytes // a protection check & read data from the dongle
EncryptUserData // a protection check & encrypting data and then decrypting the data
// these functions are the same as the functions listed above but encrypting all parameters passed to our API
ProtCheckEnc // a standard protection check
ProtCheckWithAlgEnc // a protection check & executing an Algorithm
WriteBytesEnc // a protection check & write data to the dongle
ReadBytesEnc // a protection check & read data from the dongle
EncryptUserDataEnc // a protection check & encrypting data and then decrypting the data
// this function displays the current network users
DisplayNetUsers
If you are using Dinkey Lite then you can only use 4 functions:
ProtCheck, ProtCheckWithAlg, ProtCheckEnc, ProtCheckWithAlgEnc
*/
public static void Main(string[] args)
{
// call the function(s) of your choice here
// in this example I have chosen a standard protection check
if (ProtCheck() == 0)
{
DisplayMessage("It worked!"); // NB on failure a message will have already been displayed
}
}
// **************************** ProtCheck *********************************
// standard protection check
public static int ProtCheck()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.PROTECTION_CHECK; // standard protection check
dris.flags = 0; // no extra flags, but you may want to specify some if you want to start a network user or decrement execs,...
ret_code = DinkeyPro.DDProtCheck(dris, null);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
if (dris.prodcode != MY_PRODCODE)
{
DisplayMessage("Incorrect Product Code! Please modify your source code so that MY_PRODCODE is set to be the Product Code in the dongle.");
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
// if you are using a network dongle and you want to list the network users then use this function:
//DisplayNetUsers(dris);
return 0;
}
// **************************** ProtCheckWithAlg ****************************
// !!!! You should replace this function with the one generated by the
// "generate source code" button in Algorithm tab for DinkeyAdd (if you have specified an algorithm)
// or from DinkeyLook if you are using a Dinkey Lite dongle.
private static int MyAlgorithm(int a, int b, int c, int d, int e, int f, int g, int h)
{
return a + b + c + d + e + f + g + h;
}
// NB for this to work you must program at least "user algorithm" into the dongle
// NB We have used a very simple algorithm here (in the MyAlgorithm function). You must patch this with the
// sample code generated by DinkeyAdd for the algorithm that you are using. For Dinkey Lite copy the sample code from DinkeyLook
public static int ProtCheckWithAlg()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.EXECUTE_ALGORITHM; // standard protection check & execute algorithm
dris.flags = 0; // no extra flags, but you may want to specify some if you want to start a network user or decrement execs,...
dris.alg_number = 1; // execute algorithm 1 (you do not need to specify this field if you are only using Lite models).
// you should remove these entries if you are using Dinkey Lite so that algorithm arguments are random
dris.var_a = 1; // sample values
dris.var_b = 2;
dris.var_c = 3;
dris.var_d = 4;
dris.var_e = 5;
dris.var_f = 6;
dris.var_g = 7;
dris.var_h = 8;
ret_code = DinkeyPro.DDProtCheck(dris, null);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
// if you want you can check the algorithm answer - however if algorithm is from your code then best to just use the answer in your code
// !!!! Make sure you have replaced the MyAlgorithm routine with the algorithm you have specified in DinkeyAdd
if (MyAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h) != dris.alg_answer)
{
DisplayMessage("Dinkey protection error!\nYou have not patched your algorithm in the MyAlgorithm routine");
return -1;
}
return 0;
}
// ************************** WriteBytes ******************************
// This writes the Data 0,1,2,3,4,5,6,7,8,9 to the dongle data area at offset 7
// In order for this function to work you will need to have a data area in your dongle that is at least 18 bytes long.
// if you want to write a string then you need to convert it to a byte array first:
// encoding.GetBytes(your_string, 0, your_string.Length, data, 0) where encoding is of ASCIIEncoding type.
public static int WriteBytes()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] DataToWrite = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.WRITE_DATA_AREA; // standard protection check & write data to dongle
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_offset = 7;
dris.rw_length = DataToWrite.GetLength(0);
ret_code = DinkeyPro.DDProtCheck(dris, DataToWrite);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
return 0;
}
// ************************ ReadBytes ************************************
// This reads 10 bytes of data from offset 7 in the dongle data area
// In order for this function to work you will need to have a data area in your dongle that is at least 18 bytes long.
// if you want to read a string then you need to convert it from a byte array (via an array of char)
// CharArray = encoding.GetChars(data); where CharArray is of type char[] and encoding is of type ASCIIEncoding
// your_string = new String(CharArray, 0, your_string_length);
public static int ReadBytes()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] DataToRead = new byte[10];
string DisplayString;
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.READ_DATA_AREA; // standard protection check & read data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_offset = 7;
dris.rw_length = DataToRead.GetLength(0);
ret_code = DinkeyPro.DDProtCheck(dris, DataToRead);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
DisplayString = "Dinkey Dongle data area, offset 7: " + String.Format("{0:D2} {1:D2} {2:D2} {3:D2} {4:D2} {5:D2} {6:D2} {7:D2} {8:D2} {9:D2}",
DataToRead[0], DataToRead[1], DataToRead[2], DataToRead[3], DataToRead[4], DataToRead[5], DataToRead[6], DataToRead[7], DataToRead[8], DataToRead[9]);
DisplayMessage(DisplayString);
return 0;
}
// ************************** EncryptUserData ************************************
// This function will do a protection check and ask the dongle to encrypt some data using encryption key 1
// It will then do another protection check & decrypt the data
// if you want to encrypt of decrypt string then see comment for WriteBytes and ReadBytes
public static int EncryptUserData()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] Data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
string DisplayString;
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.ENCRYPT_USER_DATA; // standard protection check & encrypt data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT;
dris.rw_length = Data.GetLength(0);
dris.data_crypt_key_num = 1;
ret_code = DinkeyPro.DDProtCheck(dris, Data);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// ... could add code to check other elements of the DRIS, e.g. ret_code, sdsn, ...
// Now decrypt the same data to get the original values
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.DECRYPT_USER_DATA; // standard protection check & read data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_length = Data.GetLength(0);
dris.data_crypt_key_num = 1;
ret_code = DinkeyPro.DDProtCheck(dris, Data);
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
DisplayString = "decrypted data is: " + String.Format("{0:D2} {1:D2} {2:D2} {3:D2} {4:D2} {5:D2} {6:D2} {7:D2} {8:D2} {9:D2}",
Data[0], Data[1], Data[2], Data[3], Data[4], Data[5], Data[6], Data[7], Data[8], Data[9]);
DisplayMessage(DisplayString);
return 0;
}
// !!!!!!!!!!! all the functions listed below encrypt all parameters to our API !!!!!!!!!!!!!!!!!!!!!
// In order for them to work properly you need to choose "Encrypt DRIS" and "Encrypt Data passed to API"
// in the Extra Security tab of DinkeyAdd. In this example, for Data Encryption I use the r/w algorithm
// but the code can be modified easily to use the 3 encryption parameters.
// !!!! please overwrite this function with the one generated by DinkeyAdd for R/W Algorithm
private static int MyRWAlgorithm(int a, int b, int c, int d, int e, int f, int g, int h)
{
return a ^ b ^ c ^ d ^ e ^ f;
}
// !!!! please overwrite this function with the one generated by DinkeyAdd
private static void CryptDRIS(DRIS dris)
{
int i, j, k;
byte[] bigseed = new byte[256];
byte[] S = new byte[256];
byte temp, t;
byte[] dris_bytes = new byte[Marshal.SizeOf(dris)];
dris.DrisToByteArray(dris, dris_bytes); // convert DRIS to byte array so we can encrypt it
for (i = 0; i < 256; i += 8)
{
dris.Set4Bytes(bigseed, i, dris.seed1);
dris.Set4Bytes(bigseed, i + 4, dris.seed2);
}
for (i = 0; i < 256; i++)
S[i] = (byte)i;
for (i = 0, j = 0; i < 256; i++)
{
j = (j + S[i] + bigseed[i] + 123) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
}
for (i = 0, j = 0, k = 16; k < Marshal.SizeOf(dris); k++)
{
i = (i + 1) % 256;
j = (j + S[i] + 212) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
t = (byte)(S[i] + S[j] + 97);
dris_bytes[k] ^= S[t];
}
dris.ByteArrayToDris(dris_bytes, dris); // convert it back again
return;
}
// !!!! please overwrite this function with the one generated by DinkeyAdd
private static void CryptApiData(DRIS dris, byte[] data, int length, int alg_answer)
{
int i, j, k;
byte[] bigseed = new byte[256];
byte[] S = new byte[256];
byte temp, t;
for (i = 0; i < 256; i += 8)
{
dris.Set4Bytes(bigseed, i, dris.seed1);
dris.Set4Bytes(bigseed, i + 4, dris.seed2);
}
for (i = 0; i < 256; i++)
S[i] = (byte)i;
for (i = 0, j = 0; i < 256; i++)
{
j = (j + S[i] + bigseed[i] + (alg_answer & 0xff)) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
}
for (i = 0, j = 0, k = 0; k < length; k++)
{
i = (i + 1) % 256;
j = (j + S[i] + ((alg_answer >> 8) & 0xff)) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
t = (byte)(S[i] + S[j] + ((alg_answer >> 16) & 0xff));
data[k] ^= S[t];
}
return;
}
// **************************** ProtCheckEnc ******************************
// We encrypt the DRIS passed to the API. Patch the CryptDRIS function in this file from source code generated by DinkeyAdd.
public static int ProtCheckEnc()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.PROTECTION_CHECK; // standard protection check
dris.flags = 0; // no extra flags, but you may want to specify some if you want to start a network user or decrement execs,...
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, null);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
if (dris.prodcode != MY_PRODCODE)
{
DisplayMessage("Incorrect Product Code! Please modify your source code so that MY_PRODCODE is set to be the Product Code in the dongle.");
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
return 0;
}
// **************************** ProtCheckWithAlgEnc *************************
// NB for this to work you must program at least "user algorithm" into the dongle
// NB We have used a very simple algorithm here (in the MyAlgorithm function). You must patch this with the
// sample code generated by DinkeyAdd for the algorithm that you are using. For Dinkey Lite copy source from DinkeyLook.
// We encrypt the DRIS passed to the API. Patch the CryptDRIS function in this file from source code generated by DinkeyAdd.
public static int ProtCheckWithAlgEnc()
{
int ret_code;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.EXECUTE_ALGORITHM; // standard protection check & execute algorithm
dris.flags = 0; // no extra flags, but you may want to specify some if you want to start a network user or decrement execs,...
dris.alg_number = 1; // execute algorithm 1 (you do not need to specify this field if you are only using Lite models).
// you should remove these entries if you are using Dinkey Lite so that algorithm arguments are random
dris.var_a = 1; // sample values
dris.var_b = 2;
dris.var_c = 3;
dris.var_d = 4;
dris.var_e = 5;
dris.var_f = 6;
dris.var_g = 7;
dris.var_h = 8;
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, null);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
// if you want you can check the algorithm answer - however if algorithm is from your code then best to just use the answer in your code
// !!!! Make sure you have replaced the MyAlgorithm routine with the algorithm you have specified in DinkeyAdd
if (MyAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h) != dris.alg_answer)
{
DisplayMessage("Dinkey protection error!\nYou have not patched your algorithm in the MyAlgorithm routine");
return -1;
}
return 0;
}
// ************************** WriteBytesEnc ***************************
// This writes the Data 0,1,2,3,4,5,6,7,8,9 to the dongle data area at offset 7
// In order for this function to work you will need to have a data area in your dongle that is at least 18 bytes long.
// We encrypt the DRIS and Data passed to the API. Patch the CryptDRIS and CryptApiData functions in this file from source code generated by DinkeyAdd.
// if you want to write strings then see comment for WriteBytes
public static int WriteBytesEnc()
{
int ret_code, alg_ans;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] DataToWrite = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.WRITE_DATA_AREA; // standard protection check & write data to dongle
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_offset = 7;
dris.rw_length = DataToWrite.GetLength(0);
// calculate r/w algorithm answer - NB need to replace MyRWAlgorithm code with code for r/w algorithm
alg_ans = MyRWAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h);
// encrypt data we want to write.
CryptApiData(dris, DataToWrite, DataToWrite.GetLength(0), alg_ans);
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, DataToWrite);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
return 0;
}
// ************************ ReadBytesEnc *********************************
// This reads 10 bytes of data from offset 7 in the dongle data area
// In order for this function to work you will need to have a data area in your dongle that is at least 18 bytes long.
// We encrypt the DRIS and Data passed to the API. Patch the CryptDRIS and CryptApiData functions in this file from source code generated by DinkeyAdd.
// if you want to read strings then see comment for ReadBytes
public static int ReadBytesEnc()
{
int ret_code, alg_ans;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
byte[] DataRead = new byte[10];
string DisplayString;
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.READ_DATA_AREA; // standard protection check & read data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris.rw_offset = 7;
dris.rw_length = DataRead.GetLength(0);
// calculate r/w algorithm answer - NB need to replace MyRWAlgorithm code with code for r/w algorithm
alg_ans = MyRWAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h);
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, DataRead);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
// later on in your program you can check the return code again
if (dris.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
// decrypt data that was read.
CryptApiData(dris, DataRead, DataRead.GetLength(0), alg_ans);
DisplayString = "Dinkey Dongle data area, offset 7: " + String.Format("{0:D2} {1:D2} {2:D2} {3:D2} {4:D2} {5:D2} {6:D2} {7:D2} {8:D2} {9:D2}",
DataRead[0], DataRead[1], DataRead[2], DataRead[3], DataRead[4], DataRead[5], DataRead[6], DataRead[7], DataRead[8], DataRead[9]);
DisplayMessage(DisplayString);
return 0;
}
// ************************** EncryptUserDataEnc *********************************
// This function will do a protection check and ask the dongle to encrypt some data using encryption key 1
// It will then do another protection & decrypt the data
// We encrypt the DRIS and Data passed to/from the API. Patch the CryptDRIS and CryptApiData functions in this file from source code generated by DinkeyAdd.
// if you want to encrypt of decrypt strings then see comment for WriteBytes and ReadBytes
public static int EncryptUserDataEnc()
{
int ret_code, alg_ans;
DRIS dris = new DRIS(); // initialise the DRIS with random values & set the header
DRIS dris2 = new DRIS(); // initialise the DRIS with random values & set the header
byte[] Data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
string DisplayString;
dris.size = Marshal.SizeOf(dris);
dris.function = DRIS.ENCRYPT_USER_DATA; // standard protection check & encrypt data
dris.flags = DRIS.USE_FUNCTION_ARGUMENT;
dris.rw_length = Data.GetLength(0);
dris.data_crypt_key_num = 1;
// calculate r/w algorithm answer - NB need to replace MyRWAlgorithm code with code for r/w algorithm
alg_ans = MyRWAlgorithm(dris.var_a, dris.var_b, dris.var_c, dris.var_d, dris.var_e, dris.var_f, dris.var_g, dris.var_h);
// encrypt data we pass to our API.
CryptApiData(dris, Data, Data.GetLength(0), alg_ans);
CryptDRIS(dris); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris, Data);
CryptDRIS(dris); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris.ext_err);
return ret_code;
}
// ... could add code to check other elements of the DRIS, e.g. ret_code, sdsn, ...
// NB use another dris so that we can ensure elements are initialised to different random numbers
dris2.size = Marshal.SizeOf(dris2);
dris2.function = DRIS.DECRYPT_USER_DATA; // standard protection check & read data
dris2.flags = DRIS.USE_FUNCTION_ARGUMENT; // you have to do it like this in C#
dris2.rw_length = Data.GetLength(0);
dris2.data_crypt_key_num = 1;
CryptDRIS(dris2); // encrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
ret_code = DinkeyPro.DDProtCheck(dris2, Data);
CryptDRIS(dris2); // decrypt DRIS (!!!!you should separate from DDProtCheck for greater security)
if (ret_code != 0)
{
DisplayError(ret_code, dris2.ext_err);
return ret_code;
}
// later in your code you can check other values in the DRIS...
if (dris2.sdsn != MY_SDSN)
{
DisplayMessage("Incorrect SDSN! Please modify your source code so that MY_SDSN is set to be your SDSN.");
return -1;
}
// later on in your program you can check the return code again
if (dris2.ret_code != 0)
{
DisplayMessage("Dinkey Dongle protection error");
return -1;
}
alg_ans = MyRWAlgorithm(dris2.var_a, dris2.var_b, dris2.var_c, dris2.var_d, dris2.var_e, dris2.var_f, dris2.var_g, dris2.var_h);
// decrypt data that was passed to us by the API.
CryptApiData(dris2, Data, Data.GetLength(0), alg_ans);
DisplayString = "decrypted data is: " + String.Format("{0:D2} {1:D2} {2:D2} {3:D2} {4:D2} {5:D2} {6:D2} {7:D2} {8:D2} {9:D2}",
Data[0], Data[1], Data[2], Data[3], Data[4], Data[5], Data[6], Data[7], Data[8], Data[9]);
DisplayMessage(DisplayString);
return 0;
}
// *********************** DisplayNetUsers *******************************
// This function displays the current network users (for DinkeyNet only).
// The DDProtCheck function must be called before this function is called.
// (Normally you would use DinkeyServer to view the network users but this enables you to do it from the client if you want)
public static int DisplayNetUsers(DRIS dris)
{
string DisplayString;
int num_net_users, extended_error, ret_code, i, max_net_users;
NU_INFO[]? nu_info;
if (dris.net_users == -1)
max_net_users = 100; // if unlimited network users are allowed then display up to 100 users (for example)
else
max_net_users = dris.net_users;
if (max_net_users == 0) // no network users are allowed, so nothing to do!
return 0;
if (dris.model < 3)
{
DisplayMessage("A network dongle has not been detected. Therefore you cannot display the network users.");
return -1;
}
ret_code = DinkeyPro.DDGetNetUserList(null, out num_net_users, out nu_info, max_net_users, out extended_error);
if (ret_code != 0)
{
DisplayMessage(String.Format("Error {0}/{1} finding network user information.", ret_code, extended_error));
}
else
{
DisplayString = String.Format("number of net users: {0}", num_net_users) + Environment.NewLine;
if (nu_info != null)
{
for (i = 0; i < num_net_users; i++)
{
DisplayString += String.Format("{0}. licence: {1}, user: {2}, computer: {3}, ip address: {4}", i + 1,
nu_info[i].licenceName, nu_info[i].userName, nu_info[i].computerName, nu_info[i].ipAddress);
DisplayString += Environment.NewLine;
}
}
DisplayMessage(DisplayString);
}
return ret_code;
}
// to display common errors that occur - !!!! you will want to change these messages
private static void DisplayError(int ret_code, int ext_err)
{
string DisplayString;
switch (ret_code)
{
case 401:
DisplayMessage("Error! No dongles detected!");
break;
case 403:
DisplayMessage("Error! A dongle was detected but it was a different type to the one specified in DinkeyAdd.");
break;
case 404:
DisplayMessage("Error! A dongle was detected but it was a different model to those specified in DinkeyAdd.");
break;
case 409:
DisplayMessage("Error! The dongle detected has not been programmed by DinkeyAdd.");
break;
case 410:
DisplayMessage("Error! A dongle was detected but it has a different Product Code to the one specified in DinkeyAdd.");
break;
case 411:
DisplayMessage("Error! The dongle detected does not contain the licence associated with this program.");
break;
case 413:
DisplayMessage("Error! This program has not been protected by DinkeyAdd. For guidance please read the DinkeyAdd chapter of the Dinkey manual.");
break;
case 417:
DisplayMessage("Error! One or more of the parameters set in the DRIS is incorrect.\nIt could also be caused if you are encrypting the DRIS in your code but did not specify DRIS encryption in DinkeyAdd - or vice versa.");
break;
case 423:
DisplayMessage("Error! The number of network users has been exceeded.");
break;
case 435:
DisplayMessage("Error! DinkeyServer has not been detected on the network.");
break;
case 922:
DisplayMessage("Error! The Software Key has expired.");
break;
// internal error - cannot load DLL
case -1:
DisplayMessage("Error! Cannot call protection check because DLL is not loaded.");
break;
default:
DisplayString = "An error occurred checking the dongle. Error: " + String.Format("{0:D}", ret_code) + "\nExtended Error: " + String.Format("{0:D}", ext_err);
DisplayMessage(DisplayString);
break;
}
return;
}
private static void DisplayMessage(string my_message)
{
// !!!! for Console programs use this line
Console.WriteLine(my_message);
// !!!! for Windows programs use this line
// MessageBox.Show(my_message, "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
}
}

View File

@@ -0,0 +1,361 @@
// !! this file should not be modified
using System;
using System.Runtime.InteropServices; // so we can marshal the DRIS as a block of memory
using System.Text; // so we can extract / set strings in the DRIS
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public class DRIS
{
// the first 4 fields are never encrypted
public byte header1; // should be set to "DRIS"
public byte header2;
public byte header3;
public byte header4;
// inputs
public int size; // size of this structure
public int seed1; // seed for data/dris encryption
public int seed2; // as above
// (maybe encrypted from now on)
public int function; // specify only one function
public int flags; // options for the function selected. To use more than one OR them together: OPTION1 | OPTION2...
public uint execs_decrement; // amount by which to dec execs if we use flag: DEC_MANY_EXECS
public int data_crypt_key_num; // number of the key (1-3) that the dongle uses to encrypt or decrypt user data
public int rw_offset; // offset in the dongle data area to read or write data
public int rw_length; // length of data are to read/write/encrypt/decrypt
public IntPtr DoNotUse; // do not use the rw_data_ptr element use the "Data" argument of the DDProtCheck function
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] // NB access this field by using alg_licence_name (see below)
private byte[] _alt_licence_name = { 0 }; // protection check for different licence instead of this one
public int var_a; // variable values for user algorithm
public int var_b;
public int var_c;
public int var_d;
public int var_e;
public int var_f;
public int var_g;
public int var_h;
public int alg_number; // the number of the user algorithm that you want to execute
// outputs
public int ret_code; // return code from the protection check
public int ext_err; // extended error
public int type; // type of dongle detected. 1 = Pro, 2 = FD
public int model; // model of dongle detected. 1 = Lite, 2 = Plus, 4 = Net 5, 7 = Net Unlimited
public int sdsn; // Software Developer's Serial Number
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)] // NB access this field by using prodcode (see below)
private byte[] _prodcode = { 0 }; // product code (null-terminated)
public uint dongle_number;
public int update_number;
public uint data_area_size; // size of the data area in the dongle detected
public int max_alg_num; // number of algorithms in the dongle detected
public int execs; // executions left: -1 indicates 'no limit'
public int exp_day; // expiry day: -1 indicates 'no limit'
public int exp_month; // expiry month: -1 indicates 'no limit'
public int exp_year; // expiry year: -1 indicates 'no limit'
public uint features; // features value
public int net_users; // maximum number of network users for the dongle detected: -1 indicates 'mo limit'
public int alg_answer; // answer to the user algorithm executed with the given variable values
public uint fd_capacity; // capacity of the data area in FD dongle. Currently fixed at ~10MB but may change in the future.
[MarshalAs(UnmanagedType.ByValArray, SizeConst=128)] // NB access this field by using fd_drive (see below)
private byte[] _fd_drive = { 0 }; // fd drive letter (null-terminated)
public int swkey_type; // 0 = no swkey detected, 1 = temporary software key, 2 = demo software key
public int swkey_exp_day; // software key expiry date (if software key detected)
public int swkey_exp_month;
public int swkey_exp_year;
// NB we have to do it this way because we cannot encrypt strings correctly unless they are byte arrays
public string prodcode
{
get
{
StringBuilder sb = new StringBuilder(12);
foreach (byte b in _prodcode)
{
if (b == 0)
return sb.ToString();
else
sb.Append((char)b);
}
return sb.ToString();
}
}
public string fd_drive
{
get
{
StringBuilder sb = new StringBuilder(128);
foreach (byte b in _fd_drive)
{
if (b == 0)
return sb.ToString();
else
sb.Append((char)b);
}
return sb.ToString();
}
}
// NB we have to do it this way because we cannot encrypt strings correctly unless they are byte arrays
public string alt_licence_name
{
set
{
int i;
StringBuilder sb = new StringBuilder(value, 256);
for (i=0; i<sb.Length; i++)
{
_alt_licence_name[i] = (byte)sb[i];
}
_alt_licence_name[i] = 0; // null terminate
}
}
// sets 4 bytes from an integer at the specified offset in a data array
public void Set4Bytes(byte[] data, int offset, int value)
{
data[offset] = (byte)(value & 0xff);
data[offset+1] = (byte)((value >> 8) & 0xff);
data[offset+2] = (byte)((value >> 16) & 0xff);
data[offset+3] = (byte)((value >> 24) & 0xff);
return;
}
// converts to DRIS structure to a byte array (so we can do encryption)
public void DrisToByteArray(DRIS dris, byte[] data)
{
GCHandle MyGC = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.StructureToPtr(dris, MyGC.AddrOfPinnedObject(), false);
MyGC.Free();
return;
}
// converts a byte array to the DRIS structure (so we can do encryption)
public void ByteArrayToDris(byte[] data, DRIS dris)
{
GCHandle MyGC = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), dris);
MyGC.Free();
return;
}
// to make a new instance of this class, initialise every element to a random value and then set the header
public DRIS()
{
Random rnd = new Random();
Byte[] temp = new Byte[Marshal.SizeOf(this)];
rnd.NextBytes(temp);
ByteArrayToDris(temp, this);
this.header1 = (byte)'D';
this.header2 = (byte)'R';
this.header3 = (byte)'I';
this.header4 = (byte)'S';
}
// functions - must specify only one
public const int PROTECTION_CHECK = 1; // checks for dongle, check program params...
public const int EXECUTE_ALGORITHM = 2; // protection check + calculate answer for specified algorithm with specified inputs
public const int WRITE_DATA_AREA = 3; // protection check + writes dongle data area
public const int READ_DATA_AREA = 4; // protection check + reads dongle data area
public const int ENCRYPT_USER_DATA = 5; // protection check + the dongle will encrypt user data
public const int DECRYPT_USER_DATA = 6; // protection check + the dongle will decrypt user data
public const int FAST_PRESENCE_CHECK = 7; // checks for the presence of the correct dongle only with minimal security, no flags allowed.
public const int STOP_NET_USER = 8; // stops a network user (a protection check is NOT performed)
// flags - can specify as many as you like
public const int DEC_ONE_EXEC = 1; // decrement execs by 1
public const int DEC_MANY_EXECS = 2; // decrement execs by number specified in execs_decrement
public const int START_NET_USER = 4; // starts a network user
public const int USE_FUNCTION_ARGUMENT = 16; // use the extra argument in the function for pointers
public const int CHECK_LOCAL_FIRST = 32; // always look in local ports before looking in network ports
public const int CHECK_NETWORK_FIRST = 64; // always look on the network before looking in local ports
public const int USE_ALT_LICENCE_NAME = 128; // use name specified in alt_licence_name instead of the default one
public const int DONT_SET_MAXDAYS_EXPIRY = 256; // if the max days expiry date has not been calculated then do not do it this time
public const int MATCH_DONGLE_NUMBER = 512; // restrict the search to match the dongle number specified in the DRIS
public const int DONT_RETURN_FD_DRIVE = 1024; // if an FD dongle has been detected then don't return the flash drive/mount name in the DRIS
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct NU_INFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string licenceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=50)]
public string userName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string computerName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=16)]
public string ipAddress;
}
// DDProtCheck
// Windows 32-bit protection check (loads 32-bit DLL)
class DDProtCheckWin32
{
[DllImport("dpwin32.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[]? data);
}
// Windows 64-bit protection check (loads 64-bit DLL)
class DDProtCheckWin64
{
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[]? data);
}
// Linux 64-bit protection check (loads 64-bit so) (NB only 64-bit Linux is supported by .NET Core)
class DDProtCheckLin64
{
[DllImport("dplin64.so", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[]? data);
}
// Mac 64-bit protection check (loads 64-bit dylib) (NB only x64 Mac code is supported by .NET Core) (NB we found that the release module dpmac64.dylib crashed)
class DDProtCheckMac64
{
[DllImport("dpmac64debug.dylib", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[]? data);
}
// DDGetNetUserList
// Windows 32-bit get network user info (loads 32-bit DLL)
class DDGetNetUserListWin32
{
[DllImport("dpwin32.dll", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string? licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// Windows 64-bit get network user info (loads 64-bit DLL)
class DDGetNetUserListWin64
{
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string? licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// Linux 64-bit get network user info (loads 64-bit DLL)
class DDGetNetUserListLin64
{
[DllImport("dplin64.so", CharSet = CharSet.Ansi)]
public static extern int DDGetNetUserList(string? licence_name, out int num_net_users, byte[] nu_info_bytes, int num_info_structs, out int extended_error);
}
// call our API - we only want to load the correct DLL for the OS and bit-ness of the computer. The other DLLs may not exist.
class DinkeyPro
{
// calls the DDProtCheck function in the appropriate DLL
public static int DDProtCheck(DRIS dris, byte[]? data)
{
int ret_code = -1;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // method valid from .NET Core 1.0 and .NET framework 4.7
{
if (Environment.Is64BitProcess) // method valid from .NET Core 2.0 and .NET framework 4.0
{
try
{
ret_code = DDProtCheckWin64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
DisplayMessage("Error! Cannot find dpwin64.dll. This should be in the same folder as DllTest.");
}
}
else
{
try
{
ret_code = DDProtCheckWin32.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
DisplayMessage("Error! Cannot find dpwin32.dll. This should be in the same folder as DllTest.");
}
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
try
{
ret_code = DDProtCheckLin64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
DisplayMessage("Error! Cannot find dplin64.so. This should be in the same folder as DllTest.");
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
try
{
ret_code = DDProtCheckMac64.DDProtCheck(dris, data);
}
catch (DllNotFoundException)
{
DisplayMessage("Error! Cannot find dpmac64debug.dylib. This should be in the same folder as DllTest.");
}
}
else
{
DisplayMessage("Error! Dinkey Pro/FD not supported on this OS.");
}
return ret_code;
}
public static int DDGetNetUserList(string? licence_name, out int num_net_users, out NU_INFO[]? nu_info, int num_info_structs, out int extended_error)
{
int ret_code = -1;
int i;
extended_error = num_net_users = 0;
byte[] nu_info_bytes = new byte[num_info_structs * Marshal.SizeOf(typeof(NU_INFO))];
byte[] nu_info_one_struct = new byte[Marshal.SizeOf(typeof(NU_INFO))];
GCHandle MyGC;
nu_info = null;
// call the function and get info as a byte array
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
if (Environment.Is64BitProcess)
ret_code = DDGetNetUserListWin64.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
else
ret_code = DDGetNetUserListWin32.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
ret_code = DDGetNetUserListLin64.DDGetNetUserList(licence_name, out num_net_users, nu_info_bytes, num_info_structs, out extended_error);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
DisplayMessage("Error! This function is not supported in the Mac debug module.");
}
if (ret_code != 0)
return ret_code;
// convert byte array to an array of structs
nu_info = new NU_INFO[num_net_users];
for (i=0; i<num_net_users; i++)
{
Array.Copy(nu_info_bytes, i*Marshal.SizeOf(typeof(NU_INFO)), nu_info_one_struct, 0, Marshal.SizeOf(typeof(NU_INFO)));
MyGC = GCHandle.Alloc(nu_info_one_struct, GCHandleType.Pinned);
NU_INFO? an_nu_info = (NU_INFO?)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), typeof(NU_INFO));
if (an_nu_info != null)
nu_info[i] = (NU_INFO)an_nu_info;
MyGC.Free();
}
return 0;
}
private static void DisplayMessage(string my_message)
{
// !!!! for Console programs use this line
Console.WriteLine(my_message);
// !!!! for Windows programs use this line
// MessageBox.Show(my_message, "Sample", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
}

View File

@@ -0,0 +1,155 @@
DllTest - sample code to call Runtime module in C# 8 using VS 2022 and higher
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is written in Visual Studio 2022 but will work in more recent versions of Visual Studio
(they will upgrade the Project to the latest version. If prompted you should also upgrade the .NET
framework the project requires). If you are using an older version of Visual Studio please use the
Visual Studio 2002 sample. The code in this project is written in C# version 10. If you are using an
older version of C# then please use the Visual Studio 2002 project.
This sample is a Console application but the code can be easily adapted to be used for other types
applications.
This sample is very similar to the Visual Studio 2002 sample - however the C# code has been updated
to prevent possible Null reference exceptions - introduced in C# version 8.
The main source files in the project are:
File name Description
program.cs main source code file for C#
dris.cs contains the DRIS structure and low-level functions to manipulate it.
The best approach is to compile the sample code and see how it works and then to take the appropriate code
and apply it to your own project. You should include the dris.cs file in your project and use/modify which
ever functions from program.cs you feel are appropriate. The dris.cs file should not be modified.
The sample code contains 11 functions. You will not need to use all these functions in your code. Just use
which ever functions are most appropriate and customise in your own way. The sample code is just a guide.
You should implement the protection in a stronger way using the techniques described in the
"Increasing your Protection" chapter of the manual.
Code marked with !!!! are places where you should customise the sample code so that it will work properly:
* Change the MY_SDSN value to the value of your SDSN
* Change the MY_PRODCODE value to the Product Code in the dongle
* Change the MyAlgorithm code (if you call a user algorithm)
* Change the CryptDRIS code (if you encrypt the DRIS)
* Change the CryptApiData (if you encrypt Data you send to our API)
* Change the MyRWAlgorithm code (if encrypt Data you send to our API using the R/W algorithm)
You will also probably want to replace our error messages with your own. However, you should still
display or log any error codes returned by the protection check otherwise you will not be able to
identify the cause of the error. (You can look up error codes in our knowledge base: microcosm.com/kb).
Note - as you are using the API method in this sample you should protect the correct Dinkey Pro runtime
(e.g. dpwin64.dll) and not your program directly. Because your program is linked to the DLL it is protected.
You can also protect your program with the Shell Method should you wish.
You need to protect the appropriate runtime module for the Platforms you support.
Windows x64 - dpwin64.dll
Windows x86 - dpwin32.dll
Linux x64 - dplin64.so
macOS x64 - dpmac64debug.dylib
If you are using "Any CPU" then include all of the modules. The protected runtime module should be in the
same directory as your compiled assemblies. e.g. bin\release\net6.0.
Note - if you need to protect multiple runtime modules then you will probably want to protect these modules
to the same licence so that they share a common set of protection parameters.
Make sure you remember to do the following:
1) Insert the following namespaces in your code file:
using System.Runtime.InteropServices;
2) Insert the dris.cs file in your project.
2) You need to output the protected runtime modules(s) (e.g. dpwin64.dll etc) to the folder that contains your
assemblies. Otherwise the System.DllNotFoundException error will appear when you run DllTest.
If you wish you can rename the runtime module(s) to a name of your choice. In this case you will need to
modify the dll name in the dris.cs file.
Note - CSharp is an interpreted language and so it is easier to decompile than other languages. You can
improve security if you use an obfuscator to obfuscate your code. Or - even better - you could use the
Shell Method to protect your assemblies. This encrypts your code (making it impossible to decompile).
Notes on Debugging 64-bit Code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you use the 64-bit runtime module (dpwin64.dll) to protect your software the anti-debug code is so
strong that if you are debugging your code, after the call DDProtCheck then it will crash with an SEH
exception. If you want to be able to debug your code then you can setup your project so that your code calls
the debug module (dpwin64debug.dll) in your "debug" build and the standard module (dpwin64.dll) in your
release build. You can do this by modifying the declaration of DDProtCheck64 in dris.cs like this:
class DDProtCheck64
{
#if DEBUG ' debug module
[DllImport("dpwin64debug.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[]? data);
#else ' standard module
[DllImport("dpwin64.dll", CharSet = CharSet.Ansi)]
public static extern int DDProtCheck([In, Out, MarshalAs(UnmanagedType.LPStruct)]DRIS dris, byte[]? data);
#endif
}
Note - the debug module has the following restrictions:
1) It will not correctly start a network user (network dongles only). However, other than that the protection
check will function correctly and return success.
2) You will not be able to encrypt the DRIS. (If you do encrypt the DRIS in your release build then you
should make sure that CryptDRIS does not get called in your debug build).
3) The protection check will take slightly longer than normal.
4) The DDGetNetUserList function will return error 428 (not implemented).
5) A temporary subprocess is created which may be (falsely) detected as malicious by anti-virus programs.
This behaviour does not occur in 32-bit code, so if you are using dpwin32.dll then you can debug your code.
Important Note for Windows Store App Developers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Universal Windows Platform (UWP) application (previously called Windows Store Apps or Metro Apps) are not
compatible with Lite or Plus dongles because the restrictions imposed by these applications. However, you
can protect these Apps with network dongles (because the restrictive access is performed by the non-UWP
DinkeyServer process). If you do this you will need to enable the "Private Networks (Client and Server)"
Capability in your package manifest.
Other Notes
~~~~~~~~~~~
The Shell Method is compatible with .NET Core Console, Windows.Forms and WPF applications. It is supported
under Windows and Linux but not MacOS. It is only supported for .NET Core version 3.0 or higher. If you are
using the Shell Method then you should protect your compiled dll and not the "appHost" (this is a native
executable which is just a stub program that loads the assemblies in your dll). Also do not use "dotnet run"
to launch your application - it will run the unprotected version. Either launch the executable or run using
"dotnet <program.dll>".
If you publish a "single-file executable" file then although this file can be protected we do not recommend
it because it is not secure. (The single-file executable just comprises a stub loader with your compiled
assemblies and configuration files appended to the end of the executable. These files are just considered as
data appended to the executable file in a custom format and therefore are not protected. When you shell
protect your executable you are just protecting the loader but not your assemblies). Instead you need to
build your code and then add protection before publishing. You should protect your assemblies in the obj
directory (and in the platform type you specified) e.g. obj/Release/net6.0/win-x64, because the publish
process takes your assemblies from this location when it builds the single-file executable. You will also
need to distribute all the extra files that DinkeyAdd generates. e.g. <file>.dp64.dll.
If you publish using the ReadytoRun compilation this will not work because it includes mixtures of .NET
assemblies and native code and the .NET Shell Method does not support that.
Visual Studio Installer Projects Extension
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use this extension to create a project in your solution that will create an installation program / msi
file. Please note that after your application has been built you need to protect it with DinkeyAdd before you
can invoke the installer project. You can do this manually by building your application project (not the entire
solution); then adding protection to your application using DinkeyAdd; then building your installer project.
Or you can automate this by executing DinkeyAddCmd as a post-build step. For example:
"c:\program files (x86)\Dinkey Pro 7.6.0\DinkeyAdd\DinkeyAddCmd.exe" c:\adir\mydapf.dapfj /a2
Note - if you specify "primary output" in your installer project then it will take the files from
obj\Release\net5.0 (for example), rather than bin\Release\net5.0. So, you need to add protection to your files
in this folder.
Note - you will also need to include in your installer project all of the output files mentioned by DinkeyAdd.
e.g. <application_name>.dp64.dll

View File

@@ -0,0 +1,23 @@
Which Project should I use?
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Visual Studio 2002 project will work for any version of Visual Studio from
Visual Studio 2002 to Visual Studio 2019. This project is a Windows Form
application targeting the .NET 4 Framework. However, it can be easily adapted to
target .NET Core or .NET 5 (and higher). The C# code is written in C# version 1.
The Visual Studio 2022 project will work with Visual Studio 2022 (and higher).
It is a Console application targeting .NET 6 and using C# version 10. If you want
to target earlier versions of .NET or C# then use the Visual Studio 2002 project.
The C# code is very similar in both projects. However, C# v8 required changes to
account for possible Null reference exceptions.
Visual Studio 2019 was the first version of VS to support C# v8. However, null
reference warnings are turned off by default, so you will get warnings if you
compile the VS2022 C# code.
On the other hand in Visual Studio 2022 null reference warnings are turned on by
default so you will get warnings if you compile the VS2002 C# code.
Whichever project you use always read the "readme" file for important instructions.