I have a C# encryption which is looking like that:
public static string EncryptAes(string value, string password, string iv)
{
var result = Encrypt<AesManaged>(value, password, iv);
return result;
}
static string Encrypt<T>(string value, string password, string salt)
where T : SymmetricAlgorithm, new()
{
DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
SymmetricAlgorithm algorithm = new T();
byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);
ICryptoTransform transform = algorithm.CreateEncryptor(rgbKey, rgbIV);
using (MemoryStream buffer = new MemoryStream())
{
using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(value);
}
}
return Convert.ToBase64String(buffer.ToArray());
}
}
The call to this function returns a string. Now I want to produce the same string in nodejs. I'm trying with npm crypto in the following manner:
function encrypt(text, password, iv) {
let cipher = crypto.createCipheriv('aes-256-cbc', password, iv);
var crypted = cipher.update(text,'utf8','base64')
crypted += cipher.final('base64');
return crypted;
}
The problem is that I can't produce the same strings.
The sole purpose of this is that I need to decrypt the c# encrypted data as shown above in nodejs. I can't change the encryption, but I can require any npm in node.
Related
In C# language, my purpose is to hash password with hash_password(), then verify it with verify() methods. I hash and salt for password 's3cr3t', then check for two examples and return true if password is 's3cr3t' and return false for password 's3cr4t'.
using System;
using System.Text;
using System.Security.Cryptography;
public class Pbkdf2_test4
{
public const int salt_size = 24;
public const int hash_size = 24;
public const int iteration = 100000;
static byte[] salt1 = new byte[salt_size];
private static Rfc2898DeriveBytes hash_password(string password)
{
RandomNumberGenerator generator = RandomNumberGenerator.Create();
byte[] salt = new byte[salt_size];
generator.GetBytes(salt);
salt1 = salt;
Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt1, iteration);
return pbkdf2;
}
private static bool verify(Rfc2898DeriveBytes pw_hash, string password)
{
//data1 can be a string or contents of a file.
string data1 = "Some test data";
try
{
Rfc2898DeriveBytes k1 = pw_hash;
Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(password, salt1, iteration);
// Encrypt the data.
Aes encAlg = Aes.Create();
encAlg.Key = k1.GetBytes(16);
MemoryStream encryptionStream = new MemoryStream();
CryptoStream encrypt = new CryptoStream(encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write);
byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(data1);
encrypt.Write(utfD1, 0, utfD1.Length);
encrypt.FlushFinalBlock();
encrypt.Close();
byte[] edata1 = encryptionStream.ToArray();
k1.Reset();
// Try to decrypt, thus showing it can be round-tripped.
Aes decAlg = Aes.Create();
decAlg.Key = k2.GetBytes(16);
decAlg.IV = encAlg.IV;
MemoryStream decryptionStreamBacking = new MemoryStream();
CryptoStream decrypt = new CryptoStream(decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
decrypt.Write(edata1, 0, edata1.Length);
decrypt.Flush();
decrypt.Close();
k2.Reset();
string data2 = new UTF8Encoding(false).GetString(decryptionStreamBacking.ToArray());
if (!data1.Equals(data2))
{
return false;
}
else
{
return true;
}
}
catch (Exception e)
{
return false;
}
}
public static void Run()
{
Rfc2898DeriveBytes pw_hash = hash_password("s3cr3t");
Console.WriteLine(System.Text.Encoding.UTF8.GetString(pw_hash.GetBytes(hash_size)));
var result1 = verify(pw_hash, "s3cr3t");
Console.WriteLine(result1);
var result2 = verify(pw_hash, "s3cr4t");
Console.WriteLine(result2);
}
}
My question, somehow there is a problem that for verify(pw_hash, "s3cr3t") that returns false however it should return true. In verify(), there is a problem but still could not understand because I give keys k1 and k2 true, but still does not receive hash/salt same, how can I fix this problem?
Apart from this, shuld I add anything to make password storage safest?
Here is program to encrypt and decrypt pass
internal class Program
{
static void Main(string[] args)
{
Pbkdf2_test4 test4 = new Pbkdf2_test4();
test4.Run();
Console.ReadLine();
}
}
public class Pbkdf2_test4
{
static string key = string.Empty;
static string iv = string.Empty;
public Pbkdf2_test4()
{
Aes encAlg = Aes.Create();
encAlg.GenerateKey();
key = Convert.ToBase64String(encAlg.Key);
encAlg.GenerateIV();
iv = Convert.ToBase64String(encAlg.IV);
}
public string Encrypt(string plainText, string Key, string IV)
{
// Check arguments.
if (string.IsNullOrWhiteSpace(plainText))
throw new ArgumentNullException(nameof(plainText));
if (string.IsNullOrWhiteSpace(Key))
throw new ArgumentNullException(nameof(Key));
if (string.IsNullOrWhiteSpace(IV))
throw new ArgumentNullException(nameof(IV));
byte[] encrypted;
// Create an AesCryptoServiceProvider object
// with the specified key and IV.
using (Aes aes = Aes.Create())
{
aes.Key = Convert.FromBase64String(Key);
aes.IV = Convert.FromBase64String(IV);
// Create an encrypt-or to perform the stream transform.
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
encrypted = msEncrypt.ToArray();
}
}
// Return the encrypted bytes from the memory stream.
return Convert.ToBase64String(encrypted);
}
public string Decrypt(string cipherText, string Key, string IV)
{
// Check arguments.
if (string.IsNullOrWhiteSpace(cipherText))
throw new ArgumentNullException(nameof(cipherText));
if (string.IsNullOrWhiteSpace(Key))
throw new ArgumentNullException(nameof(Key));
if (string.IsNullOrWhiteSpace(IV))
throw new ArgumentNullException(nameof(IV));
// Declare the string used to hold
// the decrypted text.
string plaintext = string.Empty;
// Create an AesCryptoServiceProvider object
// with the specified key and IV.
using (Aes aes = Aes.Create())
{
aes.Key = Convert.FromBase64String(Key);
aes.IV = Convert.FromBase64String(IV);
// Create a decrypt-or to perform the stream transform.
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
public void Run()
{
Console.WriteLine("Key is : " + key);
Console.WriteLine("IV is : " + iv);
string passord = "s3cr3t";
string encryptedPassowrd = Encrypt(passord, key, iv);
string decryptedPassowrd = Decrypt(encryptedPassowrd, key, iv);
Console.WriteLine($"Password = {passord} and Encrypted password = {encryptedPassowrd}");
Console.WriteLine($"Password = {passord} and Decrypted password = {decryptedPassowrd}");
string passord1 = "s3cr4t";
string encryptedPassowrd1 = Encrypt(passord1, key, iv);
string decryptedPassowrd1 = Decrypt(encryptedPassowrd1, key, iv);
Console.WriteLine($"Password = {passord1} and Encrypted password = {encryptedPassowrd1}");
Console.WriteLine($"Password = {passord1} and Decrypted password = {decryptedPassowrd1}");
}
}
I think you misunderstood the example in the documentation of Rfc2898DeriveBytes. This function can be used for password hashing (PBKDF2), but then you don't need the encryption parts. The original use case of a key derivation function like PBKDF2 was to take a (weak) user password and turn it into a (strong) key which can then be used to encrypt data (thus the name key-derivation). Later one saw that the same functions are suitable to generate password hashes.
In your case I would recommend to use an appropriate library for password hashing, like BCrypt.Net. The usage would look like:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
string hashToStoreInDb = BCrypt.HashPassword(password);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from existingHashFromDb.
bool isPasswordCorrect = BCrypt.Verify(password, existingHashFromDb);
I'm trying to decrypt AES-128 CBC strings in C# but with no success (tried every decrypt method I found on internet for this type of encryption).
The only way I got a result was decrypting those strings in PHP using this code:
<?php
$crypto_data = hex2bin($crypto_data_hex);
$real_data = openssl_decrypt($crypto_data,
'AES-128-CBC',
'23d854ce7364b4f7',
OPENSSL_RAW_DATA,
'23d854ce7364b4f7');
?>
So, is there a way to run this PHP code in .NET (using a PHP.dll library or something similar) ? Or is there a real equivalent method for this operation in .NET C# ?
Thank you
The question seems to boil down to writing C# function that is equivalent to PHP function.
Try this code:
public class Program
{
public static byte[] HexToBytes(string hex)
{
int numberChars = hex.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
{
string plaintext;
AesManaged aes = new AesManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
BlockSize = 128,
Key = key,
IV = iv
};
using (aes)
{
ICryptoTransform decryptor = aes.CreateDecryptor();
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
plaintext = reader.ReadToEnd();
}
}
}
}
return plaintext;
}
public static void Main()
{
string crypto_data_hex = "00965fa56e761b11d37b887f98e6bcc2"; // paste $crypto_data_hex value here
string sKey = "23d854ce7364b4f7";
string sIv = "23d854ce7364b4f7";
byte[] encrypted = HexToBytes(crypto_data_hex);
byte[] key = Encoding.ASCII.GetBytes(sKey);
byte[] iv = Encoding.ASCII.GetBytes(sIv);
string decrypted = Decrypt(encrypted, key, iv);
Console.WriteLine(decrypted);
}
}
I want encryption in my wcf service. For that I am writing a class to encrypt and decrypt strings. The encryption seems to work fine and produces a encrypted string but while doing decryption it was giving error of double escape not allowed or error 401. I have add in webconfig the following
<security>
<requestFiltering allowDoubleEscaping="true" />
</security>
Now it is giving error of either the length of the string is not correct or for shorter strings Bad String. The code is
To Encrypt
static string hash = "mypass#mysitec0m";
public static string Encrypt(string decrypted)
{
byte[] data = UTF8Encoding.UTF8.GetBytes(decrypted);
using (MD5CryptoServiceProvider mds = new MD5CryptoServiceProvider())
{
byte[] keys = mds.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider())
{
ICryptoTransform transform = tripDes.CreateEncryptor();
byte[] result = transform.TransformFinalBlock(data, 0, data.Length);
return Convert.ToBase64String(result);
}
}
}
and to decrypt
public static string decrypt(string encrypted)
{
byte[] data = Convert.FromBase64String(encrypted);
using (MD5CryptoServiceProvider mds = new MD5CryptoServiceProvider())
{
byte[] keys = mds.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider())
{
ICryptoTransform transform = tripDes.CreateDecryptor();
byte[] result = transform.TransformFinalBlock(data, 0, data.Length);
return UTF8Encoding.UTF8.GetString(result);
}
}
}
Why is the error there and how can I fix it.
You never initialized the cipher with your key, thus you are using one random key for the encryptor and a different random key with your decryptor.
Use the CreateEncryptor(Byte[], Byte[]) method instead, and similarly for the decryptor.
CreateEncryptor(Byte[], Byte[])...
creates a symmetric encryptor object with the specified Key property
and initialization vector (IV).
This has nothing to do with WCF, more like a question about TripleDESCryptoServiceProvider.There is an error in your encryption and decryption code. If IV is not set, the encryption mode should use ECB. The default is CBC.CBC needs to set IV.
This is my modified code:
To Encrypt
public static string Encrypt(string decrypted)
{
byte[] data = UTF8Encoding.UTF8.GetBytes(decrypted);
using (MD5CryptoServiceProvider mds = new MD5CryptoServiceProvider())
{
byte[] keys = mds.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider() {
Key=keys,
Mode=CipherMode.ECB
})
{
ICryptoTransform transform = tripDes.CreateEncryptor();
byte[] result = transform.TransformFinalBlock(data, 0, data.Length);
return Convert.ToBase64String(result);
}
}
}
To decrypt
public static string decrypt(string encrypted)
{
byte[] data = Convert.FromBase64String(encrypted);
using (MD5CryptoServiceProvider mds = new MD5CryptoServiceProvider())
{
byte[] keys = mds.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider()
{
Key = keys,
Mode = CipherMode.ECB
})
{
ICryptoTransform transform = tripDes.CreateDecryptor();
byte[] result = transform.TransformFinalBlock(data, 0, data.Length);
return UTF8Encoding.UTF8.GetString(result);
}
}
}
I would suggest you use POST in place of GET. Because encrypted string might be long and will have many special characters as you have mentioned in the question
Below is the sample.
[OperationContract(Name = "Decrypt")]
[WebInvoke(Method = "POST",
UriTemplate = "Decrypt")]
string Decrypt(string data);
I'm creating a TCP based chat client. I'm trying to Encrypt some of the data with AES (more security) I have a AES encryption class and it uses UTF-8 by default as the out going and incoming Encoding type. But for some reason when i pass the information over the TCPClient (using UTF-8) and get it the other side it is throwing an error:
`System.Security.Cryptography.CryptographicException: Length of the data to decrypt is invalid.
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()`
So I recreated the problem without using the TCP client, just taking the AES encrypted data and putting it through a UTF-8 Encoding system that gets the string of the byte array then re-gets the byte array all using UTF-8 (basically the same thing as what happens over the network (without the string))
This method works:
string dataToEncrypt = "Hello World";
byte[] key = Encryption.AesEncryption.GenerateKey(32);
byte[] iv = Encryption.AesEncryption.GenerateKey(16);
byte[] encrypted = Encryption.AesEncryption.EncryptString(dataToEncrypt, key, iv);
string decrypted = Encryption.AesEncryption.DecryptedBytes(encrypted, key, iv);
The method doesn't work (throws the error from above)
Encoding encoding = Encoding.UTF8;
string dataToEncrypt = "Hello World";
byte[] key = Encryption.AesEncryption.GenerateKey(32);
byte[] iv = Encryption.AesEncryption.GenerateKey(16);
byte[] encrypted = Encryption.AesEncryption.EncryptString(dataToEncrypt, key, iv);
string encstring = encoding.GetString(encrypted);
byte[] utf8encrypted = encoding.GetBytes(encstring);
string decrypted = Encryption.AesEncryption.DecryptedBytes(utf8encrypted, key, iv);
What am i doing wrong?
This is my Encryption Class:
public sealed class AesEncryption
{
private byte[] Key;
public Encoding Encoder = Encoding.UTF8;
public AesEncryption(byte[] key)
{
Key = key;
}
public byte[] Encrypt(string text, byte[] iv)
{
var bytes = Encoder.GetBytes(text);
var rm = new RijndaelManaged();
var encrypter = rm.CreateEncryptor(Key, iv);
var ms = new MemoryStream();
var cs = new CryptoStream(ms, encrypter, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
var output = ms.ToArray();
cs.Close();
ms.Close();
return output;
}
public string Decrypt(byte[] encrypted, byte[] iv)
{
var ms = new MemoryStream();
var cs = new CryptoStream(ms,
new RijndaelManaged().CreateDecryptor(Key, iv),
CryptoStreamMode.Write);
cs.Write(encrypted, 0, encrypted.Length);
cs.FlushFinalBlock();
var output = ms.ToArray();
cs.Close();
ms.Close();
return Encoder.GetString(output);
}
public static byte[] EncryptString(string text, byte[] key, byte[] iv)
{
var ec = new AesEncryption(key);
return ec.Encrypt(text, iv);
}
public static string DecryptedBytes(byte[] encrypted, byte[] key, byte[] iv)
{
var ec = new AesEncryption(key);
return ec.Decrypt(encrypted, iv);
}
public static byte[] GenerateKey(int length)
{
Random rnd = new Random();
var chars = "1!2#3#4$5%6^7&8*9(0)-_=+qQwWeErRtTyYuUiIoOpP[{]}\\|aAsSdDfFgGhHjJkKlL;:'\"zZxXcCvVbBnNmM,<.>/?".ToCharArray();
string randomizedKey = "";
for (int i = 0; i < length; i++)
{
randomizedKey += chars[rnd.Next(0, chars.Length)];
}
return randomizedKey.ToByteArray();
}
}
UTF-8 does not perfectly represent the bytes. The short and simple answer is: Transmit bytes, not a UTF-8 string. If you must have a string, encode it in Base64.
I need to encrypt a string which I am sending in a URL and later I need to decrypt it ...
Which approach would be better for this? I tried the following:
string s = "String to be encrypted";
string encrypted = CipherUtility.Encrypt<RijndaelManaged>(s, "pass", "salt");
string decrypted = CipherUtility.Decrypt<RijndaelManaged>(encrypted, "pass", "salt");
But the encrypted string gets an "=" at the end ... I would like to avoid that.
And I am not sure that this would be the best option ...
The CipherUtility is the following:
public class CipherUtility
{
public static string Encrypt<T>(string value, string password, string salt)
where T : SymmetricAlgorithm, new()
{
DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
SymmetricAlgorithm algorithm = new T();
byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);
ICryptoTransform transform = algorithm.CreateEncryptor(rgbKey, rgbIV);
using (MemoryStream buffer = new MemoryStream())
{
using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(value);
}
}
return Convert.ToBase64String(buffer.ToArray());
}
}
public static string Decrypt<T>(string text, string password, string salt)
where T : SymmetricAlgorithm, new()
{
DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
SymmetricAlgorithm algorithm = new T();
byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3);
byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3);
ICryptoTransform transform = algorithm.CreateDecryptor(rgbKey, rgbIV);
using (MemoryStream buffer = new MemoryStream(Convert.FromBase64String(text)))
{
using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(stream, Encoding.Unicode))
{
return reader.ReadToEnd();
}
}
}
}
}
Thank You,
Miguel
On a newsletter I received I see something like /unsubscribe?u=16b832d9ad4b28edf261f56df. I was looking for something like this with the email somehow "hidden"
This is not "hidden." All this is a reference to a repository (e.g. a database) that contains all the information necessary to unsubscribe. Essentially a key into a record that contains all the necessary info about a subscriber.
If feasible, that'll probably be easier approach than to encrypt individual values in a URL.
If you still want to encrypt the value (to avoid storage in DB and redesign), what's the issue with having = at the end of a URL? It's just a character as part of encrypted output?