示例#1
0
        private static void CreateProject()
        {
            //AsymmetricEncryption.GenerateRegisterFile("yazhi.pang", "autox");
            var fileContent = File.ReadAllText("yazhi.pang.pem");
            var forSake     = XElement.Parse(fileContent);
            var projectName = forSake.GetAttributeValue("ProjectName");

            if (MongoDBManager.GetInstance().IsProjectExisted(projectName))
            {
                Console.WriteLine("Project already existed, continue?(y/n):");
                if (!Console.ReadKey().KeyChar.Equals('y'))
                {
                    return;
                }
            }
            MongoDBManager.GetInstance().SetProject(projectName);
            var root = forSake.Element("Root");
            var publicAndPrivateKey = root.GetAttributeValue("PublicAndPrivateKey");
            var secret    = root.GetAttributeValue("Secret");
            var decrypted = AsymmetricEncryption.DecryptText(secret, 2048, publicAndPrivateKey);
            var userName  = root.GetAttributeValue("UserName");

            foreach (XElement descendant in forSake.Descendants())
            {
                DBFactory.GetData().Save(descendant);
            }
        }
示例#2
0
        public void TestAsymmetricEncryptionNonPersistedKey()
        {
            byte[] plainBytes = ByteUtil.Utf8NoBOM.GetBytes("Secret String For Testing");

            AsymmetricEncryption.GenerateNewKeys(out string publicKey, out string privateKey);

            byte[] encryptedBytes = AsymmetricEncryption.EncryptWithKey(publicKey, plainBytes);
            Assert.IsFalse(ByteUtil.ByteArraysMatch(plainBytes, encryptedBytes));

            byte[] decryptedBytes = AsymmetricEncryption.DecryptWithKey(privateKey, encryptedBytes);
            Assert.IsTrue(ByteUtil.ByteArraysMatch(plainBytes, decryptedBytes));

            // Try encrypting with the private key (usually done with only the public key).
            byte[] encryptedBytes2 = AsymmetricEncryption.EncryptWithKey(privateKey, plainBytes);
            Assert.IsFalse(ByteUtil.ByteArraysMatch(plainBytes, encryptedBytes2));

            // Try decrypting with the public key (should fail)
            try
            {
                byte[] decryptedBytes2 = AsymmetricEncryption.DecryptWithKey(publicKey, encryptedBytes);
                Assert.Fail("Expected exception when trying to decrypt with public key.");
            }
            catch { }

            // Verify that private-key-encryption worked as intended
            byte[] decryptedBytes3 = AsymmetricEncryption.DecryptWithKey(privateKey, encryptedBytes);
            Assert.IsTrue(ByteUtil.ByteArraysMatch(plainBytes, decryptedBytes3));
        }
示例#3
0
 private void CleanupKeystores()
 {
     AsymmetricEncryption.DeletePublicKeyFromKeystore(Keystore.Machine, MachineKeyContainerName);
     AsymmetricEncryption.DeletePublicKeyFromKeystore(Keystore.User, MachineKeyContainerName);
     AsymmetricEncryption.DeletePublicKeyFromKeystore(Keystore.Machine, UserKeyContainerName);
     AsymmetricEncryption.DeletePublicKeyFromKeystore(Keystore.User, UserKeyContainerName);
 }
示例#4
0
        public void Can_Give_Public_Key_As_XML_String()
        {
            string xml = AsymmetricEncryption.PublicKeyAsXml();

            Assert.NotNull(xml);
            Assert.That(xml, Is.Not.Empty);
        }
