Skip to content

Commit

Permalink
Merge pull request #76 from TRUMPF-IoT/fix/avoid-decode-in-filetransfer
Browse files Browse the repository at this point in the history
Avoid additional decode to calculate fingerprint
  • Loading branch information
berndbr authored Dec 5, 2023
2 parents a7f41e9 + e14949b commit 1663ee2
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions src/Toolbox/SAF.Toolbox/Filetransfer/TransportFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public class TransportFile

internal string Content { get; set; } = string.Empty;
internal long OriginalLength { get; set; }
internal string? Fingerprint { get; set; }

public string Name { get; }
public string? MimeType { get; }
Expand All @@ -27,7 +28,7 @@ public TransportFile(string name, string? mimeType = null, IDictionary<string, s
Properties = properties;
}

public void ReadFrom(Stream stream) => (Content, OriginalLength) = Encode(stream);
public void ReadFrom(Stream stream) => (Content, OriginalLength, Fingerprint) = Encode(stream);

public void WriteTo(Stream stream) => Decode(stream, Content);

Expand All @@ -45,9 +46,14 @@ public IDictionary<string, string> ToSerializableProperties()
properties["Content"] = Content;
properties["OriginalLength"] = $"{OriginalLength}";

using var ms = new MemoryStream();
Decode(ms, Content);
properties["Fingerprint"] = GenerateFingerprint(ms);
if (string.IsNullOrEmpty(Fingerprint))
{
using var ms = new MemoryStream();
Decode(ms, Content);
Fingerprint = GenerateFingerprint(ms);
}

properties["Fingerprint"] = Fingerprint;

return properties;
}
Expand All @@ -68,18 +74,26 @@ public bool Verify()
return StringComparer.OrdinalIgnoreCase.Compare(hash, fingerprint) == 0;
}

private static (string encodedContent, long originalLength) Encode(Stream stream)
private (string encodedContent, long originalLength, string fingerprint) Encode(Stream stream)
{
var fingerprint = GenerateFingerprint(stream);
var originalLength = stream.Position;
stream.Seek(0, SeekOrigin.Begin);

var encodedContent = EncodeStream(stream);
return (encodedContent, originalLength, fingerprint);
}

private static string EncodeStream(Stream stream)
{
using var ms = new MemoryStream();
using var cs = new CryptoStream(ms, new ToBase64Transform(), CryptoStreamMode.Write);
stream.CopyTo(cs);
var originalLength = stream.Position;

cs.FlushFinalBlock();
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(ms);
return (reader.ReadToEnd(), originalLength);
return reader.ReadToEnd();
}

private static void Decode(Stream stream, string content)
Expand Down

0 comments on commit 1663ee2

Please sign in to comment.