I have the following structure which I am using for my Encrypt
function. I'm possibly missing something from the structure in my code as I'm a PHP guy rather than a C#.
What's happening is that each time in my log the hash changes, which it shouldn't and should only equal one specific hash for the input. This ties in with this next issue..
What also happens is when I use my test passphrase, which is "MysecretPassPhrase", I have a byte length issue. I don't want to change this passphrase as it is the exact length of my true passphrase so is there anything I can do code-wise to fix the issue?
When I used a longer passphrase such as "MysecretPassPhrase123456" with "David" as the input, it will output the different hashes each time: CJ+mgAeL9x+qMLId+nHvXw==, Ladj1D+LJgZCrwPatsQsEQ==, etc.
Structure required
Error
CryptographicException: Key size not supported by algorithm
System.Security.Cryptography.SymmetricAlgorithm.set_Key (System.Byte[] value) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.Security.Cryptography/SymmetricAlgorithm.cs:176)
APIConnector.Encrypt (System.String toEncrypt) (at Assets/APIConnector.cs:59)
Code
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.IO;
void submit() {
Debug.Log ("first name is: " + firstName + " encrypted is: " + Encrypt(firstName));
}
public static string Encrypt (string toEncrypt) {
byte[] keyArray = UTF8Encoding.UTF8.GetBytes ("MysecretPassPhrase");
// 256-AES key
int numBytes = System.Text.Encoding.UTF8.GetBytes(toEncrypt).Length;
Debug.Log ("Bytes: " + numBytes);
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes (toEncrypt);
RijndaelManaged rDel = new RijndaelManaged ();
rDel.Key = keyArray;
rDel.BlockSize = 128;
rDel.Mode = CipherMode.CBC;
// http://msdn.microsoft.com/en-us/library/system.security.cryptography.ciphermode.aspx
rDel.Padding = PaddingMode.PKCS7;
// better lang support
ICryptoTransform cTransform = rDel.CreateEncryptor ();
byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String (resultArray, 0, resultArray.Length);
}
The error given above is "Key size not supported by algorithm". Your key array is 18 bytes (UTF8) which is 144 bits, not 128 bits as indicated by your BlockSize.
You must change the key to a valid size. See this article for more information.