示例#5
0
        public IHttpActionResult Get(string domain)
        {
            if (string.IsNullOrEmpty(domain))
            {
                return(BadRequest());
            }

            LicenseData license = LicenseRepository.Instance.LicenseTable[domain] as LicenseData;

            if (license == null)
            {
                return(NotFound());
            }

            var clientData = DataRepository.Instance.ClienDataList.SingleOrDefault(data => data.Domain == domain);

            if (clientData == null)
            {
                return(NotFound());
            }

            var publicKey = clientData.RemoteKey;
//			var licenseData = Encoding.UTF8.GetString(ObjectSerializer.Serialize(license));

//			byte[] encryptedLicense = AsymmetricEncryption.Encrypt(ObjectSerializer.Serialize(license), 1024, clientData.Key.PublicKey);
            var encryptedLicense = AsymmetricEncryption.Encrypt(ObjectSerializer.Serialize(license), 4096, publicKey);

            string encryptedLicenseStr           = Convert.ToBase64String(encryptedLicense);
            Dictionary <string, string> dataDict = new Dictionary <string, string> {
                { "data", encryptedLicenseStr }
            };

            return(Ok(dataDict));
        }
        private async void EncryptMessageButton_Click(object sender, RoutedEventArgs e)
        {
            StatusImage.Visibility    = Visibility.Hidden;
            ErrorTextBlock.Visibility = Visibility.Hidden;

            if (UserInputRSADetails())
            {
                return;
            }

            // ask user for location to save encrypted message
            string encryptedFile = null;

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Title  = "Save as";
            saveFileDialog.Filter = "Encrypted message (*.crypto)|*.crypto";

            if (saveFileDialog.ShowDialog() == true)
            {
                encryptedFile = saveFileDialog.FileName;
            }

            // only open filestreams if files were selected by user
            if (encryptedFile != null)
            {
                // open streams
                MemoryStream inputStream  = new MemoryStream();
                byte[]       messageBytes = Encoding.UTF8.GetBytes(InputMessageBox.Text);
                inputStream.Write(messageBytes, 0, messageBytes.Length);

                // message requires a minimum length, pad it with 32 0x00 bytes
                if (inputStream.Length < 32)
                {
                    inputStream.Write(new byte[32], 0, 32);
                }

                inputStream.Position = inputStream.Seek(0, SeekOrigin.Begin);
                FileStream outputStream = null;

                try
                {
                    outputStream = File.OpenWrite(encryptedFile);

                    await HybridEncryption.EncryptFile(inputStream, outputStream, AsymmetricEncryption.PublicKeyFromXml(PublicRSAKeyReceiver.Text));

                    MessageBox.Show("Done");
                }
                catch (IOException exception)
                {
                    ErrorTextBlock.Visibility = Visibility.Visible;
                    ErrorTextBlock.Text       = exception.Message;
                }
                finally
                {
                    inputStream?.Close();
                    outputStream?.Close();
                }
            }
        }
示例#7
0
        private bool CheckKey()
        {
            using (var config = new PosBusiness.Config())
            {
                const int keySize = 1024;

                var keyDate   = config.KeyDate();
                var publicKey = config.PublicKey();
                var decrypted = AsymmetricEncryption.DecryptText(config.KeyDate(), keySize, config.PublicKey());

                var product = decrypted.Split('|')[0];
                var date    = decrypted.Split('|')[1];

                var d = int.Parse(date.Split('/')[0]);
                var m = int.Parse(date.Split('/')[1]);
                var a = int.Parse(date.Split('/')[2]);

                var dt = new DateTime(a, m, d);

                if (DateTime.Now > dt)
                {
                    this.Alert("La clave del producto caduco, obtenga una nueva clave de producto comunicándose con soporte técnico Scripts MX", eForm.TypeError.Error);
                    return(false);
                }

                return(true);
            }
        }
        public async Task SymmetricEncryptionEqualsTest()
        {
            string message = "aw3lrifos83fusoi3fjsofisjfo";

            byte[] messageBytes = Encoding.UTF8.GetBytes(message);

            var          asymmetricEncryption = new AsymmetricEncryption(_publicKey, _privateKey);
            string       path            = Path.GetTempFileName();
            MemoryStream encryptedStream = new MemoryStream();
            await asymmetricEncryption.EnvelopeAsync(messageBytes, 256, 128, encryptedStream, CancellationToken.None);

            byte[] encryptedBytes = encryptedStream.ToArray();

            int keyLen = BitConverter.ToInt32(encryptedBytes.Take(4).ToArray(), 0);

            byte[] key = encryptedBytes.Skip(4).Take(keyLen).ToArray();

            int ivLen = BitConverter.ToInt32(encryptedBytes.Skip(4 + key.Length).Take(4).ToArray(), 0);

            byte[] iv = encryptedBytes.Skip(4 + key.Length + 4).Take(ivLen).ToArray();

            key = asymmetricEncryption.DecryptToBytes(key);
            iv  = asymmetricEncryption.DecryptToBytes(iv);

            byte[] encryptedMessageBytes = encryptedBytes.Skip(4 + keyLen + 4 + ivLen).ToArray();

            SymmetricEncryption symmetricEncryption = new SymmetricEncryption(key, iv);
            string decryptedMessage = symmetricEncryption.DecryptToString(encryptedMessageBytes, Encoding.UTF8);

            Assert.Equal(message, decryptedMessage);
        }
