Ejemplo n.º 1
0
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var seed = seedTb.Text;

                var sfd = new SaveFileDialog();
                var p   = await sfd.ShowAsync(this);

                if (p != null && seed != null && seed != "")
                {
                    var pw   = new PasswordWindow();
                    var pass = await pw.ShowDialog <string>(this);

                    string walletText = "";
                    if (pass != null)
                    {
                        walletText = AesCrypto.Encrypt(seed, pass);
                    }
                    else
                    {
                        walletText = seed;
                    }

                    File.WriteAllText(p, walletText);
                }
            }
            catch (Exception exception)
            {
            }
        }
Ejemplo n.º 2
0
        public TideResponse AddFragment(AuthenticationModel model)
        {
            try {
                var usernameHash = model.Username.ConvertToUint64();

                var result = _eos.CreateTransaction(new Transaction {
                    Actions = new List <Action> {
                        new Action {
                            Account       = _settings.Onboarding,
                            Authorization = new List <PermissionLevel> {
                                new PermissionLevel {
                                    Actor = _settings.Account, Permission = "active"
                                }
                            },
                            Name = "addfrag",
                            Data = new {
                                ork_node         = _settings.Account,
                                ork_url          = model.SiteUrl,
                                username         = usernameHash,
                                private_key_frag = AesCrypto.Encrypt(model.CvkPrivateFrag, _settings.Password),
                                public_key       = model.CvkPublic,
                                pass_hash        = AesCrypto.Encrypt(model.PasswordHash, _settings.Password),
                                ork_public       = _settings.PublicKey
                            }
                        }
                    }
                }).Result;
                _logger.LogMsg("Added fragment for user", model);
                return(new TideResponse(true, null, null));
            }
            catch (Exception e) {
                _logger.LogMsg("Failed adding fragment", model, e);
                return(new TideResponse(false, null, e.Message));
            }
        }
Ejemplo n.º 3
0
        public static void TestObjectDisposed()
        {
            AesKey key = new AesKey();
            AesIV  iv  = new AesIV();

            AesCrypto crypto = new AesCrypto(key, iv, CipherMode.CBC, PaddingMode.None);

            crypto.Dispose();

            Assert.Throws <ObjectDisposedException>(() =>
            {
                crypto.Decrypt(new byte[16]);
            });

            Assert.Throws <ObjectDisposedException>(() =>
            {
                crypto.Encrypt(new byte[16]);
            });

            Assert.Throws <ObjectDisposedException>(() =>
            {
                crypto.CreateDecryptingTransform();
            });

            Assert.Throws <ObjectDisposedException>(() =>
            {
                crypto.CreateEncryptingTransform();
            });
        }
Ejemplo n.º 4
0
        public void TestEncrypt()
        {
            String encryptBody = AesCrypto.Encrypt(body, Key, Iv);

            Assert.IsTrue(encryptBody.Length > 0);
            Console.WriteLine(encryptBody);
        }
Ejemplo n.º 5
0
        private async void Open_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                var            p   = await ofd.ShowAsync(this);


                if (p.Length > 0)
                {
                    var pw   = new PasswordWindow();
                    var pass = await pw.ShowDialog <string>(this);

                    var txt = File.ReadAllText(p[0]);

                    string seed;
                    if (pass != null)
                    {
                        seed = AesCrypto.Decrypt(txt, pass);
                    }
                    else
                    {
                        seed = txt;
                    }

                    seedTb.Text = seed;

                    NewAddrWif();
                }
            }
            catch (Exception exception)
            {
            }
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            var originalFile1 = Utils.GetFileInfo("Test.txt");
            var originalFile2 = Utils.GetFileInfo("Untitled 1.odt");

            var aes = new AesCrypto();

            aes.EncryptFile(originalFile1, password: "******", output: "encrypted");
            aes.DecryptFile(Utils.GetFileInfo("encrypted"), "secret", "decrypted");

            aes.EncryptFile(originalFile2, password: "******", output: "encrypted2");
            aes.DecryptFile(Utils.GetFileInfo("encrypted2"), "secret", "decrypted2");

            var hashGen       = new HashGenerator();
            var originalHash  = hashGen.GetFileSha512Hash(originalFile1);
            var decryptedHash = hashGen.GetFileSha512Hash(Utils.GetFileInfo("decrypted"));

            Debug.Assert(originalHash == decryptedHash);

            var base64gen     = new Base64();
            var base64_String = base64gen.EncodeText("test string");
            var base64_File   = base64gen.EncodeFile(originalFile2);

            Debug.Assert("test string" == base64gen.DecodeText(base64_String));

            _ = base64gen.DecodeFile(base64_File, "decoded_base64.odt");
        }
