Manually decrypt data encrypted with MachineKey.Protect - c#

I am trying to manually decrypt data which was encrypted with MachineKey.Protect(). I am using AES and SHA1 algoritms.
// unencrypted input in HEX: 010203
// AES key in HEX: CCA0DC9874B3F9E679E0A576F77EDF9B121CAB2F9A363A4EAF99976F7B51FA89
// want to decrypt this: A738E5F98920E37AB14C5F4332D4C7F0EC683680AAA0D34B806E75DECF04B7A3DB651E688B563F77BA107FB15990C88FB8023386
Here is an example.
// Some input data
var input = new byte[] { 1, 2, 3 };
// this just works fine
var protectedData = System.Web.Security.MachineKey.Protect(input, "ApplicationCookie", "v1");
// protectedData in hex: A738E5F98920E37AB14C5F4332D4C7F0EC683680AAA0D34B806E75DECF04B7A3DB651E688B563F77BA107FB15990C88FB8023386
// works
var unprotectedInput = System.Web.Security.MachineKey.Unprotect(protectedData, "ApplicationCookie", "v1");
// now lets do it manually
// in web.config machineKey is configured: AES and SHA1
var algorithm = new AesManaged();
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Mode = CipherMode.CBC;
algorithm.KeySize = 256;
algorithm.BlockSize = 128;
var validationAlgorithm = new HMACSHA1();
// this is the key from web.config
var key = HexToBinary("CCA0DC9874B3F9E679E0A576F77EDF9B121CAB2F9A363A4EAF99976F7B51FA89");
using (SymmetricAlgorithm encryptionAlgorithm = algorithm)
{
encryptionAlgorithm.Key = key;
int offset = encryptionAlgorithm.BlockSize / 8; //16
int buffer1Count = validationAlgorithm.HashSize / 8; // 20
int count = checked(protectedData.Length - offset - buffer1Count); // 16
byte[] numArray = new byte[offset];
Buffer.BlockCopy((Array)protectedData, 0, (Array)numArray, 0, numArray.Length);
encryptionAlgorithm.IV = numArray; // in HEX: A738E5F98920E37AB14C5F4332D4C7F0
using (MemoryStream memoryStream = new MemoryStream())
{
using (ICryptoTransform decryptor = encryptionAlgorithm.CreateDecryptor())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(protectedData, offset, count);
// Padding is invalid and cannot be removed.
cryptoStream.FlushFinalBlock();
var result = memoryStream.ToArray();
}
}
}
}
I am getting an exception (padding is not right).
I do not know what else to try...
This is the code for MachineKey.Protect, https://msdn.microsoft.com/cs-cz/library/system.web.security.machinekey.protect(v=vs.110).aspx
public byte[] Protect(byte[] clearData)
{
// this is AESManaged
using (SymmetricAlgorithm encryptionAlgorithm = this._cryptoAlgorithmFactory.GetEncryptionAlgorithm())
{
// this is our key
encryptionAlgorithm.Key = this._encryptionKey.GetKeyMaterial();
if (this._predictableIV)
encryptionAlgorithm.IV = CryptoUtil.CreatePredictableIV(clearData, encryptionAlgorithm.BlockSize);
else
encryptionAlgorithm.GenerateIV();
byte[] iv = encryptionAlgorithm.IV;
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(iv, 0, iv.Length);
using (ICryptoTransform encryptor = encryptionAlgorithm.CreateEncryptor())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(clearData, 0, clearData.Length);
cryptoStream.FlushFinalBlock();
using (KeyedHashAlgorithm validationAlgorithm = this._cryptoAlgorithmFactory.GetValidationAlgorithm())
{
validationAlgorithm.Key = this._validationKey.GetKeyMaterial();
byte[] hash = validationAlgorithm.ComputeHash(memoryStream.GetBuffer(), 0, checked ((int) memoryStream.Length));
memoryStream.Write(hash, 0, hash.Length);
return memoryStream.ToArray();
}
}
}
}
}
}

The decryption key is wrong.
MachineKey.Protect/UnProtect() modifies the key before using it.
It is doing something like this:
public static byte[] DeriveKey(byte[] key, int keySize, string primaryPurpose, params string[] specificPurposes)
{
var secureUtf8Encoding = new UTF8Encoding(false, true);
var hash = new HMACSHA512(key);
using (hash)
{
var label = secureUtf8Encoding.GetBytes(primaryPurpose);
byte[] context;
using (var memoryStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(memoryStream, secureUtf8Encoding))
{
foreach (var str in specificPurposes)
binaryWriter.Write(str);
context = memoryStream.ToArray();
}
}
return DeriveKeyImpl(hash, label, context, keySize);
}
}
public static byte[] DeriveKeyImpl(HMAC hmac, byte[] label, byte[] context, int keyLengthInBits)
{
int count1 = label != null ? label.Length : 0;
int count2 = context != null ? context.Length : 0;
byte[] buffer = new byte[checked(4 + count1 + 1 + count2 + 4)];
if (count1 != 0)
Buffer.BlockCopy((Array)label, 0, (Array)buffer, 4, count1);
if (count2 != 0)
Buffer.BlockCopy((Array)context, 0, (Array)buffer, checked(5 + count1), count2);
WriteUInt32ToByteArrayBigEndian(checked((uint)keyLengthInBits), buffer, checked(5 + count1 + count2));
int dstOffset = 0;
int val1 = keyLengthInBits / 8;
byte[] numArray = new byte[val1];
uint num = 1;
while (val1 > 0)
{
WriteUInt32ToByteArrayBigEndian(num, buffer, 0);
byte[] hash = hmac.ComputeHash(buffer);
int count3 = Math.Min(val1, hash.Length);
Buffer.BlockCopy((Array)hash, 0, (Array)numArray, dstOffset, count3);
checked { dstOffset += count3; }
checked { val1 -= count3; }
checked { ++num; }
}
return numArray;
}
It is very important to specify the right purpose. For standard MachineKey.Protect primary reason is "User.MachineKey.Protect". The key size for this example is 256 (in bits).

