Sunday, June 22, 2014


Avoid incorrect ChaCha20 implementations



ChaCha20 is a stream cipher which is gaining a lot of popularity of late. Practically every library today which provides ciphers seems to have it as an addition in their latest releases.

In cryptography, there are two kinds of ciphers, block ciphers and stream ciphers. Block ciphers are where the underlying algorithm works with data with a certain fixed chunk size (or block). Popular blocks sizes are 16 and 64 bytes. Stream ciphers are effectively block ciphers where the chunk size is a single byte.

Classical stream ciphers, such as RC4, can work with data of arbitrary size, although every single byte is dependent on every previous byte. Which means encryption/decryption cannot begin in the middle of some data, and maintain compatibility where some other starting point was used. Block ciphers generally can have their blocks encrypted and decrypted arbitrarily, with none dependent upon any other, however, they cannot work with data of arbitrary size.

In order to allow block ciphers to work with data of arbitrary size, one needs to pad the data to be encrypted to a multiple of the block size. However, a clever alternative is counter mode.

Different modes for working with block ciphers exist. Some try to improve security by making each block depend on every other, some utilize various interesting techniques for other properties.  Counter mode does not encrypt the desired data (the plaintext) directly, rather, an ever incrementing counter is encrypted. The result of this encryption is then xored with the desired data.

Counter mode effectively turns a block cipher into a stream cipher, as the plaintext is never actually passed to the block cipher. Rather, a counter which is a multiple of the block size is used. One can always xor bytes with an arbitrary size, and since that is the only step in counter mode against the plain text, it is effectively a stream cipher. Since the underlying cipher can be a block cipher with no dependency between blocks, this kind of stream cipher also allows one to jump ahead to any particular multiple of the block size in the data, and begin encryption/decryption from there.

Now while ChaCha20 is advertised as a stream cipher, it's actually designed as a block cipher in counter mode. The internal design mostly mirrors that of typical counter mode design, except that the counter components are directly fused with a large but simple block cipher. Since it's really a block cipher, it has an internal block size, and also allows one to jump ahead to some multiple of it.

Since ChaCha20 is considered to have a great level of security, and all these other wonderful properties, it's starting to see a lot of use. However, practically every implementation I'm seeing is either utterly broken, or has some ridiculous API.

Common ChaCha20 implementation mistakes:
  • Implemented as a typical block cipher, not allowing usage with arbitrary amounts of bytes, or worse, the API allows for it, but produces incorrect results.
  • Implemented as a typical stream cipher with no way to jump ahead.
  • Failing on Big-Endian systems.

