Beispiel #1
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 AsymmetricEncryption_Test_Pass()
        {
            using (var encryption = new AsymmetricEncryption())
            {
                (RSAParameters, RSAParameters)keys = new Helpers().GenerateRSAKeys();

                const string expected = "Text to encrypt";

                var encrypted = encryption.EncryptData(Encoding.UTF8.GetBytes(expected), keys.Item1);
                var decrypted = encryption.DecryptData(encrypted, keys.Item2);

                string actual            = Encoding.UTF8.GetString(decrypted);
                string encryptedAsString = Encoding.UTF8.GetString(encrypted);

                Assert.AreEqual(expected, actual);
                Assert.AreNotEqual(expected, encryptedAsString);
            }
        }