Initial commit

master
Avril 5 years ago
commit 112345328c
Signed by: flanchan
GPG Key ID: 284488987C31F630

350
.gitignore vendored

@ -0,0 +1,350 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29519.87
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "libstenet", "libstenet\libstenet.csproj", "{80064396-C3F3-4D92-9FCF-7C44B52DBC6E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{0C90F432-198A-45FD-A1A8-A14DFB47FE6B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{80064396-C3F3-4D92-9FCF-7C44B52DBC6E}.Debug|Any CPU.ActiveCfg = Release|Any CPU
{80064396-C3F3-4D92-9FCF-7C44B52DBC6E}.Debug|Any CPU.Build.0 = Release|Any CPU
{80064396-C3F3-4D92-9FCF-7C44B52DBC6E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{80064396-C3F3-4D92-9FCF-7C44B52DBC6E}.Release|Any CPU.Build.0 = Release|Any CPU
{0C90F432-198A-45FD-A1A8-A14DFB47FE6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0C90F432-198A-45FD-A1A8-A14DFB47FE6B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0C90F432-198A-45FD-A1A8-A14DFB47FE6B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0C90F432-198A-45FD-A1A8-A14DFB47FE6B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4BF5692D-8290-4789-A4FB-DDAE5062B36A}
EndGlobalSection
EndGlobal

@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
namespace EncryptedNetwork
{
public unsafe struct AESKey
{
public const int KeySize = 32;
public const int IVSize = 16;
internal fixed byte key[KeySize];
internal fixed byte iv[IVSize];
/// <summary>
/// The Key (256 bit)
/// </summary>
public byte[] Key
{
get
{
byte[] bytes = new byte[KeySize];
fixed (byte* k = key)
{
Marshal.Copy((IntPtr)k, bytes, 0, KeySize);
}
return bytes;
}
set
{
if (value.Length != KeySize) throw new ArgumentException(nameof(value) + " must be exaclty " + KeySize + " bytes (not " + value.Length + ")");
fixed (byte* k = key)
{
Marshal.Copy(value, 0, (IntPtr)k, KeySize);
}
}
}
/// <summary>
/// The IV (128 bits)
/// </summary>
public byte[] IV
{
get
{
byte[] bytes = new byte[IVSize];
fixed (byte* k = iv)
{
Marshal.Copy((IntPtr)k, bytes, 0, IVSize);
}
return bytes;
}
set
{
if (value.Length != IVSize) throw new ArgumentException(nameof(value) + " must be exaclty " + IVSize + " bytes (not " + value.Length + ")");
fixed (byte* k = iv)
{
Marshal.Copy(value, 0, (IntPtr)k, IVSize);
}
}
}
/// <summary>
/// Binary serialisation of this key
/// </summary>
public byte[] BinaryData
{
get
{
return this.ToByteArrayUnmanaged();
}
set
{
if (value.Length < sizeof(AESKey)) throw new ArgumentException(nameof(value) + " must be at least " + sizeof(AESKey) + " bytes (not " + value.Length + ")");
fixed (AESKey* k = &this)
{
Marshal.Copy(value, 0, (IntPtr)k, sizeof(AESKey));
}
}
}
/// <summary>
/// Create a new key
/// </summary>
/// <returns>The new AES Key</returns>
public static AESKey NewKey()
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buffer = new byte[sizeof(AESKey)];
rng.GetBytes(buffer);
rng.Dispose();
return buffer.ToStructureUnmanaged<AESKey>();
}
/// <summary>
/// Set the key and iv to an AesCryptoServiceProvider
/// </summary>
/// <param name="r">The CSP</param>
public void ToCSP(AesCryptoServiceProvider r)
{
r.KeySize = 256;
r.BlockSize = 128;
r.Key = Key;
r.IV = IV;
}
/// <summary>
/// Get the key and iv from and AESCryptoServiceProvider
/// </summary>
/// <param name="r">The CSP</param>
public void FromCSP(AesCryptoServiceProvider r)
{
Key = r.Key;
IV = r.IV;
}
/// <summary>
/// Initialise a new AESKey from an AESCryptoServiceProvider
/// </summary>
/// <param name="aes">The AES key</param>
public AESKey(AesCryptoServiceProvider aes)
{
FromCSP(aes);
}
}
}