The first mistake I listed is the most common. If some software is only using ChaCha20 internally, and always using it in a multiple of its block size (or it's all the crummy API offers), then things are fine. But if it's a library which is inviting others to use it, and it can be used incorrectly, expect disaster to ensue.

The reference implementation of ChaCha20 was designed that an arbitrary amount of data can be encrypted, as long as all but the last usage of the API was a multiple of the block size. This was also mentioned in its documentation. However, practically every other implementation out there copies this design in some way, but makes no note of it. Worse yet, some libraries are offering ChaCha20 with this implementation flaw alongside other stream ciphers with an identical API whereas those can be used arbitrarily throughout.

Essentially, this means if you're using ChaCha20 right now in a continuous fashion with chunks of various sizes, your data is being encrypted incorrectly, and won't be interoperable with other implementations. These broken implementations are able to output exactly one chunk correctly which is not a multiple of the block size, which destroys their internal buffers, and screws up every output thereafter.

I noticed a similar situation with hash algorithm implementations several years back. However, most hash implementations are fine. Yet with ChaCha20, practically every implementation I looked at recently was broken.

Since this situation cannot stand, especially with ChaCha20 gaining speed, I am providing a simple implementation without these flaws. This implementation is designed to be correct, portable, and simple. (Those wanting an optimized version of this should consider paying for more optimized routines)

Usage of the C99 API I designed is as follows:

Custom type: chacha20_ctx
This type is used as a context for a state of encryption.

To initialize:
void chacha20_setup(chacha20_ctx *ctx, const uint8_t *key, size_t length, uint8_t nonce[8]);

The encryption key is passed via a pointer to a byte array and its length in bytes. The key can be 16 or 32 bytes. The nonce is always 8 bytes.

Once initialized, to encrypt data:
void chacha20_encrypt(chacha20_ctx *ctx, const uint8_t *in, uint8_t *out, size_t length);

You can pass an arbitrary amount of data to be encrypted, just ensure the output buffer is always at least as large as the input buffer. This function can be called repeatedly, and it doesn't matter what was done with it previously.

To decrypt data, initialize, and then call the decryption function:
void chacha20_decrypt(chacha20_ctx *ctx, const uint8_t *in, uint8_t *out, size_t length);

For encryption or decryption, if you want to jump ahead to a particular block:
void chacha20_counter_set(chacha20_ctx *ctx, uint64_t counter);

Counter is essentially the number of the next block to encrypt/decrypt. ChaCha20's internal block size is 64 bytes, so to calculate how many bytes are skipped by a particular counter value, multiply it by 64.

In addition to just providing a library, I gathered the test vectors that were submitted for various RFCs, and included a series of unit tests to test it for correctness.

For fun, since I'm also playing around a bit with LibreSSL these days, I wrapped its API up in the API I described above. The wrapper is included in my package with the rest of the code, however it is currently not designed for serious usage outside of the included test cases.

Since I already whipped up some unit tests that anyone can use, I'll leave it as an exercise to the reader to determine which libraries are and aren't implemented correctly.

I tried to ensure my library is bug free, but I am only human. If you find a mistake, please report it.

56 comments:

circulos said...

Hi,
I was trying your test.c ... nonetheless, surprisingly, it produces this output with gcc version 4.7.0 (mingw32) on Windows:

Test Vector: Keystream #1: Success
Test Vector: Keystream #2: Success
Test Vector: Keystream #3: Success
Test Vector: Keystream #4: Success
Test Vector: Keystream #5: Failed
Test Vector: Encipherment #1: Success
Test Vector: Encipherment #2: Success
Test Vector: Encipherment #3: Failed exact length

:-o

Nathan Zimmerman said...

I had the same result... I assume they all were suppose to pass? Any idea what the issue is? I've had issues with other CHaCha implementations so I wanted to try this one out.

insane coder said...

That's weird, it's passing here, and may be due to compiler differences. I'll see what I can do.

CCoder said...

The cipher works all right but sscanf() sucks on win32. Here is a replacement for hex converter in test.c:

void hex2byte(const char *hex, uint8_t *byte)
{
/* win32: sscanf("%2hhx") sucks => always writes full word/LE */
while (*hex) { /* patched */
uint8_t b[4]; /* patched */
sscanf(hex, "%2hhx", b); /* patched */
*byte ++ = b[0]; /* patched */
hex += 2; /* patched */
}
}

jordan

HALIK said...

the famous of philppine tv shows is the pinoy lambingan pinoy tambayan pinoy ako pinoy teleserye pinoy tv channel pinoy tv replay pinoy flix tv.
pinoy tv tambayan

Anonymous said...

Students from different parts of the world rely on our service, as we are providing secure payment gateways, confidentiality agreements and financial aid centers for communication. Homework Help Sites

Nathanael Gray said...

Are you interested in updating your implementation to comply with https://tools.ietf.org/html/rfc8439 ? I have a patch which I believe is doing the right thing (mostly just expanding the nonce to 12 bytes instead of 8) and updating the test vectors, but not sure where I would send it...

Help Assignment online said...

Do you have difficulty in writing an law assignment help ? Here
is the solution! law assignment help provides assignment help
services at reasonable prices to students across the globe.
If you need expert help for your law work, visit the website
of
Diploma assignment help or talk with the academic expert for more clarification

commerce assignment help

Hindifly said...

Thanks for shairing this information
Statutory and Regulatory Provisions

Alex Kim said...

Professional Translation Services Singapore is most preferable translation services in Singapore to get PR document translation. Here, we have a great team of high experienced and capable translators who always ready to deliver you an effective, rigorous translation into desired language.

Mark Henry said...

On Yes Porn Please you will discover each day the assortment that we propose to transfer the best pornography motion pictures on the net for you to appreciate, alone or as a team, or in a gathering ;) as you favor we leave it to your decision. In the event that you return each day you will see that consistently there are numerous new recordings to watch.

