Exemple #1
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);
            }
        }
Exemple #2
0
        public static bool Initialize()
        {
            // If a settings file exists, deserialize it.
            if (File.Exists(_path))
            {
                bool readFail = false;
                var  stream   = new FileStream(_path, FileMode.Open, FileAccess.Read);
                var  reader   = new BinaryReader(stream);
                try
                {
                    byte[] encryptedBytes = reader.ReadBytes((int)stream.Length);
#if !DEMO
                    byte[] decryptedBytes = AESHelper.Decrypt(encryptedBytes, "!" + Fingerprint.Value + "!");
                    Deserialize(decryptedBytes);
#else
                    Deserialize(encryptedBytes);
#endif
                }
                catch { readFail = true; }
                reader.Close();
                stream.Close();

                // If the settings file is bad or license isn't valid
#if !DEMO
                if (readFail || !LocalSettingFileIsOriginal())
#else
                if (readFail)
#endif
                {
                    Reset();
                    return(false);
                }
            }
            return(true);
        }
Exemple #3
0
        public static bool DecryptTrackFile(StreamUrl stream, string filepath)
        {
            try
            {
                if (!System.IO.File.Exists(filepath))
                {
                    return(false);
                }
                if (stream.EncryptionKey.IsBlank())
                {
                    return(true);
                }

                byte[] security_token = System.Convert.FromBase64String(stream.EncryptionKey);

                byte[] iv  = security_token.Skip(0).Take(16).ToArray();
                byte[] str = security_token.Skip(16).ToArray();
                byte[] dec = AESHelper.Decrypt(str, MASTER_KEY, iv);

                byte[] key    = dec.Skip(0).Take(16).ToArray();
                byte[] nonce  = dec.Skip(16).Take(8).ToArray();
                byte[] nonce2 = new byte[16];
                nonce.CopyTo(nonce2, 0);

                byte[]  txt   = ReadFile(filepath);
                AES_CTR tool  = new AES_CTR(key, nonce2);
                byte[]  newt  = tool.DecryptBytes(txt);
                bool    bfalg = WriteFile(filepath, newt);
                return(bfalg);
            }
            catch
            {
                return(false);
            }
        }
        public async Task <string> ReadFromSystem(FileName name)
        {
            String result = null;

            try
            {
                string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\NotificationPI";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += "\\" + name.ToString() + ".dat";
                using (BinaryReader breader = new BinaryReader(File.OpenText(path).BaseStream))
                {
                    await Task.Run(
                        () =>
                    {
                        byte[] bytes     = breader.ReadBytes((int)breader.BaseStream.Length);
                        AESHelper cipher = new AESHelper();
                        result           = cipher.Decrypt(bytes);
                    }
                        );
                }
                return(result);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemple #5
0
        public static bool DecryptTrackFile(StreamUrl stream, string filepath)
        {
            if (!File.Exists(filepath))
            {
                return(false);
            }
            if (stream.EncryptionKey.IsBlank())
            {
                return(true);
            }

            byte[] master_key     = System.Convert.FromBase64String("UIlTTEMmmLfGowo/UC60x2H45W6MdGgTRfo/umg4754=");
            byte[] security_token = System.Convert.FromBase64String(stream.EncryptionKey);

            byte[] iv  = security_token.Skip(0).Take(16).ToArray();
            byte[] str = security_token.Skip(16).ToArray();
            byte[] dec = AESHelper.Decrypt(str, master_key, iv);

            byte[] key    = dec.Skip(0).Take(16).ToArray();
            byte[] nonce  = dec.Skip(16).Take(8).ToArray();
            byte[] nonce2 = new byte[16];
            nonce.CopyTo(nonce2, 0);

            byte[]  txt  = ReadFile(filepath);
            AES_CTR tool = new AES_CTR(key, nonce2);

            byte[] newt  = tool.DecryptBytes(txt);
            bool   bfalg = WriteFile(filepath, newt);

            return(bfalg);
        }
        public JsonResult UserLogin(string usr, string pwd, string random)
        {
            var LoginRandomStr = Session[ConstantHelper.LOGINRANDOMSTR] as string;

            if (string.IsNullOrEmpty(LoginRandomStr) || random != LoginRandomStr)
            {
                // 随机子串过期,需要重新登录
                Session[ConstantHelper.LOGINRANDOMSTR] = Guid.NewGuid().ToString();
                LoginRandomStr = Session[ConstantHelper.LOGINRANDOMSTR] as string;
                return(Json(new { state = 2, txt = "页面过期", data = LoginRandomStr }));
            }
            var user = AdminService.Instance.Login(usr);

            if (user == null)
            {
                return(Json(new { state = 0, txt = "不存在该账号信息" }));
            }
            var _pwd = usr + AESHelper.Decrypt(user.Pwz) + LoginRandomStr;

            _pwd = StringHelper.MD5(_pwd);
            if (pwd.ToUpper() == _pwd.ToUpper())
            {
                Session[ConstantHelper.CURRENTPERMISSION]      = user.PermissionInfo;
                Session[ConstantHelper.CURRENTADMINUSERENTITY] = user;
                Session[ConstantHelper.CURRENTADMINUSER]       = user.UserName;
                return(Json(new { state = 1 }));
            }
            else
            {
                return(Json(new { state = 0, txt = "帐号或密码错误" }));
            }
        }
Exemple #7
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);
        }
