Beispiel #1
0
 /// <summary>
 /// 保存用户信息
 /// </summary>
 /// <param name="user"></param>
 public int SaveAccountInfo(T_AdminUser user, string newPwz)
 {
     if (user.id.Equals(Guid.Empty))
     {
         user.id = Guid.NewGuid();
         using (var dbContext = new IPathDBEntities())
         {
             user.Pwz = AESHelper.Encrypt(user.Pwz);
             dbContext.T_AdminUser.Add(user);
             return(dbContext.SaveChanges());
         }
     }
     else
     {
         using (var dbContext = new IPathDBEntities())
         {
             dbContext.T_AdminUser.Attach(user);
             dbContext.Entry(user).Property("UserName").IsModified       = true;
             dbContext.Entry(user).Property("PermissionInfo").IsModified = true;
             if (!string.IsNullOrEmpty(newPwz))
             {
                 user.Pwz = AESHelper.Encrypt(newPwz);
                 dbContext.Entry(user).Property("Pwz").IsModified = true;
             }
             dbContext.Configuration.ValidateOnSaveEnabled = false;
             return(dbContext.SaveChanges());
         }
     }
 }
Beispiel #2
0
        static void Main(string[] args)
        {
            //var instance = new DatabaseHelper();

            //instance.Connect();
            //foreach (var s in instance.Query("select `sPasswd` from hitwhcms.accounts where `sStudentID`='admin'", "sPasswd", DatabaseHelper.TableType.Full))
            //{
            //    Console.WriteLine(s);
            //}
            //instance.Disconnect();
            string key = "haerbingongyedaxueweihai-1604102";
            //string key = "66666666666666666666666666666666";
            string enc = AESHelper.Encrypt(@"430521", key);
            //string dec = AESHelper.Decrypt(enc, key);
            string dec = AESHelper.Decrypt(enc, key);

            Console.WriteLine(enc);
            Console.WriteLine(dec);
            //StudentInfo test = new StudentInfo()
            //{
            //    CurrentFormat = DataFormat.Full,
            //    exSQL = new Exception("This is 1")
            //};
            //Console.WriteLine(test.exSQL.Message);
            //test.exSQL = new Exception("This has been changes.");
            //Console.WriteLine(test.exSQL.Message);
        }
Beispiel #3
0
        public JsonResult AESEncrypt(string code, string value)
        {
            OperationResult result = new OperationResult();

            result.Data = AESHelper.Encrypt(code, value);
            return(Json(result));
        }
Beispiel #4
0
        public void Dencrypt()
        {
            try {
                string   plain    = "Plain TextABCDEF";
                string   k1       = "0123456789ABCDEF";
                string   k2       = "io.github.odys-z";
                byte[]   iv64     = AESHelper.getRandom();
                string   iv       = AESHelper.Encode64(iv64);
                string   cypher   = AESHelper.Encrypt(plain, k1, iv64);
                string[] cypherss = AESHelper.Dencrypt(cypher, k1, iv, k2);
                Assert.AreEqual(plain, AESHelper.Decrypt(cypherss[0], k2, AESHelper.Decode64(cypherss[1])));

                Debug.WriteLine("Check this at server side:");
                Debug.WriteLine(string.Format("Cypher:\n{0}", cypherss[0]));
                Debug.WriteLine(string.Format("Key:\n{0},\nIV:\n{1}", k2, cypherss[1]));
                Debug.WriteLine(string.Format("Expacting:\n{0}", plain));

                plain    = "Слава Україні";
                cypher   = AESHelper.Encrypt(plain, k1, iv64);
                cypherss = AESHelper.Dencrypt(cypher, k1, iv, k2);
                Assert.AreEqual(plain, AESHelper.Decrypt(cypherss[0], k2, AESHelper.Decode64(cypherss[1])));
            }
            catch (Exception e) {
                Debug.WriteLine(e.ToString());
                Assert.Fail(e.Message);
            }
        }
