Example #1
0
		void CreateHSVerificationFile ()
		{
			var path = Application.dataPath.ToString() + @"/Resources/HSV.txt";

			var aes = new AES ();
			var key = aes.Encrypt(_score.ToString());

			File.WriteAllText(path, key);
		}
Example #2
0
 /// <summary>
 /// Reads a log file.
 /// </summary>
 /// <param name="filename">The filename of the log.</param>
 public static string ReadLogFile(string filename)
 {
     return(File.Exists(filename) ? Encoding.UTF8.GetString(AES.Decrypt(File.ReadAllBytes(filename))) : string.Empty);
 }
Example #3
0
        public async Task <T> ExecuteAsync <T>(IAlipayRequest <T> request, string accessToken, string appAuthToken) where T : AlipayResponse
        {
            var apiVersion = string.Empty;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                apiVersion = request.GetApiVersion();
            }
            else
            {
                apiVersion = Options.Version;
            }

            // 添加协议级请求参数
            var txtParams = new AlipayDictionary(request.GetParameters())
            {
                // 序列化BizModel
                { BIZ_CONTENT, Serialize(request.GetBizModel()) },
                // 添加协议级请求参数
                { METHOD, request.GetApiName() },
                { VERSION, apiVersion },
                { APP_ID, Options.AppId },
                { FORMAT, Options.Format },
                { TIMESTAMP, DateTime.Now },
                { ACCESS_TOKEN, accessToken },
                { SIGN_TYPE, Options.SignType },
                { TERMINAL_TYPE, request.GetTerminalType() },
                { TERMINAL_INFO, request.GetTerminalInfo() },
                { PROD_CODE, request.GetProdCode() },
                { CHARSET, Options.Charset }
            };

            if (!string.IsNullOrEmpty(request.GetNotifyUrl()))
            {
                txtParams.Add(NOTIFY_URL, request.GetNotifyUrl());
            }

            if (!string.IsNullOrEmpty(appAuthToken))
            {
                txtParams.Add(APP_AUTH_TOKEN, appAuthToken);
            }

            if (request.GetNeedEncrypt())
            {
                if (string.IsNullOrEmpty(txtParams[BIZ_CONTENT]))
                {
                    throw new Exception("api request Fail ! The reason: encrypt request is not supported!");
                }

                if (string.IsNullOrEmpty(Options.EncyptKey) || string.IsNullOrEmpty(Options.EncyptType))
                {
                    throw new Exception("encryptType or encryptKey must not null!");
                }

                if (!"AES".Equals(Options.EncyptType))
                {
                    throw new Exception("api only support Aes!");
                }

                var encryptContent = AES.Encrypt(txtParams[BIZ_CONTENT], Options.EncyptKey, AlipaySignature.AES_IV, AESCipherMode.CBC, AESPaddingMode.PKCS7);
                txtParams.Remove(BIZ_CONTENT);
                txtParams.Add(BIZ_CONTENT, encryptContent);
                txtParams.Add(ENCRYPT_TYPE, Options.EncyptType);
            }

            // 添加签名参数
            var signContent = AlipaySignature.GetSignContent(txtParams);

            txtParams.Add(SIGN, AlipaySignature.RSASignContent(signContent, PrivateRSAParameters, Options.SignType));

            var query = HttpClientEx.BuildQuery(txtParams);

            Logger?.LogTrace(0, "Request:{query}", query);

            // 是否需要上传文件
            var body = string.Empty;

            if (request is IAlipayUploadRequest <T> uRequest)
            {
                var fileParams = AlipayUtility.CleanupDictionary(uRequest.GetFileParameters());
                body = await Client.DoPostAsync(Options.ServerUrl, txtParams, fileParams);
            }
            else
            {
                body = await Client.DoPostAsync(Options.ServerUrl, query);
            }

            Logger?.LogTrace(1, "Response:{body}", body);

            T rsp = null;
            IAlipayParser <T> parser = null;

            if ("xml".Equals(Options.Format))
            {
                parser = new AlipayXmlParser <T>();
                rsp    = parser.Parse(body);
            }
            else
            {
                parser = new AlipayJsonParser <T>();
                rsp    = parser.Parse(body);
            }

            var item = ParseRespItem(request, body, parser, Options.EncyptKey, Options.EncyptType);

            rsp = parser.Parse(item.realContent);

            CheckResponseSign(request, item.respContent, rsp.IsError, parser, PublicRSAParameters, Options.SignType);

            return(rsp);
        }
Example #4
0
        private static string DecryptWallToken(string cipherText)
        {
            var hmacByte = AES.StringToByteArray(cipherText);

            return(AES.DecryptStringFromBytes_Aes(hmacByte, SampleAESKey.Key));
        }
Example #5
0
        private void AsyncReceive(object state)
        {
            while (true)
            {
                byte[] readBuffer;
                lock (_readBuffers)
                {
                    if (_readBuffers.Count == 0)
                    {
                        lock (_readingPacketsLock)
                        {
                            _readingPackets = false;
                        }
                        return;
                    }

                    readBuffer = _readBuffers.Dequeue();
                }

                _readableDataLen += readBuffer.Length;
                bool process = true;
                while (process)
                {
                    switch (_receiveState)
                    {
                    case ReceiveType.Header:
                    {
                        if (_readableDataLen >= HEADER_SIZE)
                        {         // we can read the header
                            int size = (_appendHeader) ?
                                       HEADER_SIZE - _tempHeaderOffset
                                        : HEADER_SIZE;

                            try
                            {
                                if (_appendHeader)
                                {
                                    Array.Copy(readBuffer, _readOffset, _tempHeader, _tempHeaderOffset, size);
                                    _payloadLen       = (int)_tempHeader[0] | _tempHeader[1] << 8 | _tempHeader[2] << 16;
                                    _tempHeaderOffset = 0;
                                    _appendHeader     = false;
                                }
                                else
                                {
                                    _payloadLen = (int)readBuffer[_readOffset] | readBuffer[_readOffset + 1] << 8 |
                                                  readBuffer[_readOffset + 2] << 16;
                                }

                                if (_payloadLen <= 0)
                                {
                                    throw new Exception("invalid header");
                                }
                            }
                            catch (Exception)
                            {
                                process = false;
                                break;
                            }

                            _readableDataLen -= size;
                            _readOffset      += size;
                            _receiveState     = ReceiveType.Payload;
                        }
                        else         // _parentServer.HEADER_SIZE < _readableDataLen
                        {
                            _appendHeader = true;
                            Array.Copy(readBuffer, _readOffset, _tempHeader, _tempHeaderOffset, _readableDataLen);
                            _tempHeaderOffset += _readableDataLen;
                            process            = false;
                        }
                        break;
                    }

                    case ReceiveType.Payload:
                    {
                        if (_payloadBuffer == null || _payloadBuffer.Length != _payloadLen)
                        {
                            _payloadBuffer = new byte[_payloadLen];
                        }

                        int length = _readableDataLen;
                        if (_writeOffset + _readableDataLen >= _payloadLen)
                        {
                            length = _payloadLen - _writeOffset;
                        }

                        try
                        {
                            Array.Copy(readBuffer, _readOffset, _payloadBuffer, _writeOffset, length);
                        }
                        catch
                        {
                            Disconnect();
                        }

                        _writeOffset     += length;
                        _readOffset      += length;
                        _readableDataLen -= length;

                        if (_writeOffset == _payloadLen)
                        {
                            if (encryptionEnabled)
                            {
                                _payloadBuffer = AES.Decrypt(_payloadBuffer, Encoding.UTF8.GetBytes(Settings.PASSWORD));
                            }

                            if (_payloadBuffer.Length > 0)
                            {
                                if (compressionEnabled)
                                {
                                    _payloadBuffer = new SafeQuickLZ().Decompress(_payloadBuffer, 0, _payloadBuffer.Length);
                                }

                                using (MemoryStream deserialized = new MemoryStream(_payloadBuffer))
                                {
                                    IPacket packet =
                                        Serializer.DeserializeWithLengthPrefix <IPacket>(deserialized, PrefixStyle.Fixed32);

                                    OnClientRead(packet);
                                }
                            }
                            else         // payload decryption failed
                            {
                                process = false;
                            }

                            _receiveState  = ReceiveType.Header;
                            _payloadBuffer = null;
                            _payloadLen    = 0;
                            _writeOffset   = 0;
                        }

                        if (_readableDataLen == 0)
                        {
                            process = false;
                        }

                        break;
                    }
                    }
                }

                if (_receiveState == ReceiveType.Header)
                {
                    _writeOffset = 0; // prepare for next packet
                }
                _readOffset      = 0;
                _readableDataLen = 0;
            }
        }