Exemple #8
0
        /// <summary>
        /// Converts the given base64 encoded AES-128 encrypted data
        /// </summary>
        /// <returns></returns>
        public string DoChallenge07()
        {
            byte[] encryptedData = Convert.FromBase64String(base64EncryptedData);
            byte[] key           = Encoding.ASCII.GetBytes(theMagicKey);

            return(AESHelper.Decrypt(encryptedData, key));
        }
Exemple #9
0
        /// <summary>
        /// Parse the incoming data
        /// </summary>
        /// <returns></returns>
        private bool ParseResponse()
        {
            if (_data != null && _data.Length > 0)
            {
                using (var content = new ByteList(_data))
                {
                    // Receive the device id from the response
                    DeviceId = content.Skip(8).Take(4).ToArray();

                    var timestamp = content.ReadInt32LE(12, 4);
                    if (timestamp > 0)
                    {
                        Timestamp = new ServerTimestamp(timestamp);
                    }

                    var encrypted = content.Skip(32);
                    if (encrypted.Count() > 0)
                    {
                        var decrypted = AESHelper.Decrypt(_miToken.Key, _miToken.InitializationVector, encrypted.ToArray());
                        ResponseText = ASCIIEncoding.ASCII.GetString(decrypted);
                    }
                    return(true);
                }
            }

            return(false);
        }
Exemple #10
0
 /// <summary>
 /// Get All Calls for the last x minutes
 /// </summary>
 public IEnumerable <DomainEntity> GetAllCallHistory(string licenseid, int deviceid, DateTime startTime, DateTime endTime)
 {
     using (var context = new CustomerInfoRepository())
     {
         return(context.CustomerCallHistory
                .Where(x => x.LicenseId == licenseid &&
                       x.DeviceId == deviceid &&
                       x.Created >= startTime &&
                       x.Created < endTime)
                .AsEnumerable()
                .Select(x => new DomainEntity
         {
             Type = "CallHistory",
             DateTime = x.Created,
             Text = AESHelper.Decrypt(x.Number),
             Image = "",
             DeviceId = x.DeviceId,
             DeviceName = x.Device.Name,
             DeviceType = x.Device.Type,
             //ChildName = x.
             PageClassification = ""
         })
                .ToArray());
     }
 }
Exemple #11
0
        private void EndReceive(IAsyncResult ar)
        {
            try
            {
                UdpState s = ar.AsyncState as UdpState;
                if (s != null)
                {
                    UdpClient udpClient = s.udpClient;

                    IPEndPoint ip           = s.ip;
                    Byte[]     receiveBytes = udpClient.EndReceive(ar, ref ip);
                    string     msg          = Encoding.UTF8.GetString(receiveBytes);
                    string     decryptMsg   = AESHelper.Decrypt(msg);
                    Console.WriteLine(decryptMsg);

                    //处理接收过来的数据
                    handleMsg(decryptMsg, ip);
                    udpClient.BeginReceive(EndReceive, s);//在这里重新开始一个异步接收,用于处理下一个网络请求
                }
            }
            catch (Exception ex)
            {
                //处理异常
                Console.WriteLine("server error" + ex.Message);
            }
        }
Exemple #12
0
        public string Get(string data, string key)
        {
            var res = AESHelper.Decrypt(data, key + key, key);

            //"E94B7uOi9pDeG64wyPwJ/g==";
            //fb12345
            return(res);
        }
