Beispiel #1
0
        private void Settings_Load(object sender, EventArgs e)
        {
            //Setup data for use outside of if statement
            var data = new dataJson();

            //Create Defaults
            data.key = "";

            //Load current data
            if (File.Exists(appDataPath + @"\data.json"))
            {
                var creds = File.ReadAllText(appDataPath + @"\data.json").Split(Convert.ToChar(","));
                try
                {
                    data = JsonConvert.DeserializeObject <dataJson>(EncryptProvider.AESDecrypt(creds[2], creds[0], creds[1]));
                }
                catch
                {
                    File.Delete(appDataPath + @"\data.json");
                }
            }

            //Apply saved data
            textBox1.Text = data.key;
        }
Beispiel #2
0
        public void AppSettingsIsSecureTest()
        {
            var files = Directory.GetFiles(@"./", "appsettings*.json");

            foreach (var f in files)
            {
                using (var sr = new StreamReader(f))
                {
                    bool secure;
                    try
                    {
                        JsonConvert.DeserializeObject <JObject>(sr.ReadToEnd());
                        secure = false;
                        Assert.True(secure);
                    }
                    catch (JsonException)
                    {
                        try
                        {
                            var aesKey = EncryptProvider.CreateAesKey();
                            EncryptProvider.AESDecrypt(sr.ReadToEnd(), aesKey.Key, aesKey.IV);
                            secure = false;
                            Assert.True(secure);
                        }
                        catch (ArgumentException)
                        {
                            secure = true;
                            Assert.True(secure);
                        }
                    }
                }
            }
        }
Beispiel #3
0
        private static void ConsumerOnReceived(object sender, BasicDeliverEventArgs e)
        {
            // Read the body into a UTF8 string.
            var body    = e.Body;
            var message = Encoding.UTF8.GetString(body);

            string json;

            try
            {
                json = EncryptProvider.AESDecrypt(message, KEY, IV);
                if (string.IsNullOrWhiteSpace(json))
                {
                    throw new ArgumentNullException(nameof(json));
                }
            }
            catch
            {
                Log.Warning("Invalid attempt to send message, wrong encryption Key and IV");
                return;
            }

            var service = JsonConvert.DeserializeObject <Service>(json);

            // Generate a new authentication token.
            var token = TokenProducer.ProduceToken();

            service.Token = token;

            SaveService(service);

            var producer = RabbitMqProducer.Create(service.ApplicationId);

            producer.SendMessage(token);
        }
Beispiel #4
0
 /// <summary>
 /// 数组解密
 /// </summary>
 /// <param name="bytes"></param>
 /// <returns></returns>
 public static byte[] DecryptTo(this byte[] bytes)
 {
     if (bytes == null)
     {
         return(bytes);
     }
     return(EncryptProvider.AESDecrypt(bytes, AesKey, AesIv));
 }
Beispiel #5
0
 /// <summary>
 /// 字符串解密
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static string DecryptTo(this string str)
 {
     if (string.IsNullOrWhiteSpace(str))
     {
         return(str);
     }
     return(EncryptProvider.AESDecrypt(str, AesKey, AesIv));
 }
Beispiel #6
0
        public void Aes_Decrypt_EmptyData_Fail_Test()
        {
            var aesKey    = EncryptProvider.CreateAesKey();
            var key       = aesKey.Key;
            var srcString = string.Empty;

            //Assert
            Assert.Throws <ArgumentException>(() => EncryptProvider.AESDecrypt(srcString, key));
        }
Beispiel #7
0
        public void Aes_Decrypt_ErrorKey_Fail_Test()
        {
            var aesKey    = EncryptProvider.CreateAesKey();
            var key       = "dfafa"; //must be 32 bit
            var srcString = "test aes encrypt";

            //Assert
            Assert.Throws <ArgumentOutOfRangeException>(() => EncryptProvider.AESDecrypt(srcString, key));
        }
Beispiel #8
0
        public void Aes_Decrypt_With_ErrorKey_Fail_Test()
        {
            var aesKey    = EncryptProvider.CreateAesKey();
            var key       = aesKey.Key;
            var iv        = "ikojpoi"; //must be 16 bit
            var srcString = "test aes encrypt";

            //Assert
            Assert.Throws <ArgumentOutOfRangeException>(() => EncryptProvider.AESDecrypt(srcString, key, iv));
        }
