[英]Import custom namespace into ASPX
我有一個位於命名空間內的類,它本身位於 .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;
}
%>
編輯:我的解決方案是將我的命名空間和類編譯為動態鏈接庫文件 (.dll) 並將其導入到構建文件夾中。 從那里,我可以使用<%@ Import namespace="PasswordEncryption" %>
行。
假設您有這樣的 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() %>
最終用一個 DLL 來做到這一點。 我已經在 C# 中創建了這些函數,編譯成一個 DLL,然后導入它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.