Related

The input data is not a complete block when decrypting AES with specific offset?

I'm trying to write an encryption/decryption method for practice and after getting an initial run working, I decided to step it up and make it less vulnerable by encrypting the IV into the data. I got that working, and decided to step it up again by introducing an offset for the IV's location in the data, by adding some random data to the left hand side of the IV. Up until this point, everything was working fine, but now I'm receiving an error on decryption that states:
The input data is not a complete block.
Which with my limited knowledge of encryption and decryption is quite useless to me in debugging the issue. I've searched high and low, and none of the answers to this problem, that I've found seem to fix my issue. The answers are typically along the lines of the developer isn't decrypting a byte[] but instead something like a base 64 string.
private static Guid TestGuid = Guid.NewGuid();
private static DateTime Timestamp = DateTime.Now;
private static string key = "PPPQmyuzqKtjzYlWM3mP0aDxaxCzlsACajIkTVN4IjI=";
public static void Main()
{
string data = TestGuid + "|" + Timestamp;
Console.WriteLine("Request Parameter: " + data);
string encryptedData = AESEncrypt(key, data, 1);
Console.WriteLine("Encrypted: " + encryptedData);
string decryptedData = AESDecrypt(key, encryptedData, 1);
Console.WriteLine("Decrypted: " + decryptedData);
}
public static string AESEncrypt(string key, string data, int offset)
{
if (string.IsNullOrWhiteSpace(data))
throw new ArgumentException("Data");
byte[] encryptedData;
byte[] keyData = Convert.FromBase64String(key);
using (Aes algo = Aes.Create())
{
algo.Key = keyData;
algo.GenerateIV();
algo.Padding = PaddingMode.PKCS7;
byte[] iv = new byte[offset + 16];
Random r = new Random();
using (MemoryStream ms = new MemoryStream())
{
for (int i = 0; i < offset; i++)
iv[i] = (byte)r.Next(1, 200);
for (int i = 0; i < algo.IV.Length; i++)
iv[offset + i - 1] = algo.IV[i];
ICryptoTransform encryptor = algo.CreateEncryptor(algo.Key, algo.IV);
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (BinaryWriter bw = new BinaryWriter(cs))
{
bw.Write(iv, 0, offset);
ms.Write(iv, offset, algo.IV.Length);
bw.Write(data);
cs.FlushFinalBlock();
}
encryptedData = ms.ToArray();
}
}
}
if (encryptedData != null)
return Convert.ToBase64String(encryptedData);
throw new Exception("An unxpected error occurred and the provided data was not encrypted.");
}
public static string AESDecrypt(string key, string data, int offset)
{
if (string.IsNullOrWhiteSpace(data))
throw new ArgumentException("Data");
string decryptedData;
byte[] keyData = Convert.FromBase64String(key);
using (Aes algo = Aes.Create())
{
algo.Key = keyData;
algo.Padding = PaddingMode.PKCS7;
byte[] decodedData = Convert.FromBase64String(data);
using (MemoryStream ms = new MemoryStream(decodedData))
{
byte[] ivData = new byte[offset + 16];
ms.Read(ivData, 0, offset + 16);
List<byte> iv = new List<byte>();
for (int i = offset - 1; i < ivData.Length - 1; i++)
iv.Add(ivData[i]);
algo.IV = iv.ToArray();
ICryptoTransform decryptor = algo.CreateDecryptor(algo.Key, algo.IV);
List<byte> dataToDecrypt = new List<byte>();
for (int i = 0; i + offset < decodedData.Length; i++)
dataToDecrypt.Add(decodedData[i + offset]);
using (MemoryStream ds = new MemoryStream(dataToDecrypt.ToArray()))
{
using (CryptoStream cs = new CryptoStream(ds, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decryptedData = sr.ReadToEnd();
}
}
}
}
}
if (!string.IsNullOrWhiteSpace(decryptedData))
return decryptedData;
throw new Exception("An unxpected error occurred and the provided data was not decrypted.");
}
What is causing this error, why is it causing the error, how do I resolve the error, and why does that resolution work?
Messing with the final encryption stream during the encryption process (feeding into it raw bytes) is a fatal mistake and should be avoided
The problem in question occurs because
bw.Write(iv, 0, offset);
ms.Write(iv, offset, algo.IV.Length);
Feeding the first random bytes of the modified IV to the encryption stream and the rest of it to the raw output stream, the first bytes of the modified iv will not be written to the memory stream immediately and instead will be part of the first encryption block, thus, the size of the cipher during decryption will lack some bytes, for example it lacks 1 byte where offset = 1
But you expect them to be written immediately as independent bytes, because in the decryption part you read offset + 16 bytes from the stream and thus you read into the encrypted block and cause it to be less than the block size for AES. You can see this if you debug the code. The final size of the encrypted bytes is 0x50 while the size of bytes for decryption is 0x50 - offset = 0x4f (offset = 1)
For solution,
You can derive the IV from the Key (which is not secure if you are reusing the key) and will not have to include it in your cipher.
You can prepend the IV (and your random bytes) to your encrypted buffer and read it first then use it for decryption,
like:
public static string AESEncrypt(string key, string data, int offset)
{
if (string.IsNullOrWhiteSpace(data))
throw new ArgumentException("Data");
byte[] encryptedData;
byte[] keyData = Convert.FromBase64String(key);
using (Aes algo = Aes.Create())
{
algo.Key = keyData;
algo.GenerateIV();
algo.Padding = PaddingMode.PKCS7;
Random r = new Random();
using (MemoryStream ms = new MemoryStream())
{
for (int i = 0; i < offset; i++)
{
ms.WriteByte((byte)r.Next(0, 200));
}
ms.Write(algo.IV, 0, 16);
ICryptoTransform encryptor = algo.CreateEncryptor(algo.Key, algo.IV);
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (BinaryWriter bw = new BinaryWriter(cs))
{
bw.Write(data);
cs.FlushFinalBlock();
}
encryptedData = ms.ToArray();
}
}
}
if (encryptedData != null)
return Convert.ToBase64String(encryptedData);
throw new Exception("An unxpected error occurred and the provided data was not encrypted.");
}
public static string AESDecrypt(string key, string data, int offset)
{
if (string.IsNullOrWhiteSpace(data))
throw new ArgumentException("Data");
string decryptedData;
byte[] keyData = Convert.FromBase64String(key);
using (Aes algo = Aes.Create())
{
algo.Key = keyData;
algo.Padding = PaddingMode.PKCS7;
byte[] decodedData = Convert.FromBase64String(data);
using (MemoryStream ms = new MemoryStream(decodedData))
{
for (int i = 0; i < offset; i++) ms.ReadByte();
byte[] iv = new byte[16];
ms.Read(iv, 0, 16);
algo.IV = iv.ToArray();
ICryptoTransform decryptor = algo.CreateDecryptor(algo.Key, algo.IV);
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decryptedData = sr.ReadToEnd();
}
}
}
}
if (!string.IsNullOrWhiteSpace(decryptedData))
return decryptedData;
throw new Exception("An unxpected error occurred and the provided data was not decrypted.");
}