示例#9
0
        public void SymmetricEncryptionEqualsTest()
        {
            string message = "aw3lrifos83fusoi3fjsofisjfo";

            byte[] messageBytes = Encoding.Unicode.GetBytes(message);

            var    asymmetricEncryption = new AsymmetricEncryption(_publicKey, _privateKey);
            string path       = Path.GetTempFileName();
            string outputPath = Path.GetTempFileName();

            asymmetricEncryption.EncryptSymmetrically(messageBytes, 256, 128, outputPath);

            byte[] encryptedBytes = File.ReadAllBytes(outputPath);

            int keyLen = BitConverter.ToInt32(encryptedBytes.Take(4).ToArray(), 0);

            byte[] key = encryptedBytes.Skip(4).Take(keyLen).ToArray();

            int ivLen = BitConverter.ToInt32(encryptedBytes.Skip(4 + key.Length).Take(4).ToArray(), 0);

            byte[] iv = encryptedBytes.Skip(4 + key.Length + 4).Take(ivLen).ToArray();

            key = asymmetricEncryption.DecryptToBytes(key);
            iv  = asymmetricEncryption.DecryptToBytes(iv);

            byte[] encryptedMessageBytes = encryptedBytes.Skip(4 + keyLen + 4 + ivLen).ToArray();

            SymmetricEncryption symmetricEncryption = new SymmetricEncryption(key, iv);
            string decryptedMessage = symmetricEncryption.DecryptToString(encryptedMessageBytes);

            Assert.AreEqual(message, decryptedMessage);
        }
示例#10
0
        private async void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            // make sure user can't press button multiple times
            LoginButton.IsEnabled = false;

            try
            {
                // load RSA key
                string containerName = RSAKeyTextBox.Text;
                await Task.Run(() => { AsymmetricEncryption.SelectKeyPair(containerName, 4096); });

                // log in and wait for at least 1.5s, whichever finishes last
                List <Task> tasks = new List <Task>();

                tasks.Add(Client.Login(EmailTextBox.Text, PasswordPasswordBox.Password));

                tasks.Add(Task.Delay(1_500));

                await Task.WhenAll(tasks);

                //move to chat window
                ChatWindow chat = new ChatWindow();
                chat.Show();
                this.Close();
            }
            catch (ClientException exception)
            {
                // show error message
                ErrorLabel.Visibility = Visibility.Visible;
                ErrorLabel.Content    = exception.Message;
            }

            // re-enable user input
            LoginButton.IsEnabled = true;
        }
示例#11
0
 private void btnDecrypt_Click(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(textBox2.Text))
     {
         textBox3.Text = AsymmetricEncryption.DecryptText(textBox2.Text, keySize, publicAndPrivateKey);
     }
 }
示例#12
0
        public static string RSAEncrypt(this string s)
        {
            const int keySize    = 2048;
            var       key        = AsymmetricEncryption.PemToXml(Settings.RSAKey);
            var       base64Card = Convert.ToBase64String(Encoding.UTF8.GetBytes(s));

            return(AsymmetricEncryption.EncryptText(base64Card, keySize, key));
        }