Beispiel #9
0
        public void Aes_Decrypt_With_ErrorIV_Fail_Test()
        {
            var aesKey    = EncryptProvider.CreateAesKey();
            var key       = "j1l23kj1j"; //must be 32 bit
            var iv        = aesKey.IV;
            var srcString = "test aes encrypt";

            //Assert
            Assert.Throws <ArgumentOutOfRangeException>(() => EncryptProvider.AESDecrypt(srcString, key, iv));
        }
Beispiel #10
0
        private bool signFile(ApiActivity ac)
        {
            // ---- SIGN FILE

            // prepare run
            ProcessStartInfo psi = new ProcessStartInfo();

            psi.FileName = Directory.GetCurrentDirectory() + @"\lib\signtool.exe";
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute        = false;
            if (ac.EncCertPw != null && ac.EncCertPw.Length > 0)
            {
                // Read secrets --> decrpyt certPW
                JObject secretsConfig = JObject.Parse(System.IO.File.ReadAllText(@"secrets.json")); //secrets.json file not checked in. .gitignore
                var     aesKey        = (string)secretsConfig["aesKey"];
                var     certPw        = EncryptProvider.AESDecrypt(ac.EncCertPw, aesKey);
                psi.Arguments = $"sign /debug /v /fd sha256 /f \"{ac.SystemCertFilename}\" /p {certPw} \"{ac.SystemOfficeFilename}\"";
            }
            else
            {
                psi.Arguments = $"sign /debug /v /fd sha256 /f \"{ac.SystemCertFilename}\" \"{ac.SystemOfficeFilename}\"";
            }
            _l.Debug($"Executing {psi.FileName} {psi.Arguments}...");

            // execute run
            StringBuilder stdOut = new StringBuilder();
            StringBuilder stdErr = new StringBuilder();
            Process       p      = new Process();

            p.StartInfo = psi;
            p.Start();

            while (!p.StandardOutput.EndOfStream)
            {
                stdOut.AppendLine(p.StandardOutput.ReadLine());
            }
            while (!p.StandardError.EndOfStream)
            {
                stdErr.AppendLine(p.StandardError.ReadLine());
            }
            p.WaitForExit();
            _l.Debug("Process exited. Parsing...");

            // parse result, prepare return json
            ac = SignToolOutputParser.parseSignToolOutput(SignToolOutputParser.SignToolOperation.Sign, ac, stdOut.ToString(), stdErr.ToString());
            if (ac.Status == ApiActivity.ApiStatus.Ready)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #11
0
        public void ReloadAccounts()
        {
            string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\SteamAccountGenerator";

            if (File.Exists(appDataPath + @"\accounts.json"))
            {
                var creds = File.ReadAllText(appDataPath + @"\accounts.json").Split(Convert.ToChar(","));
                var data  = EncryptProvider.AESDecrypt(creds[2], creds[0], creds[1]);
                richTextBox1.Text = data;
            }
        }
Beispiel #12
0
        public static string AesDecrypt(this string text, string Key)
        {
            if (string.IsNullOrEmpty(Key) || string.IsNullOrWhiteSpace(Key))
            {
                throw new ArgumentNullException("Key Cannot be null.");
            }

            string Decrypt = EncryptProvider.AESDecrypt(text, Key);

            return(Decrypt);
        }
Beispiel #13
0
        static void Main()
        {
            Console.WriteLine("Hello World!");
            byte[] clearBytes = File.ReadAllBytes(@"C:\Users\Antonio\Pictures\image.jpg");

            string encrypted = EncryptProvider.AESEncrypt("antonio", "7c529a69-2a26-4ed6-85da-16beef35db4a");
            string decrypted = EncryptProvider.AESDecrypt(encrypted, "7c529a69-2a26-4ed6-85da-16beef35db4a");

            Console.ReadLine();
            //File.WriteAllBytes(@"C:\Users\Antonio\Pictures\image_dec.jpg", decryptedBytes);
        }
        /// <summary>
        /// عملیات رمز گشایی
        /// </summary>
        public static string AesDecrypt(this string text, string key)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException("لطفا مقدار کلید را وارد نمایید.");
            }

            string decrypt = EncryptProvider.AESDecrypt(text, key);

            return(decrypt);
        }
 /// <summary>
 /// aes解密
 /// </summary>
 /// <param name="input">字符串</param>
 /// <param name="key">秘钥</param>
 /// <returns></returns>
 //public static string AesDescry(this string input, string key = null)
 //{
 //    if (key.IsNull()) key = EncryptContext.AesKey;
 //    return EncryptProvider.AESDecrypt(input, key);
 //}
 /// <summary>
 /// AesEncry 解密 带偏移量
 /// </summary>
 /// <param name="input">字符串</param>
 /// <param name="key">秘钥</param>
 /// <param name="iv">偏移量</param>
 /// <returns></returns>
 public static string AesDescry(this string input, string key = null, string iv = null)
 {
     if (key.IsNull())
     {
         key = EncryptContext.AesKey;
     }
     if (iv.IsNull())
     {
         iv = EncryptContext.AesIv;
     }
     return(EncryptProvider.AESDecrypt(input, key, iv));
 }
        public void DecryptFileAES(string filepath)
        {
            var key = aesKey.Key;
            var iv  = aesKey.IV;

            string contents  = File.ReadAllText(filepath);
            string decrypted = EncryptProvider.AESDecrypt(contents, key, iv);

            File.WriteAllText(filepath, decrypted);

            //TODO Error handling - you are out of luck!
        }