AES Encryption Invalid Padding

I am trying to convert a previous working script that handled AES encryption using a 256byte key. I am trying to have the script use 128bye, but i am getting a padding invalid and cannot be removed error at line 110. Any help or tips would be helpful.
I have tried playing around with the keySize, or the blocksize but have yet to get it to work.
Here is the code.
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Response.Write(timeNow.ToString());
string str = #"{""dataset"":{""schema"" :{""manifest"":{""datasetname"":""/Apps/SM/Custom/Shoppers/ShopperMailbox_GetAssignedInstances"",""datafieldsmode"":""D"",""dbsqltype"":""P"",""schemaformat"":""JSON"",""dataformat"":""json"",""encoding"":""utf-8"",""security"":{},""cacheable"":{},""hasoutputparameters"":false,""meta"":{}},""parameters"":[{""name"":""SecurityObjectUserID"",""heading"":""SecurityObjectUserID"",""headingglobalizationenabled"":true,""sqlparamname"":""#SecurityObjectUserID"",""datatype"":""bigint"",""datatypecharlength"":null,""datatypenumericprecision"":19,""datatypenumericprecisionradix"":10,""datatypenumericscale"":0,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":1,""direction"":null,""lookup"":null},{""name"":""ShopperPhoneNumber"",""heading"":""ShopperPhoneNumber"",""headingglobalizationenabled"":true,""sqlparamname"":""#ShopperPhoneNumber"",""datatype"":""varchar"",""datatypecharlength"":63,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":2,""direction"":null,""lookup"":null},{""name"":""ShopperEmailAddress"",""heading"":""ShopperEmailAddress"",""headingglobalizationenabled"":true,""sqlparamname"":""#ShopperEmailAddress"",""datatype"":""nvarchar"",""datatypecharlength"":222,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":3,""direction"":null,""lookup"":null},{""name"":""MiscSettings"",""heading"":""MiscSettings"",""headingglobalizationenabled"":true,""sqlparamname"":""#MiscSettings"",""datatype"":""nvarchar"",""datatypecharlength"":-1,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":4,""direction"":null,""lookup"":null}],""columns"":[{""name"":""Shopper Email Address"",""heading"":""Shopper Email Address"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":222,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":0,""direction"":null,""lookup"":null},{""name"":""Instance ID"",""heading"":""Instance ID"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""bigint"",""datatypecharlength"":null,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":1,""direction"":null,""lookup"":null},{""name"":""Location Street Address"",""heading"":""Location Street Address"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":150,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":2,""direction"":null,""lookup"":null},{""name"":""Location City"",""heading"":""Location City"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":50,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":3,""direction"":null,""lookup"":null},{""name"":""Location State"",""heading"":""Location State"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":8,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":4,""direction"":null,""lookup"":null},{""name"":""Location Postal Code"",""heading"":""Location Postal Code"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":12,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":5,""direction"":null,""lookup"":null},{""name"":""Client Name"",""heading"":""Client Name"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":200,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":6,""direction"":null,""lookup"":null},{""name"":""Survey Title"",""heading"":""Survey Title"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":500,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":7,""direction"":null,""lookup"":null},{""name"":""Planned Date"",""heading"":""Planned Date"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""date"",""datatypecharlength"":null,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":8,""direction"":null,""lookup"":null},{""name"":""Due Date"",""heading"":""Due Date"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""datetime"",""datatypecharlength"":null,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":9,""direction"":null,""lookup"":null},{""name"":""Campaign"",""heading"":""Campaign"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":50,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":10,""direction"":null,""lookup"":null}]},""data"":[{""Shopper Email Address"":""frecklegami8#gmail.com"",""Instance ID"":416722,""Location Street Address"":""2700 Potomac Mills Circle"",""Location City"":""Woodbridge"",""Location State"":""VA"",""Location Postal Code"":""22192"",""Client Name"":""Christmas Tree Shops "",""Survey Title"":""CTS In Store Mystery Shop"",""Planned Date"":null,""Due Date"":""2018-01-17 00:59:00"",""Campaign"":""2018-01""},{""Shopper Email Address"":""frecklegami8#gmail.com"",""Instance ID"":418529,""Location Street Address"":""4830 Crossings Court"",""Location City"":""Massaponax"",""Location State"":""VA"",""Location Postal Code"":""22407"",""Client Name"":""Steak 'N Shake - Virginia"",""Survey Title"":""Steak 'N Shake Dine In Evaluation v2"",""Planned Date"":null,""Due Date"":""2018-01-20 23:59:00"",""Campaign"":""2018-01""}]}}";
string encryptedString = AESEncryption.Encrypt(str, "ds!5da%-0sadg$!$2fDUC-51AHB)!"); //, "ASDdasdsa213DSA#4!##!##dsadsa", "SHA512", 10000, IV);
Response.Write(encryptedString);
//Response.Write("<br/>");
//Response.Write("<br/>");
//Response.Write("<br/>");
//Response.Write("<br/>");
encryptedString = #"dFmyMsfNxzWqVqfYG14ueWRrxA2EezLcatVo9127uRpFZEnYepm9yXv2SQpD+UtX5Fuag9mpJrQL1I0QX7KSGp87TrEH0y6PXlLsjbXSO8hIv0XybmaxAS0/xKmkCdxz";
Response.Write(AESEncryption.Decrypt(encryptedString, "ds!5da%-0sadg$!$2fDUC-51AHB)!")); //, "ASDdasdsa213DSA#4!##!##dsadsa", "SHA512", 10000, IV));
}
}
public static class AESEncryption
{
#region Static Functions
// This constant is used to determine the keysize of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private const int Keysize = 128;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 100000;
public static string Encrypt(string plainText, string passPhrase)
{
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = Generate256BitsOfRandomEntropy();
var ivStringBytes = Generate256BitsOfRandomEntropy();
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
public static string Decrypt(string cipherText, string passPhrase)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
if (String.IsNullOrEmpty(cipherText))
{
return "Empty string";
}
if (!IsBase64String(cipherText))
{
return "Not a valid Base64 string";
}
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 16 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 16 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 5)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
private static byte[] Generate256BitsOfRandomEntropy()
{
var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.
using (var rngCsp = new RNGCryptoServiceProvider())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
private static bool IsBase64String(string value)
{
if (string.IsNullOrEmpty(value))
{
return false;
}
// if(value == null || value.Length == 0 || value.Length % 4 != 0 || value.Contains(" ") || value.Contains("\t") || value.Contains("\r") || value.Contains("\n"))
// {
// return false;
// }
try
{
Convert.FromBase64String(value);
return true;
//if (value.EndsWith("="))
//{
// value = value.Trim();
// int mod4 = value.Length % 4;
// if (mod4 != 0)
// {
// return false;
// }
// return true;
//}
//else
//{
// return false;
//}
}
catch (FormatException)
{
return false;
}
}
public static string Left(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return (value.Length <= maxLength
? value
: value.Substring(0, maxLength)
);
}
#endregion
}
You have the bug in this line:
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 5)).ToArray();
Why do you take only cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 5) bytes? As I can see in your encryption alogithm all bytes remaining after removing of salt and IV should be taken.
I.e. replace the line with
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).ToArray();
and decryption will work fine.
UPD: Remove your hardcoded encodedString and try decrypting previously generated string. It seems that your hardcoded string was encrypted using different alogrithm.

