J'ai un code de cryptage hérité en C# et maintenant je dois faire le même cryptage en JavaScript. J'ai fait quelques recherches et essayé 3 bibliothèques différentes, mais je n'ai pas pu obtenir les mêmes résultats. La dernière bibliothèque que j'ai utilisée est CryptoJS et je dois comprendre pourquoi je reçois des résultats différents.Les méthodes de cryptage C# & JS retournent des résultats différents
Voici les extraits de code:
code C#:
text = "chocolate";
PasswordHash = "hashhash";
SaltKey = "saltsaltsaltsa";
VIKey = "iviviviviviviviv";
byte[] plainTextBytes = Encoding.UTF8.GetBytes(text);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256/8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
byte[] cipherTextBytes;
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
cryptoStream.Close();
}
memoryStream.Close();
}
var result = Convert.ToBase64String(cipherTextBytes);
résultat ==> "8AbNsyyqHHfi/PEF/bbiew =="
code JavaScript:
pass = 'chocolate';
//Creating the Vector Key
var iv = CryptoJS.enc.Utf8.parse('iviviviviviviviv');
//Encoding the Password in from UTF8 to byte array
var passHash = CryptoJS.enc.Utf8.parse('hashhash');
//Encoding the Salt in from UTF8 to byte array
var Salt = CryptoJS.enc.Utf8.parse("saltsaltsaltsa");
//Creating the key in PBKDF2 format to be used during the encryption
var key128Bits1000Iterations = CryptoJS.PBKDF2(passHash, Salt, { keySize: 256/8, iterations: 1000 });
//Encrypting the string contained in cipherParams using the PBKDF2 key
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(pass), key128Bits1000Iterations, { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.ZeroPadding });
var result = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
résultat = "dpgTA41PD yrM8ef9C1c8iA == "
vous semblez utiliser 'Encoding.ASCII' en C# et 'CryptoJS.enc.Utf8' dans le JS ..? – stuartd
@stuartd - pensé à ce sujet, même comportement pour ASCII et UTF8 dans un scénario donné – Niro