示例#13
0
        public void BytecodeApi_Cryptography_AsymmetricEncryption()
        {
            byte[] data = MathEx.RandomNumberGenerator.GetBytes(32);
            AsymmetricEncryption.GenerateKeyPair(out RSAParameters publicKey, out RSAParameters privateKey);

            Assert.IsTrue(AsymmetricEncryption.Decrypt(AsymmetricEncryption.Encrypt(data, Resources.RSAPublicKey), Resources.RSAPrivateKey).Compare(data));
            Assert.IsTrue(AsymmetricEncryption.Decrypt(AsymmetricEncryption.Encrypt(data, publicKey), privateKey).Compare(data));
        }
示例#14
0
        public void Can_Encrypt_Data()
        {
            byte[] rawData = Random.GetNumbers(128);

            byte[] encryptedData = AsymmetricEncryption.Encrypt(rawData, publicKey);

            Assert.NotNull(encryptedData);
            Assert.AreNotEqual(rawData, encryptedData);
        }
示例#15
0
        public void Can_Convert_XML_String_To_Public_Key()
        {
            string xml = AsymmetricEncryption.PublicKeyAsXml();

            RSAParameters rsaParameters = AsymmetricEncryption.PublicKeyFromXml(xml);

            Assert.NotNull(rsaParameters);
            CollectionAssert.AreEqual(publicKey.Exponent, rsaParameters.Exponent);
            CollectionAssert.AreEqual(publicKey.Modulus, rsaParameters.Modulus);
        }
示例#16
0
        public void SelectKeyPair_Should_Change_Public_Key()
        {
            RSAParameters beforeParams = AsymmetricEncryption.PublicKey;

            AsymmetricEncryption.SelectKeyPair("otherPair", 512);

            RSAParameters afterParams = AsymmetricEncryption.PublicKey;

            Assert.That(beforeParams, Is.Not.EqualTo(afterParams));
        }
示例#17
0
        public static LicenseData Read(string key)
        {
            var encryptedStr = File.ReadAllText(FilePath);

            byte[] encryptedData = Convert.FromBase64String(encryptedStr);

            var         licenseData = AsymmetricEncryption.Decrypt(encryptedData, 4096, key);
            LicenseData license     = ObjectSerializer.Deserialize(licenseData) as LicenseData;

            return(license);
        }
        public void EncryptedData_DecryptWithPublicKey_IsNotSuccessfullyDecrypted()
        {
            // Arrange
            var message = "my super secret message";
            var key     = AsymmetricEncryption.GenerateKey(32);

            var encryptedData = AsymmetricEncryption.Encrypt(message, key.PublicKey);

            // Act / Assert
            Assert.ThrowsAny <System.Security.Cryptography.CryptographicException>(() => { AsymmetricEncryption.DecryptValue(encryptedData.EncryptedData, key.PublicKey); });
        }
示例#19
0
文件: Program.cs 项目: wynhaat/Aptech
        public static void Main(string[] args)
        {
            string text          = "123456";
            RSA    rsa           = RSA.Create();
            string encryptedText = AsymmetricEncryption.Encrypt(text, rsa);
            string decryptedText = AsymmetricEncryption.Decrypt(encryptedText, rsa);

            Console.WriteLine("haha");
            CreateWebHostBuilder(args).Build().Run();
            //Test secure password
        }
        public void Encrypt()
        {
            var data = "P@ssw0rd";

            var keys      = AsymmetricEncryption.GenerateKeys();
            var encrypted = AsymmetricEncryption.Encrypt(data, keys.PublicKey);
            var decrypted = AsymmetricEncryption.Decrypt(encrypted, keys.KeysPair);

            Console.WriteLine(encrypted);
            Assert.AreEqual(data, decrypted);
        }
        /// <summary>
        /// Create a new RSA key
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateRSAKey_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(PrivateRSAContainerName.Text))
            {
                ErrorTextBlock.Visibility = Visibility.Visible;
                ErrorTextBlock.Text       = "Provide a valid container name";
                return;
            }

            AsymmetricEncryption.CreateNewKeyPair(PrivateRSAContainerName.Text.Trim(), 4096);
        }