Encode CryptoStream to Base64 String in Chunks in C#

There is a method (Version1) that encodes an input stream and there is a function Decrypt() that successfully decodes encoded data. But when the input data is large there could be an error OutOfMemory (on the line "string textEncrypted = Convert.ToBase64String (ms.ToArray())").
Version1
private static Stream EncryptRijndael1(byte[] key, byte[] iv, Stream plainText)
{
if (plainText == null)
return null;
byte[] bytesEncrypted;
RijndaelManaged rjndl = RijndaelManagedWithConfig(key, iv);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, rjndl.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
byte[] buffer = new byte[16 * 1024];
int readed;
while ((readed = (plainText.Read(buffer, 0, buffer.Length))) > 0)
{
cs.Write(buffer, 0, readed);
}
}
string textEncrypted = Convert.ToBase64String(ms.ToArray());
bytesEncrypted = Encoding.ASCII.GetBytes(textEncrypted);
}
return new MemoryStream(bytesEncrypted);
}
So I modified the method to process an array part by part (chunks).
Here is Version2. It causes an error "offset and length must refer to a position in the string" in the line Convert.ToBase64String (ms.ToArray(), offset, read).
Version2
private static Stream EncryptRijndael2(byte[] key, byte[] iv, Stream plainText)
{
if (plainText == null)
return null;
byte[] bytesEncrypted;
RijndaelManaged rjndl = RijndaelManagedWithConfig(key, iv);
string textEncrypted = String.Empty;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, rjndl.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
byte[] buffer = new byte[16 * 1024];
int readed;
int offset = 0;
while ((readed = (plainText.Read(buffer, 0, buffer.Length))) > 0)
{
cs.Write(buffer, 0, readed);
textEncrypted += Convert.ToBase64String(ms.ToArray(), offset, readed);
offset += readed;
}
}
bytesEncrypted = Encoding.ASCII.GetBytes(textEncrypted);
}
return new MemoryStream(bytesEncrypted);
}
Then I made Version3. It works without errors but the output data length now is bigger than in Version1 having the same input data.
Decryt() function throws an error "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
Version3
private static Stream EncryptRijndael3(byte[] key, byte[] iv, Stream plainText)
{
if (plainText == null)
return null;
byte[] bytesEncrypted;
RijndaelManaged rjndl = RijndaelManagedWithConfig(key, iv);
using (MemoryStream ms = new MemoryStream())
{
string textEncrypted = String.Empty;
using (CryptoStream cs = new CryptoStream(ms, rjndl.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
byte[] buffer = new byte[16*1024];
int readed;
while ((readed = (plainText.Read(buffer, 0, buffer.Length))) > 0)
{
cs.Write(buffer, 0, readed);
}
}
byte[] buffer1 = new byte[16*1024];
int readed1;
using (MemoryStream ms1 = new MemoryStream(ms.ToArray()))
{
while ((readed1 = (ms1.Read(buffer1, 0, buffer1.Length))) > 0)
{
if (readed1 < buffer1.Length)
{
var lastBuf = new List<Byte>();
for (int i = 0; i < readed1; i++)
{
lastBuf.Add(buffer1[i]);
}
textEncrypted += Convert.ToBase64String(lastBuf.ToArray());
continue;
}
textEncrypted += Convert.ToBase64String(buffer1);
}
}
bytesEncrypted = Encoding.ASCII.GetBytes(textEncrypted);
}
return new MemoryStream(bytesEncrypted);
}
My RijndaelManaged
private static RijndaelManaged RijndaelManagedWithConfig(byte[] key, byte[] iv)
{
RijndaelManaged rjndl = new RijndaelManaged();
rjndl.KeySize = 256;
rjndl.BlockSize = 128;
rjndl.Key = key;
rjndl.IV = iv;
rjndl.Mode = CipherMode.CBC;
rjndl.Padding = PaddingMode.PKCS7;
return rjndl;
}
Please help me to get rid of the errors or tell me how to make the Version1 process Convert.ToBase64String data partially.
I have achieved the decision
private static Stream EncryptRijndael(byte[] key, byte[] iv, Stream plainText)
{
if (plainText == null)
return null;
byte[] buffer = new byte[5120 * 1024];
RijndaelManaged rjndl = RijndaelManagedWithConfig(key, iv);
using (var memoryStream = new MemoryStream())
{
int readedBytes;
using (var cs = new CryptoStream(memoryStream, rjndl.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
while ((readedBytes = (plainText.Read(buffer, 0, buffer.Length))) > 0)
{
cs.Write(buffer, 0, readedBytes);
}
}
using (var cryptoMemoryStream = new MemoryStream(memoryStream.ToArray()))
{
using (var base64MemoryStream = new MemoryStream())
{
using (ICryptoTransform transform = new ToBase64Transform())
{
using (var cryptStream = new CryptoStream(base64MemoryStream, transform, CryptoStreamMode.Write))
{
while ((readedBytes = cryptoMemoryStream.Read(buffer, 0, buffer.Length)) > 0)
{
cryptStream.Write(buffer, 0, readedBytes);
}
cryptStream.FlushFinalBlock();
}
return new MemoryStream(base64MemoryStream.ToArray());
}
}
}
}
}

Cryptographic code in CSharp similar to code in Go (AES,CFB,XorKeyStream)

I have cryptographic code in Go but I can't hard find similar code in CSharp.
I am debating to make my own implementation of XorKeyStream but I am told that there is legal issue if I write my own cryptographic code. I am sure there must be similar code in CSharp.
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
func main() {
k1 := []byte("0123456789abcdef")
r1 := []byte("1234567890abcdef")
data := []byte("0123456789")
fmt.Printf("original %x %s\n", data, string(data))
{
block, _ := aes.NewCipher(k1)
stream := cipher.NewCFBEncrypter(block, r1)
stream.XORKeyStream(data, data)
fmt.Printf("crypted %x\n", data)
}
{
block, _ := aes.NewCipher(k1)
stream := cipher.NewCFBDecrypter(block, r1)
stream.XORKeyStream(data, data)
fmt.Printf("decrypted %x %s\n", data, string(data))
}
}
http://play.golang.org/p/EnJ56dYX_-
output
original 30313233343536373839 0123456789
crypted 762b6dcea9c2a7460db7
decrypted 30313233343536373839 0123456789
PS
Some people marked that question as possible duplicate of question: "C# AES: Encrypt a file causes “Length of the data to encrypt is invalid.” error"
I look for identical code in CSharp for existing code in Go. That question is about padding. This algorithm needs "Key stream" that will xor text.
It is different questions.
Here is your code
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
class AES_CFB_XorKeyStream
{
static void Main(string[] args)
{
byte[] data = Encoding.UTF8.GetBytes("0123456789");
byte [] k1 = Encoding.UTF8.GetBytes("0123456789abcdef");
byte [] r1 = Encoding.UTF8.GetBytes("1234567890abcdef");
Console.WriteLine("original " + BitConverter.ToString(data));
using (RijndaelManaged Aes128 = new RijndaelManaged())
{
Aes128.BlockSize = 128;
Aes128.KeySize = 128;
Aes128.Mode = CipherMode.CFB;
Aes128.FeedbackSize = 128;
Aes128.Padding = PaddingMode.None;
Aes128.Key = k1;
Aes128.IV = r1;
using (var encryptor = Aes128.CreateEncryptor())
using (var msEncrypt = new MemoryStream())
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var bw = new BinaryWriter(csEncrypt, Encoding.UTF8))
{
bw.Write(data);
bw.Close();
data = msEncrypt.ToArray();
Console.WriteLine("crypted " + BitConverter.ToString(data));
}
}
using (RijndaelManaged Aes128 = new RijndaelManaged())
{
Aes128.BlockSize = 128;
Aes128.KeySize = 128;
Aes128.Mode = CipherMode.CFB;
Aes128.FeedbackSize = 128;
Aes128.Padding = PaddingMode.None;
Aes128.Key = k1;
Aes128.IV = r1;
using (var decryptor = Aes128.CreateDecryptor())
using (var msEncrypt = new MemoryStream())
using (var csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Write))
using (var bw = new BinaryWriter(csEncrypt, Encoding.UTF8))
{
bw.Write(data);
bw.Close();
data = msEncrypt.ToArray();
Console.WriteLine("decrypted " + BitConverter.ToString(data));
}
}
}
}
output
original 30-31-32-33-34-35-36-37-38-39
crypted 76-2B-6D-CE-A9-C2-A7-46-0D-B7
decrypted 30-31-32-33-34-35-36-37-38-39
I had this exact same issue with only the first byte of each decrypted block being correct, but I did not have the luxury of being able to change source on the Go program.
I ended up implementing my own padding. Just pad the encrypted bytes with 0 bytes to make it divisible by the block size of 128, then after running through the decryption routine, chop that number of bytes off the end.
Example code:
using System;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
public static class Program
{
static RijndaelManaged aes = new RijndaelManaged(){
Mode = CipherMode.CFB,
BlockSize = 128,
KeySize = 128,
FeedbackSize = 128,
Padding = PaddingMode.None
};
public static void Main(){
byte[] key = Encoding.UTF8.GetBytes("0123456789abcdef");
byte[] iv = Encoding.UTF8.GetBytes("1234567890abcdef");
byte[] encryptedBytes = new byte[]{0x76, 0x2b, 0x6d, 0xce, 0xa9, 0xc2, 0xa7, 0x46, 0x0d, 0xb7};
// Custom pad the bytes
int padded;
encryptedBytes = PadBytes(encryptedBytes, aes.BlockSize, out padded);
// Decrypt bytes
byte[] decryptedBytes = DecryptBytesAES(encryptedBytes, key, iv, encryptedBytes.Length);
// Check for successful decrypt
if(decryptedBytes != null){
// Unpad
decryptedBytes = UnpadBytes(decryptedBytes, padded);
Console.Write("Decrypted: " + Encoding.UTF8.GetString(decryptedBytes));
}
}
// Just an elegant way of initializing an array with bytes
public static byte[] Initialize(this byte[] array, byte value, int length)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = value;
}
return array;
}
// Custom padding to get around the issue of how Go uses CFB mode without padding differently than C#
public static byte[] PadBytes(byte[] encryptedBytes, int blockSize, out int numPadded)
{
numPadded = 0;
// Check modulus of block size
int mod = encryptedBytes.Length % blockSize;
if (mod != 0)
{
// Calculate number to pad
numPadded = blockSize - mod;
// Build array
return encryptedBytes.Concat(new byte[numPadded].Initialize(0, numPadded)).ToArray();
}
else {
// No padding needed
return encryptedBytes;
}
}
public static byte[] UnpadBytes(byte[] decryptedBytes, int numPadded)
{
if(numPadded != 0)
{
byte[] unpaddedBytes = new byte[decryptedBytes.Length - numPadded];
Array.Copy(decryptedBytes, unpaddedBytes, unpaddedBytes.Length);
return unpaddedBytes;
}
else
{
return decryptedBytes;
}
}
public static byte[] DecryptBytesAES(byte[] cipherText, byte[] Key, byte[] IV, int size)
{
byte[] array = new byte[size];
try{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(cipherText))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read))
{
cryptoStream.Read(array, 0, size);
}
}
}
catch(Exception e){
return null;
}
return array;
}
}
.NET Fiddle: https://dotnetfiddle.net/NPHKN3

