Reputation: 3242
I am beginner in nodejs. I have already implemented encryption and decryption through sha1 and using in asp.net projects. Now we started new project in node and angular. Here i need same login mechanism including encryption and decryption using sha1.
Here is my workable code:
Dependent variable must need for me
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;
Encryption method to encrypt password or any text.
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;
}
Decryption method to encrypt password or any text.
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;
}
Upvotes: 0
Views: 1550
Reputation: 561
SHA1 is hash function. It's no way to get original data from hash (except collisions).
Your problem is not a hash, it's encrypt/decrypt algorithm. Try to use js-crypto-pbkdf from NPM.
Upvotes: 1