@ -0,0 +1,436 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Threading;
namespace EncryptedNetwork
{
internal interface IEncryptedContainer
{
EncryptedNetworkStream Parent { get; }
EncryptedNetworkStreamBlock WriteBlock();
EncryptedNetworkStreamBlock ReadBlock();
EncryptedNetworkStreamBlock ReadBlock(int msTimeout);
Task<EncryptedNetworkStreamBlock> ReadBlockAsync(CancellationToken cancel);
Task<EncryptedNetworkStreamBlock> ReadBlockAsync();
}
/// <summary>
/// An encrypted block container for an <see cref="EncryptedNetworkStream"/>.
/// </summary>
public abstract class EncryptedNetworkStreamBlock : BackedStream, IEncryptedContainer
{
internal EncryptedNetworkStreamBlock(Stream back) : base(back) { }
/// <summary>
/// The EncryptedNetworkStream that owns this block.
/// </summary>
public abstract EncryptedNetworkStream Parent { get; }
/// <summary>
/// Start a Read block synchronously with a milisecond timeout.
/// </summary>
/// <param name="msTimeout">The timeout</param>
/// <returns>The new Read block.</returns>
public abstract EncryptedNetworkStreamBlock ReadBlock(int msTimeout);
/// <summary>
/// Start a Read block synchronously.
/// </summary>
/// <returns>The new Read block.</returns>
public abstract EncryptedNetworkStreamBlock ReadBlock();
/// <summary>
/// Start a Write block.
/// </summary>
/// <returns></returns>
public abstract EncryptedNetworkStreamBlock WriteBlock();
/// <summary>
/// Start a Read block asynchronously.
/// </summary>
/// <param name="cancel">Token for cancellation.</param>
/// <returns>Awaitable Task for new Read block.</returns>
public async virtual Task<EncryptedNetworkStreamBlock> ReadBlockAsync(CancellationToken cancel)
{
return await Task.Run(ReadBlock);
}
/// <summary>
/// Start a Read block asynchronously.
/// </summary>
/// <returns>Awaitable Task for new Read block.</returns>
public virtual Task<EncryptedNetworkStreamBlock> ReadBlockAsync() => ReadBlockAsync(CancellationToken.None);
}
/// <summary>
/// Proveides RSA & AES cryptography wrapper over a <see cref="NetworkStream"/>.
/// </summary>
public class EncryptedNetworkStream : BackedStream, IEncryptedContainer
{
private class EncryptedReadBlock : EncryptedNetworkStreamBlock
{
private AesCryptoServiceProvider aes = null;
EncryptedNetworkStream ens;
public EncryptedReadBlock(BackedStream ens, IEncryptedContainer container)
: base(ens)
{
KeepBackingStreamAlive = true;
this.ens = container.Parent;
}
public override bool KeepBackingStreamAlive { get => true; set { if (!value) throw new NotSupportedException("Cannot set ReadBlock to dispose of its parent."); } }
public override EncryptedNetworkStream Parent => ens;
public async Task Initialise(CancellationToken cancel)
{
ens.ThrowIfNotExchanged();
aes = new AesCryptoServiceProvider();
try
{
var len = (await backing.BlockingReadValueUnmanagedAsync<int>(cancel)).NetOrd();
if (len <= 0)
throw new ArgumentException("Invalid length read. ("+len+")");
byte[] by = new byte[len];
await backing.BlockingReadAsync(by, 0, len, cancel);
var decrypted = ens.you.Decrypt(by, false);
var key = decrypted.ToStructureUnmanaged<AESKey>();
key.ToCSP(aes);
}
catch(Exception ex)
{
aes.Dispose();
aes = null;
throw ex;
}
}
public override int Read(byte[] buffer, int offset, int count)
=> ReadAsync(buffer, offset, count, CancellationToken.None).Sync();
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
static int roundUp(int numToRound, int multiple)
{
if (multiple == 0)
return numToRound;
int remainder = Math.Abs(numToRound) % multiple;
if (remainder == 0)
return numToRound;
if (numToRound < 0)
return -(Math.Abs(numToRound) - remainder);
return numToRound + multiple - remainder;
}
if (aes == null)
return await backing.ReadAsync(buffer, offset, count, cancellationToken);
else
{
byte[] byr = new byte[count % 16 == 0 ? count + 16 : roundUp(count, 16)];
await backing.BlockingReadAsync(byr, 0, byr.Length, cancellationToken);
using (var dec = aes.CreateDecryptor())
{
Array.Copy(dec.TransformFinalBlock(byr, 0, byr.Length), 0, buffer, offset, count);
return count;
}
}
}
public override void Write(byte[] buffer, int offset, int count)
=> backing.Write(buffer, offset, count);
public override EncryptedNetworkStreamBlock WriteBlock()
{
var w = new EncryptedWriteBlock(this, this);
w.Initialise();
return w;
}
public override EncryptedNetworkStreamBlock ReadBlock()
{
var r = new EncryptedReadBlock(this, this);
r.Initialise(CancellationToken.None).Sync();
return r;
}
public override EncryptedNetworkStreamBlock ReadBlock(int msTimeout)
{
var r = new EncryptedReadBlock(this, this);
r.Initialise(CancellationToken.None).Sync(msTimeout);
return r;
}
public async override Task<EncryptedNetworkStreamBlock> ReadBlockAsync(CancellationToken cancel)
{
var r = new EncryptedReadBlock(this, this);
await r.Initialise(cancel);
return r;
}
~EncryptedReadBlock() { Dispose(false); aes = null; }
}
private class EncryptedWriteBlock : EncryptedNetworkStreamBlock
{
private AesCryptoServiceProvider aes = null;
EncryptedNetworkStream ens;
public override EncryptedNetworkStream Parent => ens;
public override bool KeepBackingStreamAlive { get => true; set { if (!value) throw new NotSupportedException("Cannot set WriteBlock to dispose of its parent."); } }
public EncryptedWriteBlock(BackedStream ens, IEncryptedContainer container)
: base(ens)
{
KeepBackingStreamAlive = true;
this.ens = container.Parent;
}
public void Initialise()
{
ens.ThrowIfNotExchanged();
aes = new AesCryptoServiceProvider();
try
{
var key = AESKey.NewKey();
key.ToCSP(aes);
var encrypted = ens.them.Encrypt(key.ToByteArrayUnmanaged(), false);
var size = encrypted.Length.NetOrd();
backing.WriteValueUnmanaged(size);
backing.Write(encrypted, 0, encrypted.Length);
}
catch(Exception ex)
{
aes.Dispose();
aes = null;
throw ex;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
aes.Dispose();
}
public override int Read(byte[] buffer, int offset, int count)
=> backing.Read(buffer, offset, count);
public override void Write(byte[] buffer, int offset, int count)
{
if (aes == null)
backing.Write(buffer, offset, count);
else
{
using(var enc = aes.CreateEncryptor())
{
var ebuf = enc.TransformFinalBlock(buffer, offset, count);
backing.Write(ebuf, 0, ebuf.Length);
}
}
}
public override EncryptedNetworkStreamBlock WriteBlock()
{
var w = new EncryptedWriteBlock(this, this);
w.Initialise();
return w;
}
public override EncryptedNetworkStreamBlock ReadBlock()
{
var r = new EncryptedReadBlock(this, this);
r.Initialise(CancellationToken.None).Sync();
return r;
}
public override EncryptedNetworkStreamBlock ReadBlock(int msTimeout)
{
var r = new EncryptedReadBlock(this, this);
r.Initialise(CancellationToken.None).Sync(msTimeout);
return r;
}
public async override Task<EncryptedNetworkStreamBlock> ReadBlockAsync(CancellationToken cancel)
{
var r = new EncryptedReadBlock(this, this);
await r.Initialise(cancel);
return r;
}
~EncryptedWriteBlock() { Dispose(false); aes = null; }
}
private readonly RSACryptoServiceProvider you;
private RSACryptoServiceProvider them;
/// <summary>
/// Your local RSA CSP (with both public and private keys.)
/// </summary>
public RSACryptoServiceProvider PrivateCSP => you;
/// <summary>
/// Your local RSA public key.
/// </summary>
public RSAPublicKey LocalPublicKey => RSAPublicKey.FromCSP(you);
/// <summary>
/// Remote endpoint's RSA public key.
/// </summary>
/// <exception cref="ArgumentException">Thrown if RSA public keys have not been exchanged yet.</exception>
public RSAPublicKey RemotePublicKey => them == null ? throw ThrowNotYetExchangedException() : RSAPublicKey.FromCSP(them);
private static ArgumentException ThrowNotYetExchangedException() => throw new ArgumentException("Keys not yet exchanged.");
private void ThrowIfNotExchanged() { if (!Exchanged) ThrowNotYetExchangedException(); }
/// <summary>
/// Have RSA public keys been exchanged yet?
/// </summary>
public bool Exchanged => them != null;
EncryptedNetworkStream IEncryptedContainer.Parent => this;
/// <summary>
/// Initialise a new <see cref="EncryptedNetworkStream"/> from a <seealso cref="NetworkStream"/>
/// </summary>
/// <param name="stream">The Stream to set backing for.</param>
/// <param name="key">Your local RSA CSP to use for private a public keys.</param>
public EncryptedNetworkStream(NetworkStream stream, RSACryptoServiceProvider key)
:base(stream)
{
you = key;
}
/// <summary>
/// Initialise a new <see cref="EncryptedNetworkStream"/> from a <seealso cref="NetworkStream"/>
/// </summary>
/// <param name="stream">The Stream to set backing for.</param>
public EncryptedNetworkStream(NetworkStream stream) : this(stream, new RSACryptoServiceProvider()) { }
/// <summary>
/// Initialise a new <see cref="EncryptedNetworkStream"/> from a <seealso cref="Socket"/>
/// </summary>
/// <param name="stream">The Socket to set backing for. (NOTE: Closes the socket on dispose)</param>
/// <param name="key">Your local RSA CSP to use for private a public keys.</param>
public EncryptedNetworkStream(Socket sock, RSACryptoServiceProvider key)
: this(new NetworkStream(sock, true), key) { }
/// <summary>
/// Initialise a new <see cref="EncryptedNetworkStream"/> from a <seealso cref="Socket"/>
/// </summary>
/// <param name="stream">The Socket to set backing for. (NOTE: Closes the socket on dispose)</param>
public EncryptedNetworkStream(Socket sock)
: this(sock, new RSACryptoServiceProvider()) { }
/// <summary>
/// Exchange the RSA public keys asynchronously.
/// </summary>
/// <returns>Awaitable Task that completes when the operation is successful.</returns>
public Task ExchangeAsync() => ExchangeAsync(CancellationToken.None);
/// <summary>
/// Exchange the RSA public keys asynchronously.
/// </summary>
/// <param name="cancel">Cancellation token.</param>
/// <returns>Awaitable Task that completes when the operation is successful.</returns>
public async Task ExchangeAsync(CancellationToken cancel)
{
backing.WriteValueUnmanaged(LocalPublicKey);
try
{
var pub = await backing.BlockingReadValueUnmanagedAsync<RSAPublicKey>(cancel);
them??= new RSACryptoServiceProvider();
pub.ToCSP(them);
}
catch (Exception ex)
{
them?.Dispose();
them = null;
throw ex;
}
}
/// <summary>
/// Exchange RSA public keys synchronously with a milisecond timeout.
/// </summary>
/// <param name="msTimeout">The timout.</param>
public void Exchange(int msTimeout)
=> ExchangeAsync().Sync(msTimeout);
/// <summary>
/// Exchange RSA public keys synchronously.
/// </summary>
public void Exchange()
=> ExchangeAsync().Sync();
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
/// <summary>
/// Read unencrypted data from the backing stream.
/// </summary>
/// <param name="buffer">Buffer to read into.</param>
/// <param name="offset">Offset of buffer.</param>
/// <param name="count">Number of bytes to read into buffer.</param>
/// <returns>The number of bytes successfully read.</returns>
public override int Read(byte[] buffer, int offset, int count)
=> backing.Read(buffer, offset, count);
/// <summary>
/// Write unencrypted data to the backing stream.
/// </summary>
/// <param name="buffer">Buffer to write from.</param>
/// <param name="offset">Offset of buffer.</param>
/// <param name="count">Number of bytes to write from buffer.</param>
public override void Write(byte[] buffer, int offset, int count)
=> backing.Write(buffer, offset, count);
/// <summary>
/// Create a new encrypted write block for this stream.
/// </summary>
/// <returns>The new WriteBlock.</returns>
public EncryptedNetworkStreamBlock WriteBlock()
{
var w = new EncryptedWriteBlock(this, this);
w.Initialise();
return w;
}
/// <summary>
/// Create a new encrypted read block for this stream synchronously.
/// </summary>
/// <returns>The new ReadBlock.</returns>
public EncryptedNetworkStreamBlock ReadBlock()
{
var r = new EncryptedReadBlock(this, this);
r.Initialise(CancellationToken.None).Sync();
return r;
}
/// <summary>
/// Create a new encrypted read block for this stream synchronously with a milisecond timeout.
/// </summary>
/// <param name="msTimeout">The timeout.</param>
/// <returns>The new ReadBlock.</returns>
public EncryptedNetworkStreamBlock ReadBlock(int msTimeout)
{
var r = new EncryptedReadBlock(this, this);
r.Initialise(CancellationToken.None).Sync(msTimeout);
return r;
}
/// <summary>
/// Create a new encrypted read block for this stream asynchronously.
/// </summary>
/// <param name="cancel">Cancellation token.</param>
/// <returns>Awaitable Task that completes and returns the new ReadBlock.</returns>
public async Task<EncryptedNetworkStreamBlock> ReadBlockAsync(CancellationToken cancel)
{
var r = new EncryptedReadBlock(this, this);
await r.Initialise(cancel);
return r;
}
/// <summary>
/// Create a new encrypted read block for this stream asynchronously.
/// </summary>
/// <returns>Awaitable Task that completes and returns the new ReadBlock.</returns>
public Task<EncryptedNetworkStreamBlock> ReadBlockAsync() => ReadBlockAsync(CancellationToken.None);
}
}

