Repository navigation
Description
Rationale
There is a general need for a number of ciphers for encryption. Todays mix of interfaces and classes has become a little disjointed. Also there is no support for AEAD style ciphers as they need the ability to provide extra authentication information. The current designs are also prone to allocation and these are hard to avoid due to the returning arrays.
Proposed API
A general purpose abstract base class that will be implemented by concrete classes. This will allow for expansion and also by having a class rather than static methods we have the ability to make extension methods as well as hold state between calls. The API should allow for recycling of the class to allow for lower allocations (not needing a new instance each time, and to catch say unmanaged keys). Due to the often unmanaged nature of resources that are tracked the class should implement IDisposable
public abstract class Cipher : IDisposable
{
public virtual int TagSize { get; }
public virtual int IVSize { get; }
public virtual int BlockSize { get; }
public virtual bool SupportsAssociatedData { get; }
public abstract void Init(ReadOnlySpan<byte> key, ReadOnlySpan<byte> iv);
public abstract void Init(ReadOnlySpan<byte> iv);
public abstract int Update(ReadOnlySpan<byte> input, Span<byte> output);
public abstract int Finish(ReadOnlySpan<byte> input, Span<byte> output);
public abstract void AddAssociatedData(ReadOnlySpan<byte> associatedData);
public abstract int GetTag(Span<byte> span);
public abstract void SetTag(ReadOnlySpan<byte> tagSpan);
}Example Usage
(the input/output source is a mythical span based stream like IO source)
using (var cipher = new AesGcmCipher(bitsize: 256))
{
cipher.Init(myKey, nonce);
while (!inputSource.EOF)
{
var inputSpan = inputSource.ReadSpan(cipher.BlockSize);
cipher.Update(inputSpan);
outputSource.Write(inputSpan);
}
cipher.AddAssociatedData(extraInformation);
cipher.Finish(finalBlockData);
cipher.GetTag(tagData);
}API Behaviour
- If get tag is called before finish a [exception type?] should be thrown and the internal state should be set to invalid
- If the tag is invalid on finish for decrypt it should be an exception thrown
- Once finished is called, a call to anything other than one of the Init methods will throw
- Once Init is called, a second call without "finishing" will throw
- If the type expects an key supplied (a straight "new'd" up instance) if the Initial "Init" call only has an IV it will throw
- If the type was generated say from a store based key and you attempt to change the key via Init and not just the IV it will throw
- If get tag is not called before dispose or Init should an exception be thrown? To stop the user not collecting the tag by accident?
Reference dotnet/corefx#7023
Updates
- Changed nonce to IV.
- Added behaviour section
- Removed the single input/output span cases from finish and update, they can just be extension methods
- Changed a number of spans to readonlyspan as suggested by @bartonjs
- Removed Reset, Init with IV should be used instead
Activity
sdrapkin commentedon Aug 29, 2017
Quick-to-judge feedback on the proposed API (trying to be helpful):
Span<T>is not in NetStandard2.As a proof of AEAD API sanity, the first implementation of such proposed API should not be AES-GCM, but the classic/default AES-CBC with an HMAC tag. The simple reason for it is that anyone can build AES-CBC+HMAC AEAD implementation today, with simple, existing, well-known .NET classes. Let's get a boring old [AES-CBC+HMAC] working over the new AEAD APIs first, since that's easy for everyone to MVP and test-drive.
Drawaes commentedon Aug 29, 2017
The nonce/IV naming issue was something I was undecided about, happy with a change to IV so will change.
As for Get methods returning something, this avoids any allocations. There could be an overload Get() that returns something. Maybe it requires a naming change, but I am pretty married to the idea that the whole API needs to be basically allocation free.
As for streams etc, I am not overly bothered with that as they are higher level API's that can easily be constructed from the lower level primitives.
Obtaining a Tag before you have finished should not be allowed, however you should know when you have called finish, so I am not sure it should be in the API, however it should be a defined behaviour so I have updated the API design to include a behaviour section so we can capture any others that are thought of.
As for which cipher, I don't think any specific cipher should be the sole target, in order to prove out a new general purpose API it needs to fit a number. AES GCM, and CBC should both be covered.
(all on topic feedback good or bad is always helpful! )
bartonjs commentedon Aug 29, 2017
morganbr commentedon Aug 29, 2017
@Drawaes thanks for getting the ball rolling on this API. A few thoughts:
Drawaes commentedon Aug 29, 2017
@bartonjs
Also a sealed class from a abstract type is actually faster (as of now) because the jitt can devirtualise the methods now ... So it's basically free. interface dispatch isn't as good (still good just not as good)
It's not initialized. It's disposable so any refs can be dropped by normal disposable pattern. If they try to set the key throw an invalid operation exception.
Yes to the read-only spans I will adjust when I am not on the tube on my phone.
Drawaes commentedon Aug 29, 2017
@morganbr no problem... I just want to see it happen more than anything ;)
bartonjs commentedon Aug 29, 2017
The problem would be that container formats like EnvelopedCms (or EncryptedXml) may need to work with 3DES-CBC, AES-CBC, etc. Someone wanting to decrypt something encrypted with ECIES/AES-256-CBC-PKCS7/HMAC-SHA-2-256 probably wouldn't feel that they're doing old and crufty things.
If it's only supposed to be for AE, then that should be reflected somewhere in the name. Right now it's generic "cipher" (which I was/am, at some point, going to sit down with a dictionary/glossary and find out if there's a word for "an encryption algorithm in a mode of operation", since I think that "cipher" == "algorithm", therefore "Aes").
Drawaes commentedon Aug 29, 2017
:) I was merely pointing out that it's not my subject area or of much interest to me so I am willing to defer to you and the community on this topic I haven't thought through the implications for this.
After quickly scanning through these, one option is allow them to take an instance of the "Cipher" or whatever it's called class. This might not be done in the first wave, but could quickly follow it up. If the API is super efficient then I see no reason they should do their own thing internally and is exactly the use case for this API.
Drawaes commentedon Aug 29, 2017
As a side bar on the naming... I must admit its a tough one however
Openssl = cipher
Ruby = cipher
Go = cipher package with ducktyped interfaces for AEAD etc
Java = cipher
Now I am all for being different but... there is a trend. If something better is possible that is cool.
Possibly "BlockModeCipher" ... ?
Drawaes commentedon Aug 29, 2017
I have made a few changes, I will change naming if a better name is decided upon.
morganbr commentedon Aug 30, 2017
When I started trying to answer questions, I realized the API is already missing encryption/decryption differentiation, so in your example, it doesn't know whether to encrypt or decrypt data. Getting that put in might add some clarity.
I could imagine a couple ways that the API could enforce proper tag usage (based on the assumption that this is an AEAD API, not just symmetric encryption since we already have SymmetricAlgorithm/ICryptoTransform/CryptoStream). Don't take these as prescriptive, just as an example of enforcing the tagging.
By method:
By class:
That said, if it doesn't buffer on decryption, is it practical to ensure decryption actually gets finished and the tag gets checked? Can Update somehow figure out that it's time to check? Is that something Dispose should do? (Dispose is a bit dangerous since you may have already trusted the data by the time you dispose the object)
As far as naming, our precedent is SymmetricAlgorithm and AsymmetricAlgorithm. If this is intended for AEAD, some ideas could be AuthenticatedSymmetricAlgorithm or AuthenticatedEncryptionAlgorithm.
sdrapkin commentedon Aug 30, 2017
Some thoughts & API ideas:
morganbr commentedon Aug 30, 2017
@sdrapkin , thanks for contributing thoughts. Where should tags go in your API? Are they implicitly part of the ciphertext? If so, that implies a protocol that some algorithms don't actually have. I'd like to understand what protocols people might care about to see whether implicit tag placement is acceptable or if it needs to be carried separately.
Drawaes commentedon Aug 30, 2017
@morganbr I noticed the encrypt/decrypt issue as well but hadn't had time tonight to fix so glad for your design. I prefer the methods over the class as it allows better aggressive recycling (buffers for keys and IV's can add up).
As for a check before the dispose. It's not possible to tell the end of an operation unfortunately.
@sdrapkin interfaces I would say are a no go due to the version problem mentioned previously. Unless we rely on default implantation in the future. Also interface dispatch is slower.. the array segments also are our as span is the more versatile lower primitive. However extension methods could be added for arraysegment to span if there was demand later.
Some of your properties are of interest so will update when I am at a computer rather than on my phone.
Good feedback all round!
sdrapkin commentedon Aug 30, 2017
@morganbr Tags are part of ciphertext. This is modelled after CAESAR API (which includes AES-GCM).
@Drawaes I've used interfaces to illustrate thoughts only - I'm perfectly ok with static methods/classes. Span does not exist. I don't care about what may or may not be coming - it is not in NetStandard2, and it is not in the normal .NET that serious projects actually use (yeah, yeah, I know it's in Core, but Core is a toy for now). I'd be happy to personally consider Span when I see it - until then ArraySegment is the closest NetStandard API that actually ships.
119 remaining items
pgolebiowski commentedon Apr 13, 2018
am I defending streaming AES-GCM anywhere? can't recall. but can recall saying:
or stating an open problem for corefx:
bonus:
Drawaes commentedon Apr 13, 2018
Just as an aside I never really wanted "streaming" in the sense that most are thinking. I just wanted "block" processing for perf and memory use reasons. I don't actually want to "stream" out the results. This is what openssl and cng support seems a shame to lose that and basically makes the "primatives" useless in any scenario I can think of.
Timovzl commentedon Apr 16, 2018
@Drawaes Come to think of it, block operation might be much safer than using streams. A layman may touch streams, but he will much rather use the one-shot API than block operation. Moreover, block operation cannot straightforwardly be combined with, say,
XmlReader. So actually, many of the dangers discussed apply to stream objects, but not to block operation.To work with block operation when a one-shot API is also available, suggests that we know what we are doing, and that we specifically require low-level tweaking. We could protect the layman and have flexibility.
As for avoiding RUP, I'm still pondering how much of an advantage block operation truly is for GCM. Encryption reaps the full benefits, whereas decryption benefits only somewhat. We can avoid storing the full ciphertext, but we must still buffer the full plaintext. A decryptor could choose to store the intermediate plaintext on disk. But in return, we have introduced more room for error. Do we have a convincing argument to not solve this problem at a higher level (e.g. chunk there, or use a truly streaming algorithm)?
Drawaes commentedon Apr 16, 2018
TLS and pipelines. Currently (and for the foreseeable future) pipelines uses 4k blocks but a tls message can be 16k of cipher text.with a one shot you will need to copy the 16k to a single contingous buffer before you can decrypt. With blocks you might have say 4 or 5 and you might need to buffer upto 16 bytes to ensure compete blocks.
Timovzl commentedon Apr 16, 2018
@Drawaes 16k is still constant and not huge. Does it make much of a difference in this context?
Drawaes commentedon Apr 16, 2018
Yes, it means another copy in the pipeline. This has a major and measurable effect on perf.
pgolebiowski commentedon Aug 17, 2018
What is needed to make this happen? What are the next steps? @Drawaes
pgolebiowski commentedon Aug 17, 2018
As for AES-GCM, I think that its delivery is impaired due to the corresponding issue being locked: https://github.com/dotnet/corefx/issues/7023. @blowdart, could you unlock? It is really hard to have progress when people can't discuss. Or, if that's not an option, maybe propose an alternative solution that allows bringing this feature to the public.
blowdart commentedon Aug 18, 2018
Nope, I'm not unlocking that. A decision has been made, the topic is done.
pgolebiowski commentedon Aug 18, 2018
@blowdart Thanks for the reply. I understand that maybe this was not clear enough:
I appreciate that there is a decision for supporting AES-GCM. This is great, I definitely want that algorithm. Thus, now it would be cool to actually have it supported. Would you like the discussion on AES-GCM design and implementation be held here or in a new issue?
Also, if that topic is done, why not close it? And make it more explicit by changing the title of that issue, as right now it suggests that the discussion on the implementation would be held here: https://github.com/dotnet/corefx/issues/7023. Maybe something like Decide which AEAD algorithm to support first.
In other words: I provide feedback that in the current situation it is unclear what is needed to push AES-GCM forward.
@karelz
bartonjs commentedon Aug 18, 2018
@pgolebiowski There's already a PR out. It'll probably be available in master Wednesday next week.