daviddesmet / nacl.core Goto Github PK
View Code? Open in Web Editor NEWπ NaCl.Core, a cryptography library for .NET
License: MIT License
π NaCl.Core, a cryptography library for .NET
License: MIT License
Keep an eye on XChaCha RFC Draft repo and on the draft itself.
Hello,
I'm trying to use your code on small buffers for network encryption and the Decrypt function throws a CryptographyException "The ciphertext is too short."
I compared it to other ChaCha20Poly1305 implementations and removed the _snuffle.NonceSizeInBytes()
. I'm not even close to understanding the consequences but all your unit tests are still working as expected.
Is it safe to use the code that way?
Example:
public struct KeepAlivePacket {
public uint clientIndex;
public uint maxClients;
}
//in unit test
var packet = new KeepAlivePacket {
clientIndex = 0,
maxClients = 6
};
byte[] key = ByteUtils.Generate256BitKey();
byte[] add = EncryptionHelper.CreateAdditionalData(...);
byte[] nonce = EncryptionHelper.CreateNonce(...);
var chacha = new ChaCha20Poly1305(key);
byte[] encrypted = chacha.Encrypt(packetBuffer, additionalData, nonce);
byte[] decrypted = chacha.Decrypt(encrypted, additionalData, nonce);
I'd love to get a reply,
Cheers
Add support for .NET 5 once released.
Consider using modern .NET API types like Span and ReadOnlySpan.
More information at: All About Span: Exploring a New .NET Mainstay.
NOTE: It will require .NET Core 2.1; there's a System.Memory.dll package thatβs compatible with .NET Standard 1.1.
Hi,
The class ByteIntegerConverter
have methods like LoadLittleEndian32
and StoreLittleEndian32
which is not checking for system endianness (which is not guaranteed to be little-endian in .NET). In the old .NET days, we were checking System.BitConverter.IsLittleEndian
field to finding out system endianness and reversing the bytes to achieve the endianness that we were looking for, but in this modern .NET age we should consider using System.Buffers.BinaryPrimitives
class (my benchmarks showed me it is significantly faster than bitwise operations like <<
and ||
since it takes advantage of CPU instructions like rotl
and rotr
on X86 machines).
Implement Ed25519 by Daniel J. Bernstein, EdDSA signature scheme.
Microsoft have added support for AES-GCM and AES-CCM ciphers, implemented via System.Security.Cryptography.AesGcm
and System.Security.Cryptography.AesCcm
. These algorithms are the first Authenticated Encryption (AE) algorithms added to .NET Core 3.0 (starting from Preview 1). Since it will be supported out-of-the-box, I don't see the benefit of adding support for those.
The following code demonstrates using AesGcm cipher to encrypt and decrypt random data. The code for AesCcm would look almost identical (only the class variable names would be different):
// key should be: pre-known, derived, or transported via another channel, such as RSA encryption
byte[] key = new byte[16];
RandomNumberGenerator.Fill(key);
byte[] nonce = new byte[12];
RandomNumberGenerator.Fill(nonce);
// normally this would be your data
byte[] dataToEncrypt = new byte[1234];
byte[] associatedData = new byte[333];
RandomNumberGenerator.Fill(dataToEncrypt);
RandomNumberGenerator.Fill(associatedData);
// these will be filled during the encryption
byte[] tag = new byte[16];
byte[] ciphertext = new byte[dataToEncrypt.Length];
using (AesGcm aesGcm = new AesGcm(key))
{
aesGcm.Encrypt(nonce, dataToEncrypt, ciphertext, tag, associatedData);
}
// tag, nonce, ciphertext, associatedData should be sent to the other part
byte[] decryptedData = new byte[ciphertext.Length];
using (AesGcm aesGcm = new AesGcm(key))
{
aesGcm.Decrypt(nonce, ciphertext, tag, decryptedData, associatedData);
}
// do something with the data
// this should always print that data is the same
Console.WriteLine($"AES-GCM: Decrypted data is{(dataToEncrypt.SequenceEqual(decryptedData) ? "the same as" : "different than")} original data.");
There is a new System.Security.Cryptography.AesGcm API in .NET Core, it might be beneficial to add the same method signatures into NaCl.Core.
Note: this new API seems to interop to native OS libraries, I'm intrigued to see how they compare against the intrinsic-optimised NaCl.Core, so I will probably try this at some point.
Hello,
My library that uses NaCl.Core has 2 variants, one that uses NaCl.Core, and the other that uses the libsodium native library. The libsodium variant runs 4 times faster, but has deployment pitfalls where you have to ensure the correct native file is used for the processor architecture and OS. I've worked around those pitfalls but it got me wondering about optimization in NaCl.Core as a fully managed solution has less friction.
I was wondering if you had looked at the System.Runtime.Intrinsics.X86
namespace in .NET Core 3.0?
I am new to intrinsics so don't consider the following to be authoritative but I thought I'd present my experience as a data point for using intrinsics.
I did a proof of concept on an easy bit to update - the XOR in Snuffle.cs
(this doesn't improve performance much).
At the top:
#if NETCOREAPP3_0
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
#endif
In Process
:
using (var owner = MemoryPool<byte>.Shared.Rent(BLOCK_SIZE_IN_BYTES))
{
for (var i = 0; i < numBlocks; i++)
{
ProcessKeyStreamBlock(nonce, i + InitialCounter, owner.Memory.Span);
#if NETCOREAPP3_0
if (i == numBlocks - 1)
Xor(output, input, owner.Memory.Span, length % BLOCK_SIZE_IN_BYTES, offset, i); // last block
else
XorIntrinsic(output, input, owner.Memory.Span, BLOCK_SIZE_IN_BYTES, offset, i);
#else
if (i == numBlocks - 1)
Xor(output, input, owner.Memory.Span, length % BLOCK_SIZE_IN_BYTES, offset, i); // last block
else
Xor(output, input, owner.Memory.Span, BLOCK_SIZE_IN_BYTES, offset, i);
#endif
owner.Memory.Span.Clear();
}
}
New method at the bottom:
#if NETCOREAPP3_0
private static unsafe void XorIntrinsic(Span<byte> output, ReadOnlySpan<byte> input, ReadOnlySpan<byte> block, int len, int offset, int curBlock)
{
var blockOffset = curBlock * BLOCK_SIZE_IN_BYTES;
//To do - input length validation checks
fixed (byte* pOut = output, pInA = input, pInB = block)
{
byte* pOutEnd = pOut + offset + blockOffset + len;
byte* pOutCurrent = pOut + offset + blockOffset;
byte* pInACurrent = pInA + blockOffset;
byte* pInBCurrent = pInB;
while (pOutCurrent + 8 <= pOutEnd)
{
var inputAVector = Avx.LoadVector256(pInACurrent);
var inputBVector = Avx.LoadVector256(pInBCurrent);
var outputVector = Avx2.Xor(inputAVector, inputBVector);
Avx.Store(pOutCurrent, outputVector);
pOutCurrent += 8;
pInACurrent += 8;
pInBCurrent += 8;
}
}
}
#endif
That compiled and benchmarked successfully, running approximately the same speed, perhaps a tiny amount faster.
It seems that to fully implement intrinsics in the Snuffle.cs
class (and hence get large performance gains) ProcessKeyStreamBlock
would be the place to start, and hence the implementation of u0.h/u1.h/u4.h/u8.h
in this directory.
Whilst I don't have the bandwidth for a pull request that is a mass update to include intrinsics, if you were to establish a style/methodology for including intrinsics, I could contribute in parts when time allows.
Implement Curve25519 by Daniel J. Bernstein, for fast Diffie-Hellman key agreement.
Testing should be taking around 2 minutes but is taking longer than usual on Linux.
I had the same issue with another project when running against SDK 2.2.300 as specified here and here.
GitHub Actions CI result:
Test Run Successful.
Total tests: 121
Passed: 121
Total time: 7.7948 Minutes
Azure DevOps CI result:
Total tests: 121. Passed: 121. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 8.5036 Minutes
AppVeyor CI result (it took longer than it reports):
Test Run Successful.
Total tests: 121
Passed: 121
Total time: 2.2034 Minutes
Skip duplicates when pushing a NuGet package to Azure Artifacts by passing true
to allowPackageConflicts
.
- task: NuGetCommand@2
displayName: 'Push NuGet'
inputs:
command: 'push'
packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg;!$(Build.ArtifactStagingDirectory)/**/*.symbols.nupkg'
nuGetFeedType: 'internal'
publishVstsFeed: 'ffbd9fd0-ffca-4040-8576-0fa5065bd6d9/b465c74e-3671-458e-996f-8bbf45f957bc'
allowPackageConflicts: true
Hi,
The stackalloc
keyword and Span<T>
type can eliminate a lot of allocations in the library and removing the need of types like Array8
and Array16
.
The Snuffle base class's constructor's first parameter is in byte[] key
which doesn't make sense, in
is same as ref
keyword (which means a reference to the specified value rather than value itself as you know) with the difference that in
doesn't allow modifications to the value that being referenced (at the language level).
So what is happening here in this constructor is that we are passing a reference to a byte array (which arrays are references too) so the goal we are looking for (a read-only input or const char *key
in C) is not achieved here. In order to fix this problem, we have to replace the in byte[] key
with ReadOnlyMemory<byte> key
which introduces a lot of changes in the code plus it is a breaking change.
Regards.
When I read the authoritative source:
https://cr.yp.to/mac.html
It talks of a 16 byte nonce for Poly1305 MACs.
Using the code below to generate MACs, where is the nonce involved?
// Use the primitive to compute a tag
var tag = Poly1305.ComputeMac(key, data);
// ... or to verify a tag
Poly1305.VerifyMac(key, data, tag);
Thanks.
Hi,
Making the classes that are not going to become base classes like XChaCha20Poly1305
class
sealed
results in better performance as the virtual method calls become direct method calls.
Also, I have to point out this is a breaking change.
Regards.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.