Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
Crypto.cs
1using System;
2using System.IO;
3using System.Security.Cryptography;
4using System.Threading.Tasks;
5
6namespace Waher.Security
7{
11 public static class Crypto
12 {
19 public static Task CryptoTransform(ICryptoTransform Transform, Stream Source, Stream Destination)
20 {
21 return CryptoTransform(Transform, Source, Destination, 65536);
22 }
23
31 public static async Task CryptoTransform(ICryptoTransform Transform, Stream Source, Stream Destination, int BufferSize)
32 {
33 if (BufferSize <= 0)
34 throw new ArgumentException("Invalid buffer size.", nameof(BufferSize));
35
36 long l = Source.Length;
37
38 BufferSize = (int)Math.Min(l, BufferSize);
39
40 byte[] Input = new byte[BufferSize];
41 byte[] Output = new byte[BufferSize];
42 int j;
43
44 while (l > 0)
45 {
46 j = (int)Math.Min(BufferSize, l);
47 if (await Source.ReadAsync(Input, 0, j) != j)
48 throw new IOException("Unexpected end of file.");
49
50 l -= j;
51 if (l <= 0)
52 {
53 Output = Transform.TransformFinalBlock(Input, 0, j);
54 await Destination.WriteAsync(Output, 0, Output.Length);
55 }
56 else
57 {
58 j = Transform.TransformBlock(Input, 0, j, Output, 0);
59 await Destination.WriteAsync(Output, 0, j);
60 }
61 }
62 }
63
71 public static async Task<bool> CopyAsync(Stream From, Stream To, long DataLen)
72 {
73 if (DataLen > 0)
74 {
75 int BufSize = (int)Math.Min(DataLen, 65536);
76 byte[] Buffer = new byte[BufSize];
77
78 while (DataLen > 0)
79 {
80 if (DataLen < BufSize)
81 BufSize = (int)DataLen;
82
83 if (await From.ReadAsync(Buffer, 0, BufSize) != BufSize)
84 return false;
85
86 await To.WriteAsync(Buffer, 0, BufSize);
87 DataLen -= BufSize;
88 }
89 }
90
91 return true;
92 }
93
94 }
95}
Helper methods for encrypting and decrypting streams of data.
Definition: Crypto.cs:12
static async Task CryptoTransform(ICryptoTransform Transform, Stream Source, Stream Destination, int BufferSize)
Transforms a stream of data.
Definition: Crypto.cs:31
static async Task< bool > CopyAsync(Stream From, Stream To, long DataLen)
Copies DataLen number of bytes from From to To .
Definition: Crypto.cs:71
static Task CryptoTransform(ICryptoTransform Transform, Stream Source, Stream Destination)
Transforms a stream of data.
Definition: Crypto.cs:19