/// <inheritdoc/> public byte[] Protect(byte[] userData) { byte[] dataHash; using (var sha = _sha256Provider.Create()) { dataHash = sha.ComputeHash(userData); } using (var algorithm = _aesProvider.Create()) { algorithm.Key = _keyMaterial; algorithm.GenerateIV(); using (var encryptor = algorithm.CreateEncryptor(algorithm.Key, algorithm.IV)) { using (var msEncrypt = new MemoryStream()) { msEncrypt.Write(algorithm.IV, 0, 16); using (var stream = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (var writer = new BinaryWriter(stream)) { writer.Write(dataHash); writer.Write(userData.Length); writer.Write(userData); } } return(msEncrypt.ToArray()); } } } }
public AesDataProtector(IAesProvider aesProvider, ISha256Provider sha256Provider, string key, string primaryPurpose, string[] specificPurposes) { _aesProvider = aesProvider; _sha256Provider = sha256Provider; _appKey = key; using (var sha = _sha256Provider.Create()) { using (var writer = new BinaryWriter(new CryptoStream(new MemoryStream(), sha, CryptoStreamMode.Write), new UTF8Encoding(false, true))) { writer.Write(key); writer.Write(primaryPurpose); if (specificPurposes != null) { foreach (var purpose in specificPurposes) { writer.Write(purpose); } } } _keyMaterial = sha.Hash; } }