Example #6
0
        /// <summary>
        /// Builds a client executable. Assumes that the binaries for the client exist.
        /// </summary>
        /// <param name="output">The name of the final file.</param>
        /// <param name="host">The URI location of the host.</param>
        /// <param name="password">The password that is used to connect to the website.</param>
        /// <param name="installsub">The sub-folder to install the client.</param>
        /// <param name="installname">Name of the installed executable.</param>
        /// <param name="mutex">The client's mutex</param>
        /// <param name="startupkey">The registry key to add for running on startup.</param>
        /// <param name="install">Decides whether to install the client on the machine.</param>
        /// <param name="startup">Determines whether to add the program to startup.</param>
        /// <param name="hidefile">Determines whether to hide the file.</param>
        /// <param name="keylogger">Determines if keylogging functionality should be activated.</param>
        /// <param name="port">The port the client will use to connect to the server.</param>
        /// <param name="reconnectdelay">The amount the client will wait until attempting to reconnect.</param>
        /// <param name="installpath">The installation path of the client.</param>
        /// <param name="adminelevation">Determines whether the client should (attempt) to obtain administrator privileges.</param>
        /// <param name="iconpath">The path to the icon for the client.</param>
        /// <param name="asminfo">Information about the client executable's assembly information.</param>
        /// <param name="version">The version number of the client.</param>
        /// <exception cref="System.Exception">Thrown if the builder was unable to rename the client executable.</exception>
        /// <exception cref="System.ArgumentException">Thrown if an invalid special folder was specified.</exception>
        /// <exception cref="System.IO.FileLoadException">Thrown if the client binaries do not exist.</exception>
        public static void Build(string output, string host, string password, string installsub, string installname,
                                 string mutex, string startupkey, bool install, bool startup, bool hidefile, bool keylogger, int port,
                                 int reconnectdelay,
                                 int installpath, bool adminelevation, string iconpath, string[] asminfo, string version)
        {
            // PHASE 1 - Settings
            string             encKey = Helper.Helper.GetRandomName(20);
            AssemblyDefinition asmDef;

            try
            {
                asmDef = AssemblyDefinition.ReadAssembly("client.bin");
            }
            catch (Exception ex)
            {
                throw new FileLoadException(ex.Message);
            }

            foreach (var typeDef in asmDef.Modules[0].Types)
            {
                if (typeDef.FullName == "xClient.Config.Settings")
                {
                    foreach (var methodDef in typeDef.Methods)
                    {
                        if (methodDef.Name == ".cctor")
                        {
                            int strings = 1, bools = 1, ints = 1;

                            for (int i = 0; i < methodDef.Body.Instructions.Count; i++)
                            {
                                if (methodDef.Body.Instructions[i].OpCode.Name == "ldstr") // string
                                {
                                    switch (strings)
                                    {
                                    case 1:     //version
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(version, encKey);
                                        break;

                                    case 2:     //ip/hostname
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(host, encKey);
                                        break;

                                    case 3:     //password
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(password, encKey);
                                        break;

                                    case 4:     //installsub
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(installsub, encKey);
                                        break;

                                    case 5:     //installname
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(installname, encKey);
                                        break;

                                    case 6:     //mutex
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(mutex, encKey);
                                        break;

                                    case 7:     //startupkey
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(startupkey, encKey);
                                        break;

                                    case 8:     //random encryption key
                                        methodDef.Body.Instructions[i].Operand = encKey;
                                        break;
                                    }
                                    strings++;
                                }
                                else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.1" ||
                                         methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.0") // bool
                                {
                                    switch (bools)
                                    {
                                    case 1:     //install
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(install));
                                        break;

                                    case 2:     //startup
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(startup));
                                        break;

                                    case 3:     //hidefile
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(hidefile));
                                        break;

                                    case 4:     //AdminElevation
                                        methodDef.Body.Instructions[i] =
                                            Instruction.Create(BoolOpcode(adminelevation));
                                        break;

                                    case 5:     //Keylogger
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(keylogger));
                                        break;
                                    }
                                    bools++;
                                }
                                else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4") // int
                                {
                                    switch (ints)
                                    {
                                    case 1:     //port
                                        methodDef.Body.Instructions[i].Operand = port;
                                        break;

                                    case 2:     //reconnectdelay
                                        methodDef.Body.Instructions[i].Operand = reconnectdelay;
                                        break;
                                    }
                                    ints++;
                                }
                                else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.s") // sbyte
                                {
                                    methodDef.Body.Instructions[i].Operand = GetSpecialFolder(installpath);
                                }
                            }
                        }
                    }
                }
            }

            // PHASE 2 - Renaming
            Renamer r = new Renamer(asmDef);

            if (!r.Perform())
            {
                throw new Exception("renaming failed");
            }

            // PHASE 3 - Saving
            r.AsmDef.Write(output);

            // PHASE 4 - Assembly Information changing
            if (asminfo != null)
            {
                VersionResource versionResource = new VersionResource();
                versionResource.LoadFrom(output);

                versionResource.FileVersion    = asminfo[7];
                versionResource.ProductVersion = asminfo[6];
                versionResource.Language       = 0;

                StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"];
                stringFileInfo["CompanyName"]      = asminfo[2];
                stringFileInfo["FileDescription"]  = asminfo[1];
                stringFileInfo["ProductName"]      = asminfo[0];
                stringFileInfo["LegalCopyright"]   = asminfo[3];
                stringFileInfo["LegalTrademarks"]  = asminfo[4];
                stringFileInfo["ProductVersion"]   = versionResource.ProductVersion;
                stringFileInfo["FileVersion"]      = versionResource.FileVersion;
                stringFileInfo["Assembly Version"] = versionResource.ProductVersion;
                stringFileInfo["InternalName"]     = asminfo[5];
                stringFileInfo["OriginalFilename"] = asminfo[5];

                versionResource.SaveTo(output);
            }

            // PHASE 5 - Icon changing
            if (!string.IsNullOrEmpty(iconpath))
            {
                IconInjector.InjectIcon(output, iconpath);
            }
        }
Example #7
0
        /// <summary>
        /// Builds a client executable.
        /// </summary>
        /// <remarks>
        /// Assumes the 'client.bin' file exist.
        /// </remarks>
        public static void Build(BuildOptions options)
        {
            // PHASE 1 - Settings
            string encKey = FileHelper.GetRandomFilename(20), key, authKey;

            CryptographyHelper.DeriveKeys(options.Password, out key, out authKey);
            AssemblyDefinition asmDef = AssemblyDefinition.ReadAssembly("client.bin");

            foreach (var typeDef in asmDef.Modules[0].Types)
            {
                if (typeDef.FullName == "xClient.Config.Settings")
                {
                    foreach (var methodDef in typeDef.Methods)
                    {
                        if (methodDef.Name == ".cctor")
                        {
                            int strings = 1, bools = 1;

                            for (int i = 0; i < methodDef.Body.Instructions.Count; i++)
                            {
                                if (methodDef.Body.Instructions[i].OpCode.Name == "ldstr") // string
                                {
                                    switch (strings)
                                    {
                                    case 1:     //version
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.Version, encKey);
                                        break;

                                    case 2:     //ip/hostname
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.RawHosts, encKey);
                                        break;

                                    case 3:     //key
                                        methodDef.Body.Instructions[i].Operand = key;
                                        break;

                                    case 4:     //authkey
                                        methodDef.Body.Instructions[i].Operand = authKey;
                                        break;

                                    case 5:     //installsub
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.InstallSub, encKey);
                                        break;

                                    case 6:     //installname
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.InstallName, encKey);
                                        break;

                                    case 7:     //mutex
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.Mutex, encKey);
                                        break;

                                    case 8:     //startupkey
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.StartupName, encKey);
                                        break;

                                    case 9:     //encryption key
                                        methodDef.Body.Instructions[i].Operand = encKey;
                                        break;

                                    case 10:     //tag
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.Tag, encKey);
                                        break;

                                    case 11:     //LogDirectoryName
                                        methodDef.Body.Instructions[i].Operand = AES.Encrypt(options.LogDirectoryName, encKey);
                                        break;
                                    }
                                    strings++;
                                }
                                else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.1" ||
                                         methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.0") // bool
                                {
                                    switch (bools)
                                    {
                                    case 1:     //install
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.Install));
                                        break;

                                    case 2:     //startup
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.Startup));
                                        break;

                                    case 3:     //hidefile
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.HideFile));
                                        break;

                                    case 4:     //Keylogger
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.Keylogger));
                                        break;

                                    case 5:     //HideLogDirectory
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.HideLogDirectory));
                                        break;

                                    case 6:     // HideInstallSubdirectory
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.HideInstallSubdirectory));
                                        break;
                                    }
                                    bools++;
                                }
                                else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4") // int
                                {
                                    //reconnectdelay
                                    methodDef.Body.Instructions[i].Operand = options.Delay;
                                }
                                else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.s") // sbyte
                                {
                                    methodDef.Body.Instructions[i].Operand = GetSpecialFolder(options.InstallPath);
                                }
                            }
                        }
                    }
                }
            }

            // PHASE 2 - Renaming
            Renamer r = new Renamer(asmDef);

            if (!r.Perform())
            {
                throw new Exception("renaming failed");
            }

            // PHASE 3 - Saving
            r.AsmDef.Write(options.OutputPath);

            // PHASE 4 - Assembly Information changing
            if (options.AssemblyInformation != null)
            {
                VersionResource versionResource = new VersionResource();
                versionResource.LoadFrom(options.OutputPath);

                versionResource.FileVersion    = options.AssemblyInformation[7];
                versionResource.ProductVersion = options.AssemblyInformation[6];
                versionResource.Language       = 0;

                StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"];
                stringFileInfo["CompanyName"]      = options.AssemblyInformation[2];
                stringFileInfo["FileDescription"]  = options.AssemblyInformation[1];
                stringFileInfo["ProductName"]      = options.AssemblyInformation[0];
                stringFileInfo["LegalCopyright"]   = options.AssemblyInformation[3];
                stringFileInfo["LegalTrademarks"]  = options.AssemblyInformation[4];
                stringFileInfo["ProductVersion"]   = versionResource.ProductVersion;
                stringFileInfo["FileVersion"]      = versionResource.FileVersion;
                stringFileInfo["Assembly Version"] = versionResource.ProductVersion;
                stringFileInfo["InternalName"]     = options.AssemblyInformation[5];
                stringFileInfo["OriginalFilename"] = options.AssemblyInformation[5];

                versionResource.SaveTo(options.OutputPath);
            }

            // PHASE 5 - Icon changing
            if (!string.IsNullOrEmpty(options.IconPath))
            {
                IconInjector.InjectIcon(options.OutputPath, options.IconPath);
            }
        }