Beispiel #5
0
        public bool CheckIdentity(string id, string name)
        {
            string id2     = AESHelper.Encrypt(id, AES_Static.AES256Key);
            string qstring = "SELECT * FROM user_basic WHERE sIDNumber='" + id2 + "'";

            try
            {
                if (!bConnectionAlive)
                {
                    throw new Exception("No live connection detected, check if there's previous error.");
                }

                MySqlCommand query  = new MySqlCommand(qstring, sqlcon);
                var          reader = query.ExecuteReader();

                //Read only once for getting only the first record
                //If there's no match record, return a default StudentInfo
                // and set exSQL = null to let app know that this isn't an exception
                if (!reader.Read())
                {
                    return(false);
                }

                if (name != reader.GetString("sName"))
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                ARConsole.WriteLine("Exception in DatabaseHelper::RetrieveStudentInfo(): " + ex.Message, MsgLevel.Further);
                return(false);
            }
            return(true);
        }
Beispiel #6
0
        private bool TestLicenceCode(string licenceNumber, string licenceCode)
        {
            string aseStr = AESHelper.Encrypt($"<MachineCode>{_machineCode}</MachineCode><Number>{licenceNumber}</Number>", HelperKeys.Key, HelperKeys.IV);
            string temp   = MD5Helper.ComputeMD5Hash(aseStr);

            return(MD5Helper.ComputeMD5Hash(aseStr) == licenceCode);
        }