Assignment service provider said...

Students in Malaysia can get our assignment help online from experts who have years of experience and knowledge in curating top-notch quality assignments from students across the world. All we professionals have high qualifications such as a Ph.D. or master's degree from renowned colleges and universities worldwide. They know what the university or college guidelines demand, and accordingly, they composed the assignment for students to get top marks and improve their overall grades. We make sure to provide our assistance at a low cost so that it is accessible to all with no hassle!


Henry Jones said...

Hey this is cool and nice share for me as well as the people who are depressed for not getting the assignment help services on time and should be worried from the people whoa re rich enough to get that easily and accordingly. Thanks for this ultiamte share that includes assignment help Canada services at even fair deals.

For more information - Check out - assignment help

singapore assignment help said...

SingaporeAssignmentHelp.com is most unique dissertation writing services providers who always manage to give best assignment help support in dissertation writing services at reasonable price.

Sarah Winget said...

ABC Assignment Help gives 100% genuine work in less time at reasonable costs. A great thesis mirrors a solid comprehension of the hypothetical ideas. These ideas are identified with the subject being investigated and broad examination. Which are showed through the inductions drawn from logical thinking and writing audit. Our thesis writing administration realizes well how to address your thoughts and join them in your thesis writing to make it a superb thesis work.
assignment provider
assignment help melbourne

Logisticguru said...


Great post; I think you can get every information about LogisticGuru.PVT the best Car Transport In Pune. They have a vast and robust network of more than 70 destinations nationwide. All branches in all over India are entirely computerized and linked through. Their unmatched and reliable car transport service makes LogisticGuru.PVT the unbeatable car shipping company in India.

singapore assignment help said...

Thank you very much for this post, I agree with what is written there . singapore homework helper

Help in Homework said...

Isn’t Chemistry a wonderful subject? It brings the students closer to nature while still providing the power of looking at things with a new perspective. However, when it comes to writing chemistry assignments, it is almost a compulsion to look for the best and affordable Chemistry Assignment Help so as to stay away from the stress. If you want a premium quality, budget-friendly, and instant chemistry assignment help get in touch with our experts at Help in Homework and remain stress-free and a top scorer.

clickonwebsite741♡ said...

Everyone loves it when folks come together and share opinions.
Great site, stick with it! 메이저사이트

rioraj said...

This post is so usefull and informative.keep updating with more information...
Quality Software
Benefits Of Software Testing

Gaurav said...

Find the latest Status about jyeshta nakshatra famous personalities from top creators only on eastrohelp India.

Mr Frudo said...

Livingfeeds agree with your blog ideas

totosafeguide said...

I am unable to read articles online very often, but I’m glad I did today. This is very well written and your points are well-expressed. Please, don’t ever stop writing. Feel free to visit my website; 먹튀검증

totosafeguide said...

This article was written by a real thinking writer without a doubt. I agree many of the with the solid points made by the writer. I’ll be back day in and day for further new updates. Feel free to visit my website; 바카라사이트

Unknown said...

You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. Feel free to visit my website; 야설

Unknown said...

My website is in the exact same niche as yours and my visitors would genuinely benefit from some of the information you provide here. Please let me know if this okay with you. This paragraph is genuinely a nice one it assists new net visitors, who are wishing in favor of blogging. Thanks Feel free to visit my website; 일본야동

Easy Loan Mart said...

Hi....
Avoid incorrect ChaCha20 implementations. ChaCha20 is a stream cipher which is gaining a lot of popularity of late.
You are also read more Apply Online Home Loan