示例#22
0
 /// <summary>
 /// Returns true if the given keystore contains the given key container.
 /// </summary>
 /// <param name="useMachineKeyStore">Specify which keystore to look in.</param>
 /// <param name="keyContainerName">Name of the key container to find.</param>
 /// <returns></returns>
 private bool KeystoreContainsKeyContainer(Keystore keystore, string keyContainerName)
 {
     if (fastKeystoreCheck)
     {
         return(AsymmetricEncryption.GetKeyFromKeystore(keystore, keyContainerName, false) != null);
     }
     else
     {
         List <string> containerNames = Helpers.IterateOverKeyContainers.GetKeyContainerNames(keystore == Keystore.Machine);
         return(containerNames.Contains(keyContainerName));
     }
 }
        public void EncryptedData_WithKey_IsSuccessfullyDecrypted()
        {
            // Arrange
            var message = "my super secret message";
            var keyPair = AsymmetricEncryption.GenerateKey(32);

            // Act
            var encryptedData = HybridEncryption.Encrypt(message, keyPair.PublicKey);
            var decryptedData = HybridEncryption.DecryptValue(encryptedData.EncryptedData, keyPair.PrivateKey, encryptedData.EncryptedKey, encryptedData.InitializationVector);

            // Assert
            Assert.Equal(message, decryptedData);
            Assert.NotEqual(encryptedData.EncryptedData, System.Text.Encoding.UTF8.GetBytes(message));
        }
示例#24
0
 private void GenerateKeyFile(object sender, RoutedEventArgs e)
 {
     if (AsymmetricEncryption.GenerateRegisterFile())
     {
         MessageBox.Show(
             "Create Register File Successfully! \nCopy and send the *.pem file to the Service Provider!",
             "Congratulation!");
     }
     else
     {
         MessageBox.Show("Please add your user name to the config file, remove entry of \"PublicKey\"",
                         "Failed, Check and Do Again");
     }
 }
示例#25
0
        public IHttpActionResult Token([FromBody] Aparte.Credentials.UserCredential user)
        {
            //Authentication codes here
            var context    = new ApiContext();
            var pw         = AsymmetricEncryption.Decrypt(user.Password, AuthenticationServer.PRIVATE_KEY);
            var systemUser = Aparte.WebApi.BeginApiSession.ValidatePassword(context, user.UserId, pw);

            if (systemUser == null)
            {
                return(null);//this.Unauthorized(null);
            }
            var encryptedToken = ProduceToken(systemUser.PK, KeyFile.JEDIX_WIN_CLIENT_NAME, context);

            return(Ok <string>(encryptedToken));
        }
示例#26
0
        public void Test()
        {
            Random rand             = new Random();
            AsymmetricEncryption ae = new AsymmetricEncryption();

            for (int i = 0; i < 100; i++)
            {
                byte[] data = new byte[10000];
                rand.NextBytes(data);
                string text       = data.ToBase64String();
                string ciphertext = ae.EncryptToString(text);
                string plaintext  = ae.DecryptToString(ciphertext);
                Assert.AreEqual(text, plaintext);
            }
        }
示例#27
0
        public void GenerateKeyPAir_Returns_Valid_Public_Key()
        {
            RSAParameters rsaParameters = AsymmetricEncryption.CreateNewKeyPair(TestContainerName, 4096);

            // public exponent
            Assert.NotNull(rsaParameters.Exponent);
            CollectionAssert.IsNotEmpty(rsaParameters.Exponent);

            // modulus
            Assert.NotNull(rsaParameters.Modulus);
            CollectionAssert.IsNotEmpty(rsaParameters.Modulus);

            // private exponent
            Assert.IsNull(rsaParameters.D);
        }
