c# - 如何在.net C#中实现的nodejs中转换SHA1哈希函数
问题描述
我是nodejs的初学者。我已经通过sha1实现了加解密,并在asp.net项目中使用。现在我们在节点和角度开始了新项目。这里我需要相同的登录机制,包括使用 sha1 的加密和解密。
这是我的可行代码:
我必须需要因变量
static string passPhrase = "Paaaa5p***";
static string saltValue = "s@1t***lue";
static string hashAlgorithm = "SHA1";
static int passwordIterations = 2;
static string initVector = "@1B2c3D4e5F6****";
static int keySize = 256;
加密密码或任何文本的加密方法。
public static string EncryptText(string text)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(text);
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor,
CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string decryptText = Convert.ToBase64String(cipherTextBytes);
return decryptText;
}
加密密码或任何文本的解密方法。
public static string DecryptText(string encryptText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] cipherTextBytes = Convert.FromBase64String(encryptText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
decryptor,
CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes,
0,
plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
string text = Encoding.UTF8.GetString(plainTextBytes,
0,
decryptedByteCount);
return text;
}
解决方案
SHA1 是哈希函数。无法从哈希中获取原始数据(冲突除外)。
您的问题不是哈希,而是加密/解密算法。尝试使用NPM 中的 js-crypto-pbkdf。
推荐阅读
- c# - 如何通过单击按钮(asp.net)下载文件?
- javascript - 相关性和系数
- java - 如何在java中将JSON转换为属性文件?
- python - 'function' 和 'int' 不支持的操作数,lambdas 正在杀死我
- android - 片段重新创建时芯片组侦听器更改芯片位置
- java - 使用 Jlabel 和 JTextField 数组以某种格式显示
- javascript - 从同步的 Gmail 邮件线程中检测引用内容的最佳方法是什么?
- ios - 如何对 App Store 提交的 Carthage 框架进行代码签名?
- dart - Flutter 在获取数据时抛出错误。我该如何解决?
- javascript - 为什么在我打开检查工具之前我的图像不会加载到 carousal 中?