Exemple #13
0
        public override void Start()
        {
            string key = "esupport.enterprise";

            DisplayMessage(string.Format("key:{0}, value:{1}", key, value));
            //DisplayMessage(string.Format("Decrypt base64: {0}", AESHelper.DecryptFromBase64(key, value)));
            DisplayMessage(string.Format("Decrypt hex: {0}", AESHelper.Decrypt(key, value)));
        }
        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));
        }
Exemple #15
0
        public CreditCardInfo GetCreditCardInfo()
        {
#if !DEMO
            byte[] decryptedBytes = AESHelper.Decrypt(SerializedCardInfo, "ThePriceIsRight");
            return(decryptedBytes.DeserializeObject() as CreditCardInfo);
#else
            return(SerializedCardInfo.DeserializeObject() as CreditCardInfo);
#endif
        }
Exemple #16
0
        private string GetResponseContent(IRestResponse response, bool useGZip)
        {
            var data = AESHelper.Decrypt(response.RawBytes, this._secretKey, null, CipherMode.ECB, PaddingMode.PKCS7);

            if (useGZip)
            {
                data = GZipHelper.Decompress(data);
            }
            return(Encoding.UTF8.GetString(data));
        }
Exemple #17
0
        public void DecryptTest()
        {
            string base64 = "bjt1UATPu/dzzr1IO1ayXw==";
            string key    = "testtesttesttest";
            string iv     = "testtesttesttest";

            string decryptResult = AESHelper.Decrypt(base64, key, iv);

            Assert.AreEqual("test", decryptResult);
        }
Exemple #18
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);
        }
Exemple #19
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);
        }
Exemple #20
0
        /// <summary>
        /// Read from cookie or Create
        /// </summary>
        /// <returns></returns>
        public static AppAuthorization GetSession()
        {
            var json = HttpContext.Current.Request.Headers[APIConstants.AUTHORIZATION];

            if (String.IsNullOrEmpty(json))
            {
                return(new AppAuthorization());
            }

            var txt = AESHelper.Decrypt(json, AppConfig.Settings.AesKey);

            return(JsonConvert.DeserializeObject <AppAuthorization>(txt));
        }
Exemple #21
0
        public static bool DecryptFile(string sText)
        {
            byte[] master_key     = Convert.FromBase64String("UIlTTEMmmLfGowo/UC60x2H45W6MdGgTRfo/umg4754=");
            byte[] security_token = Convert.FromBase64String(sText);

            byte[] iv  = security_token.Skip(0).Take(16).ToArray();
            byte[] str = security_token.Skip(16).ToArray();
            byte[] dec = AESHelper.Decrypt(str, master_key, iv);

            byte[] key   = dec.Skip(0).Take(16).ToArray();
            byte[] nonce = dec.Skip(16).Take(8).ToArray();
            return(true);
        }
Exemple #22
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);
        }
Exemple #23
0
 //百姓码
 public string Common(string result)
 {
     if (string.IsNullOrEmpty(result))
     {
         return("请求参数存在空值");
     }
     else
     {
         //设置请求接口
         var request = (HttpWebRequest)WebRequest.Create("https://api.bechangedt.com/api/healthcode/verify");
         //请求参数
         var postData = "{" + '"' + "healthQrCode" + '"' + ":" + '"' + result + '"' + "}";
         var data     = Encoding.ASCII.GetBytes(postData);
         //请求方式
         request.Method = "POST";
         //请求头参数设置
         request.Headers.Add("organizationId", "002504421");
         request.Headers.Add("appId", "6737FDA2D");
         request.Headers.Add("dataSources", "3");
         request.Headers.Add("tradeCode", "60002");
         var requestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
         request.Headers.Add("requestTime", requestTime);
         string md5 = YunSendMsg.GenerateMD5("002504421" + "6737FDA2D" + "840CA391C69950D13514A2A3CD572506" + "3" + "60002" + requestTime).ToUpper();
         request.Headers.Add("sign", md5);
         request.ContentType           = "application/json;charset=UTF-8";
         request.ContentLength         = data.Length;
         request.UseDefaultCredentials = true;
         using (var stream = request.GetRequestStream())
         {
             stream.Write(data, 0, data.Length);
         }
         //结果返回
         var responses = (HttpWebResponse)request.GetResponse();
         //转字符串
         var responseString = new StreamReader(responses.GetResponseStream(), Encoding.UTF8).ReadToEnd();
         //转换为json对象
         CommonCard commodel = JsonConvert.DeserializeObject <CommonCard>(responseString);
         if (commodel.code != 1 || commodel.data == null)
         {
             return(commodel.msg);
         }
         else
         {
             var           card      = AESHelper.Decrypt(commodel.data.verifyResp, "HEALTHCODEVERIFY");
             CommonCardMan commodels = JsonConvert.DeserializeObject <CommonCardMan>(card);
             return(commodels.idCardValue);
         }
     }
 }
