asp.net-core - .Net Core:仅加密为 az 字符
问题描述
我正在使用以下加密类
public static class Extensions
{
static string key = "jdsg432387#";
static byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
public static string Encrypt(this string plainText)
{
byte[] EncryptKey = { };
EncryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByte = Encoding.UTF8.GetBytes(plainText);
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(EncryptKey, IV), CryptoStreamMode.Write);
cStream.Write(inputByte, 0, inputByte.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
public static string Decrypt(this string encryptedText)
{
byte[] DecryptKey = { };
byte[] inputByte = new byte[encryptedText.Length];
DecryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByte = Convert.FromBase64String(encryptedText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(DecryptKey, IV), CryptoStreamMode.Write);
cs.Write(inputByte, 0, inputByte.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
}
但是它会在加密结果字符串中生成特殊字符(例如 +、=)
我如何将加密结果字符串限制为仅 az 字符?
解决方案
您可以将字符串转换为十六进制
public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
Byte[] stringBytes = encoding.GetBytes(input);
StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
foreach (byte b in stringBytes)
{
sbBytes.AppendFormat("{0:X2}", b);
}
return sbBytes.ToString();
}
并将十六进制解密为字符串
public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
int numberChars = hexInput.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
}
return encoding.GetString(bytes);
}
推荐阅读
- java - 在 JSP 中进行表单验证和提交后,选定的标签消失
- javascript - 如何在Javascript中将具有相同属性值的对象值推送到同一个子数组?
- reactjs - 操作必须是普通对象,使用自定义中间件进行异步操作
- python - 使用 python 多线程池 API 解析多个链接
- pdo - Drupal 8 连接获得 PDO 权限被拒绝
- laravel - 将 Laravel Vue 组件编译成不同的 js 文件
- gradle - 通过 gradle 命令行运行单个 Runner 类 - karate
- java - 使用 Runtime.getRuntime().exec 提交时找不到 spark-submit 命令
- c# - .NET Core 在另一个单例服务中注入单例服务
- php - 如何将用户通过 GET 输入发送的文本保存在 php 中的单独文本文件中?