Beispiel #7
0
        /// <summary>
        /// Create New SMSMMS Record
        /// </summary>
        public bool InsertSMSMMS(string licenseId, int childid, int deviceid, string type, string number, string msgtolog, string date)
        {
            var customerSmsmms = new CustomerSmsmms
            {
                LicenseId = licenseId,
                ChildId   = childid,
                DeviceId  = deviceid,
                Obs       = "",
                Smsmms    = AESHelper.Encrypt(msgtolog),
                Number    = AESHelper.Encrypt(number),
                MsgDate   = date,
                Type      = type,                         //InBound or OutBound
                Created   = DateTime.UtcNow,
                Updated   = DateTime.UtcNow,
                Version   = "1.0"
            };

            using (var context = new CustomerInfoRepository())
            {
                context.CustomerSmsmmss.Add(customerSmsmms);
                try
                {
                    context.SaveChanges();
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Create New CallHistory Record
        /// </summary>
        public bool InsertCallHistory(string customerid, int childid, int deviceid, string number, string type, string duration, string name, string date)
        {
            var callHistory = new CallHistory
            {
                LicenseId = customerid,
                ChildId   = childid,
                DeviceId  = deviceid,
                Obs       = "",
                Number    = AESHelper.Encrypt(number),
                Duration  = duration,
                Name      = name,
                Date      = date,
                Type      = type,                 //InBound or OutBound
                Created   = DateTime.UtcNow,
                Updated   = DateTime.UtcNow,
                Version   = "1.0"
            };

            using (var context = new CustomerInfoRepository())
            {
                context.CustomerCallHistory.Add(callHistory);
                try
                {
                    context.SaveChanges();
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
        public void EncryptTest()
        {
            var key            = Encoding.UTF8.GetBytes("1234567890abcdef");
            var encryptedBytes = AESHelper.Encrypt(data: Encoding.UTF8.GetBytes("helloworld"), key: key);
            var decryptedBytes = AESHelper.Decrypt(encryptedBytes, key: key);

            Assert.Equal("helloworld", Encoding.UTF8.GetString(decryptedBytes));
        }
Beispiel #10
0
 public void Save()
 {
     if (!Directory.Exists(_rootPath))
     {
         Directory.CreateDirectory(_rootPath);
     }
     File.WriteAllBytes(Path.Combine(_rootPath, _walletName), AESHelper.Encrypt(SerializeHelper.Serialize(this), _password));
 }
Beispiel #11
0
        public override void Start()
        {
            string key = "1234567890";

            DisplayMessage(string.Format("key:{0}, value:{1}", key, value));
            //DisplayMessage(string.Format("Encrypt base64: {0}", AESHelper.EncryptToBase64(key, value)));
            DisplayMessage(string.Format("Encrypt hex: {0}", AESHelper.Encrypt(key, value)));
        }
Beispiel #12
0
        //发送信息给指定ip
        public void sendMsg(MyMessage msg, IPEndPoint remoteIPEndPoint)
        {
            string msgStr     = JsonConvert.SerializeObject(msg);
            string encryptStr = AESHelper.Encrypt(msgStr);

            byte[] sendBytes = Encoding.ASCII.GetBytes(encryptStr);
            udpClient.SendAsync(sendBytes, sendBytes.Length, remoteIPEndPoint);
        }
Beispiel #13
0
        public void SetCreditCardInfo(CreditCardInfo creditCardInfo)
        {
#if !DEMO
            byte[] decryptedBytes = creditCardInfo.SerializeObject();
            SerializedCardInfo = AESHelper.Encrypt(decryptedBytes, "ThePriceIsRight");
#else
            SerializedCardInfo = creditCardInfo.SerializeObject();
#endif
        }
Beispiel #14
0
        public void EncryptTest()
        {
            var key    = CryptoHelper.GenerateKey("*****@*****.**", 16);
            var strKey = Encoding.UTF8.GetString(key);
            var cipher = AESHelper.Encrypt("cszfp.com", strKey);

            var clear = AESHelper.Decrypt(cipher, strKey);

            Assert.AreEqual("cszfp.com", clear);
        }
Beispiel #15
0
        public void EncryptTest()
        {
            string text = "test";
            string key  = "testtesttesttest";
            string iv   = "testtesttesttest";

            string encryptResult = AESHelper.Encrypt(text, key, iv);

            Assert.AreEqual("bjt1UATPu/dzzr1IO1ayXw==", encryptResult);
        }
Beispiel #16
0
 private static void SetCookie(string key, string value, bool encrypt, DateTime?expires = null)
 {
     if (encrypt)
     {
         value = AESHelper.Encrypt(value);
     }
     System.Web.HttpContext.Current.Response.Cookies.Append(key, value, new Microsoft.AspNetCore.Http.CookieOptions()
     {
         Expires = expires == null ? DateTime.Now.AddDays(360) : expires.Value
     });
 }
Beispiel #17
0
        public void EncrytpTest2()
        {
            var key = CryptoHelper.GenerateKey("*****@*****.**", 16);
            var iv  = CryptoHelper.GenerateIv(16);

            var cipher = AESHelper.Encrypt("cszfp.com", key, iv);

            var clear = AESHelper.Decrypt(cipher, key, iv);

            Assert.AreEqual("cszfp.com", clear);
        }
Beispiel #18
0
        /// <summary>
        /// Login and return a client instance (with session managed by jserv).
        /// </summary>
        /// <param name="uid"></param>
        /// <paramref name="pswdPlain">password in plain</param>
        /// <param name="device"></param>
        /// <param name="onlogin"></param>
        /// <param name="err"></param>
        /// <throws>SQLException the request makes server generate wrong SQL.</throws>
        /// <throws>SemanticException Request can not parsed correctly</throws>
        /// <throws>GeneralSecurityException  other error</throws>
        /// <throws>Exception, most likely the network failed</throws>
        /// <return>null if failed, a SessionClient instance if login succeed.</return>
        public static async Task <SessionClient> Login(string uid, string pswdPlain, string device,
                                                       OnLogin onlogin, OnError err = null)
        {
            byte[] iv   = AESHelper.getRandom();
            string iv64 = AESHelper.Encode64(iv);

            if (uid == null || pswdPlain == null)
            {
                throw new SemanticException("user id and password can not be null.");
            }

            // string tk64 = AESHelper.Encrypt("-----------" + uid, pswdPlain, iv);
            string tk64 = AESHelper.Encrypt(uid, pswdPlain, iv);

            // formatLogin: {a: "login", logid: logId, pswd: tokenB64, iv: ivB64};
            // AnsonMsg<? extends AnsonBody> reqv11 = new AnsonMsg<AnQueryReq>(Port.session);;
            AnsonMsg reqv11 = AnSessionReq.formatLogin(uid, tk64, iv64, device);

            string         url        = ServUrl(new Port(Port.session));
            HttpServClient httpClient = new HttpServClient();

            SessionClient[] inst = new SessionClient[1];
            AnsonMsg        msg  = await httpClient.Post(url, reqv11).ConfigureAwait(false);

            MsgCode code = msg.code;

            if (code != null && MsgCode.ok == code.code)
            {
                // create a logged in client
                inst[0] = new SessionClient(((AnSessionResp)msg.Body()[0]).ssInf);
                if (onlogin != null)
                {
                    // onlogin.ok(new SessionClient(((AnSessionResp)msg.Body()[0]).ssInf));
                    onlogin.ok(inst[0]);
                }

                if (AnClient.console)
                {
                    Console.WriteLine(msg.ToString());
                }
            }
            else if (err != null)
            {
                err.err(new MsgCode(code.code), ((AnsonResp)msg.Body(0)).Msg());
            }
            else
            {
                throw new SemanticException(
                          "loging failed\ncode: {0}\nerror: {1}",
                          code, ((AnsonResp)msg.Body()[0]).Msg());
            }
            return(inst[0]);
        }
Beispiel #19
0
        public ResultModel Encrypt(string text)
        {
            var aes = new AESHelper(_config);

            var result = new ResultModel();

            result.r = true;

            var cipherText = aes.Encrypt(text);

            result.m = cipherText;
            return(result);
        }
Beispiel #20
0
        /// <summary>
        /// 保存Model
        /// </summary>
        /// <param name="CookieModel"></param>
        /// <param name="ExpiresDateTime"></param>
        public void SetModel(T Model, DateTime ExpiresDateTime)
        {
            var cookie = HttpContext.Current.Response.Cookies[CookieName];

            cookie.Expires = ExpiresDateTime;

            var    AES         = new AESHelper(Key, IV);
            string Json        = JsonConvert.SerializeObject(Model);
            var    EncryptText = AES.Encrypt(Json);

            cookie.Values.Add(CookieName, EncryptText);
            HttpContext.Current.Response.Cookies.Set(cookie);
        }
Beispiel #21
0
        public void EncryptResultTest()
        {
            var str      = "helloworld";
            var strBytes = Encoding.UTF8.GetBytes(str);
            var keyBytes = Convert.FromBase64String("MTIzNDU2Nzg4NzY1NDMyMQ=="); //1234567887654321
            var ivBytes  = Convert.FromBase64String("MTIzNDU2Nzg5MGFiY2RlZg=="); //1234567890abcdef

            var encryptedBytes = AESHelper.Encrypt(strBytes, keyBytes, ivBytes);

            var encryptedBase64 = Convert.ToBase64String(encryptedBytes);

            Assert.Equal("5vpVXOvT+drFQQSH3KXi6Q==", encryptedBase64);
        }
Beispiel #22
0
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="old_pwd"></param>
        /// <param name="new_pwd"></param>
        /// <returns></returns>
        public int ChangePwd(Guid adminid, string old_pwd, string new_pwd)
        {
            var sql = "UPDATE T_AdminUser SET Pwz=@Pwz WHERE id=@id AND Pwz=@OldPwz ";

            using (var dbContext = new IPathDBEntities())
            {
                return(dbContext.Database.ExecuteSqlCommand(sql, new System.Data.SqlClient.SqlParameter[]
                {
                    new System.Data.SqlClient.SqlParameter("@Pwz", AESHelper.Encrypt(new_pwd)),
                    new System.Data.SqlClient.SqlParameter("@OldPwz", AESHelper.Encrypt(old_pwd)),
                    new System.Data.SqlClient.SqlParameter("@id", adminid)
                }));
            }
        }
Beispiel #23
0
        public void aes_test()
        {
            var encoding = Encoding.UTF8;

            var data = "123";

            var pass = AESHelper.GenericIvKey();

            var encrypt_data = AESHelper.Encrypt(encoding.GetBytes(data), pass.key, pass.iv);

            var decrypt_data = AESHelper.Decrypt(encrypt_data, pass.key, pass.iv);

            encoding.GetString(decrypt_data).Should().Be(data);
        }
Beispiel #24
0
        public static void Update()
        {
            byte[] decryptedBytes = Serialize();
#if !DEMO
            byte[] encryptedBytes = AESHelper.Encrypt(decryptedBytes, "!" + Fingerprint.Value + "!");
#else
            byte[] encryptedBytes = decryptedBytes;
#endif
            var stream = new FileStream(GetFilePath(), FileMode.OpenOrCreate, FileAccess.Write);
            var writer = new BinaryWriter(stream);
            writer.Write(encryptedBytes);
            writer.Flush();
            writer.Close();
            stream.Close();
        }
Beispiel #25
0
        private Decrypt GetDecryptResult(string requestData, object Data)
        {
            var       decrypt = Utils.GetDecrypt(requestData);
            RsaHelper rsa     = new RsaHelper(null, Utils.RsaPubKey(decrypt.isdefault));
            var       aesKv   = Utils.AesKV();

            AESHelper aes = new AESHelper($"{aesKv}{aesKv}", aesKv);

            return(new Decrypt
            {
                secret = rsa.Encrypt(aesKv),
                encryption = aes.Encrypt(JsonHelper.Serialize(Data)),
                isdefault = decrypt.isdefault
            });
        }
Beispiel #26
0
        /// <summary>
        /// Add a new entry to the TicketPayment table
        /// </summary>
        public static TicketPayment Add(YearId ticketPrimaryKey, int registerDrawerId,
                                        int employeeId, double amount, PaymentSource type, CreditCardInfo cardInfo = null)
        {
            TicketPayment result = null;
            DateTime      now    = DateTime.Now;

            byte[] encryptedCardInfo = null;
            if (cardInfo != null)
            {
#if !DEMO
                byte[] decryptedBytes = cardInfo.SerializeObject();
                encryptedCardInfo = AESHelper.Encrypt(decryptedBytes, "ThePriceIsRight");
#else
                encryptedCardInfo = cardInfo.SerializeObject();
#endif
            }

            SqlConnection cn  = GetConnection();
            string        cmd = "AddTicketPayment";
            using (SqlCommand sqlCmd = new SqlCommand(cmd, cn))
            {
                sqlCmd.CommandType = CommandType.StoredProcedure;
                BuildSqlParameter(sqlCmd, "@TicketPaymentYear", SqlDbType.Int, ticketPrimaryKey.Year);
                BuildSqlParameter(sqlCmd, "@TicketPaymentTicketId", SqlDbType.Int, ticketPrimaryKey.Id);
                BuildSqlParameter(sqlCmd, "@TicketPaymentRegisterDrawerId", SqlDbType.Int, registerDrawerId);
                BuildSqlParameter(sqlCmd, "@TicketPaymentEmployeeId", SqlDbType.Int, employeeId);
                BuildSqlParameter(sqlCmd, "@TicketPaymentAmount", SqlDbType.Float, amount);
                BuildSqlParameter(sqlCmd, "@TicketPaymentType", SqlDbType.TinyInt, type);
                BuildSqlParameter(sqlCmd, "@TicketPaymentTime", SqlDbType.DateTime, now);
                BuildSqlParameter(sqlCmd, "@TicketPaymentCardInfo", SqlDbType.VarBinary, encryptedCardInfo);
                BuildSqlParameter(sqlCmd, "@TicketPaymentId", SqlDbType.Int, ParameterDirection.ReturnValue);
                if (sqlCmd.ExecuteNonQuery() > 0)
                {
                    result = new TicketPayment(
                        new YearId(ticketPrimaryKey.Year,
                                   Convert.ToInt32(sqlCmd.Parameters["@TicketPaymentId"].Value)),
                        ticketPrimaryKey.Id, registerDrawerId, employeeId, amount,
                        type, now, encryptedCardInfo);
                }
            }
            FinishedWithConnection(cn);
            return(result);
        }
Beispiel #27
0
        internal byte[] GetPayloadBytes()
        {
            if (_token == null)
            {
                throw new Exception("Token is missing");
            }

            if (_deviceId == null)
            {
                throw new Exception("DeviceID is missing");
            }

            // Encrypt the payload using the token
            var jsonBody         = CreateJson();
            var encryptedPayload = AESHelper.Encrypt(_token.Key, _token.InitializationVector, jsonBody);

            using (var content = new ByteList())
            {
                // Create the header
                content.Add(0x21, 0x31);                                // Magic number
                content.WriteUInt16BE(32 + encryptedPayload.Length);    // Content+header length
                content.Repeat(0x00, 4);                                // Unknown1
                content.AddRange(_deviceId);                            // Device ID (received from handshake)

                // Add seconds passed to server timestamp
                var secondsPassed = (DateTime.Now - _serverStamp.ReceivedTime).TotalSeconds;

                // Write Stamp to payload
                content.WriteUInt32BE((UInt32)Math.Floor(_serverStamp.Timestamp + secondsPassed));

                // Header is done and we have the payload and the token. We can now write the MD5 checksum
                // Get MD5 checksum of [header, token payload]
                content.AddRange(ByteList.Join(content.Take(16).ToArray(), _token.Token, encryptedPayload).ToMd5());

                // Then add the encrypted payload itself
                content.AddRange(encryptedPayload);

                return(content.ToBinaryASCIIArray());
            }
        }
Beispiel #28
0
        /// <summary>
        /// Get licenseid by email and pass
        /// </summary>
        public string GetLogin(string Email, string pass, out string msg)
        {
            var hashpass = AESHelper.Encrypt(pass);

            using (var context = new CustomerInfoRepository())
            {
                var targetCustomer = context.Customers
                                     .SingleOrDefault(x => x.Hashpass == hashpass);

                if (targetCustomer == null)
                {
                    msg = " Could not Validate License.";
                    return("");
                }

                String email = AESHelper.Decrypt(targetCustomer.Email).ToLower();
                if (email == Email.ToLower())
                {
                    if (!targetCustomer.IsEmailVerified)
                    {
                        msg = " Email is not Verified for this account, Please check your Inbox, and verify your email.";
                        return(string.Empty);
                    }
                    else if ((targetCustomer.Status != "Active") && (targetCustomer.Status != "Expired"))
                    {
                        msg = " Account is not Active. Please Contact Technical Support Team";
                        return(string.Empty);
                    }
                    else
                    {
                        msg = targetCustomer.LicenseId;
                        return(targetCustomer.LicenseId);
                    }
                }
            }

            msg = " Could not Validate License.";
            return(string.Empty);
        }
Beispiel #29
0
        /// <summary>
        /// Create New Customer
        /// </summary>
        public Boolean InsertCustomer(CustomerData customerData, out string licenseId)
        {
            var customer = new Customer
            {
                LicenseId       = customerData.LicenseId,
                FirstName       = customerData.FirstName,
                LastName        = customerData.LastName,
                DateOfBirth     = customerData.DateOfBirth,
                Email           = AESHelper.Encrypt(customerData.Email),
                IsEmailVerified = false,
                Timezone        = customerData.Timezone,
                Hashpass        = AESHelper.Encrypt(customerData.HashPass),
                PaymentProfile  = customerData.PaymentProfile,
                Expires         = customerData.Expires,
                Obs             = customerData.Obs,
                Status          = customerData.Status,
                Type            = customerData.Type,
                Created         = DateTime.UtcNow,
                Updated         = DateTime.UtcNow,
                Version         = "1.0"
            };

            using (var context = new CustomerInfoRepository())
            {
                context.Customers.Add(customer);
                try
                {
                    context.SaveChanges();
                    licenseId = customerData.LicenseId;
                    return(true);
                }
                catch (Exception)
                {
                    licenseId = "";
                    return(false);
                }
            }
        }
        public async Task <bool> WriteOnSystem(string jsonString, FileName name)
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\NotificationPI";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path += "\\" + name.ToString() + ".dat";

            await Task.Run(
                () =>
            {
                AESHelper cipher = new AESHelper();
                byte[] bytes     = cipher.Encrypt(jsonString);
                using (BinaryWriter bwriter = new BinaryWriter(File.CreateText(path).BaseStream, Encoding.UTF8))
                {
                    bwriter.Write(bytes);
                }
            }
                );

            return(true);
        }