Beispiel #17
0
        private string GetDecryPtModelFile(string filePath)
        {
            var aseKey = EncryptProvider.CreateAesKey();

            aseKey.Key = "SAGjstcSTC79dx2SwsYfS23xeUHKBgLq";
            aseKey.IV  = "0SyzJl5yaZqwIWj5";
            var b2         = File.ReadAllBytes(filePath);
            var dBytes     = EncryptProvider.AESDecrypt(b2, aseKey.Key, aseKey.IV);
            var deFilePath = filePath + "_DE";

            File.WriteAllBytesAsync(deFilePath, dBytes).GetAwaiter().GetResult();
            return(deFilePath);
        }
Beispiel #18
0
        public static byte[] Decode(byte[] bytes, string password)
        {
            var sha      = SHA256.Create();
            var sb       = new StringBuilder();
            var keyBytes = sha.ComputeHash(Encoding.UTF8.GetBytes(password.ToCharArray())).ToList();

            keyBytes.ForEach(x => sb.Append(x));
            var key            = new string(sb.ToString().Take(32).ToArray());
            var iv             = new string(sb.ToString().Take(16).ToArray());
            var encryptedBytes = EncryptProvider.AESDecrypt(bytes, key, iv);

            return(encryptedBytes);
        }
        public async Task <IActionResult> SendEmail(Email email)
        {
            var siteOptions = await _context.SiteOption.ToListAsync();

            string smtpHost = siteOptions[0].SMTPHost;
            int    smtpPort = siteOptions[0].SMTPPort;
            string smtpUser = siteOptions[0].SMTPUser;

            var    encryptString = siteOptions[0].SMTPPassword.Split(".");
            var    key           = encryptString[1];
            var    iv            = encryptString[2];
            string smtpPassword  = EncryptProvider.AESDecrypt(encryptString[0], key, iv);

            bool encryption = siteOptions[0].Encryption;

            SmtpClient client = new SmtpClient();

            client.Host                  = smtpHost;
            client.Port                  = smtpPort;
            client.EnableSsl             = encryption;
            client.UseDefaultCredentials = false;
            client.Credentials           = new NetworkCredential(smtpUser, smtpPassword);

            MailAddress from    = new MailAddress(smtpUser, "Blog Info", System.Text.Encoding.UTF8);
            MailAddress to      = new MailAddress(_configuration["ContactEmail"]);
            MailAddress replyto = new MailAddress(email.Recipient);

            MailMessage message = new MailMessage(from, to);

            message.Subject         = email.Subject;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.Body            = email.Content;
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.ReplyToList.Add(replyto);

            try
            {
                await client.SendMailAsync(message);

                return(Ok(new Response {
                    Status = "Success", Message = "Mail was send successfully."
                }));
            }
            catch (Exception e)
            {
                return(Ok(new Response {
                    Status = "Error", Message = e.ToString()
                }));
            }
        }
Beispiel #20
0
 private byte[] RealizarDecryptPorTipoCriptografia(byte[] pBytesFile, Criptografia pCriptografia, string pChave)
 {
     if (pCriptografia == Criptografia.Base64)
     {
         return(Convert.FromBase64String(EncryptProvider.Base64Decrypt(Convert.ToBase64String(pBytesFile))));
     }
     else if (pCriptografia == Criptografia.DES)
     {
         return(EncryptProvider.DESDecrypt(pBytesFile, BuildKey(pChave, 24)));
     }
     else
     {
         return(Convert.FromBase64String(EncryptProvider.AESDecrypt(Convert.ToBase64String(pBytesFile), BuildKey(pChave, 32))));
     }
 }
