Trying to convert C# Rijndael decryption code to Node.js but getting the error bad decrypt
C# code for Decryption:
RijndaelManaged RMCrypto = new RijndaelManaged();
byte[] data = Convert.FromBase64String(strCript.Replace(" ", "+"));
byte[] initVectorBytes;
initVectorBytes = Encoding.ASCII.GetBytes("#1***********H8");
byte[] saltValueBytes;
saltValueBytes = Encoding.ASCII.GetBytes("i**************ng");
PasswordDeriveBytes password;
password = new PasswordDeriveBytes("KEY**************KEY", saltValueBytes, "SHA1", 1);
byte[] keyBytes;
keyBytes = password.GetBytes(256 / 8);
byte[] Key = keyBytes;
byte[] IV = initVectorBytes;
MemoryStream msDncrypt = new MemoryStream(data);
CryptoStream CryptStream = new CryptoStream(msDncrypt, RMCrypto.CreateDecryptor(Key, IV), CryptoStreamMode.Read);
byte[] fromEncrypt = new byte[data.Length];
int len = CryptStream.Read(fromEncrypt, 0, fromEncrypt.Length);
byte[] decrypted = new byte[len];
Array.Copy(fromEncrypt, decrypted, len);
return Encoding.UTF8.GetString(decrypted); //(decrypted,0,decrypted.Length);
Node.js code for Decryption:
const crypto = require("crypto");
let passkey= "KEY*********KEY";
let salt = "i****************ng"
let d = "u***************=";
d = Buffer.from(d,"base64");
salt = Buffer.from(salt);
const derivedKey = crypto.pbkdf2Sync(passkey,salt, 1000, 32, "sha1");
let iv = Buffer.from("#1B2c3D4e5F6g7H8");
const decipher = crypto.createDecipheriv("aes-256-cbc", derivedKey, iv);
let buf = Buffer.concat([decipher.update(d), decipher.final()]);
let decrypted = buf.toString("utf8");
console.log(decrypted);
Related
I have encryption and decryption methods but the encryption method's output is wrong. The key is "u1S1t12vTeZtlRHd" and the output must be "kJtXKmIiP9f73IZJim16LA==" ( Please check decryiption method) but the encryption method is giving me this output "VmmB3k7hVoKF9/cAQedaYQ==". How can i fix it?
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] bytes = utf8Encoding.GetBytes("u1S1t12vTeZtlRHd");
RijndaelManaged rijndaelManaged = new RijndaelManaged
{
Key = bytes,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
byte[] bytes2 = utf8Encoding.GetBytes("FAILED");
rijndaelManaged.CreateEncryptor();
byte[] inArray;
try
{
inArray = rijndaelManaged.CreateEncryptor().TransformFinalBlock(bytes2, 0, bytes2.Length);
}
finally
{
rijndaelManaged.Clear();
}
Console.WriteLine(Convert.ToBase64String(inArray));
byte[] array = Convert.FromBase64String("kJtXKmIiP9f73IZJim16LA==");
byte[] bytes = Encoding.ASCII.GetBytes("u1S1t12vTeZtlRHd");
ICryptoTransform transform = new RijndaelManaged
{
Mode = CipherMode.ECB,
Padding = PaddingMode.None
}.CreateDecryptor(bytes, null);
MemoryStream memoryStream = new MemoryStream(array);
CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read);
byte[] array2 = new byte[checked(array.Length - 1 + 1)];
int count = cryptoStream.Read(array2, 0, array2.Length);
memoryStream.Close();
cryptoStream.Close();
Console.WriteLine(Encoding.UTF8.GetString(array2, 0, count));
I did some encryption using PHP in my Database and would normally decrypt using:
$encrypt_method = "AES-256-CBC";
$secret_key = "testing";
$secret_iv = "testingyes!!!";
$key = hash('sha256', $secret_key); // hash the key
$iv = substr(hash('sha256', $secret_iv), 0, 16); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
echo(openssl_decrypt(base64_decode($data), $encrypt_method, $key, 0, $iv)); // the decrypted data
I'm trying to do the same task but with C# 2013 to decrypt the same data, any ideas?
I would encrypt in php using:
$encrypt_method = "AES-256-CBC";
$secret_key = "testing";
$secret_iv = "testingyes!!!";
$key = hash('sha256', $secret_key); // hash the key
$iv = substr(hash('sha256', $secret_iv), 0, 16); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
echo(base64_encode(openssl_encrypt($data, $encrypt_method, $key, 0, $iv))); // the encrypted data
encrypting: this is a test
gives: d0EzQ2MvMHkxRks2cXg5NkFkK2twZz09=
I tried this in C#:
public static String sha256_hash(String value)
{
StringBuilder Sb = new StringBuilder();
using (SHA256 hash = SHA256Managed.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value));
foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
private static String AES_decrypt(String Input)
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 256;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
aes.Key = Convert.FromBase64String(sha256_hash("testing"));
aes.IV = Convert.FromBase64String(sha256_hash("testingyes!!!").Substring(0, 16));
var decrypt = aes.CreateDecryptor();
byte[] xBuff = null;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
{
byte[] xXml = Convert.FromBase64String(Input);
cs.Write(xXml, 0, xXml.Length);
}
xBuff = ms.ToArray();
}
String Output = Encoding.UTF8.GetString(xBuff);
return Output;
}
string cipherData = "d0EzQ2MvMHkxRks2cXg5NkFkK2twZz09=";
string f = AES_decrypt(cipherData);
Console.Write(f);
But I'm getting error: specified key is not a valid size for this algorithm
However the key I'm using is working when I use PHP
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 256;
Block size should be 128 to be compatible with AES-256-CBC.
Rijndael supports variable block sizes - AES does not.
I have c sharp code snippet for encryption which uses .Key file for key and my requirement is to decrypt the encrypted text using same key in android, having problem
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) {
byte[] encryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
If you want to decrypt some data with AES you can use this method:
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
for complete code look at : android encryption/decryption with AES
I have been looking everywhere for some sample code on how to encrypt a simple string with the encryption in the title using the Bouncy Castle Framework.
This code will run on a Windows Universal project.
My previous attempts to encrypt using the build in API's failed to decrypt on the server.
I tried this: which gives me a string like:
4pQUfomwVVsl68oQqWoWYNRmRM+Cp+vNFXBNdkN6dZPQ34VZ35vsKn9Q7QGTDVOj+w5mqVYHnGuAOFOgdgl8kA==
s = String.Format("{0}_{1}", s, DateTime.Now.ToString("ddMMyyyyHmmss"));
SymmetricKeyAlgorithmProvider algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
IBuffer keymaterial = CryptographicBuffer.ConvertStringToBinary("[Key]", BinaryStringEncoding.Utf8);
CryptographicKey KEY = algorithm.CreateSymmetricKey(keymaterial);
IBuffer IV = CryptographicBuffer.ConvertStringToBinary("[IV]", BinaryStringEncoding.Utf8);
IBuffer data = CryptographicBuffer.ConvertStringToBinary(s, BinaryStringEncoding.Utf8);
IBuffer output = CryptographicEngine.Encrypt(KEY, data, IV);
return CryptographicBuffer.EncodeToBase64String(output);
The server does encryption/decryption with
public static string Encrypt(string text, byte[] key, byte[] iv, int keysize = 128, int blocksize = 128, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = blocksize;
aes.KeySize = keysize;
aes.Mode = cipher;
aes.Padding = padding;
byte[] src = Encoding.UTF8.GetBytes(text);
using (ICryptoTransform encrypt = aes.CreateEncryptor(key, iv))
{
byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
encrypt.Dispose();
return Convert.ToBase64String(dest);
}
}
public static string Decrypt(string text, byte[] key, byte[] iv, int keysize = 128, int blocksize = 128, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = blocksize;
aes.KeySize = keysize;
aes.Mode = cipher;
aes.Padding = padding;
byte[] src = Convert.FromBase64String(text);
using (ICryptoTransform decrypt = aes.CreateDecryptor(key, iv))
{
byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
decrypt.Dispose();
return Encoding.UTF8.GetString(dest); //Padding is invalid and cannot be removed.
}
}
But it fails becasue:
Padding is invalid and cannot be removed.
That's why I want to try Bouncy Castle, but I can't find any suitable example code.
EDIT
I tried using Bouncy Castle with the code provided in the answer.
Now I'm getting the error:
initialisation vector must be the same length as block size
byte[] inputBytes = Encoding.UTF8.GetBytes(s);
byte[] IV = Encoding.UTF8.GetBytes("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
byte[] key = Encoding.UTF8.GetBytes("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
//Set up
AesEngine engine = new AesEngine();
CbcBlockCipher blockCipher = new CbcBlockCipher(engine);
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
Debug.WriteLine(IV.Length); //32
Debug.WriteLine(cipher.GetBlockSize()); //16
KeyParameter keyParam = new KeyParameter(key);
ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, IV);
cipher.Init(true, keyParamWithIv); //Error Message thrown
byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; //cip
int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
cipher.DoFinal(outputBytes, length); //Do the final block
string encryptedInput = Convert.ToBase64String(outputBytes);
The length on the server is 128. How can I force it to be equal and same length?
Here are snippets I use. It uses the default built-in System.Security.Cryptography. It doesn't need to be BC
/// <summary>
/// Encrypt a byte array using AES 128
/// </summary>
/// <param name="key">128 bit key</param>
/// <param name="secret">byte array that need to be encrypted</param>
/// <returns>Encrypted array</returns>
public static byte[] EncryptByteArray(byte[] key, byte[] secret)
{
using (MemoryStream ms = new MemoryStream())
{
using (AesManaged cryptor = new AesManaged())
{
cryptor.Mode = CipherMode.CBC;
cryptor.Padding = PaddingMode.PKCS7;
cryptor.KeySize = 128;
cryptor.BlockSize = 128;
//We use the random generated iv created by AesManaged
byte[] iv = cryptor.IV;
using (CryptoStream cs = new CryptoStream(ms, cryptor.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(secret, 0, secret.Length);
}
byte[] encryptedContent = ms.ToArray();
//Create new byte array that should contain both unencrypted iv and encrypted data
byte[] result = new byte[iv.Length + encryptedContent.Length];
//copy our 2 array into one
System.Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
System.Buffer.BlockCopy(encryptedContent, 0, result, iv.Length, encryptedContent.Length);
return result;
}
}
}
/// <summary>
/// Decrypt a byte array using AES 128
/// </summary>
/// <param name="key">key in bytes</param>
/// <param name="secret">the encrypted bytes</param>
/// <returns>decrypted bytes</returns>
public static byte[] DecryptByteArray(byte[] key, byte[] secret)
{
byte[] iv = new byte[16]; //initial vector is 16 bytes
byte[] encryptedContent = new byte[secret.Length - 16]; //the rest should be encryptedcontent
//Copy data to byte array
System.Buffer.BlockCopy(secret, 0, iv, 0, iv.Length);
System.Buffer.BlockCopy(secret, iv.Length, encryptedContent, 0, encryptedContent.Length);
using (MemoryStream ms = new MemoryStream())
{
using (AesManaged cryptor = new AesManaged())
{
cryptor.Mode = CipherMode.CBC;
cryptor.Padding = PaddingMode.PKCS7;
cryptor.KeySize = 128;
cryptor.BlockSize = 128;
using (CryptoStream cs = new CryptoStream(ms, cryptor.CreateDecryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(encryptedContent, 0, encryptedContent.Length);
}
return ms.ToArray();
}
}
}
If you really need BC, here is a quick test I manage to write based on the test suit from https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/crypto/test/AESFastTest.cs
You can tailor it for your need
private static void TestBC()
{
//Demo params
string keyString = "jDxESdRrcYKmSZi7IOW4lw==";
string input = "abc";
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] iv = new byte[16]; //for the sake of demo
//Set up
AesEngine engine = new AesEngine();
CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7
KeyParameter keyParam = new KeyParameter(Convert.FromBase64String(keyString));
ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);
// Encrypt
cipher.Init(true, keyParamWithIV);
byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
cipher.DoFinal(outputBytes, length); //Do the final block
string encryptedInput = Convert.ToBase64String(outputBytes);
Console.WriteLine("Encrypted string: {0}", encryptedInput);
//Decrypt
cipher.Init(false, keyParamWithIV);
byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)];
length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0);
cipher.DoFinal(comparisonBytes, length); //Do the final block
Console.WriteLine("Decrypted string: {0}",Encoding.UTF8.GetString(comparisonBytes)); //Should be abc
}
enter link description here
byte[] k; //32 byte
string para; // plaintext
string msgRefNo; // 16byte
byte[] inputBytes = Encoding.UTF8.GetBytes(para);
byte[] IV = Encoding.UTF8.GetBytes(msgRefNo);
byte[] key = k;
AesEngine engine = new AesEngine();
CbcBlockCipher blockCipher = new CbcBlockCipher(engine);
PaddedBufferedBlockCipher cipher1 = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
KeyParameter keyParam = new KeyParameter(key);
ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, IV);
cipher1.Init(true, keyParamWithIv); //Error Message thrown
byte[] outputBytes = new byte[cipher1.GetOutputSize(inputBytes.Length)]; //cip
int length = cipher1.ProcessBytes(inputBytes, outputBytes, 0);
cipher1.DoFinal(outputBytes, length); //Do the final block
string encryptedInput = Convert.ToBase64String(outputBytes);
return encryptedInput;
I am using Windows Live Id service for logging and authentication for my application. I get a token in the response sent by the Windows Live Id Service after the user get authenticated. I wish to decode this token in order to obtain the Unique Identifier out of it.Here is the link which explains this better:
http://msdn.microsoft.com/en-us/library/bb676622.aspx
I see exceptions while debugging in visual studio when I try to create a CryptoStream Object although the code does not break.
But when I try to convert the stream to bytes it throws an error and the code breaks.
It says:
"Length of the data to decrypt is invalid"
Here is the code that I am using:
string token=""; //Token Sent by the service
string SecretKey = ""; //SecretKey Obtained while registering my application
byte[] cryptKey = derive(secretKey, "ENCRYPTION");
static byte[] derive(string secret, string prefix)
{
using(HashAlgorithm hashAlg = HashAlgorithm.Create("SHA256"))
{
const int keyLength = 16;
byte[] data = Encoding.Default.GetBytes(prefix+secret);
byte[] hashOutput = hashAlg.ComputeHash(data);
byte[] byteKey = new byte[keyLength];
Array.Copy(hashOutput, byteKey, keyLength);
return byteKey;
}
}
const int ivLength = 16;
token = HttpUtility.UrlDecode(token);
byte[] ivAndEncryptedValue = Convert.FromBase64String(token);
aesAlg = new RijndaelManaged();
aesAlg.KeySize = 128;
aesAlg.Key = cryptKey;
aesAlg.Padding = PaddingMode.PKCS7;
memStream = new MemoryStream(ivAndEncryptedValue);
byte[] iv = new byte[ivLength];
memStream.Read(iv, 0, ivLength);
aesAlg.IV = iv;
cStream = new CryptoStream(memStream, aesAlg.CreateDecryptor(), CryptoStreamMode.Read);
sReader = new StreamReader(cStream, Encoding.ASCII);
The next line of code throws error: "Length of the data to decrypt is invalid"
decodedValue = sReader.ReadToEnd(); //Throws error:"Length of the data to decrypt is invalid"
Does anyone have any idea as to what can be the reason behind this?
Any kind of help or guidance will be greatly appreciated.
Thank you in advance.
Regards,
Abhishek
Here is an example of something that I currently use when Decrypting a value
I hope that this will help you in regards to seeing what you have done incorrectly in your existing code
static string Decrypt()
{
byte[] keyBytes = Convert.FromBase64String("U6XksFkhWV4.......eo3fRg=="");
byte[] iv = Convert.FromBase64String("KLnP....wA=="");
byte[] cipherTextBytes = Convert.FromBase64String("Put the EncryptedText here");
var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, IV = iv, KeySize = 128, Key = keyBytes, Padding = PaddingMode.Zeros};
using (var decryptor = symmetricKey.CreateDecryptor())
using (var ms = new MemoryStream(cipherTextBytes))
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) {
var plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cs.Read(plainTextBytes, 0, plainTextBytes.Length);
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}