AES256 Encryption/Decryption in both NodeJS and C#

I've taken some liberties with the results of the following questions:
AES encrypt in .NET and decrypt with Node.js crypto?
Decrypting AES256 encrypted data in .NET from node.js - how to obtain IV and Key from passphrase
C# version of OpenSSL EVP_BytesToKey method?
And created the following class file...
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace T1.CoreUtils.Utilities
{
public static class CryptoUtility
{
public static string Encrypt(string input, string passphrase = null)
{
byte[] key, iv;
DeriveKeyAndIV(Encoding.ASCII.GetBytes(passphrase), null, 1, out key, out iv);
return Convert.ToBase64String(EncryptStringToBytes(input, key, iv));
}
public static string Decrypt(string inputBase64, string passphrase = null)
{
byte[] key, iv;
DeriveKeyAndIV(Encoding.ASCII.GetBytes(passphrase), null, 1, out key, out iv);
return DecryptStringFromBytes(Convert.FromBase64String(inputBase64), key, iv);
}
private static void DeriveKeyAndIV(byte[] data, byte[] salt, int count, out byte[] key, out byte[] iv)
{
List<byte> hashList = new List<byte>();
byte[] currentHash = new byte[0];
int preHashLength = data.Length + ((salt != null) ? salt.Length : 0);
byte[] preHash = new byte[preHashLength];
System.Buffer.BlockCopy(data, 0, preHash, 0, data.Length);
if (salt != null)
System.Buffer.BlockCopy(salt, 0, preHash, data.Length, salt.Length);
MD5 hash = MD5.Create();
currentHash = hash.ComputeHash(preHash);
for (int i = 1; i < count; i++)
{
currentHash = hash.ComputeHash(currentHash);
}
hashList.AddRange(currentHash);
while (hashList.Count < 48) // for 32-byte key and 16-byte iv
{
preHashLength = currentHash.Length + data.Length + ((salt != null) ? salt.Length : 0);
preHash = new byte[preHashLength];
System.Buffer.BlockCopy(currentHash, 0, preHash, 0, currentHash.Length);
System.Buffer.BlockCopy(data, 0, preHash, currentHash.Length, data.Length);
if (salt != null)
System.Buffer.BlockCopy(salt, 0, preHash, currentHash.Length + data.Length, salt.Length);
currentHash = hash.ComputeHash(preHash);
for (int i = 1; i < count; i++)
{
currentHash = hash.ComputeHash(currentHash);
}
hashList.AddRange(currentHash);
}
hash.Clear();
key = new byte[32];
iv = new byte[16];
hashList.CopyTo(0, key, 0, 32);
hashList.CopyTo(32, iv, 0, 16);
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.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 encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(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;
}
}
}
From here, I generated the following via node:
var crypto = require('crypto');
var input = "This is î╥≤ what it is.";
var passkey= "This is my password.";
var cipher = crypto.createCipher('aes-256-cbc', passkey);
var encrypted = cipher.update(input, 'utf8', 'base64') + cipher.final('base64');
encrypted
// '9rTbNbfJkYVE2m5d8g/8b/qAfeCU9rbk09Na/Pw0bak='
input = "I am the walrus, coo coo cachoo!";
passkey = "I am a ≥ò'ÿ boy baby!";
cipher = crypto.createCipher('aes-256-cbc', passkey);
encrypted = cipher.update(input, 'utf8', 'base64') + cipher.final('base64');
// 'j/e+f5JU5yerSvO7FBJzR1tGro0Ie3L8sWYaupRW1JJhraGqBfQ9z+h85VhSzEjD'
var decipher = crypto.createDecipher('aes-256-cbc', passkey);
var plain = decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8');
plain
// 'I am the walrus, coo coo cachoo!'
From this, I create the following test case:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace T1.CoreUtils.Test.Utilities.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void EncryptReturnsExpectedValue1_unicode_in_plaintext()
{
var passkey = "This is my password.";
var plain = "This is î╥≤ what it is.";
var encrypted = "9rTbNbfJkYVE2m5d8g/8b/qAfeCU9rbk09Na/Pw0bak=";
var actual = T1.CoreUtils.Utilities.CryptoUtility.Encrypt(plain, passkey);
Assert.AreEqual(encrypted, actual);
}
[TestMethod]
public void EncryptReturnsExpectedValue2_unicode_in_passkey()
{
var passkey = "I am a ≥ò'ÿ boy baby!";
var plain = "I am the walrus, coo coo cachoo!";
var encrypted = "j/e+f5JU5yerSvO7FBJzR1tGro0Ie3L8sWYaupRW1JJhraGqBfQ9z+h85VhSzEjD";
var actual = T1.CoreUtils.Utilities.CryptoUtility.Encrypt(plain, passkey);
Assert.AreEqual(encrypted, actual);
}
[TestMethod]
public void DecryptReturnsExpectedValue1()
{
var passkey = "This is my password.";
var plain = "This is î╥≤ what it is.";
var encrypted = "9rTbNbfJkYVE2m5d8g/8b/qAfeCU9rbk09Na/Pw0bak=";
var actual = T1.CoreUtils.Utilities.CryptoUtility.Decrypt(encrypted, passkey);
Assert.AreEqual(plain, actual);
}
[TestMethod]
public void DecryptReturnsExpectedValue2()
{
var passkey = "I am a ≥ò'ÿ boy baby!";
var plain = "I am the walrus, coo coo cachoo!";
var encrypted = "j/e+f5JU5yerSvO7FBJzR1tGro0Ie3L8sWYaupRW1JJhraGqBfQ9z+h85VhSzEjD";
var actual = T1.CoreUtils.Utilities.CryptoUtility.Decrypt(encrypted, passkey);
Assert.AreEqual(plain, actual);
}
}
}
Passes:
EncryptReturnsExpectedValue1_unicode_in_plaintext
DecryptReturnsExpectedValue1
Fails:
EncryptReturnsExpectedValue2_unicode_in_passkey
DecryptReturnsExpectedValue2
I can only guess that the issue is in the DeriveKeyAndIV method. Will try a few different approaches and answer if I find it on my own.
Okay, upon inspecting the node.js source for crypto, I determined, that the encoding was using a new Buffer(passkey, 'binary'), which was only using the original value xand 0xFF for the bytes used, so I created a matching method in C#... here's the method in question...
private static byte[] RawBytesFromString(string input)
{
var ret = new List<Byte>();
foreach (char x in input)
{
var c = (byte)((ulong)x & 0xFF);
ret.Add(c);
}
return ret.ToArray();
}
And the updated/working CryptoUtil.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace T1.CoreUtils.Utilities
{
public static class CryptoUtility
{
/* Wanting to stay compatible with NodeJS
* http://stackoverflow.com/questions/18502375/aes256-encryption-decryption-in-both-nodejs-and-c-sharp-net/
* http://stackoverflow.com/questions/12261540/decrypting-aes256-encrypted-data-in-net-from-node-js-how-to-obtain-iv-and-key
* http://stackoverflow.com/questions/8008253/c-sharp-version-of-openssl-evp-bytestokey-method
*
* var cipher = crypto.createCipher('aes-256-cbc', 'passphrase');
* var encrypted = cipher.update("test", 'utf8', 'base64') + cipher.final('base64');
*
* var decipher = crypto.createDecipher('aes-256-cbc', 'passphrase');
* var plain = decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8');
*/
public static string Encrypt(string input, string passphrase = null)
{
byte[] key, iv;
DeriveKeyAndIV(RawBytesFromString(passphrase), null, 1, out key, out iv);
return Convert.ToBase64String(EncryptStringToBytes(input, key, iv));
}
public static string Decrypt(string inputBase64, string passphrase = null)
{
byte[] key, iv;
DeriveKeyAndIV(RawBytesFromString(passphrase), null, 1, out key, out iv);
return DecryptStringFromBytes(Convert.FromBase64String(inputBase64), key, iv);
}
private static byte[] RawBytesFromString(string input)
{
var ret = new List<Byte>();
foreach (char x in input)
{
var c = (byte)((ulong)x & 0xFF);
ret.Add(c);
}
return ret.ToArray();
}
private static void DeriveKeyAndIV(byte[] data, byte[] salt, int count, out byte[] key, out byte[] iv)
{
List<byte> hashList = new List<byte>();
byte[] currentHash = new byte[0];
int preHashLength = data.Length + ((salt != null) ? salt.Length : 0);
byte[] preHash = new byte[preHashLength];
System.Buffer.BlockCopy(data, 0, preHash, 0, data.Length);
if (salt != null)
System.Buffer.BlockCopy(salt, 0, preHash, data.Length, salt.Length);
MD5 hash = MD5.Create();
currentHash = hash.ComputeHash(preHash);
for (int i = 1; i < count; i++)
{
currentHash = hash.ComputeHash(currentHash);
}
hashList.AddRange(currentHash);
while (hashList.Count < 48) // for 32-byte key and 16-byte iv
{
preHashLength = currentHash.Length + data.Length + ((salt != null) ? salt.Length : 0);
preHash = new byte[preHashLength];
System.Buffer.BlockCopy(currentHash, 0, preHash, 0, currentHash.Length);
System.Buffer.BlockCopy(data, 0, preHash, currentHash.Length, data.Length);
if (salt != null)
System.Buffer.BlockCopy(salt, 0, preHash, currentHash.Length + data.Length, salt.Length);
currentHash = hash.ComputeHash(preHash);
for (int i = 1; i < count; i++)
{
currentHash = hash.ComputeHash(currentHash);
}
hashList.AddRange(currentHash);
}
hash.Clear();
key = new byte[32];
iv = new byte[16];
hashList.CopyTo(0, key, 0, 32);
hashList.CopyTo(32, iv, 0, 16);
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged cipher = new RijndaelManaged())
{
cipher.Key = Key;
cipher.IV = IV;
//cipher.Mode = CipherMode.CBC;
//cipher.Padding = PaddingMode.PKCS7;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = cipher.CreateEncryptor(cipher.Key, cipher.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 encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (var cipher = new RijndaelManaged())
{
cipher.Key = Key;
cipher.IV = IV;
//cipher.Mode = CipherMode.CBC;
//cipher.Padding = PaddingMode.PKCS7;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = cipher.CreateDecryptor(cipher.Key, cipher.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(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;
}
}
}
NOTE: Some more code related to this...
https://github.com/tracker1/T1.CoreUtils/blob/master/T1.CoreUtils/Utilities/CryptoUtility.cs
https://github.com/tracker1/t1-coreutils-node/blob/master/lib/hashutils.js
These are not in nuget or npm respectively as they really don't belong there... it's mainly for ideas and reference. I do need to flush out the node side a bit better so it matches up.

Categories