Exemple #24
0
        public static string AESDecrypt(string encrypt_data, string iv, string session_key)
        {
            var bs = AESHelper.Decrypt(
                encryptedData: Convert.FromBase64String(encrypt_data),
                key: Convert.FromBase64String(session_key),
                iv: Convert.FromBase64String(iv),
                keySize: 128,
                blockSize: 128,
                mode: System.Security.Cryptography.CipherMode.CBC,
                padding: System.Security.Cryptography.PaddingMode.PKCS7);

            var data = Encoding.UTF8.GetString(bs);

            return(data);
        }
Exemple #25
0
        /// <summary>
        /// Get All
        /// </summary>
        public IEnumerable <CallHistory> GetAllCallHistory(string licenseid, string childid, int?deviceid)
        {
            using (var context = new CustomerInfoRepository())
            {
                var result = context.CustomerCallHistory
                             .Where(x => x.LicenseId == licenseid && x.DeviceId == deviceid).ToArray();

                foreach (var callHistory in result)
                {
                    callHistory.Number = AESHelper.Decrypt(callHistory.Number);
                }

                return(result);
            }
        }
Exemple #26
0
        /// <summary>
        /// Get All
        /// </summary>
        public IEnumerable <CustomerSmsmms> GetAllSMSMMS(string licenseid, string childid, int?deviceid)
        {
            using (var context = new CustomerInfoRepository())
            {
                var result = context.CustomerSmsmmss.Where(x => x.LicenseId == licenseid && x.DeviceId == deviceid).ToArray();

                foreach (var customerBlocker in result)
                {
                    customerBlocker.Number = AESHelper.Decrypt(customerBlocker.Number);
                    customerBlocker.Smsmms = AESHelper.Decrypt(customerBlocker.Smsmms);
                }

                return(result);
            }
        }
Exemple #27
0
        /// <summary>
        /// 取得Model
        /// </summary>
        public T GetModel()
        {
            var cookie = HttpContext.Current.Request.Cookies[CookieName];

            if (cookie != null)
            {
                var CookieValue = cookie.Values[CookieName];

                var    AES           = new AESHelper(Key, IV);
                string DecryptText   = AES.Decrypt(CookieValue);
                T      OperatorModel = JsonConvert.DeserializeObject <T>(DecryptText);
                return(OperatorModel);
            }
            else
            {
                return(default(T));
            }
        }
Exemple #28
0
        public static Wallet Load(string password)
        {
            if (!Directory.Exists(_rootPath))
            {
                Directory.CreateDirectory(_rootPath);
            }
            if (!File.Exists(Path.Combine(_rootPath, _walletName)))
            {
                new Wallet(password)
                {
                    PasswordSignature = HashHelper.Sha256(password)
                }.Save();
            }
            var wallet = SerializeHelper.Deserialize <Wallet>(AESHelper.Decrypt(File.ReadAllBytes(Path.Combine(_rootPath, _walletName)), password));

            wallet._password = password;
            return(wallet);
        }
Exemple #29
0
        /// <summary>
        /// Get Specific Customer
        /// </summary>
        public Customer GetCustomer(string licenseId)
        {
            if (licenseId == null)
            {
                return(null);
            }

            using (var context = new CustomerInfoRepository())
            {
                var targetCustomer = context.Customers.FirstOrDefault(x => x.LicenseId == licenseId);
                if (targetCustomer != null)
                {
                    targetCustomer.Email    = AESHelper.Decrypt(targetCustomer.Email);
                    targetCustomer.Hashpass = AESHelper.Decrypt(targetCustomer.Hashpass);
                    return(targetCustomer);
                }
                else
                {
                    return(null);
                }
            }
        }
Exemple #30
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);
        }