【发布时间】:2020-02-16 02:09:36
【问题描述】:
我是 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;
}
【问题讨论】:
-
哈希函数不能加密/解密。您尝试的是使用PasswordDeriveBytes 中的哈希函数从密码中获取密钥。它使用 PBKDF1 的扩展。
-
您的目标和代码令人困惑。您正在使用 PasswordDeriveBytes 派生要在 RijndaelManaged 中使用的密钥。它是一种对称算法,是 AES 竞赛的获胜者。请注意 AES !=Rijndael。你使用的是一个非常古老的图书馆。为了存储密码,我们没有加密它们,我们用盐对它们进行哈希处理。使用 PBKF2、Bcrypt、Scrypt 等密码哈希标准越好,新的赢家 Argon2 越好。
标签: c# node.js encryption sha1