Assignment Experts said...

Online Assignment help Edmonton

Quimesherlie871 said...

스포츠토토
토토사이트

Thanks for sharing your info. I truly appreciate your efforts and I am waiting for your next post thanks once again.

MalaysiaAssignmentHelp said...


Your search who can write my essay Malaysia on google then the only platform that can help you is “MalaysiaAssignmnethelp.com” we provide all types of assignment helps as the students need in Malaysian universities, our experts have 15+ years of experience so they can assist you to upgrade your grade and make you a topper in your field.

토토사이트 said...

Major private Toto refers to a company that shares high dividend rates and various events while having few restrictions while using the Toto site. Companies that participate in the operation of excellent ozmakers and manage site security in real time are called safety playgrounds or major playgrounds in the Totosite industry. 토토사이트 뱃사공 안전놀이터

Jone Marsh said...

Our Law Assignment Help expert is ready to complete your requirement. They have the sure assurance to take over your subject requirement and provide the same solution as you’re ever expected.

Unknown said...

How Online Operations Management Assignment Help Can Boost Your Grades : Brief Info

Neena07 said...

If you are a student and you want Dissertation help? then Do not get Tension, "Uk assignment help" is always with you if you have any problem completing your dissertation writing work then don't waste time, just hire "Dissertation help online UK" and get the best solution.

Nelson Lima said...

Are you worried about deadlines to finish the essay writing assignment? don't worry qqiassignments.com is the best website to get expert help through our essay writer ireland service. With our help, you will be able to pursue your dream grades not only in school but also in college.

Mary Taylor said...

If you want solutions of coca cola Case Study solution for your assignments and case study writing, you should definitely choose IAH.AU (Instant Assignment Help Australia). They have highly qualified and experienced writers that write 100% plagiarism free content and delivers it on time.

charles said...


My Blogs - Visit for more information
FOr HBO hbomax.com/tvsignin
For fox news foxnews.com/connect
For Disney disneyplus.com/begin code
FOr disneyplus Disneyplus.com/begin

Edna Lucas said...

Top BSchool Admission is Consultancy service expert counsellors who guide how to get direct admission in top MBA/PGDM/BCOM/ BBA colleges. We are one of the oldest and leading MBA/ PGDM/ BCOM/ BBA education and admission consulting associations in this country. Our expert counselors guide you for best colleges across the India. Select your desired course with good specialization is very important, we surely help you to decide College, as per your desire like their location, affiliation, fees, placement. Get in symbiosis banglore direct admission

darkdalesmith said...

Bring all kinds of academic services from Do My Assignment Bristol of GotoAssignmentHelp. Get your assignments done by the top rated experts and have a wonderful academic career.


buy online case study

Sneha sharma said...

TopEngineering College expert counselors guide you to the best colleges across India. We will help you to choose a college that offers your preferred course of study with a good specialization. provide college admission and consulting services for getting you into the universities of your choice anywhere in India.
Providing the highest level of education consultation services, our team of counselors are the best in the business. Get direct admission in sinhgad college lonavala

Greatassignmenthelper.com said...

Hey, my name is Mike Taylor. I have been working as an academic writing consultant with Great Assignment Helper for over 9 years. GAH has got the best Assignment Helper & assignment writers on board who offer premium assignment help. My Assignment Helper Online is the fastest growing and most reliable assignment help platform that offers most affordable and bespoke online assignment help.
Law homework Help
MY Assignment Help
edit my paper

Kalpita kumar said...

A top, popular, and trending AI-based Text to Speech web application is Speakatoo. In just a few easy steps, create voice overs that sound entirely human. The tool is renowned for its Client Satisfaction, Award Winning Support, and Ease of Use. The programme has been created such that it translates any text into 100% Human Voice overs in over 120 Languages & 700 Voices quickly & effortlessly, regardless of whether you are a techie or a learner.Get Text to Speech in Urdu

ireland assignment help said...

Really very happy to say,your post is very interesting to read.I never stop myself to say something about it.You’re doing a great job.Keep it up. essay writers ireland