示例#28
0
        public JsonResult AsymmetricEncrypt(WebSecurity.Models.EncryptionModel encryption, string ButtonType)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            string publicKey  = string.Empty; // false to get the public key
            string privateKey = string.Empty; // true to get the private key

            if (!string.IsNullOrEmpty(encryption.PublicKey) && !string.IsNullOrEmpty(encryption.PrivateKey))
            {
                publicKey  = HttpUtility.HtmlDecode(encryption.PublicKey);
                privateKey = HttpUtility.HtmlDecode(encryption.PrivateKey);
            }
            else
            {
                publicKey  = rsa.ToXmlString(false); // false to get the public key
                privateKey = rsa.ToXmlString(true);  // true to get the private key
            }

            var result = new EncryptionModel();

            var asymEncryption = new AsymmetricEncryption();

            if (ButtonType == "Encrypt")
            {
                var encryptedText = asymEncryption.EncryptText(publicKey, encryption.PlainText);
                result = new EncryptionModel()
                {
                    EncryptedText = encryptedText,
                    PlainText     = encryption.PlainText,
                    PublicKey     = HttpUtility.HtmlEncode(publicKey),
                    PrivateKey    = HttpUtility.HtmlEncode(privateKey)
                };
            }
            else if (ButtonType == "Decrypt")
            {
                var plainText = asymEncryption.DecryptData(HttpUtility.HtmlDecode(encryption.PrivateKey), encryption.EncryptedText);

                result = new EncryptionModel()
                {
                    EncryptedText = encryption.EncryptedText,
                    PlainText     = plainText,
                    PublicKey     = HttpUtility.HtmlEncode(publicKey),
                    PrivateKey    = HttpUtility.HtmlEncode(privateKey)
                };
            }

            return(Json(result));
        }
        public void EncryptedData_WithModifiedHMAC_IsNotSuccessfullyDecrypted()
        {
            // Arrange
            var message = "my super secret message";
            var keyPair = AsymmetricEncryption.GenerateKey(32);

            var encryptedData = HybridEncryption.Encrypt(message, keyPair.PublicKey);

            encryptedData.Hmac[1] = byte.MaxValue;

            // Act
            var exception = Assert.ThrowsAny <System.Security.Cryptography.CryptographicException>(() => { HybridEncryption.DecryptValue(encryptedData.EncryptedData, keyPair.PrivateKey, encryptedData.EncryptedKey, encryptedData.InitializationVector, encryptedData.Hmac); });

            // Assert
            Assert.Contains("HMAC for decryption does not match encrypted packet", exception.Message);
        }
示例#30
0
        private static void ForTempSave(string userName)
        {
            const int keySize = 2048;
            string    publicAndPrivateKey;
            string    publicKey;
            var       root = new XElement("Root");

            root.SetAttributeValue(Constants._ID, Guid.NewGuid().ToString());
            AsymmetricEncryption.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);
            Console.WriteLine(@"public key:" + publicKey);
            Console.WriteLine(@"public & private key:" + publicAndPrivateKey);
            root.SetAttributeValue("PublicKey", publicKey);
            root.SetAttributeValue("PublicAndPrivateKey", publicAndPrivateKey);
            var productid = AsymmetricEncryption.GetProductId();

            root.SetAttributeValue("ProductId", productid);

            //string userName = "******";
            var text      = userName + productid;
            var encrypted = AsymmetricEncryption.EncryptText(text, keySize, publicKey);

            Console.WriteLine(@"Encrypted: {0}", encrypted);

            //send encrypted data to service
            File.WriteAllText(userName + ".pem",
                              @"UserName:
"******"
Public Key:" + publicKey + @"
Public and Private Key:
" +
                              publicAndPrivateKey + @"Secrect:
" + encrypted + @"
For Test:
" + productid);
            var decrypted = AsymmetricEncryption.DecryptText(encrypted, keySize, publicAndPrivateKey);

            //service person do below
            Console.WriteLine(@"Decrypted: {0}", decrypted);

            //            Configuration.Set("UserName", userName);
            //            Configuration.Set("PublicKey", publicKey);
            //            Configuration.SaveSettings();
            DBFactory.GetData().Save(root);
            Console.WriteLine(DBFactory.GetData().Read("a02cf4ad-ba0c-4c69-9f7c-e7d73a8fecad"));
        }