Ejemplo n.º 7
0
    public static string EnAes(string data)
    {
        string appAesKey = "*7956$1lo0@#Zxp;";
        string appAesIV  = "@-8523769lQovg%&";

        return(AesCrypto.Encrypt(data, appAesKey, appAesIV));
    }
Ejemplo n.º 8
0
        public TestAesCrypto()
        {
            var keyValue = AesCrypto.CreateKeyAndIv();

            Key = keyValue.Key;
            Iv  = keyValue.Value;
        }
Ejemplo n.º 9
0
        private void btn_Encrypt_Click(object sender, EventArgs e)
        {
            String key  = textBox_Key.Text.Trim(),
                   iv   = textBox_IV.Text.Trim(),
                   body = textBox_Body.Text.Trim();

            if (String.IsNullOrEmpty(key))
            {
                MessageBox.Show("秘钥不能为空!", "温馨提示");
                return;
            }

            if (String.IsNullOrEmpty(iv) && isIvEncrypt())
            {
                MessageBox.Show("偏移量不能为空!", "温馨提示");
                return;
            }

            if (String.IsNullOrEmpty(body))
            {
                MessageBox.Show("待处理文本不能为空!", "温馨提示");
                return;
            }
            var keyValue = KeyToBytes();

            byte[] bytes = AesCrypto.Encrypt(Encoding.UTF8.GetBytes(body), keyValue.Key, keyValue.Value);
            DisplayCiphertexts(bytes);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Subkey"/> class. Different data is encrypted using
        /// different variants of the master encryption key.
        /// </summary>
        /// <param name="masterKey">The master key.</param>
        /// <param name="headerSubkey">The header subkey.</param>
        public Subkey(AesKey masterKey, HeaderSubkey headerSubkey)
        {
            if (masterKey == null)
            {
                throw new ArgumentNullException("masterKey");
            }

            byte[] block = new byte[16];
            byte subKeyValue;
            switch (headerSubkey)
            {
                case HeaderSubkey.Hmac:
                    subKeyValue = 0;
                    break;
                case HeaderSubkey.Validator:
                    subKeyValue = 1;
                    break;
                case HeaderSubkey.Headers:
                    subKeyValue = 2;
                    break;
                case HeaderSubkey.Data:
                    subKeyValue = 3;
                    break;
                default:
                    throw new InternalErrorException("headerSubkey");
            }

            block[0] = subKeyValue;
            using (AesCrypto aesCrypto = new AesCrypto(masterKey))
            {
                _subKey = new AesKey(aesCrypto.Encrypt(block));
            }
        }
Ejemplo n.º 11
0
        private void buttonAesDecrypt_Click(object sender, EventArgs e)
        {
            var crypto = new AesCrypto(this.textAesKey.Text, this.textAesIv.Text);

            this.textAesDecryptedOutput.Text = crypto.Decrypt(this.textAesEncryptedInput.Text);
            Clipboard.SetText(textAesDecryptedOutput.Text);
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> ExchangeCallbackAsync(GetSimpleWalletExchangeRequest request,
                                                                [FromServices] IConfiguration config,
                                                                [FromServices] ILogger logger,
                                                                [FromServices] IHubContext <SimpleWalletHub> hubContext,
                                                                [FromServices] AesCrypto aesCrypto,
                                                                CancellationToken cancellationToken)
        {
            logger.LogInfo(JsonConvert.SerializeObject(request));
            //var verify = aesCrypto.Encrypt(request.UUID) == request.Sign;
            //we will fix it later
            if (true)
            {
                await hubContext.Clients.Groups(request.UUID).SendAsync("simpleWalletExchangeSucceeded", cancellationToken);

                return(Json(new PostSimpleWalletLoginResponse
                {
                    Code = 0
                }));
            }

            return(Json(new PostSimpleWalletLoginResponse
            {
                Code = 1,
                Error = "sign error"
            }));
        }
Ejemplo n.º 13
0
        public void TestEncryptNoIv()
        {
            var    key         = AesCrypto.CreateKey();
            String encryptBody = AesCrypto.Encrypt(body, Encoding.UTF8.GetBytes(key));

            Assert.IsTrue(encryptBody.Length > 0);
            Console.WriteLine(encryptBody);
        }
Ejemplo n.º 14
0
        public void TestCreateKey()
        {
            var key = AesCrypto.CreateKey();

            Assert.IsNotNull(key);
            Assert.IsTrue(key.Length > 0);
            Console.WriteLine("Key:{0}", key);
        }
Ejemplo n.º 15
0
        public void Encryption_Test()
        {
            string    testStr   = Convert.ToBase64String(Encoding.ASCII.GetBytes("dev:test"));
            AesCrypto encryptor = new AesCrypto {
                KeyPhrase = "dev"
            };

            Console.WriteLine(encryptor.Encrypt(testStr));
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            Console.WriteLine("Testing...");
            string input  = Console.ReadLine();
            string output = AesCrypto.Decrypt(input);

            Console.WriteLine($"Result: {output}");
            Console.ReadLine();
        }
Ejemplo n.º 17
0
        private static string DecryptedCustomVariableValue(CustomVariable customVariable, bool leaveValueEncrypted)
        {
            if (!customVariable.ValueIsEncrypted || leaveValueEncrypted)
            {
                return(customVariable.Value);
            }

            return(AesCrypto.Decrypt(customVariable.Value));
        }
Ejemplo n.º 18
0
        public void Decryption_Test()
        {
            string    testStr   = "TIksnh/5Qf33CzOBvVeiog==";
            AesCrypto encryptor = new AesCrypto {
                KeyPhrase = "dev"
            };

            Console.WriteLine(encryptor.Decrypt(testStr));
        }
Ejemplo n.º 19
0
        public void Should_Entrypt_Decrypt()
        {
            var person    = "HassanHashemi";
            var salt      = Encoding.UTF8.GetBytes("*****@*****.**");
            var aes       = new AesCrypto(salt, "pass");
            var encrypted = aes.Encrypt(person);
            var result    = aes.Decrypt(encrypted);

            Assert.True(person == result);
        }
Ejemplo n.º 20
0
        private void btn_CreateKey_Click(object sender, EventArgs e)
        {
            var keyValue = AesCrypto.CreateKeyAndIvBytes();

            if (!isIvEncrypt())
            {
                keyValue = new KeyValuePair <byte[], byte[]>(keyValue.Key, null);
            }
            DisplayKey(keyValue);
        }
Ejemplo n.º 21
0
        public static async Task <T> SendPostRequest <T>(this L2Request req) where T : L2Response
        {
            var request = await new HttpClient().PostAsync(Startup.Configuration.GetValue <string>("ApiEndpoint"), new JsonContent(req));

            var result = AesCrypto.DecryptRijndael(await request.Content.ReadAsStringAsync(), Startup.Configuration.GetValue <string>("CryptoSalt"));

            var responseObject = JsonConvert.DeserializeObject <T>(result);

            return(responseObject);
        }
Ejemplo n.º 22
0
        public static async Task <T> SendPostRequest <T>(this L2Request req) where T : L2Response
        {
            var request = await new HttpClient().PostAsync(ApiUrl, new JsonContent(req));

            var result = AesCrypto.DecryptRijndael(await request.Content.ReadAsStringAsync(), Constants.Salt);

            var responseObject = JsonConvert.DeserializeObject <T>(result);

            return(responseObject);
        }
Ejemplo n.º 23
0
        public void Decrypt_should_decrypt_cipherText(string cipherText, string key)
        {
            var aesCrypto = new AesCrypto();

            var encodedKey = Encoding.UTF8.GetBytes(Guid.Parse(key).ToString("N"));
            var decrypted  = aesCrypto.Decrypt(cipherText, encodedKey);

            decrypted.Should().NotBeNullOrWhiteSpace();
            decrypted.Should().Be(_plainText);
        }
Ejemplo n.º 24
0
        public void TestCreateKeyAndIv()
        {
            var keyValue = AesCrypto.CreateKeyAndIv();

            Assert.IsNotNull(keyValue);
            Assert.IsTrue(keyValue.Key.Length > 0);
            Assert.IsTrue(keyValue.Value.Length > 0);
            Console.WriteLine("Key:{0}", keyValue.Key);
            Console.WriteLine("IV:{0}", keyValue.Value);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Jelszó AES256 dekódolása, "lx" esetén nem dekódol
        /// </summary>
        /// <param name="kodoltJelszo">Kódolt bemenet</param>
        /// <returns>Nem kódolt kimenet</returns>
        public static string DBPassDecode(string kodoltJelszo)
        {
            if (LXUSER.Equals(kodoltJelszo, StringComparison.OrdinalIgnoreCase))
            {
                return(kodoltJelszo);
            }

            string key = Encoding.Unicode.GetString(Convert.FromBase64String(DBPASS_ENCRIPTIONKEY));

            return(AesCrypto.AesDecryptString(kodoltJelszo, key, Encoding.Unicode));
        }
        /// <summary>
        /// Renders a hidden form field that contains a value encrypted with AES. The key for the encryption must
        /// be set in your web.config with the <see cref="CryptoConfigurationSection"/>.
        /// </summary>
        /// <param name="html">The <see cref="HtmlHelper"/></param>
        /// <param name="name">The name of the field</param>
        /// <param name="value">The value to encrypt</param>
        /// <param name="htmlAttributes">An object containing the HTML attributes for the element.</param>
        /// <returns>The HTML</returns>
        public static MvcHtmlString EncryptedHidden(this HtmlHelper html, string name, string value, IDictionary <string, object> htmlAttributes)
        {
            string encryptedValue;

            using (ICrypto crypto = new AesCrypto())
            {
                encryptedValue = crypto.EncryptToBase64(value);
            }

            return(html.Hidden(name, encryptedValue, htmlAttributes));
        }
Ejemplo n.º 27
0
        public void TestDecrypt()
        {
            String encryptBody = AesCrypto.Encrypt(body, Key, Iv);
            String decryptBody = AesCrypto.Decrypt(encryptBody, Key, Iv);

            Assert.IsNotNull(decryptBody);
            Assert.IsTrue(decryptBody.Length > 0);
            Console.WriteLine("密文:{0}", encryptBody);
            Console.WriteLine("明文:{0}", decryptBody);
            Assert.IsTrue(decryptBody.Equals(body));
        }
Ejemplo n.º 28
0
        public void AesCryptoToFromEncrypted()
        {
            var expected = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";

            using (var crypto = new AesCrypto("Passphrase", new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 }))
            {
                string encrypted = crypto.AesEncrypt(expected);
                string actual = crypto.AesDecrypt(encrypted, true);

                Assert.AreEqual(expected, actual);
            }
        }
Ejemplo n.º 29
0
        public ReadPage()
        {
            InitializeComponent();

            try
            {
                var json    = Uri.UnescapeDataString(new Uri(App.UriData).Query.Replace("?data=", string.Empty));
                var message = JsonConvert.DeserializeObject <KriptalMessage>(json);

                var aes = new AesCrypto();
                var rsa = new RsaCrypto();

                var localDataManager = new LocalDataManager(App.Password);
                var privateKey       = localDataManager.GetPrivateKey();

                var textAesKey = rsa.DecryptWithPrivate(message.TextAesKey, privateKey);
                var textAesIv  = rsa.DecryptWithPrivate(message.TextAesIv, privateKey);
                var text       = aes.Decrypt(message.TextData, textAesKey, Convert.FromBase64String(textAesIv));
                MessageText = text;

                if (!string.IsNullOrEmpty(message.BlockchainStampUrl))
                {
                    var blockchainUrl = rsa.DecryptWithPrivate(message.BlockchainStampUrl, privateKey);
                    BlockchainReciptUrl = blockchainUrl;
                }

                if (message.FileName != string.Empty)
                {
                    FileName = rsa.DecryptWithPrivate(message.FileName, privateKey);
                    var fileAesKey = rsa.DecryptWithPrivate(message.FileAesKey, privateKey);
                    var fileAesIv  = rsa.DecryptWithPrivate(message.FileAesIv, privateKey);
                    FileData      = aes.Decrypt(message.FileData, fileAesKey, Convert.FromBase64String(fileAesIv));
                    HasAttachment = true;
                }
                else
                {
                    HasAttachment = false;
                }

                var fromId = rsa.DecryptWithPrivate(message.FromId, privateKey);
                var user   = localDataManager.Get <User>(u => u.Id == fromId);
                UserName = user.Name;

                App.UriData = string.Empty;

                BindingContext = this;
            }
            catch
            {
                DisplayAlert(AppResources.Title, AppResources.CantRead, AppResources.OK);
            }
        }
Ejemplo n.º 30
0
        private void SetMasterKeyForEncryptedHeaderBlocks(IList <HeaderBlock> headerBlocks)
        {
            AesCrypto headerCrypto = new AesCrypto(HeadersSubkey.Key);

            foreach (HeaderBlock headerBlock in headerBlocks)
            {
                EncryptedHeaderBlock encryptedHeaderBlock = headerBlock as EncryptedHeaderBlock;
                if (encryptedHeaderBlock != null)
                {
                    encryptedHeaderBlock.HeaderCrypto = headerCrypto;
                }
            }
        }
Ejemplo n.º 31
0
 public string Encrypt(string valueToEncrypt)
 {
     try
     {
         var encryptedValue = AesCrypto.Encrypt(valueToEncrypt);
         return(encryptedValue);
     }
     catch (Exception ex)
     {
         Logger.LogException(ex);
         throw Helper.CreateHttpResponseException(ex, "Error Encrypting Value");
     }
 }
Ejemplo n.º 32
0
        public void TestDecryptNoIv()
        {
            var    key         = AesCrypto.CreateKey();
            String encryptBody = AesCrypto.Encrypt(body, Encoding.UTF8.GetBytes(key));

            Console.WriteLine("密文:{0}", encryptBody);

            String decryptBody = AesCrypto.Decrypt(encryptBody, Encoding.UTF8.GetBytes(key));

            Assert.IsNotNull(decryptBody);
            Assert.IsTrue(decryptBody.Length > 0);
            Console.WriteLine("明文:{0}", decryptBody);
            Assert.IsTrue(decryptBody.Equals(body));
        }
Ejemplo n.º 33
0
        public static void TestDoubleDispose()
        {
            AesKey key = new AesKey();
            AesIV iv = new AesIV();

            AesCrypto crypto = new AesCrypto(key, iv, CipherMode.CBC, PaddingMode.None);
            crypto.Dispose();
            Assert.Throws<ObjectDisposedException>(() =>
            {
                crypto.CreateDecryptingTransform();
            });
            crypto.Dispose();
            Assert.Throws<ObjectDisposedException>(() =>
            {
                crypto.CreateDecryptingTransform();
            });
        }
Ejemplo n.º 34
0
        private void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                if (_dataCrypto != null)
                {
                    _dataCrypto.Dispose();
                    _dataCrypto = null;
                }
                if (_reader != null)
                {
                    _reader.Dispose();
                    _reader = null;
                }
            }

            _disposed = true;
        }