Beispiel #21
0
        private void Form1_Load(object sender, EventArgs e)
        {
            string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\SteamAccountGenerator";

            if (!Directory.Exists(appDataPath))
            {
                Directory.CreateDirectory(appDataPath);
            }
            if (File.Exists(appDataPath + @"\accounts.json"))
            {
                var creds = File.ReadAllText(appDataPath + @"\accounts.json").Split(Convert.ToChar(","));
                var data  = EncryptProvider.AESDecrypt(creds[2], creds[0], creds[1]);
                richTextBox1.Text = data;
            }
        }
Beispiel #22
0
        public void Aes_Decryt_Success_Test()
        {
            var aesKey = EncryptProvider.CreateAesKey();
            var key    = aesKey.Key;

            var srcString = "test aes encrypt";

            //Ack
            var encrypted = EncryptProvider.AESEncrypt(srcString, key);
            var decrypted = EncryptProvider.AESDecrypt(encrypted, key);

            //Assert
            Assert.NotEmpty(encrypted);
            Assert.NotEmpty(decrypted);
            Assert.Equal(srcString, decrypted);
        }
Beispiel #23
0
        public static string AESDecrypt(string encryptedSource, CryptAESKey key)
        {
            if (!string.IsNullOrEmpty(encryptedSource) && key != null && string.IsNullOrEmpty(key.IV))
            {
                //不带加密向量
                var encrypted = EncryptProvider.AESDecrypt(encryptedSource, key.Key);
                return(encrypted);
            }
            else if (!string.IsNullOrEmpty(encryptedSource) && key != null)
            {
                //带加密向量
                var encrypted = EncryptProvider.AESDecrypt(encryptedSource, key.Key, key.IV);
                return(encrypted);
            }

            return(encryptedSource);
        }
        public override async Task <string> GetAuthenticatorKeyAsync(IdentityUser user)
        {
            var databaseKey = await base.GetAuthenticatorKeyAsync(user);

            if (databaseKey == null)
            {
                return(null);
            }

            // Decryption
            bool.TryParse(_configuration["TwoFactorAuthentication:EncryptionEnabled"], out bool encryptionEnabled);

            var originalAuthenticatorKey = encryptionEnabled
                ? EncryptProvider.AESDecrypt(databaseKey, _configuration["TwoFactorAuthentication:EncryptionKey"])
                : databaseKey;

            return(originalAuthenticatorKey);
        }
Beispiel #25
0
        public void Aes_File_Test()
        {
            var rootDir = Path.Combine(AppContext.BaseDirectory, "Assets");

            if (!Directory.Exists(rootDir))
            {
                Directory.CreateDirectory(rootDir);
            }

            var file = Path.Combine(rootDir, "AES_File_Test.txt");

            if (!File.Exists(file))
            {
                using (var fileStream = File.OpenWrite(file))
                {
                    var tempDatas = Encoding.UTF8.GetBytes("May be you shoud get all the buffer of file,and then decrypt by EncryptProvider.");
                    fileStream.Write(tempDatas, 0, tempDatas.Length);
                }
            }

            var aesKey = EncryptProvider.CreateAesKey();

            //encrypt
            var text  = File.ReadAllText(file);
            var datas = File.ReadAllBytes(file);

            var encryptedDatas = EncryptProvider.AESEncrypt(datas, aesKey.Key, aesKey.IV);
            var encryptedFile  = Path.Combine(rootDir, "AES_File_Test_Encrypted.txt");

            using (var fileStream = File.OpenWrite(encryptedFile))
            {
                fileStream.Write(encryptedDatas, 0, encryptedDatas.Length);
            }

            //decrypt
            var encryptedFileDatas = File.ReadAllBytes(encryptedFile);
            var decryptedDatas     = EncryptProvider.AESDecrypt(encryptedFileDatas, aesKey.Key, aesKey.IV);

            var decryptedText = Encoding.UTF8.GetString(decryptedDatas);

            //assert
            Assert.NotNull(decryptedDatas);
            Assert.Equal(decryptedText, text);
        }
        public override async Task <IEnumerable <string> > GenerateNewTwoFactorRecoveryCodesAsync(IdentityUser user, int number)
        {
            var tokens = await base.GenerateNewTwoFactorRecoveryCodesAsync(user, number);

            var generatedTokens = tokens as string[] ?? tokens.ToArray();

            if (!generatedTokens.Any())
            {
                return(generatedTokens);
            }

            bool.TryParse(_configuration["TwoFactorAuthentication:EncryptionEnabled"], out bool encryptionEnabled);

            return(encryptionEnabled
                ? generatedTokens
                   .Select(token =>
                           EncryptProvider.AESDecrypt(token, _configuration["TwoFactorAuthentication:EncryptionKey"]))
                : generatedTokens);
        }
