gpt4 book ai didi

c# - 将自定义命名空间导入 ASPX

转载 作者:行者123 更新时间:2023-12-04 17:05:54 26 4
gpt4 key购买 nike

我有一个位于命名空间内的类,它本身位于 .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() %>

关于c# - 将自定义命名空间导入 ASPX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60980722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com