Импорт пользовательского пространства имен в ASPX - PullRequest
0 голосов
/ 02 апреля 2020

У меня есть класс шифрования, который находится внутри пространства имен, которое само находится внутри файла .cs (C#)

Я хочу импортировать этот файл (класс) на мою веб-страницу ASPX. Как я могу это сделать?

Класс, который я хочу импортировать:

namespace PasswordEncryption
{
    public static class StringCipher

Хотите импортировать это на мою страницу ASPX. Оба файла (файл класса C# и файл ASPX) находятся в одной папке.

РЕДАКТИРОВАТЬ: Добавлен код.

<%@ Page Language="C#"%>
<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.Data.OleDb" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.Collections.Generic" %>
<%@ Import namespace="System.IO" %>
<%@ Import namespace="System.Linq" %>
<%@ Import namespace="System.Security.Cryptography" %>
<%@ Import namespace="System.Text" %>

<%
        string connectionStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + AppDomain.CurrentDomain.BaseDirectory + @"\Login\database.mdb;User Id=admin;Password=;";
        OleDbConnection connection = new OleDbConnection(connectionStr);
        if (!(Request.Form.AllKeys.Contains("username") && Request.Form.AllKeys.Contains("firstName") && Request.Form.AllKeys.Contains("lastName")
            && Request.Form.AllKeys.Contains("email") && Request.Form.AllKeys.Contains("password"))) {
            Response.Write("Form has been tampered with.");
        } else {
            string firstName = Request.Form["firstName"];
            string lastName = Request.Form["lastName"];
            string username = Request.Form["username"];
            string email = Request.Form["email"];
            string password = Request.Form["password"];
            Regex nameRegex = new Regex(@"^[A-Za-z]+$");
            Regex usernameRegex = new Regex(@"^[A-Za-z0-9_.]+$");
            Regex emailRegex = new Regex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$");
            Regex passwordRegex = new Regex(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&*()_+\-\\/\[\].])[A-Za-z\d!@#$%^&*()_+\-\\/\[\].]{8,36}$");
            if (firstName.Length == 0 || firstName.Length > 14 || lastName.Length == 0 || lastName.Length > 14
                || username.Length == 0 || username.Length > 16 || email.Length == 0 || email.Length > 45 ||
                password.Length == 0 || password.Length > 36) {
                Response.Write("Form has been tampered with.");
            } else if (!(nameRegex.IsMatch(firstName) || nameRegex.IsMatch(lastName) || usernameRegex.IsMatch(username) || emailRegex.IsMatch(email) || passwordRegex.IsMatch(password))) {
                Response.Write("Form has been tampered with.");
            } else {
                string queryUsername = "SELECT COUNT(*) FROM Users WHERE Username = \"" + username + "\";";
                string queryEmail = "SELECT COUNT(*) FROM Users WHERE Email = \"" + email + "\";";
                password = StringCipher.Encrypt(password, password);
                string querySuccess = "INSERT INTO Users VALUES(\"" + username + "\", \"" + password + "\", \"" + email + "\", \"" + firstName + "\", \"" + lastName + "\");";
                OleDbCommand commandUsername = new OleDbCommand(queryUsername, connection);
                OleDbCommand commandEmail = new OleDbCommand(queryEmail, connection);
                OleDbCommand commandCreateUser = new OleDbCommand(querySuccess, connection);
                connection.Open();
                int userExist = (int)commandUsername.ExecuteScalar();
                int emailExist = (int)commandEmail.ExecuteScalar();
                if (userExist > 0) {
                    Response.Write("This username is taken.");
                } else if (emailExist > 0) {
                    Response.Write("This address is already in use.");
                } else {
                    commandCreateUser.ExecuteNonQuery();
                    Response.Write("Success!");
                }
            }
        }}
%>

<% // THE CODE BELOW IS THE CODE I WANT TO ADD USING AN EXTERNAL METHOD (EXTERNAL FILE)
    public static class StringCipher
    {
        // This constant is used to determine the keysize of the encryption algorithm in bits.
        // We divide this by 8 within the code below to get the equivalent number of bytes.
        private const int Keysize = 128;

        // This constant determines the number of iterations for the password bytes generation function.
        private const int DerivationIterations = 1000;

        public static string Encrypt(string plainText, string passPhrase)
        {
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
            // so that the same Salt and IV values can be used when decrypting.  
            var saltStringBytes = Generate128BitsOfRandomEntropy();
            var ivStringBytes = Generate128BitsOfRandomEntropy();
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 128;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Convert.ToBase64String(cipherTextBytes);
                            }
                        }
                    }
                }
            }
        }

        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [16 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 16 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 16 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 128;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                            }
                        }
                    }
                }
            }
        }

        private static byte[] Generate128BitsOfRandomEntropy()
        {
            var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.
            using (var rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with cryptographically secure random bytes.
                rngCsp.GetBytes(randomBytes);
            }
            return randomBytes;
        }

%>

1 Ответ

0 голосов
/ 02 апреля 2020

Допустим, у вас есть c# метод Test() примерно так: (Внимание: класс должен быть public, а функция должна быть public static)

namespace PasswordEncryption
{
    public static class StringCipher
    {
        public static string Test()
        {
            return "Example string";
        }
    }
}

А также необходимо добавить это пространство имен в файл aspx:

<%@ Import Namespace="PasswordEncryption" %>

Затем вы можете вызвать эту функцию в aspx, как:

<%= StringCipher.Test() %>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...