Example #8
0
        private StringBuilder PrepareDataJson_WeedMeeting(WeedMeetingModels model, string couter)
        {
            //duong dan file encryption key
            FunctionXML   function       = new FunctionXML(Functions.MapPath("~/Xml/Config/encryptionkeyEncodeLink.config"));
            StringBuilder sbResult       = new StringBuilder();
            string        strEncryptCode = AES.EncryptText(model.macuochop.ToString(), function.ReadXMLGetKeyEncrypt());

            try
            {
                sbResult.Append("{");
                sbResult.Append("\"col_class\":\"rows-box\",");
                sbResult.Append("\"col_id\":\"" + strEncryptCode + "\",");
                sbResult.Append("\"col_attr\":[{\"name\":\"" + "subparent" + "\", \"value\":\"" + AES.EncryptText(model.macuochop.ToString(), function.ReadXMLGetKeyEncrypt()) + "\"}],");
                sbResult.Append("\"col_value\":[");
                #region Data cell
                //colum checkbox
                string strHTML_Checkbox = string.Format("<input type='checkbox' onclick='Select(this);' class='chkCheck' codeid='{0}' macuochop='" + strEncryptCode + "'/>", model.macuochop);
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col1\",");
                sbResult.Append("\"col_id\":\"1\",");
                sbResult.Append("\"col_value\":\"" + strHTML_Checkbox + "\"");
                sbResult.Append("},");
                //stt
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col2 stt\",");
                sbResult.Append("\"col_id\":\"2\",");
                sbResult.Append("\"col_value\":\"" + couter + "\"");
                sbResult.Append("},");

                //Mã đơn vị
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col3\",");
                sbResult.Append("\"col_id\":\"3\",");
                //sbResult.Append("\"col_value\":\"" + model.tenlop + "\"");
                sbResult.Append("\"col_value\":\"" + "<a href='" + Url.Action("Edit", "WeedMeeting2", new { macuochop = strEncryptCode }) + "'title='" + model.matuan + "'>" + model.tentuan + "</a>\"");
                sbResult.Append("},");

                //Mã nhân viên
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col4\",");
                sbResult.Append("\"col_id\":\"4\",");
                sbResult.Append("\"col_value\":\"" + "<a href='" + Url.Action("Edit", "WeedMeeting2", new { macuochop = strEncryptCode }) + "'title='" + model.ngayhop + "'>" + model.ngayhop + "</a>\"");
                //sbResult.Append("\"col_value\":\"" + model.tenkhoahoc + "\"");
                sbResult.Append("},");

                //Họ và tên
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col5\",");
                sbResult.Append("\"col_id\":\"5\",");
                sbResult.Append("\"col_value\":\"" + "<a href='" + Url.Action("Edit", "WeedMeeting2", new { macuochop = strEncryptCode }) + "'title='" + model.loaicuochop + "'>" + model.tenloaicuochop + "</a>\"");
                sbResult.Append("},");


                //Tên đon vi
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col6\",");
                sbResult.Append("\"col_id\":\"6\",");
                //sbResult.Append("\"title\":\"" + model.madonvi + "\",");
                sbResult.Append("\"col_value\":\"" + "<a href='" + Url.Action("Edit", "WeedMeeting2", new { macuochop = strEncryptCode }) + "'title='" + model.maphongban + "'>" + model.tenphongban + "</a>\"");
                sbResult.Append("},");

                ////Tên phòng ban
                //sbResult.Append("{");
                //sbResult.Append("\"colspan\":\"1\",");
                //sbResult.Append("\"col_class\":\"ovh col7\",");
                //sbResult.Append("\"col_id\":\"7\",");
                //sbResult.Append("\"col_value\":\"" + model.lydobuoihop + "\"");
                //sbResult.Append("},");

                ////Tên phòng ban
                //sbResult.Append("{");
                //sbResult.Append("\"colspan\":\"1\",");
                //sbResult.Append("\"col_class\":\"ovh col8\",");
                //sbResult.Append("\"col_id\":\"8\",");

                //sbResult.Append("\"col_value\":\"" + model.thanhphanthamdu + "\"");
                //sbResult.Append("},");

                //Tên phòng ban
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col9\",");
                sbResult.Append("\"col_id\":\"9\",");
                sbResult.Append("\"col_value\":\"<a href='" + Url.Action("DownloadFile", "WeedMeeting2", new { tenfile = model.tenfile, idcode = model.uploadfile }) + "'>" + model.tenfile + "</a>\"");
                sbResult.Append("}");

                #endregion
                sbResult.Append("]");
                sbResult.Append("},");
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            return(sbResult);
        }
Example #9
0
 /// <summary>
 /// //AES解密 只解密
 /// </summary>
 /// <param name="data"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static byte[] nouncompress_aes(byte[] data, byte[] key)
 {
     data = AES.AESDecrypt(data, key);
     //data = ZipUtils.deCompressBytes(data);
     return(data);
 }
Example #10
0
 public SecureLineServer(string pubKey)
 {
     _rsaKeyXchS = new RsaKeyExchServer(pubKey);
     _aes        = new AES();
 }
Example #11
0
        static void EncryptFile(string source, string output, string password)
        {
            Console.Clear();
            Console.WriteLine("Begin to Enctypt File ...");
            try
            {
                using (FileStream fsr = new FileStream(source, FileMode.Open))
                {
                    using (FileStream fsw = new FileStream(output, FileMode.Create))
                    {
                        var length       = fsr.Length;
                        var readsize     = 0;
                        var delta        = (_SkipSize + _BlockSize) * 1.0F / length;
                        var totalpercent = 0.0;

                        AES    aes       = new AES(AES.KeySize.Bits256, Security.GetKey(password));
                        byte[] buffer    = new byte[_BlockSize];
                        byte[] newbuffer = new byte[_BlockSize];
                        readsize = fsr.Read(buffer, 0, _BlockSize);
                        while (readsize != 0)
                        {
                            //Encrypt Para
                            aes.Cipher(buffer, newbuffer);
                            fsw.Write(newbuffer, 0, readsize);
                            //Skip Para
                            buffer   = new byte[_SkipSize];
                            readsize = fsr.Read(buffer, 0, _SkipSize);
                            if (readsize == 0)
                            {
                                break;
                            }
                            fsw.Write(buffer, 0, readsize);
                            //Read New Para
                            buffer   = new byte[_BlockSize];
                            readsize = fsr.Read(buffer, 0, _BlockSize);
                            if (readsize == 0)
                            {
                                break;
                            }
                            totalpercent += delta;
                            Console.Clear();
                            Console.WriteLine("Begin to Enctypt File ...");
                            Console.WriteLine(totalpercent * 100 + "%");
                        }
                    }
                }
                Console.WriteLine("Encrypt Completed !");
                System.Diagnostics.Process.Start("explorer.exe ", Path.GetDirectoryName(output));
                Console.WriteLine("Press Any Key to Back to Menu");
                Console.ReadKey();
                Console_Init();
            }
            catch (Exception ex)
            {
                Console.Clear();
                Console.WriteLine("Encrypt Failed ! ErrorMessage :" + ex.Message);
                Console.WriteLine("Press Any Key to Back to Menu");
                Console.ReadKey();
                Console_Init();
            }
        }