Beispiel #27
0
        internal void DoOpen(string path)
        {
            var ctx    = new FileContext(path);
            var oldctx = DataContext as FileContext;

            try
            {
                DataContext = ctx;
                ctx.Status  = FcStatus.Opening;
                if (ctx.Path.EndsWith(".bad"))
                {
                    CommandSetPassword.Execute(null, this);
                    try
                    {
                        ctx.Content = EncryptProvider.AESDecrypt(FakeJapaneseToBase64(File.ReadAllText(ctx.Path)), EncryptProvider.Md5(ctx.Password));
                    }
                    catch (Exception)
                    {
                        ctx.Content = null;
                    }
                    if (string.IsNullOrEmpty(ctx.Content))
                    {
                        MessageBox.Show(this, "解密失败,文件格式不正确或密码有错。");
                        ctx.Path    = string.Empty;
                        DataContext = oldctx;
                        return;
                    }
                    ctx.isBADFile = true;
                }
                else
                {
                    ctx.isBADFile = false;
                    ctx.Content   = File.ReadAllText(ctx.Path);
                }
                ctx.Status = FcStatus.Opened;
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("程序无权访问该文件,请尝试使用管理员权限运行。");
                DataContext = oldctx;
            }
        }
Beispiel #28
0
        private void GetBanned()
        {
            Console.WriteLine("[Steam] Checking Account if Banned" + "\n");
            account_status.Text      = "Loading...";
            account_status.ForeColor = Color.Blue;
            steamClient = new SteamClient();
            manager     = new CallbackManager(steamClient);
            steamUser   = steamClient.GetHandler <SteamUser>();

            manager.Subscribe <SteamClient.ConnectedCallback>(OnConnected);
            manager.Subscribe <SteamClient.DisconnectedCallback>(OnDisconnected);

            manager.Subscribe <SteamUser.LoggedOnCallback>(OnLoggedOn);
            manager.Subscribe <SteamUser.LoggedOffCallback>(OnLoggedOff);

            isRunning = true;

            Console.WriteLine("[Steam] Connecting to Steam..." + "\n");

            // initiate the connection
            steamClient.Connect();

            // create our callback handling loop
            while (isRunning)
            {
                // in order for the callbacks to get routed, they need to be handled by the manager
                manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
            }

            if (File.Exists(appDataPath + @"\data.json"))
            {
                var creds = File.ReadAllText(appDataPath + @"\data.json").Split(Convert.ToChar(","));
                var data  = JsonConvert.DeserializeObject <dataJson>(EncryptProvider.AESDecrypt(creds[2], creds[0], creds[1]));
            }
            else
            {
                MessageBox.Show("Please set your settings\nthis menu will now close", "Error");
                steamUser.LogOff();
                steamClient.Disconnect();
                this.Close();
            }
        }
Beispiel #29
0
        private static void Method()
        {
            Console.WriteLine("Gratulacje!");
            Console.WriteLine("Poprawnie wykonałeś zadanie.");

            var key       = ConfigurationManager.AppSettings["key"];
            var encrypted = EncryptProvider.AESEncrypt("DOTNET2020", key);

            var group    = EncryptProvider.AESDecrypt(ConfigurationManager.AppSettings["group"], key);
            var password = EncryptProvider.AESDecrypt(ConfigurationManager.AppSettings["password"], key);

            Console.WriteLine();
            Console.WriteLine($"Teraz dołącz do grupy: {group}");
            Console.WriteLine($"podając hasło: {password}");

            Console.WriteLine();
            Console.WriteLine("Do zobaczenia na grupie!");

            Console.ReadLine();
        }
Beispiel #30
0
        private IDictionary <string, string> UnEncryptMyConfiguration()
        {
            IDictionary <string, string> unEncryptedCollection = new Dictionary <string, string>();
            JObject rawJObject;

            using (var sr = new StreamReader($"appsettings-{Environment.GetEnvironmentVariable("ENV")}.json"))
            {
                rawJObject = JsonConvert.DeserializeObject <JObject>(EncryptProvider.AESDecrypt(sr.ReadToEnd(),
                                                                                                Environment.GetEnvironmentVariable("AES_KEY"), Environment.GetEnvironmentVariable("AES_IV")));
            }

            foreach (var property in rawJObject.Properties())
            {
                foreach (var childProperty in property.Value)
                {
                    var realProp = (JProperty)childProperty;
                    unEncryptedCollection.Add($"{property.Name}:{realProp.Name}", realProp.Value.ToString());
                }
            }

            return(unEncryptedCollection);
        }