Peter said...

Wow, this is so amazing, This will increase my productivity. Now it's time to avail Email Support for more information.

Unknown said...

How to Deal with My Yahoo Email Is Not Updating? | ContactforService

When you are facing the issue of my my Yahoo email is not updating then you need to start by resetting the browser. There are chances that the data and cookies that users have accumulated while browsing might affect how websites include Yahoo. So, you need to try to close and restart it first and if it doesn’t wok then you can smoothly reset the Chrome or restore Safari. It is advisable to make sure that everything is up-to-date. Yahoo mail update behind the scenes said that you don’t necessarily know when a new version is up.

ireland assignment help said...

Great Article. I was checking continuously this blog and I’m impressed! Extremely helpful info particularly. dissertation writing service

myassignmenthelp21 said...

great content and great content always deserve to be praised.
If you are looking for someone to pay to write your homework,
You can buy cheap help with your homework from My Assignment Help Singapore. We are a legitimate and genuine Singapore-based company, dedicated to easing your burden by bringing to you a whole new world of homework assistance and providing online homework help, thereby helping you achieve your dream grades, that too, at affordable prices. Click on; homework helper singapore.

Noud said...

free credit, hard crack slots 2023 should adjust the screen light to fit the vision. Not too bright and สล็อตxo

Jason Phelph said...

Great post! I particularly enjoyed your unique perspective on the topic. Your writing style is so engaging and easy to read. Thank you for sharing! I am an academic writer at help assignment providing assessment help services to university students. We provide assignment help services to students to help them in completing their assignments and help them to score good grades on exams.

jane robert said...

What a fantastic post! I was especially delighted by your distinct point of view on the subject matter. Your writing style is engaging and effortlessly readable. Thank you for sharing your insights
Separation Agreement in Virginia

Sophie Owens said...

The art of effective academic writing is honed over time, help with my dissertation offer invaluable support in this area. These services provide writing assistance, helping students structure their dissertations, improve coherence, and enhance the overall quality of their writing. Additionally, they offer meticulous proofreading and editing services to ensure grammatical accuracy, adherence to academic conventions, and clarity of expression.

Ava James said...

Your articles are really amazing and I enjoyed it a lot while reading this article. Your writing style engages me to read this article. I am very thankful for this article. Keep sharing with us. Now its time to avail Limo service West Palm Beach for more information.

My Translation Services said...

Nice blog
"Discover professional Certified Translators in Bristol at My Translation Services. Our dedicated team excels in Marketing Translation, Legal Translation, and Transcription Services. We understand the importance of precise and culturally appropriate translations. Whether you need multilingual content for your marketing campaigns or legal documents translated accurately, our Certified Translators Bristol have got you covered. Visit our website today to access our language expertise and take your communication to new heights."

Alghubaiba said...

As a senior content writer with extensive knowledge in the HVAC industry, I couldn't agree more with the significance of regular HVAC service. HVAC systems play a vital role in maintaining indoor comfort and enhancing energy efficiency. Ignoring their maintenance can lead to a myriad of issues, ranging from poor air quality to skyrocketing utility bills.

CV Writing Services said...

Looking for a cheap CV writing service that doesn't compromise on quality? Discover our affordable and professional CV writing solutions. Our expert writers craft compelling resumes that make you stand out. Get noticed with our budget-friendly CV writing services today!

Assignment Help Online said...

I would like to extend my sincere appreciation for sharing an outstanding article. Your dedication in offering this invaluable information is truly commendable and has not only benefited me but, I believe, numerous others as well. Your commitment to delivering such informative content is highly valued. Please continue the excellent work and consistently provide articles of this quality. Your contributions make a substantial impact, and we are grateful for the knowledge and insights you generously share. Thank you once again for your considerate and enlightening posts! On the hunt for assignment aid? Your search terminates right here! We extend our management assignment help services within your reach, featuring a proficient squad of 2000+ assignment professionals. Rest assured, we're committed to shepherding you through your assignments. Queries? Contact us promptly.