Example #12
0
        public async Task <AuthKey> Generate(TelegramDC dc, int maxRetries)
        {
            ConnectedEvent += delegate {};
            await ConnectAsync(dc, maxRetries);



            random.NextBytes(nonce);

            using (MemoryStream memoryStream = new MemoryStream()) {
                using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) {
                    binaryWriter.Write(0x60469778);
                    binaryWriter.Write(nonce);
                    Send(memoryStream.ToArray());
                }
            }

            completionSource = new TaskCompletionSource <byte[]>();
            byte[] response = await completionSource.Task;

            BigInteger    pq;
            List <byte[]> fingerprints = new List <byte[]>();

            using (var memoryStream = new MemoryStream(response, false)) {
                using (var binaryReader = new BinaryReader(memoryStream)) {
                    int responseCode = binaryReader.ReadInt32();
                    if (responseCode != 0x05162463)
                    {
                        logger.error("invalid response code: {0}", responseCode);
                        return(null);
                    }


                    byte[] nonceFromServer = binaryReader.ReadBytes(16);
                    if (!nonceFromServer.SequenceEqual(nonce))
                    {
                        logger.debug("invalid nonce from server");
                        return(null);
                    }


                    serverNonce = binaryReader.ReadBytes(16);

                    byte[] pqbytes = Serializers.Bytes.read(binaryReader);
                    pq = new BigInteger(1, pqbytes);

                    int vectorId = binaryReader.ReadInt32();

                    if (vectorId != 0x1cb5c415)
                    {
                        logger.debug("invalid fingerprints vector id: {0}", vectorId);
                        return(null);
                    }

                    int fingerprintCount = binaryReader.ReadInt32();
                    for (int i = 0; i < fingerprintCount; i++)
                    {
                        byte[] fingerprint = binaryReader.ReadBytes(8);
                        fingerprints.Add(fingerprint);
                    }
                }
            }

            FactorizedPair pqPair = Factorizator.Factorize(pq);

            logger.debug("stage 1: ok");

            random.NextBytes(newNonce);

            byte[] reqDhParamsBytes;

            using (MemoryStream pqInnerData = new MemoryStream(255)) {
                using (BinaryWriter pqInnerDataWriter = new BinaryWriter(pqInnerData)) {
                    pqInnerDataWriter.Write(0x83c95aec); // pq_inner_data
                    Serializers.Bytes.write(pqInnerDataWriter, pq.ToByteArrayUnsigned());
                    Serializers.Bytes.write(pqInnerDataWriter, pqPair.Min.ToByteArrayUnsigned());
                    Serializers.Bytes.write(pqInnerDataWriter, pqPair.Max.ToByteArrayUnsigned());
                    pqInnerDataWriter.Write(nonce);
                    pqInnerDataWriter.Write(serverNonce);
                    pqInnerDataWriter.Write(newNonce);

                    logger.debug("pq_inner_data: {0}", BitConverter.ToString(pqInnerData.GetBuffer()));

                    byte[] ciphertext        = null;
                    byte[] targetFingerprint = null;
                    foreach (byte[] fingerprint in fingerprints)
                    {
                        ciphertext = RSA.Encrypt(BitConverter.ToString(fingerprint).Replace("-", string.Empty),
                                                 pqInnerData.GetBuffer(), 0, (int)pqInnerData.Position);
                        if (ciphertext != null)
                        {
                            targetFingerprint = fingerprint;
                            break;
                        }
                    }

                    if (ciphertext == null)
                    {
                        logger.error("not found valid key for fingerprints: {0}", String.Join(", ", fingerprints));
                        return(null);
                    }

                    using (MemoryStream reqDHParams = new MemoryStream(1024)) {
                        using (BinaryWriter reqDHParamsWriter = new BinaryWriter(reqDHParams)) {
                            reqDHParamsWriter.Write(0xd712e4be); // req_dh_params
                            reqDHParamsWriter.Write(nonce);
                            reqDHParamsWriter.Write(serverNonce);
                            Serializers.Bytes.write(reqDHParamsWriter, pqPair.Min.ToByteArrayUnsigned());
                            Serializers.Bytes.write(reqDHParamsWriter, pqPair.Max.ToByteArrayUnsigned());
                            reqDHParamsWriter.Write(targetFingerprint);
                            Serializers.Bytes.write(reqDHParamsWriter, ciphertext);

                            logger.debug("sending req_dh_paras: {0}", BitConverter.ToString(reqDHParams.ToArray()));
                            reqDhParamsBytes = reqDHParams.ToArray();
                        }
                    }
                }
            }

            completionSource = new TaskCompletionSource <byte[]>();
            Send(reqDhParamsBytes);
            response = await completionSource.Task;

            logger.debug("dh response: {0}", BitConverter.ToString(response));

            byte[] encryptedAnswer;

            using (MemoryStream responseStream = new MemoryStream(response, false)) {
                using (BinaryReader responseReader = new BinaryReader(responseStream)) {
                    uint responseCode = responseReader.ReadUInt32();

                    if (responseCode == 0x79cb045d)
                    {
                        // server_DH_params_fail
                        logger.error("server_DH_params_fail: TODO");
                        return(null);
                    }

                    if (responseCode != 0xd0e8075c)
                    {
                        logger.error("invalid response code: {0}", responseCode);
                        return(null);
                    }

                    byte[] nonceFromServer = responseReader.ReadBytes(16);
                    if (!nonceFromServer.SequenceEqual(nonce))
                    {
                        logger.debug("invalid nonce from server");
                        return(null);
                    }

                    byte[] serverNonceFromServer = responseReader.ReadBytes(16);
                    if (!serverNonceFromServer.SequenceEqual(serverNonce))
                    {
                        logger.error("invalid server nonce from server");
                        return(null);
                    }

                    encryptedAnswer = Serializers.Bytes.read(responseReader);
                }
            }

            logger.debug("encrypted answer: {0}", BitConverter.ToString(encryptedAnswer));

            AESKeyData key = AES.GenerateKeyDataFromNonces(serverNonce, newNonce);

            byte[] plaintextAnswer = AES.DecryptAES(key, encryptedAnswer);

            logger.debug("plaintext answer: {0}", BitConverter.ToString(plaintextAnswer));

            int        g;
            BigInteger dhPrime;
            BigInteger ga;

            using (MemoryStream dhInnerData = new MemoryStream(plaintextAnswer)) {
                using (BinaryReader dhInnerDataReader = new BinaryReader(dhInnerData)) {
                    byte[] hashsum = dhInnerDataReader.ReadBytes(20);
                    uint   code    = dhInnerDataReader.ReadUInt32();
                    if (code != 0xb5890dba)
                    {
                        logger.error("invalid dh_inner_data code: {0}", code);
                        return(null);
                    }

                    logger.debug("valid code");

                    byte[] nonceFromServer1 = dhInnerDataReader.ReadBytes(16);
                    if (!nonceFromServer1.SequenceEqual(nonce))
                    {
                        logger.error("invalid nonce in encrypted answer");
                        return(null);
                    }

                    logger.debug("valid nonce");

                    byte[] serverNonceFromServer1 = dhInnerDataReader.ReadBytes(16);
                    if (!serverNonceFromServer1.SequenceEqual(serverNonce))
                    {
                        logger.error("invalid server nonce in encrypted answer");
                        return(null);
                    }

                    logger.debug("valid server nonce");

                    g       = dhInnerDataReader.ReadInt32();
                    dhPrime = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader));
                    ga      = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader));

                    int serverTime = dhInnerDataReader.ReadInt32();
                    timeOffset = serverTime - (int)(Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000);

                    logger.debug("g: {0}, dhprime: {1}, ga: {2}", g, dhPrime, ga);
                }
            }

            BigInteger b   = new BigInteger(2048, random);
            BigInteger gb  = BigInteger.ValueOf(g).ModPow(b, dhPrime);
            BigInteger gab = ga.ModPow(b, dhPrime);

            logger.debug("gab: {0}", gab);

            // prepare client dh inner data
            byte[] clientDHInnerDataBytes;
            using (MemoryStream clientDhInnerData = new MemoryStream()) {
                using (BinaryWriter clientDhInnerDataWriter = new BinaryWriter(clientDhInnerData)) {
                    clientDhInnerDataWriter.Write(0x6643b654); // client_dh_inner_data
                    clientDhInnerDataWriter.Write(nonce);
                    clientDhInnerDataWriter.Write(serverNonce);
                    clientDhInnerDataWriter.Write((long)0);  // TODO: retry_id
                    Serializers.Bytes.write(clientDhInnerDataWriter, gb.ToByteArrayUnsigned());

                    using (MemoryStream clientDhInnerDataWithHash = new MemoryStream()) {
                        using (BinaryWriter clientDhInnerDataWithHashWriter = new BinaryWriter(clientDhInnerDataWithHash)) {
                            using (SHA1 sha1 = new SHA1Managed()) {
                                clientDhInnerDataWithHashWriter.Write(sha1.ComputeHash(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position));
                                clientDhInnerDataWithHashWriter.Write(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position);
                                clientDHInnerDataBytes = clientDhInnerDataWithHash.ToArray();
                            }
                        }
                    }
                }
            }

            logger.debug("client dh inner data papared len {0}: {1}", clientDHInnerDataBytes.Length, BitConverter.ToString(clientDHInnerDataBytes).Replace("-", ""));

            // encryption
            byte[] clientDhInnerDataEncryptedBytes = AES.EncryptAES(key, clientDHInnerDataBytes);

            logger.debug("inner data encrypted {0}: {1}", clientDhInnerDataEncryptedBytes.Length, BitConverter.ToString(clientDhInnerDataEncryptedBytes).Replace("-", ""));

            // prepare set_client_dh_params
            byte[] setclientDhParamsBytes;
            using (MemoryStream setClientDhParams = new MemoryStream()) {
                using (BinaryWriter setClientDhParamsWriter = new BinaryWriter(setClientDhParams)) {
                    setClientDhParamsWriter.Write(0xf5045f1f);
                    setClientDhParamsWriter.Write(nonce);
                    setClientDhParamsWriter.Write(serverNonce);
                    Serializers.Bytes.write(setClientDhParamsWriter, clientDhInnerDataEncryptedBytes);

                    setclientDhParamsBytes = setClientDhParams.ToArray();
                }
            }

            logger.debug("set client dh params prepared: {0}", BitConverter.ToString(setclientDhParamsBytes));


            completionSource = new TaskCompletionSource <byte[]>();
            Send(setclientDhParamsBytes);
            response = await completionSource.Task;

            using (MemoryStream responseStream = new MemoryStream(response)) {
                using (BinaryReader responseReader = new BinaryReader(responseStream)) {
                    uint code = responseReader.ReadUInt32();
                    if (code == 0x3bcbf734)  // dh_gen_ok
                    {
                        logger.debug("dh_gen_ok");

                        byte[] nonceFromServer = responseReader.ReadBytes(16);
                        if (!nonceFromServer.SequenceEqual(nonce))
                        {
                            logger.error("invalid nonce");
                            return(null);
                        }

                        byte[] serverNonceFromServer = responseReader.ReadBytes(16);

                        if (!serverNonceFromServer.SequenceEqual(serverNonce))
                        {
                            logger.error("invalid server nonce");
                            return(null);
                        }

                        byte[] newNonceHash1 = responseReader.ReadBytes(16);
                        logger.debug("new nonce hash 1: {0}", BitConverter.ToString(newNonceHash1));

                        AuthKey authKey = new AuthKey(gab);

                        byte[] newNonceHashCalculated = authKey.CalcNewNonceHash(newNonce, 1);

                        if (!newNonceHash1.SequenceEqual(newNonceHashCalculated))
                        {
                            logger.error("invalid new nonce hash");
                            return(null);
                        }

                        logger.info("generated new auth key: {0}", gab);
                        logger.info("saving time offset: {0}", timeOffset);
                        TelegramSession.Instance.TimeOffset = timeOffset;
                        return(authKey);
                    }
                    else if (code == 0x46dc1fb9)  // dh_gen_retry
                    {
                        logger.debug("dh_gen_retry");
                        return(null);
                    }
                    else if (code == 0xa69dae02)
                    {
                        // dh_gen_fail
                        logger.debug("dh_gen_fail");
                        return(null);
                    }
                    else
                    {
                        logger.debug("dh_gen unknown: {0}", code);
                        return(null);
                    }
                }
            }
        }
