public void EncryptToStream <T>(T obj, Stream stream, string password) { stream.Seek(0, SeekOrigin.Begin); var keyBytes = GetRestructuredKeyBytes(password); // Generate new IV for each new saving using var aesObj = Aes.Create(); var ivBytes = aesObj.IV; // Get copy and serialize var jsonText = JsonSerializer.Serialize(obj); var encryptedBytes = AesCryptographyHelper.EncryptStringToBytes(jsonText, keyBytes, ivBytes); using var bw = new BinaryWriter(stream); bw.Write(ivBytes); bw.Write(encryptedBytes); }
public T DecryptFromStream <T>(Stream stream, string password) { stream.Seek(0, SeekOrigin.Begin); var br = new BinaryReader(stream); var ivLength = AesCryptographyHelper.IVLength; var ivBytes = new byte[ivLength]; br.Read(ivBytes); var encryptedBytes = new byte[stream.Length - ivLength]; br.Read(encryptedBytes); // During loading, it's required to set key bytes for future var keyBytes = GetRestructuredKeyBytes(password); var jsonText = AesCryptographyHelper.DecryptStringFromBytes(encryptedBytes, keyBytes, ivBytes); return(JsonSerializer.Deserialize <T>(jsonText)); }