@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace EncryptedNetwork
{
/// <summary>
/// Provides a wrapper to override methods of a Stream
/// </summary>
public abstract class BackedStream : Stream
{
protected Stream backing;
/// <summary>
/// The Stream used as the backing
/// </summary>
public Stream Backing { get { return backing; } }
/// <summary>
/// Keep the backing stream alive after the class is disposed (default <c>false</c>)
/// </summary>
public virtual bool KeepBackingStreamAlive { get; set; } = false;
/// <summary>
/// Initialise an instance of the BackedStream class
/// </summary>
/// <param name="s">The initial Stream</param>
public BackedStream(Stream s)
{
backing = s;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (!KeepBackingStreamAlive) backing.Dispose();
}
}
#region Stream Overrides
public override bool CanRead
{
get { return Backing.CanRead; }
}
public override bool CanSeek
{
get { return Backing.CanSeek; }
}
public override bool CanWrite
{
get { return Backing.CanWrite; }
}
public override void Flush()
{
Backing.Flush();
}
public override long Length
{
get { return Backing.Length; }
}
public override long Position
{
get
{
return Backing.Position;
}
set
{
Backing.Position = value;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
return Backing.Seek(offset, origin);
}
public override void SetLength(long value)
{
Backing.SetLength(value);
}
#endregion
}
internal static class Extensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void WriteValueUnmanaged<T>(this Stream s, T t) where T : unmanaged
{
byte[] buffer = new byte[sizeof(T)];
fixed (byte* ptr = buffer)
{
*(T*)ptr = t;
}
s.Write(buffer, 0, buffer.Length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T ReadValueUnmanaged<T>(this Stream s) where T : unmanaged
{
T output;
byte[] buffer = new byte[sizeof(T)];
s.Read(buffer, 0, buffer.Length);
fixed (byte* ptr = buffer)
{
output = *(T*)ptr;
}
return output;
}
public static unsafe T SwapByteOrder<T>(this T v) where T: unmanaged
{
Span<byte> b = new Span<byte>(&v, sizeof(T));
b.Reverse();
return v;
}
/*public static unsafe T Little<T>(this T v) where T : unmanaged
{
if (BitConverter.IsLittleEndian) return v;
else return v.SwapByteOrder();
}*/
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T NetOrd<T>(this T v) where T : unmanaged
{
if (!BitConverter.IsLittleEndian) return v;
else return v.SwapByteOrder();
}
public static T Sync<T>(this Task<T> task, int timeout)
{
task.Wait(timeout);
if (task.IsFaulted)
throw task.Exception;
return task.Result;
}
public static T Sync<T>(this Task<T> task)
{
task.Wait();
if (task.IsFaulted)
throw task.Exception;
return task.Result;
}
public static void Sync(this Task task)
{
task.Wait();
if (task.IsFaulted)
throw task.Exception;
}
public static void Sync(this Task task, int msTimeout)
{
task.Wait(msTimeout);
if (task.IsFaulted)
throw task.Exception;
}
public static async Task<T> BlockingReadValueUnmanagedAsync<T>(this Stream s, System.Threading.CancellationToken? cancel) where T : unmanaged
{
int size;
unsafe
{
size = sizeof(T);
}
byte[] buffer = new byte[size];
await s.BlockingReadAsync(buffer, 0, size, cancel);
return buffer.ToStructureUnmanaged<T>();
}
public static async Task BlockingReadAsync(this Stream s, byte[] to, int offset, int length, System.Threading.CancellationToken? cancel)
{
int read = 0;
while ((read += await (cancel == null ? s.ReadAsync(to, offset + read, length - read) : s.ReadAsync(to, offset + read, length - read, cancel.Value))) < length) cancel?.ThrowIfCancellationRequested();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T ToStructureUnmanaged<T>(this byte[] bytes) where T : unmanaged
{
fixed (byte* ptr = bytes)
{
return *(T*)ptr;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe byte[] ToByteArrayUnmanaged<T>(this T t) where T : unmanaged
{
byte[] o = new byte[sizeof(T)];
fixed (byte* ptr = o)
{
*(T*)ptr = t;
}
return o;
}
}
}

@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
namespace EncryptedNetwork
{
public unsafe struct RSAPublicKey
{
public const int ModulusSize = 128;
public const int ExponentSize = 3;
internal fixed byte mod[ModulusSize];
internal fixed byte exp[ExponentSize];
/// <summary>
/// The modulus of this key
/// </summary>
public byte[] Modulus
{
get
{
byte[] bytes = new byte[ModulusSize];
fixed (byte* m = mod)
{
Marshal.Copy((IntPtr)m, bytes, 0, ModulusSize);
}
return bytes;
}
set
{
if (value.Length != ModulusSize) throw new ArgumentException(nameof(value) + " must be exaclty " + ModulusSize + " bytes (not " + value.Length + ")");
fixed (byte* m = mod)
{
Marshal.Copy(value, 0, (IntPtr)m, ModulusSize);
}
}
}
/// <summary>
/// The public exponent of this key
/// </summary>
public byte[] Exponent
{
get
{
byte[] bytes = new byte[ExponentSize];
fixed (byte* m = exp)
{
Marshal.Copy((IntPtr)m, bytes, 0, ExponentSize);
}
return bytes;
}
set
{
if (value.Length != ExponentSize) throw new ArgumentException(nameof(value) + " must be exaclty " + ExponentSize + " bytes (not " + value.Length + ")");
fixed (byte* m = exp)
{
Marshal.Copy(value, 0, (IntPtr)m, ExponentSize);
}
}
}
/// <summary>
/// Binary serialisation of this key
/// </summary>
public byte[] BinaryData
{
get
{
return this.ToByteArrayUnmanaged();
}
set
{
if (value.Length < sizeof(RSAPublicKey)) throw new ArgumentException(nameof(value) + " must be at least " + sizeof(RSAPublicKey) + " bytes (not " + value.Length + ")");
fixed (RSAPublicKey* k = &this)
{
Marshal.Copy(value, 0, (IntPtr)k, sizeof(RSAPublicKey));
}
}
}
/// <summary>
/// Set the public key to a RSACryptoServiceProvider
/// </summary>
/// <param name="csp">The CSP to set the key to</param>
public void ToCSP(RSACryptoServiceProvider csp)
{
var p = csp.ExportParameters(false);
p.Modulus = Modulus;
p.Exponent = Exponent;
csp.ImportParameters(p);
}
/// <summary>
/// Get the public key information from an RSACryptoServiceProvider and return it in an RSAPublicKey struct
/// </summary>
/// <param name="csp">The CSP</param>
/// <returns>A new RSAPublicKey struct</returns>
public static RSAPublicKey FromCSP(RSACryptoServiceProvider csp)
{
RSAPublicKey rp = new RSAPublicKey();
var p = csp.ExportParameters(false);
rp.Modulus = p.Modulus;
rp.Exponent = p.Exponent;
return rp;
}
public static implicit operator byte[](RSAPublicKey rp)
{
return rp.ToByteArrayUnmanaged();
}
public static explicit operator RSAPublicKey(byte[] byt)
{
return byt.ToStructureUnmanaged<RSAPublicKey>();
}
}
}

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<RootNamespace>EncryptedNetwork</RootNamespace>
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<Version>3.0.0</Version>
<Authors>Avril</Authors>
<Company />
<Description>Simple RSA &amp; AES wrapper around NetworkStream</Description>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Optimize>true</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
</Project>

@ -0,0 +1,112 @@
using System;
using EncryptedNetwork;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace test
{
class Program
{
static async Task client()
{
try
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await sock.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 24444));
using (var ens = new EncryptedNetworkStream(sock))
{
await ens.ExchangeAsync();
using(var read = await ens.ReadBlockAsync())
{
Console.WriteLine(await read.ReadStringAsync());
using (var write = read.WriteBlock())
{
write.WriteString("World.");
}
}
}
}
catch(Exception ex)
{
Console.WriteLine("CLIENT: " + ex.Message);
}
}
static Task server()
{
return Task.Run(async () =>
{
TcpListener listen = new TcpListener(24444);
listen.Start();
Task c = client();
while(true)
{
var sock = await listen.AcceptSocketAsync();
using(var ens = new EncryptedNetworkStream(sock))
{
await ens.ExchangeAsync();
using(var write = ens.WriteBlock())
{
write.WriteString("Hello");
using (var read = await write.ReadBlockAsync())
{
Console.WriteLine(await read.ReadStringAsync());
}
}
}
break;
}
listen.Stop();
await c;
});
}
static void Main(string[] args)
{
var serv = server();
serv.Wait();
if (serv.IsFaulted)
Console.WriteLine("SERVER FAILED: " + serv.Exception.Message);
Console.ReadKey();
}
}
static class Extensions
{
public static void WriteString(this Stream stream, string str)
{
byte[] buf = System.Text.Encoding.UTF8.GetBytes(str);
var l = buf.Length;
var num = BitConverter.GetBytes(l);
stream.Write(num, 0, sizeof(int));
stream.Write(buf, 0, buf.Length);
}
public static async Task<string> ReadStringAsync(this Stream stream)
{
byte[] num = new byte[sizeof(int)];
await stream.ReadAsync(num, 0, sizeof(int));
int l = BitConverter.ToInt32(num, 0);
if (l <= 0) throw new ArgumentException(l + " not valid length for string.");
byte[] buf = new byte[l];
await stream.ReadAsync(buf, 0, l);
return System.Text.Encoding.UTF8.GetString(buf);
}
}
}

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\libstenet\libstenet.csproj" />
</ItemGroup>
</Project>
Loading…
Cancel
Save