Example #13
0
        public override void Write(Stream stream)
        {
            // 0x10 ignored bytes
            stream.Write(new byte[0x10], 0, 0x10);
            FileStreamCreator originalStream = this.TryGetOriginalFileStreamCreator();

            // optimization: Check if we have the data from the original file, and we don't need to encrypt and compress it again
            if (originalStream != null)
            {
                originalStream.WriteRaw(stream);
            }
            else
            {
                // we need to create it..
                Stream baseStream = new StreamKeeper(stream);
                using (Stream input = this.Data.GetStream())
                {
                    using (Stream output = IsResourceEncrypted(this.ResourceType) ? Platform.GetCompressStream(AES.EncryptStream(baseStream)) : Platform.GetCompressStream(baseStream))
                    {
                        input.CopyTo(output);
                    }
                }
            }
        }
       public void Method(AES abc)
       {
           objAes = abc;

       }
Example #15
0
        private void DecryptButton_Click(object sender, RoutedEventArgs e)
        {
            try     //+4917639275150
            {
                /*string[] input = InputTextBox.Text.Split('#');
                 * byte[] salt = Encoding.ASCII.GetBytes(input[0]);
                 * ResultBox.Text = AES.DecryptString(input[1], KeyPasswordBox.Password,ref salt);*/
                string[] input = { InputTextBox.Text };
                byte[]   salt;
                int      iterations = 0;
                if (!int.TryParse(IterationsBox.Text, out iterations) || iterations < 1)
                {
                    MessageBox.Show("Iterations can't be 0 or empty!", "Wrong iterations format", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (RandomRadio.IsChecked == true)
                {
                    input    = InputTextBox.Text.Split('#');
                    salt     = Convert.FromBase64String(input[0]);
                    input[0] = input[1];
                }
                else if (CustomRadio.IsChecked == true)
                {
                    if (ANSIRadio.IsChecked == true)
                    {
                        salt = Encoding.GetEncoding(1252).GetBytes(SaltTextBox.Text);
                    }
                    else if (Base64Radio.IsChecked == true)
                    {
                        salt = Convert.FromBase64String(SaltTextBox.Text);
                    }
                    else
                    {
                        SaltTextBox.Text = SaltTextBox.Text.ToUpper();
                        SaltTextBox.Text = SaltTextBox.Text.Replace(' ', '-');
                        SaltTextBox.Text = SaltTextBox.Text.Replace('-', ':');
                        if (SaltTextBox.Text.Contains(":"))
                        {
                            List <byte> saltList = new List <byte>();
                            foreach (string s in SaltTextBox.Text.Split(':'))
                            {
                                saltList.Add(Convert.ToByte(s, 16));
                            }

                            salt = saltList.ToArray();
                        }
                        else
                        {
                            salt = BitConverter.GetBytes(Convert.ToInt32(SaltTextBox.Text, 16));
                            if (BitConverter.IsLittleEndian)
                            {
                                Array.Reverse(salt);
                            }
                        }
                    }
                }
                else
                {
                    ResultBox.Text = AES.DecryptString("EAAAA" + InputTextBox.Text, KeyPasswordBox.Password, iterations);
                    return;
                }

                ResultBox.Text = AES.DecryptString("EAAAA" + input[0], KeyPasswordBox.Password, ref salt, iterations);
            }
            catch (ArgumentNullException)
            {
                MessageBox.Show("Please enter a text and a password!", "Nothing entered", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Salt must be at least 8 bytes (8 characters) long!", "Salt too small", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (System.Security.Cryptography.CryptographicException)
            {
                MessageBox.Show("Wrong password, salt or number of iterations!", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (FormatException)
            {
                MessageBox.Show("Invalid encrypted text!", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (IndexOutOfRangeException)
            {
                MessageBox.Show("Invalid encrypted text!", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An unexpected error occured!", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #16
0
		void UploadCachedHighScore ()
		{
			Resources.UnloadUnusedAssets();
			
			var doc = (TextAsset)Resources.Load("HSV", typeof(TextAsset));

			var hsvString = doc.text;

			var cachedScore = PlayerPrefsManager.GetHighScore();

			var aes = new AES();

			var cachedScoreAESString = aes.Encrypt(cachedScore.ToString());

			print (cachedScore);

			print (cachedScoreAESString + " | " + hsvString);

			if (hsvString == cachedScoreAESString)
			{
				_hiscoreSystem.AddScore(cachedScore);
			}
			else
			{
				PlayerPrefsManager.SetHighScore(1);
				throw new UnityException("The cached highscore has been tampered with and will not be uploaded. The score has been cleared and the app will now close.");
			}
		}
Example #17
0
        public static byte[] compress_aes(byte[] data, byte[] key)
        {
            data = ZipUtils.compressBytes(data);

            return(AES.AESEncrypt(data, key));
        }
Example #18
0
        public ActionResult Edit(string macuochop)
        {
            if (!IsLogged())
            {
                return(BackToLogin());
            }
            Item_weedModels        param          = new Item_weedModels();
            DanhmucServices        service        = new DanhmucServices();
            List <Item_weedModels> lstResult_Tuan = service.SelectRows_giaovien(param);
            StringBuilder          sbtuan         = new StringBuilder();

            foreach (var item in lstResult_Tuan)
            {
                item.tentuan = item.tentuan + "   " + item.tungay + " - " + item.denngay;
                sbtuan.Append(string.Format("<option value='{0}'>{1}</option>", item.matuan, item.tentuan));
            }
            ViewBag.sbtuan = sbtuan.ToString();

            //phong ban
            PhongBanModels        parampb            = new PhongBanModels();
            List <PhongBanModels> lstResult_phongban = service.SelectRows2(parampb);
            StringBuilder         sbphongban         = new StringBuilder();
            string pb         = "";
            string maphongban = Session["maphongban"].ToString().Trim();

            if (Session["loginid"].ToString().Trim().ToLower() == "admin" || Session["grouptk"].ToString().Trim() == "1")
            {
                pb = pb + "<option value=0>Chọn phòng ban</option>";
                foreach (var item in lstResult_phongban)
                {
                    pb = pb + "<option value=" + item.maphongban + "> " + item.tenphongban + " </option>";
                }
            }
            else
            {
                foreach (var item in lstResult_phongban.Where(p => p.maphongban == maphongban))
                {
                    pb = pb + "<option value=" + item.maphongban + "> " + item.tenphongban + " </option>";
                }
            }
            ViewBag.sbphongban = pb.ToString();

            StringBuilder sbphonghop = new StringBuilder();

            sbphonghop.Append(string.Format("<option value={0}>{1}</option>", "0", "Lựa chọn Phòng họp"));
            sbphonghop.Append(string.Format("<option value={0}>{1}</option>", "1", "Tầng 3 - Phòng họp 1"));
            sbphonghop.Append(string.Format("<option value={0}>{1}</option>", "2", "Tầng 3 - Phòng họp 2"));
            sbphonghop.Append(string.Format("<option value={0}>{1}</option>", "3", "Tầng 3 - Phòng họp lớn"));
            sbphonghop.Append(string.Format("<option value={0}>{1}</option>", "4", "Tầng 3A - Phòng họp nhỏ"));
            sbphonghop.Append(string.Format("<option value={0}>{1}</option>", "5", "Tầng 3A - Phòng họp lớn"));
            sbphonghop.Append(string.Format("<option value={0}>{1}</option>", "6", "Khác"));
            ViewBag.sbphonghop = sbphonghop.ToString();

            FunctionXML function = new FunctionXML(Functions.MapPath("~/Xml/Config/encryptionkeyEncodeLink.config"));

            macuochop = AES.DecryptText(macuochop, function.ReadXMLGetKeyEncrypt());
            DaotaoServices           servicevpp = new DaotaoServices();
            List <WeedMeetingModels> lstResult  = new List <WeedMeetingModels>();

            lstResult = servicevpp.SelectRows_WeedMeeting_hieuchinh(macuochop);
            if (lstResult.Count > 0)
            {
                //replace(/'/g, "daunhaydon").replace(/"/g, '').replace(/&/g, 'daukytuva') + "',";
                lstResult[0].lydobuoihop     = lstResult[0].lydobuoihop.Replace("daunhaydon", "'").Replace("daukytuva", "&");
                lstResult[0].thanhphanthamdu = lstResult[0].thanhphanthamdu.Replace("daunhaydon", "'").Replace("daukytuva", "&");

                //System.Text.RegularExpressions.Regex.Replace(json["noidungcuochop"].ToString().Trim(), @"\n", "\\n").Replace("'", "");
                string   chuoinoidungs  = "";
                string   chuoinoidung   = System.Text.RegularExpressions.Regex.Replace(lstResult[0].noidungcuochop, @"\\n", "\n");
                string[] noisungcuochop = chuoinoidung.Split(new char[] { '\n' });
                for (int i = 0; i < noisungcuochop.Length; i++)
                {
                    chuoinoidungs = chuoinoidungs + noisungcuochop[i].Replace("daunhaydon", "'").Replace("daukytuva", "&") + Environment.NewLine;
                }
                lstResult[0].noidungcuochop = chuoinoidungs;
                return(View(lstResult[0]));
            }

            return(View());
        }
Example #19
0
 public static byte[] nocompress_aes(byte[] data, byte[] key)
 {
     return(AES.AESEncrypt(data, key));
 }
Example #20
0
 public static string AESEncrypt(string data, string encyptKey)
 {
     return(AES.Encrypt(data, encyptKey, AES_IV, CipherMode.CBC, PaddingMode.PKCS7));
 }
Example #21
0
        public string Save_ykiensaodautao(string DataJson, string nguoitao, string matiepnhan)
        {
            logger.Start("Save_ykiensaodautao");
            string matiepnhanid = "";

            try
            {
                sqlMap.BeginTransaction();
                Hashtable param = new Hashtable();
                JObject   json  = JObject.Parse(DataJson);
                param["malop"]         = json["data1"]["malop"].ToString();
                param["manv"]          = json["data1"]["manv"].ToString();
                param["email"]         = json["data1"]["email"].ToString();
                param["hovaten"]       = json["data1"]["hovaten"].ToString();
                param["maphongban"]    = json["data1"]["maphongban"].ToString();
                param["tieudekhoahoc"] = json["data1"]["tieudekhoahoc"].ToString();
                param["tengiaovien"]   = json["data1"]["tengiaovien"].ToString();
                param["ngaydaotao"]    = json["data1"]["ngaydaotao"].ToString();
                param["nguoitao"]      = nguoitao;

                param["matiepnhan"] = json["data1"]["matiepnhan"].ToString();

                if (param["matiepnhan"].ToString().Trim() == "0")
                {
                    param["matiepnhan"] = GetSequence_All("dm_seq", "daotao_ykiensaodaotao");
                    sqlMap.Insert("Saudaotao.InsertRow_Saudaotao", param);
                }
                else
                {
                    param["matiepnhan"] = param["matiepnhan"].ToString().Trim();
                    sqlMap.Update("Saudaotao.UpdateRow_Saudaotao", param);
                }
                matiepnhanid = param["matiepnhan"].ToString();
                Hashtable   param1           = new Hashtable();
                JArray      json_vpp_chitiet = (JArray)json["data2"];
                FunctionXML function         = new FunctionXML(Functions.MapPath("~/Xml/Config/encryptionkeyEncodeLink.config"));
                for (int i = 0; i < json_vpp_chitiet.Count(); i++)
                {
                    param1 = new Hashtable();

                    param1["matiepnhan_tieuchidaotao"] = AES.DecryptText(json_vpp_chitiet[i]["matiepnhan_tieuchidaotao"].ToString().Trim(), function.ReadXMLGetKeyEncrypt());
                    param1["matieuchi"]  = AES.DecryptText(json_vpp_chitiet[i]["matieuchi"].ToString().Trim(), function.ReadXMLGetKeyEncrypt());
                    param1["matiepnhan"] = matiepnhanid;

                    param1["tentieuchi"] = json_vpp_chitiet[i]["tentieuchi"].ToString().Trim();// ["kem"] = "undefined"

                    if (json_vpp_chitiet[i]["kem"].ToString().Trim() == "true")
                    {
                        param1["kem"] = "1";
                    }
                    else
                    {
                        param1["kem"] = "0";
                    }

                    if (json_vpp_chitiet[i]["trungbinh"].ToString().Trim() == "true")
                    {
                        param1["trungbinh"] = "1";
                    }
                    else
                    {
                        param1["trungbinh"] = "0";
                    }

                    if (json_vpp_chitiet[i]["kha"].ToString().Trim() == "true")
                    {
                        param1["kha"] = "1";
                    }
                    else
                    {
                        param1["kha"] = "0";
                    }

                    if (json_vpp_chitiet[i]["tot"].ToString().Trim() == "true")
                    {
                        param1["tot"] = "1";
                    }
                    else
                    {
                        param1["tot"] = "0";
                    }

                    if (json_vpp_chitiet[i]["rattot"].ToString().Trim() == "true")
                    {
                        param1["rattot"] = "1";
                    }
                    else
                    {
                        param1["rattot"] = "0";
                    }

                    param1["danhmuccha"] = json_vpp_chitiet[i]["danhmuccha"].ToString().Trim();
                    param1["danhmucgoc"] = json_vpp_chitiet[i]["danhmucgoc"].ToString().Trim();

                    param1["nguoitao"] = nguoitao;
                    if (param1["matiepnhan_tieuchidaotao"].ToString() == "" || param1["matiepnhan_tieuchidaotao"].ToString() == "0" || param1["matiepnhan_tieuchidaotao"].ToString() == null)
                    {
                        sqlMap.Insert("Saudaotao.InsertRow_Saudaotao_chitiet", param1);
                    }
                    else
                    {
                        sqlMap.Update("Saudaotao.UpdateRow_Saudaotao_chitiet", param1);
                    }
                }
                sqlMap.CommitTransaction();
            }
            catch (Exception ex)
            {
                sqlMap.RollbackTransaction();
                logger.Error(ex.Message);
            }
            logger.End("Save_ykiensaodautao");
            return(matiepnhanid);
        }
Example #22
0
 private void regBtn_Click(object sender, RoutedEventArgs e)
 {
     if (username.Text == "" || (man.IsChecked == false && woman.IsChecked == false) || password1.Password == "" || password2.Password == "")
     {
         MessageBox.Show("请填写完整必要的信息", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
     }
     else if (password1.Password != password2.Password)
     {
         MessageBox.Show("两次输入的密码不相等,请重新输入!");
     }
     else if (key1.Text == "" || key2.Text == "" || key3.Text == "" || key4.Text == "")
     {
         MessageBox.Show("请输入完整的注册号码");
     }
     else
     {
         try
         {
             using (SqlConnection conn = new SqlConnection(conStr))
             {
                 conn.Open();
                 using (SqlCommand cmd = new SqlCommand("", conn))
                 {
                     string regID = key1.Text + key2.Text + key3.Text + key4.Text;
                     byte[] bregID;
                     bregID          = AES.AESEncrypt(regID);
                     cmd.CommandText = "select * from RegTable where RegID=@RegID";
                     cmd.Parameters.Clear();
                     cmd.Parameters.AddWithValue("RegID", bregID);
                     SqlDataReader dr = cmd.ExecuteReader();
                     if (!dr.Read())
                     {
                         MessageBox.Show("输入的注册码不正确!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                     }
                     else
                     {
                         dr.Close();
                         string cipherpwd = password1.Password;
                         byte[] bcipherpwd;
                         bcipherpwd      = AES.AESEncrypt(cipherpwd);
                         cmd.CommandText = "insert into AuthorTable(Name,Sex,AutherPWD,RegTime) values(@Name,@Sex,@AutherPWD,@RegTime)";
                         cmd.Parameters.Clear();
                         cmd.Parameters.AddWithValue("Name", username.Text);
                         if (man.IsChecked == true)
                         {
                             cmd.Parameters.AddWithValue("Sex", "男");
                         }
                         else
                         {
                             cmd.Parameters.AddWithValue("Sex", "女");
                         }
                         cmd.Parameters.AddWithValue("AutherPWD", bcipherpwd);
                         cmd.Parameters.AddWithValue("RegTime", DateTime.Now);
                         cmd.ExecuteNonQuery();
                         MessageBox.Show("注册成功!欢迎使用数模助理");
                         username.Clear();
                         man.IsChecked   = false;
                         woman.IsChecked = false;
                         password1.Clear();
                         password2.Clear();
                         key1.Clear();
                         key2.Clear();
                         key3.Clear();
                         key4.Clear();
                     }
                 }
             }
         }
         catch
         {
             MessageBox.Show("无法连接数据库!");
             this.Close();
         }
     }
 }
Example #23
0
            public IndexTable(CacheBase Cache)
            {
                cache = Cache;

                var IH     = cache.IndexHeader;
                var CH     = cache.Header;
                var Reader = cache.Reader;

                ClassList = new List <TagClass>();

                #region Read Class List

                Reader.SeekTo(IH.tagClassIndexOffset);
                for (int i = 0; i < IH.tagClassCount; i++)
                {
                    TagClass tc = new TagClass();
                    tc.ClassCode = Reader.ReadString(4);
                    tc.Parent    = Reader.ReadString(4);
                    tc.Parent2   = Reader.ReadString(4);
                    tc.StringID  = Reader.ReadInt32();
                    ClassList.Add(tc);
                }
                #endregion

                #region Read Tags' Info
                Reader.SeekTo(IH.tagInfoOffset);
                for (int i = 0; i < IH.tagCount; i++)
                {
                    IndexItem item = new IndexItem()
                    {
                        Cache = cache
                    };
                    item.ClassIndex = Reader.ReadInt16();
                    item.ID         = (Reader.ReadInt16() << 16) | i;
                    item.Offset     = Reader.ReadInt32() - cache.Magic;
                    item.metaIndex  = i;
                    this.Add(item);
                }
                #endregion

                #region Read Indices
                Reader.SeekTo(CH.fileTableIndexOffset);
                int[] indices = new int[IH.tagCount];
                for (int i = 0; i < IH.tagCount; i++)
                {
                    indices[i] = Reader.ReadInt32();
                }
                #endregion

                #region Read Names
                Reader.SeekTo(CH.fileTableOffset);
                EndianReader newReader = (cache.tagsKey == "" || cache.tagsKey == null)
                    ? new EndianReader(new MemoryStream(Reader.ReadBytes(CH.fileTableSize)), EndianFormat.Big)
                    : AES.DecryptSegment(Reader, CH.fileTableOffset, CH.fileTableSize, cache.tagsKey);

                for (int i = 0; i < indices.Length; i++)
                {
                    if (indices[i] == -1)
                    {
                        this[i].Filename = "<null>";
                        continue;
                    }

                    newReader.SeekTo(indices[i]);

                    int length;
                    if (i == indices.Length - 1)
                    {
                        length = CH.fileTableSize - indices[i];
                    }
                    else
                    {
                        if (indices[i + 1] == -1)
                        {
                            int index = -1;

                            for (int j = i + 1; j < indices.Length; j++)
                            {
                                if (indices[j] != -1)
                                {
                                    index = j;
                                    break;
                                }
                            }

                            length = (index == -1) ? CH.fileTableSize - indices[i] : indices[index] - indices[i];
                        }
                        else
                        {
                            length = indices[i + 1] - indices[i];
                        }
                    }

                    if (length == 1)
                    {
                        this[i].Filename = "<blank>";
                        continue;
                    }

                    if (length < 0)
                    {
                        int i0 = indices[i];
                        int i1 = indices[i + 1];
                        int i2 = indices[i + 2];
                        int i3 = indices[i + 3];
                    }

                    this[i].Filename = newReader.ReadString(length);
                }

                newReader.Close();
                newReader.Dispose();
                #endregion
            }
Example #24
0
        private void AsyncReceive(IAsyncResult result)
        {
            int bytesTransferred = -1;

            try
            {
                bytesTransferred = _handle.EndReceive(result);

                if (bytesTransferred <= 0)
                {
                    OnClientState(false);
                    return;
                }
            }
            catch (Exception ex)
            {
                OnClientState(false);
                return;
            }

            _readableDataLen += bytesTransferred;
            bool process = true;

            while (process)
            {
                if (_receiveState == ReceiveType.Header)
                {
                    process = _readableDataLen >= HEADER_SIZE;
                    if (process)
                    {
                        _payloadLen = BitConverter.ToInt32(_buffer, _readOffset);

                        _readableDataLen -= HEADER_SIZE;
                        _readOffset      += HEADER_SIZE;
                        _receiveState     = ReceiveType.Payload;
                    }
                }
                else if (_receiveState == ReceiveType.Payload)
                {
                    process = _readableDataLen >= _payloadLen;
                    if (process)
                    {
                        byte[] payload = new byte[_payloadLen];
                        Array.Copy(this._buffer, _readOffset, payload, 0, payload.Length);

                        if (encryptionEnabled)
                        {
                            payload = AES.Decrypt(payload, Encoding.UTF8.GetBytes(Settings.PASSWORD));
                        }

                        if (payload.Length > 0)
                        {
                            if (compressionEnabled)
                            {
                                payload = new SafeQuickLZ().Decompress(payload, 0, payload.Length);
                            }

                            using (MemoryStream deserialized = new MemoryStream(payload))
                            {
                                IPacket packet = Serializer.DeserializeWithLengthPrefix <IPacket>(deserialized,
                                                                                                  PrefixStyle.Fixed32);

                                OnClientRead(packet);
                            }
                        }

                        _readOffset      += _payloadLen;
                        _readableDataLen -= _payloadLen;
                        _receiveState     = ReceiveType.Header;
                    }
                }
            }

            int len = _receiveState == ReceiveType.Header ? HEADER_SIZE : _payloadLen;

            if (_readOffset + len >= this._buffer.Length)
            {
                //copy the buffer to the beginning
                Array.Copy(this._buffer, _readOffset, this._buffer, 0, _readableDataLen);
                _writeOffset = _readableDataLen;
                _readOffset  = 0;
            }
            else
            {
                //payload fits in the buffer from the current offset
                //use BytesTransferred to write at the end of the payload
                //so that the data is not split
                _writeOffset += bytesTransferred;
            }

            try
            {
                if (_buffer.Length - _writeOffset > 0)
                {
                    _handle.BeginReceive(this._buffer, _writeOffset, _buffer.Length - _writeOffset, SocketFlags.None, AsyncReceive, null);
                }
                else
                {
                    //Shoudln't be even possible... very strange
                    Disconnect();
                }
            }
            catch
            {
                Disconnect();
            }
        }
Example #25
0
 public static string Encrypt(string data, string password = null)
 {
     return(AES.Encrypt(System.Text.Encoding.UTF8.GetBytes(data), password));
 }
Example #26
0
    public static void testPay()
    {
        //一键支付URL前缀
        string apiprefix = APIURLConfig.payMobilePrefix;

        //网页支付地址
        string creditpayURI = APIURLConfig.creditWebpayURI;

        //商户账户编号
        string merchantAccount = Config.merchantAccount;

        //商户公钥(该商户公钥需要在易宝一键支付商户后台报备)
        string merchantPublickey = Config.merchantPublickey;

        //商户私钥(商户公钥对应的私钥)
        string merchantPrivatekey = Config.merchantPrivatekey;

        //易宝支付分配的公钥(进入商户后台公钥管理,报备商户的公钥后分派的字符串)
        string yibaoPublickey = Config.yibaoPublickey;

        //随机生成商户AESkey
        string merchantAesKey = AES.GenerateAESKey();

        int    amount         = 2;                 //支付金额为分
        int    currency       = 156;
        string identityid     = "447769804451095"; //用户身份标识
        int    identitytype   = 0;
        Random ra             = new Random();
        string orderid        = "1234567" + 50 * ra.Next();
        string other          = "00-23-5A-15-99-42"; //mac地址
        string productcatalog = "1";                 //商品类别码,商户支持的商品类别码由易宝支付运营人员根据商务协议配置
        string productdesc    = "我叫MT";
        string productname    = "符石";

        DateTime t1        = DateTime.Now;
        DateTime t2        = new DateTime(1970, 1, 1);
        double   t         = t1.Subtract(t2).TotalSeconds;
        int      transtime = (int)t;

        string userip = "172.18.66.218";
        //商户提供的商户后台系统异步支付回调地址
        string callbackurl = "http://172.18.66.107:8082/payapi-java-demo/callback";
        //商户提供的商户前台系统异步支付回调地址
        string fcallbackurl = "http://172.18.66.107:8082/payapi-java-demo/fcallback";
        //用户浏览器ua
        string userua = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1";


        SortedDictionary <string, object> sd = new SortedDictionary <string, object>();

        sd.Add("merchantaccount", merchantAccount);
        sd.Add("amount", amount);
        sd.Add("currency", currency);
        sd.Add("identityid", identityid);
        sd.Add("identitytype", identitytype);
        sd.Add("orderid", orderid);
        sd.Add("other", other);
        sd.Add("productcatalog", productcatalog);
        sd.Add("productdesc", productdesc);
        sd.Add("productname", productname);
        sd.Add("transtime", transtime);
        sd.Add("userip", userip);
        sd.Add("callbackurl", callbackurl);
        sd.Add("fcallbackurl", fcallbackurl);
        sd.Add("userua", userua);

        //生成RSA签名
        string sign = EncryptUtil.handleRSA(sd, merchantPrivatekey);

        Console.WriteLine("生成的签名为:" + sign);

        sd.Add("sign", sign);

        //将网页支付对象转换为json字符串
        string wpinfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);

        Console.WriteLine("网页支付明文数据json格式为:" + wpinfo_json);
        string datastring = AES.Encrypt(wpinfo_json, merchantAesKey);

        Console.WriteLine("网页支付业务数据经过AES加密后的值为:" + datastring);

        //将商户merchantAesKey用RSA算法加密
        Console.WriteLine("merchantAesKey为:" + merchantAesKey);
        string encryptkey = RSAFromPkcs8.encryptData(merchantAesKey, yibaoPublickey, "UTF-8");

        Console.WriteLine("encryptkey为:" + encryptkey);

        //打开浏览器访问一键支付网页支付链接地址,请求方式为get
        string postParams = "data=" + HttpUtility.UrlEncode(datastring) + "&encryptkey=" + HttpUtility.UrlEncode(encryptkey) + "&merchantaccount=" + merchantAccount;
        string url        = apiprefix + creditpayURI + "?" + postParams;

        //url = "www.sina.com";
        Console.WriteLine("网页支付链接地址为:" + url);
        Console.WriteLine("网页支付链接地址长度为:" + url.Length);
        System.Diagnostics.Process.Start("iexplore.exe", url);    //打开IE浏览器
        //System.Diagnostics.Process.Start("firefox.exe", url);//打开firefox浏览器
        System.Diagnostics.Process.Start(url);

        Console.ReadLine();
    }
Example #27
0
 public static string Decrypt(string cypher, string password = "")
 {
     return(AES.Decrypt(cypher, password));
 }
Example #28
0
 public CLIClient(IPEndPoint serverEndPoint, string aesPass)
 {
     _serverEndPoint = serverEndPoint;
     _aes            = new AES(aesPass);
 }
Example #29
0
        public byte[] ToBytes(byte[] nonce, byte[] serverNonce, byte[] newNonce, byte[] encryptedAnswer)
        {
            this.newNonce = newNonce;
            AESKeyData key = AES.GenerateKeyDataFromNonces(serverNonce, newNonce);

            byte[] plaintextAnswer = AES.DecryptAES(key, encryptedAnswer);

            // logger.debug("plaintext answer: {0}", BitConverter.ToString(plaintextAnswer));

            int        g;
            BigInteger dhPrime;
            BigInteger ga;

            using (MemoryStream dhInnerData = new MemoryStream(plaintextAnswer))
            {
                using (BinaryReader dhInnerDataReader = new BinaryReader(dhInnerData))
                {
                    byte[] hashsum = dhInnerDataReader.ReadBytes(20);
                    uint   code    = dhInnerDataReader.ReadUInt32();
                    if (code != 0xb5890dba)
                    {
                        throw new InvalidOperationException($"invalid dh_inner_data code: {code}");
                    }

                    // logger.debug("valid code");

                    byte[] nonceFromServer1 = dhInnerDataReader.ReadBytes(16);
                    if (!nonceFromServer1.SequenceEqual(nonce))
                    {
                        throw new InvalidOperationException("invalid nonce in encrypted answer");
                    }

                    // logger.debug("valid nonce");

                    byte[] serverNonceFromServer1 = dhInnerDataReader.ReadBytes(16);
                    if (!serverNonceFromServer1.SequenceEqual(serverNonce))
                    {
                        throw new InvalidOperationException("invalid server nonce in encrypted answer");
                    }

                    // logger.debug("valid server nonce");

                    g       = dhInnerDataReader.ReadInt32();
                    dhPrime = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader));
                    ga      = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader));

                    int serverTime = dhInnerDataReader.ReadInt32();
                    timeOffset = serverTime - (int)(Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000);

                    // logger.debug("g: {0}, dhprime: {1}, ga: {2}", g, dhPrime, ga);
                }
            }

            BigInteger b  = new BigInteger(2048, new Random());
            BigInteger gb = BigInteger.ValueOf(g).ModPow(b, dhPrime);// encrypt data generate public key

            _gab = ga.ModPow(b, dhPrime);

            // logger.debug("gab: {0}", gab);

            // prepare client dh inner data
            byte[] clientDHInnerDataBytes;
            using (MemoryStream clientDhInnerData = new MemoryStream())
            {
                using (BinaryWriter clientDhInnerDataWriter = new BinaryWriter(clientDhInnerData))
                {
                    clientDhInnerDataWriter.Write(0x6643b654); // client_dh_inner_data
                    clientDhInnerDataWriter.Write(nonce);
                    clientDhInnerDataWriter.Write(serverNonce);
                    clientDhInnerDataWriter.Write((long)0); // TODO: retry_id
                    Serializers.Bytes.write(clientDhInnerDataWriter, gb.ToByteArrayUnsigned());

                    using (MemoryStream clientDhInnerDataWithHash = new MemoryStream())
                    {
                        using (BinaryWriter clientDhInnerDataWithHashWriter = new BinaryWriter(clientDhInnerDataWithHash))
                        {
                            using (SHA1 sha1 = new SHA1Managed())
                            {
                                clientDhInnerDataWithHashWriter.Write(sha1.ComputeHash(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position));
                                clientDhInnerDataWithHashWriter.Write(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position);
                                clientDHInnerDataBytes = clientDhInnerDataWithHash.ToArray();
                            }
                        }
                    }
                }
            }

            // logger.debug("client dh inner data papared len {0}: {1}", clientDHInnerDataBytes.Length, BitConverter.ToString(clientDHInnerDataBytes).Replace("-", ""));

            // encryption
            //TODO: uncomment encryption
            //byte[] clientDhInnerDataEncryptedBytes = clientDHInnerDataBytes;
            byte[] clientDhInnerDataEncryptedBytes = AES.EncryptAES(key, clientDHInnerDataBytes);

            // logger.debug("inner data encrypted {0}: {1}", clientDhInnerDataEncryptedBytes.Length, BitConverter.ToString(clientDhInnerDataEncryptedBytes).Replace("-", ""));

            // prepare set_client_dh_params
            byte[] setclientDhParamsBytes;
            using (MemoryStream setClientDhParams = new MemoryStream())
            {
                using (BinaryWriter setClientDhParamsWriter = new BinaryWriter(setClientDhParams))
                {
                    setClientDhParamsWriter.Write(0xf5045f1f);
                    setClientDhParamsWriter.Write(nonce);
                    setClientDhParamsWriter.Write(serverNonce);
                    Serializers.Bytes.write(setClientDhParamsWriter, clientDhInnerDataEncryptedBytes);

                    setclientDhParamsBytes = setClientDhParams.ToArray();
                }
            }

            // logger.debug("set client dh params prepared: {0}", BitConverter.ToString(setclientDhParamsBytes));

            return(setclientDhParamsBytes);
        }
Example #30
0
        private void FinishClicked(object sender, EventArgs e)
        {
            if (!MigrateAndCreateDB())
            {
                Close();
                return;
            }

            // update the settings
            config.AppSettings.Settings["ConnectionStringExpressDataSource"].Value = tbServerName.Text;

            config.AppSettings.Settings["ConnectionStringExpressInitialCatalog"].Value = ddlCatalog.Text != String.Empty ? ddlCatalog.Text : tbNewDBName.Text;

            config.AppSettings.Settings["ConnectionStringExpressIntegratedSecurity"].Value = Convert.ToString(ddlAuthType.Text == "Windows Authentication");
            config.AppSettings.Settings["ConnectionStringExpressUserID"].Value             = tbLogin.Text;
            config.AppSettings.Settings["ConnectionStringExpressPassword"].Value           = AES.Encrypt(tbPassword.Text);
            config.AppSettings.Settings["CompactDatabaseType"].Value = "False";

            config.Save();

            // close form and restart application
            Close();

            MessageBox.Show(
                "In order to use the new database settings, AuditWizard will now restart.",
                "AuditWizard", MessageBoxButtons.OK, MessageBoxIcon.Information);

            System.Diagnostics.Process.Start(Application.ExecutablePath);
            Application.Exit();
            return;
        }
Example #31
0
        private void ButtonEncrypt_Click(object sender, EventArgs e)
        {
            if (hideSize > hiderSize)
            {
                this.toolStripStatusLabel.Text = "Please, select another image!";
                //MessageBox.Show("Please, select another image!");
                return;
            }
            if (hideModeSwitcher.Text == "Text" && (dataToEncrypt = textToHide.Text.ToString()) == "")
            {
                dataToEncrypt = "empty";
            }
            else
            if (hideModeSwitcher.Text == "Picture" && pictureHide.Image == null)
            {
                dataToEncrypt = "empty";
            }
            else if (hideModeSwitcher.Text == "Picture")
            {
                dataToEncrypt = AES.Base64Encode(ImageWithSecret <string> .ImageToByteArray(pictureHide.Image));
            }

            var lib = new ImageWithSecret <string>
            {
                ImageModifying = ImageOriginalHider,
                imageArray     = ImageHelper.BmpToArr(ImageOriginalHider),
                DataReader     = new StringData(),
                WriteReadData  = new EmptyWriteReadPixelData()
            };

            if (checkInteractive.Checked)
            {
                lib.interactive = true;
            }

            foreach (var checkedItems in listOfEncryptions.CheckedItems)
            {
                foreach (var encryptionClass in GetAllEntities(false))
                {
                    if ((string)encryptionClass.GetField("EncryptionName").GetValue(null) == checkedItems.ToString())
                    {
                        if (encryptionClass.Name == "SHI")
                        {
                            lib.Encrypts.Add(new SHI(textKey.Text, SHI.Operator.LEFT));
                        }
                        else
                        {
                            lib.Encrypts.Add((IEncrypt)Activator.CreateInstance(encryptionClass, new Object[] { textKey.Text }));
                        }
                    }
                }
            }
            foreach (var checkedItems in listOfCompressions.CheckedItems)
            {
                foreach (var compressionClass in GetAllEntities(true))
                {
                    if ((string)compressionClass.GetField("CompressionName").GetValue(null) == checkedItems.ToString())
                    {
                        lib.DataCompression = (ICompression)Activator.CreateInstance(compressionClass, null);
                    }
                }
            }
            imageHidden           = lib.Encrypt(dataToEncrypt);
            pictureHidden.Image   = imageHidden;
            buttonDecrypt.Enabled = true;
            labelHidden.Visible   = true;
        }
Example #32
0
        private void EncryptButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                byte[] salt;
                string saltString = "";
                int    iterations = 0;
                if (!int.TryParse(IterationsBox.Text, out iterations) || iterations < 1)
                {
                    MessageBox.Show("Iterations can't be 0 or empty!", "Wrong iterations format", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                if (RandomRadio.IsChecked == true)
                {
                    if (SaltLengthBox.Text.Length < 1)
                    {
                        throw new ArgumentException();
                    }
                    salt       = AES.RandomSalt(int.Parse(SaltLengthBox.Text));
                    saltString = Convert.ToBase64String(salt) + "#";  //# is seperator char
                }
                else if (CustomRadio.IsChecked == true)
                {
                    if (ANSIRadio.IsChecked == true)
                    {
                        salt = Encoding.GetEncoding(1252).GetBytes(SaltTextBox.Text);
                    }
                    else if (Base64Radio.IsChecked == true)
                    {
                        salt = Convert.FromBase64String(SaltTextBox.Text);
                    }
                    else
                    {
                        SaltTextBox.Text = SaltTextBox.Text.ToUpper();
                        SaltTextBox.Text = SaltTextBox.Text.Replace(' ', '-');
                        SaltTextBox.Text = SaltTextBox.Text.Replace('-', ':');
                        if (SaltTextBox.Text.Contains(":"))
                        {
                            List <byte> saltList = new List <byte>();
                            foreach (string s in SaltTextBox.Text.Split(':'))
                            {
                                saltList.Add(Convert.ToByte(s, 16));
                            }

                            salt = saltList.ToArray();
                        }
                        else
                        {
                            salt = BitConverter.GetBytes(Convert.ToInt32(SaltTextBox.Text, 16));
                            if (BitConverter.IsLittleEndian)
                            {
                                Array.Reverse(salt);
                            }
                        }
                    }
                }
                else
                {
                    ResultBox.Text = AES.EncryptString(InputTextBox.Text, KeyPasswordBox.Password, iterations).Remove(0, 5);
                    return;
                }

                ResultBox.Text = saltString + AES.EncryptString(InputTextBox.Text, KeyPasswordBox.Password, ref salt, iterations).Remove(0, 5);
            }
            catch (ArgumentNullException)
            {
                MessageBox.Show("Please enter a text and a password!", "Nothing entered", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Salt must be at least 8 bytes (8 characters) long!", "Salt too small", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (FormatException)
            {
                MessageBox.Show("If you check Base64 then the salt must be in Base64 format!", "No Base64 format", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception)
            {
                MessageBox.Show("An unexpected error occured!", "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #33
0
 //https://www.namecheap.com/support/knowledgebase/article.aspx/29/11/how-do-i-use-a-browser-to-dynamically-update-the-hosts-ip
 public override void LoadSettings(string settings)
 {
     base.LoadSettings(settings);
     Settings.Password = AES.Decrypt(Settings.Password, "Gm<&9.7exSbu>GVP");
 }