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.Authentication;
5using System.Threading.Tasks;
7
8namespace Waher.Security
9{
13 public static class Crypto
14 {
18 public const SslProtocols SecureTls = (SslProtocols)((int)SslProtocols.Tls12 | 12288 /* TLS 1.3 */);
19
23 public const SslProtocols TlsOnly = (SslProtocols)((int)SslProtocols.Tls | (int)SslProtocols.Tls11 | (int)SslProtocols.Tls12 | 12288 /* TLS 1.3 */);
24
31 public static Task CryptoTransform(ICryptoTransform Transform, Stream Source, Stream Destination)
32 {
33 return CryptoTransform(Transform, Source, Destination, 65536);
34 }
35
43 public static async Task CryptoTransform(ICryptoTransform Transform, Stream Source, Stream Destination, int BufferSize)
44 {
45 if (BufferSize <= 0)
46 throw new ArgumentException("Invalid buffer size.", nameof(BufferSize));
47
48 long l = Source.Length;
49
50 BufferSize = (int)Math.Min(l, BufferSize);
51
52 byte[] Input = new byte[BufferSize];
53 byte[] Output = new byte[BufferSize];
54 int j;
55
56 while (l > 0)
57 {
58 j = (int)Math.Min(BufferSize, l);
59 await Source.ReadAllAsync(Input, 0, j);
60
61 l -= j;
62 if (l <= 0)
63 {
64 Output = Transform.TransformFinalBlock(Input, 0, j);
65 await Destination.WriteAsync(Output, 0, Output.Length);
66 }
67 else
68 {
69 j = Transform.TransformBlock(Input, 0, j, Output, 0);
70 await Destination.WriteAsync(Output, 0, j);
71 }
72 }
73 }
74
82 public static async Task<bool> CopyAsync(Stream From, Stream To, long DataLen)
83 {
84 if (DataLen > 0)
85 {
86 int BufSize = (int)Math.Min(DataLen, 65536);
87 byte[] Buffer = new byte[BufSize];
88
89 while (DataLen > 0)
90 {
91 if (DataLen < BufSize)
92 BufSize = (int)DataLen;
93
94 if (await From.TryReadAllAsync(Buffer, 0, BufSize) != BufSize)
95 return false;
96
97 await To.WriteAsync(Buffer, 0, BufSize);
98 DataLen -= BufSize;
99 }
100 }
101
102 return true;
103 }
104 }
105}
Helper methods for encrypting and decrypting streams of data.
Definition: Crypto.cs:14
static async Task CryptoTransform(ICryptoTransform Transform, Stream Source, Stream Destination, int BufferSize)
Transforms a stream of data.
Definition: Crypto.cs:43
const SslProtocols SecureTls
TLS 1.2 & 1.3
Definition: Crypto.cs:18
const SslProtocols TlsOnly
TLS 1.0, 1.1, 1.2 & 1.3
Definition: Crypto.cs:23
static async Task< bool > CopyAsync(Stream From, Stream To, long DataLen)
Copies DataLen number of bytes from From to To .
Definition: Crypto.cs:82
static Task CryptoTransform(ICryptoTransform Transform, Stream Source, Stream Destination)
Transforms a stream of data.
Definition: Crypto.cs:31