Using the same encryption key and IV, I am getting varying results between the two encryption libraries.
JSvar crypto = {
var encryptionKey,
password,
salt,
cryptoParams = {
iterations: 1000,
keyLength: 256
};
function computeKey() {
// Added a func to misc that uses SHA1 rather than SHA256 as
// .NET's RFC2898DeriveBytes class uses SHA1
encryptionKey = sjcl.misc.pbkdf2_sha1(password, salt, cryptoParams.iterations, cryptoParams.keyLength);
encryptionKey = new sjcl.cipher.aes(encryptionKey);
}
function encrypt(message) {
// Will eventually use randomWords
var iv = sjcl.codec.hex.toBits('8291ff107e798a298291ff107e798a29');
// Only compute key once
if (encryptionKey === undefined) {
computeKey();
}
message = sjcl.codec.utf8String.toBits(message);
// Do the encryption
encryptedMessage = sjcl.mode.ccm.encrypt(encryptionKey, message, iv);
// Using this as a means to compare results
encryptedMessage = sjcl.codec.bytes.fromBits(encryptedMessage);
// Generally I will encode the bytes of the IV into encryptedMessage
// That is omitted here as just the result of the encryption-to-bytes
// already differs
return encryptedMessage;
}
return {
encrypt: encrypt
};
};
public static string AESEncrypt(byte[] unencryptedData, byte[] encryptionKey)
{
// Same as var iv = sjcl.codec.hex.toBits('8291ff107e798a298291ff107e798a29');
byte[] initializationVector = new byte[] { 130, 145, 255, 16, 126, 121, 138, 41, 130, 145, 255, 16, 126, 121, 138, 41 };
// Encrypt the bytes.
byte[] encryptedData = AESEncrypt(unencryptedData, encryptionKey, initializationVector);
// Convert the bytes into a base 64 string.
string encryptedString = System.Convert.ToBase64String(encryptedData);
return encryptedString;
}
private static byte[] AESEncrypt(byte[] inputData, byte[] key, byte[] initializationVector)
{
// Create the object that will do the encryption or decryption.
using (SymmetricAlgorithm algorithm = Rijndael.Create())
{
// Set the key and initialization vector.
algorithm.Key = key;
algorithm.IV = initializationVector;
using (ICryptoTransform transform = algorithm.CreateEncryptor())
{
// Create a CryptoStream that we'll use to write to the memory stream.
using (MemoryStream memoryStream = new MemoryStream())
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
{
// Write the data to encrypt or decrypt it.
cryptoStream.Write(inputData, 0, inputData.Length);
cryptoStream.Close();
// Now get the encrypted or decrypted data from the MemoryStream.
byte[] encryptedDecryptedData = memoryStream.ToArray();
return encryptedDecryptedData;
}
}
}
}