Ejemplo n.º 1
0
        /// <summary>
        /// 开始线程.
        /// </summary>
        /// <param name="SESSION">会话端.</param>
        /// <param name="InPacket">入口数据包.</param>
        /// <param name="OutPacket">出口数据包.</param>
        /// <param name="Key">The key.</param>
        protected override void ExecutePlugIn(eTerm.AsyncSDK.Core.eTerm363Session SESSION, eTerm.AsyncSDK.Core.eTerm363Packet InPacket, eTerm.AsyncSDK.Core.eTerm363Packet OutPacket, eTerm.AsyncSDK.AsyncLicenceKey Key)
        {
            string ExpressValue = Regex.Match(Encoding.GetEncoding("gb2312").GetString(SESSION.UnInPakcet(InPacket)).Trim(), @"^!api\s+([A-Z0-9]+)", RegexOptions.IgnoreCase | RegexOptions.Multiline).Groups[1].Value;

            try
            {
                StringBuilder ApiKey = new StringBuilder();
                foreach (byte c in TEACrypter.MD5(Encoding.Default.GetBytes(Key.Company)))
                {
                    ApiKey.Append(String.Format("{0:X}", c).PadLeft(2, '0'));
                }
                if (!ApiKey.ToString().Equals(ExpressValue))
                {
                    SESSION.Close(); return;
                }
                ApiKey = new StringBuilder();
                foreach (byte c in TEACrypter.MD5(Encoding.Default.GetBytes(ExpressValue)))
                {
                    ApiKey.Append(String.Format("{0:X}", c).PadLeft(2, '0'));
                }
                SESSION.SendPacket(__eTerm443Packet.BuildSessionPacket(SESSION.SID, SESSION.RID, ApiKey.ToString()));
            }
            catch (Exception ex)
            {
                SESSION.Close();
                //SESSION.SendPacket(__eTerm443Packet.BuildSessionPacket(SESSION.SID, SESSION.RID, ex.Message));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Handles the Click event of the btnBuilder control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnBuilder_Click(object sender, EventArgs e)
        {
            try {
                TEACrypter Crypter = new TEACrypter();
                byte[]     keys    = TEACrypter.MD5(Encoding.Default.GetBytes(string.Format(@"{0}", this.txtCode.Text)));
                //byte[] Result = Crypter.Encrypt(Encoding.Default.GetBytes(this.txtCode.Text), keys);



                AsyncLicenceKey Key = new AsyncLicenceKey()
                {
                    Company            = txtCompany.Text,
                    ExpireDate         = this.PickerExpire.Value,
                    Key                = keys,
                    MaxAsync           = int.Parse(txtASyncCount.Value.ToString()),
                    MaxTSession        = int.Parse(txtMaxTSession.Value.ToString()),
                    AllowDatabase      = chkAllowDb.Checked,
                    MaxCommandPerMonth = int.Parse(maskedTextBox1.Text),
                    connectionString   = this.txtConnectString.Text,
                    providerName       = this.txtProviderName.Text,
                    AllowAfterValidate = true,
                    AllowIntercept     = chkAllowInter.Checked,
                    RemainingMinutes   = ((TimeSpan)(this.PickerExpire.Value - DateTime.Now)).TotalMinutes,
                    AllowDbLog         = checkBox1.Checked
                };

                byte[] Buffer = Key.XmlSerialize(keys, this.txtFileName.Text);
                MessageBox.Show(string.Format(@"授权文件{0}已经生成!", txtFileName.Text), "授权提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Validates the net.
        /// </summary>
        /// <returns></returns>
        public bool ValidateNet()
        {
            __flag = true;
            string cpuCode = GetCpuSN();

#if DEBUG
            using (FileStream fs = new FileStream(@"C:\AsyncSDK3.0.Bin", FileMode.OpenOrCreate)) {
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(cpuCode);
                sw.Flush();
                sw.Close();
            }
#endif
            __AsyncKey = TEACrypter.MD5(Encoding.Default.GetBytes(cpuCode));
            //开如处理授权码
            //LicenceBody = new AsyncLicenceKey().DeXmlSerialize(__AsyncKey,AsyncLicense);
#if DEBUG
            //if (LicenceBody != null) {
            //    Console.WriteLine(LicenceBody.Company);
            //}
            //else {
            //    Console.WriteLine("DeserializeObject Error");
            //    return false;
            //}
#endif
            //if (LicenceBody.ExpireDate < DateTime.Now) __flag = false;
            //if (Encoding.UTF8.GetString(new TEACrypter().Decrypt( LicenceBody.Key,__AsyncKey)) != cpuCode) __flag = false;
            return(__flag);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ASyncAuthorize"/> class.
 /// </summary>
 public ASyncAuthorize()
 {
     InitializeComponent();
     this.Load += new EventHandler(
         delegate(object sender, EventArgs e) {
         this.txtCompany.Text = LicenceManager.Instance.LicenceBody.Company;
         //this.txtDbString.Text = LicenceManager.Instance.LicenceBody.connectionString;
         this.txtExpire.Value        = LicenceManager.Instance.LicenceBody.ExpireDate;
         this.txtMaxASync.Value      = LicenceManager.Instance.LicenceBody.MaxAsync;
         this.txtMaxSession.Value    = LicenceManager.Instance.LicenceBody.MaxTSession;
         this.chkOpenDb.Checked      = LicenceManager.Instance.LicenceBody.AllowDatabase;
         this.txtCode.Text           = LicenceManager.Instance.SerialNumber;
         this.txtRemainMinutes.Value = LicenceManager.Instance.LicenceBody.RemainingMinutes;
         this.checkBoxX1.Checked     = LicenceManager.Instance.LicenceBody.AllowDbLog ?? false;
         foreach (byte c in TEACrypter.MD5(Encoding.Default.GetBytes(LicenceManager.Instance.LicenceBody.Company)))
         {
             this.flowLayoutPanel1.Controls.Add(new TextBox()
             {
                 Width = 20, Text = String.Format("{0:X}", c).PadLeft(2, '0')
             });
         }
         //this.txtSDKey.Text = Encoding.Default.GetString(TEACrypter.MD5(Encoding.Default.GetBytes(LicenceManager.Instance.LicenceBody.Company)));
     }
         );
 }
        private byte[] EncryptDataFile(byte[] fileBytes)
        {
            byte[] encryptedBytes;
            switch (Settings.Default.DataFileCryption)
            {
            case CryptoChoices.OneTimePad:
                OneTimePadCrypter otp = new OneTimePadCrypter(Encoding.UTF8.GetBytes(Settings.Default.CryptionDataKey));
                encryptedBytes = otp.Encrypt(fileBytes);
                break;

            case CryptoChoices.TEA:
                TEACrypter tea = new TEACrypter(Encoding.UTF8.GetBytes(Settings.Default.CryptionDataKey));
                if (TEACrypter.CheckIfDataNeedsPadding(fileBytes))
                {
                    fileBytes = TEACrypter.PadData(fileBytes);
                    Settings.Default.DataFilePadded = true;
                    Settings.Default.Save();
                }
                encryptedBytes = tea.Encrypt(fileBytes);
                break;

            default:
                throw new InvalidOperationException("Cryption settings are not valid: Desired cryption algorithm doesn't exist.");
            }

            return(encryptedBytes);
        }
        internal byte[] DecryptFileExplicit(byte[] encryptedBytes, CryptoChoice settings)
        {
            byte[] fileBytes;
            switch (settings.Choice)
            {
            case CryptoChoices.OneTimePad:
                OneTimePadCrypter otp = new OneTimePadCrypter(settings.Key);
                fileBytes = otp.Decrypt(encryptedBytes);
                break;

            case CryptoChoices.TEA:
                TEACrypter tea = new TEACrypter(settings.Key);
                fileBytes = tea.Decrypt(encryptedBytes);
                if (settings.Depad)
                {
                    fileBytes = TEACrypter.DepadData(fileBytes);
                }
                break;

            default:
                throw new InvalidOperationException("Cryption settings are not valid: Desired cryption algorithm doesn't exist.");
            }

            return(fileBytes);
        }
Ejemplo n.º 7
0
        public void ShouldEncryptAndDecryptFullBlockByTEA()
        {
            var rnd   = new Random(19);
            var block = new byte[8];
            var key   = new byte[16];

            rnd.NextBytes(block);
            rnd.NextBytes(key);

            var crypter = new TEACrypter(key);
            var encrypt = crypter.Encrypt(block);
            var decrypt = crypter.Decrypt(encrypt);

            decrypt.Should().BeEquivalentTo(block, o => o.WithStrictOrdering());
        }
        public byte[] EncryptFile(string fileName, byte[] fileBytes, CryptoChoice settings, bool replaceRecordIfConflict = false)
        {
            if (ReadRecord(fileName) != null)
            {
                if (replaceRecordIfConflict)
                {
                    RemoveRecord(fileName);
                }
                else
                {
                    throw new InvalidOperationException("The record for a file with this name already exists. If you want to replace it, pass another bool as an argument to the method.");
                }
            }

            SHA1Hasher sha1 = new SHA1Hasher();

            sha1.ComputeHash(fileBytes);
            string fileHash = sha1.HashedString;

            byte[] encryptedBytes;

            switch (settings.Choice)
            {
            case CryptoChoices.OneTimePad:
                OneTimePadCrypter otp = new OneTimePadCrypter(settings.Key);
                encryptedBytes = otp.Encrypt(fileBytes);
                break;

            case CryptoChoices.TEA:
                TEACrypter tea = new TEACrypter(settings.Key);
                if (TEACrypter.CheckIfDataNeedsPadding(fileBytes))
                {
                    fileBytes      = TEACrypter.PadData(fileBytes);
                    settings.Depad = true;
                }
                encryptedBytes = tea.Encrypt(fileBytes);
                break;

            default:
                throw new InvalidOperationException("Cryption settings are not valid: Desired cryption algorithm doesn't exist.");
            }

            AddRecord(fileName, settings, fileHash);

            return(encryptedBytes);
        }
        public byte[] DecryptFile(byte[] encryptedBytes, string fileName)
        {
            var foundRecord = ReadRecord(fileName);

            if (foundRecord == null)
            {
                throw new ArgumentException("There is no record for this file.");
            }

            CryptoChoice settings         = foundRecord.Item1;
            string       originalFileHash = foundRecord.Item2;

            byte[] fileBytes;
            switch (settings.Choice)
            {
            case CryptoChoices.OneTimePad:
                OneTimePadCrypter otp = new OneTimePadCrypter(settings.Key);
                fileBytes = otp.Decrypt(encryptedBytes);
                break;

            case CryptoChoices.TEA:
                TEACrypter tea = new TEACrypter(settings.Key);
                fileBytes = tea.Decrypt(encryptedBytes);
                if (settings.Depad)
                {
                    fileBytes = TEACrypter.DepadData(fileBytes);
                }
                break;

            default:
                throw new InvalidOperationException("Cryption settings are not valid: Desired cryption algorithm doesn't exist.");
            }

            SHA1Hasher sha1 = new SHA1Hasher();

            sha1.ComputeHash(fileBytes);

            if (originalFileHash != sha1.HashedString)
            {
                throw new Exception("The hash value of the decrypted file and the original file hash value do not match. Access denied.");
            }

            return(fileBytes);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Validates the net.
        /// </summary>
        /// <returns></returns>
        private bool ValidateNet(string Identification)
        {
            __flag = true;
            byte[] buffer;
            LicenceBody = new AsyncLicenceKey();
            byte[] KeyNumbers = Encoding.Default.GetBytes(@"eTermASyncSDK3.0&[email protected]#20859fk27)7361");
            try
            {
                __serialNumber = GetCpuSN();
                //string SingleKey = string.Format(@"{0}", __serialNumber);
                __identification = Identification;

                StringBuilder sb = new StringBuilder();
                foreach (byte SnByte in TEACrypter.MD5(TEACrypter.MD5(Encoding.Default.GetBytes(__serialNumber))))
                {
                    sb.Append(String.Format("{0:X}", SnByte).PadLeft(2, '0'));
                }
                __serialNumber = sb.ToString();


                __secreteKey = TEACrypter.MD5(Encoding.Default.GetBytes(Encrypt(__serialNumber)));
                using (FileStream fs = new FileStream(Identification, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    BinaryReader br = new BinaryReader(fs);
                    buffer = new byte[fs.Length];
                    br.Read(buffer, 0, buffer.Length);
                    LicenceBody = LicenceBody.DeXmlSerialize(KeyNumbers, buffer);
                    __flag      = CompareBytes(LicenceBody.Key, __secreteKey);
                    __flag      = __flag && LicenceBody.ExpireDate >= DateTime.Now;
                    __flag      = __flag && LicenceBody.RemainingMinutes > 0;
                }
            }
            catch
            {
                __flag = false;
            }
            return(__flag);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// 激活数据收取事件通知.
 /// </summary>
 protected override void FireOnPacketReceive()
 {
     if (base.InPacket.Sequence == 1)
     {
         if (ValidateTSession != null && ValidateTSession(base.InPacket, this))
         {
         }
         else
         {
             FireOnDisconnect();
             return;
         }
         SendPacket(new byte[] {
             0x01, 0xFE, 0x00, 0x11, 0x14, 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
         });
         //if (OnValidated != null)OnValidated(this, EventArgs.Empty);
     }
     else if (base.InPacket.Sequence == 2)
     {
         //协议改进版本(自动读取SID、RID)
         if (this.SID == 0)
         {
             this.SID = base.InPacket.OriginalBytes[8];
         }
         if (this.RID == 0)
         {
             this.RID = base.InPacket.OriginalBytes[9];
         }
         base.InPacket = new eTermApiPacket();
         new Timer(new TimerCallback(delegate(object sender) {
             Send(string.Format(@"!api {0}", this.apiKey));
         }), null, 500, Timeout.Infinite);
         //
     }
     else if (base.InPacket.Sequence == 3)
     {
         StringBuilder ApiKey = new StringBuilder();
         foreach (byte c in TEACrypter.MD5(Encoding.GetEncoding(@"gb2312").GetBytes(this.apiKey)))
         {
             ApiKey.Append(String.Format("{0:X}", c).PadLeft(2, '0'));
         }
         if (Regex.IsMatch(Encoding.GetEncoding(@"gb2312").GetString(UnOutPakcet(InPacket)), ApiKey.ToString(), RegexOptions.IgnoreCase | RegexOptions.Multiline) && this.OnValidated != null)
         {
             CanSendPacket = true;
             OnValidated(this, EventArgs.Empty);
         }
         else
         {
             this.Close();
         }
         base.InPacket = new eTermApiPacket();
     }
     else
     {
         //__DefendStatement = __DefendStatement;
         InPacket = new eTermApiPacket()
         {
             Sequence = InPacket.Sequence, PacketDateTime = DateTime.Now, Session = InPacket.Session, OriginalBytes = UnOutPakcet(InPacket)
         };
         base.FireOnPacketReceive();
     }
 }