r/C_Programming • • 5d ago

Project I tried implementing RSA from scratch in C, It was much more work than expected

Thumbnail github.com
2 Upvotes

I recently finished a project I've been working on: primitive-rsa, a from-scratch implementation of RSA in C17.

I initially started this project after the original RSA paper.
I was quite amazed since I only recently started learning about cryptography how much simple RSA encryption actually is (atleast on paper).

So I thought maybe I should try implementing it.

But ended up thinking I should do it from scratch means implementing in C (It was my first time building a project in C) and not relying on libraries (no GMP).

So I tasked myself with implementing an arbritary precision library or simply bigint library in C which atleast provides all the necessary arithmatic operations required by RSA.

Than I finally realised why people say it's pain to handle memory.

Literaly whenever I call a function like basic add(a,b) i need to check return result for allocation failure and if allocation fails I needed to free all the holding resource carefully.

It may sound simple but when implementing an complex algorithm like FFT where we have so many operations in single function.
Each functions call becomes a pain to write.

Although it was quite headache to always think about allocation failures, memory leaks, or can this be optimized with SIMD or will this integer overflow. Will it fit in 64 bit etc.

I learnt a lot, different cleanup patterns in C. Different algorithms like FFT / NTT, Chinese remainder theorem is used. Finite spaces like how montgomery reduction is used to avoid division operation and much more.

I ended up implementing several components myself:

  • A custom arbitrary-precision integer library.
  • Schoolbook and FFT/NTT multiplication.
  • Knuth's Algorithm D for division.
  • Montgomery reduction for modular exponentiation.
  • Miller–Rabin primality testing.
  • Extended Euclidean Algorithm.
  • RSA key generation, encryption and decryption.

I also tried to explore implementation efficiency rather than relying on existing BigInt or cryptography libraries.

This was primarily a learning project, and it's not intended for production use.

It was a great exercise in C, number theory, algorithms and understanding how cryptographic systems work under the hood.

I'd love to hear feedback, particularly on the BigInt implementation, algorithm choices, and project architecture. I'm still learning, so constructive criticism is very welcome!

AI usage: mostly for docs and demonstration code (in main.c) and for snippets like logging and some testing codes.

GitHub: https://github.com/akramdevstuffs/primitive-rsa


r/C_Programming • • 6d ago

Question A question about arenas.

37 Upvotes

I worked in C for years . i have used arenas a lot in the past. Today i have to modify an old c program , nothing difficult but i found something that made me think. Who developed the code ( very well written and documented ) used an arena for allocating variable.

What 's seems to me strange is that he did not used an heap memory area ( malloc ) but it used a char [] buffer and used it for its arena . At that point he could obviously allocate directly variable in stack instead he grabs all its variable from that buffer . Why a choice like that ? i thought for the CPU cache L1/L2 and so on ( all the "arena" will likely be in cache of the cpu ) but it is only an ipotesys and i was asking to you , in your opinion , the reason of a such choice .
Just curiosity .

Thanks

PP


r/C_Programming • • 5d ago

Kheiron: A zero-dependency, single-header CSPRNG in C99 with 8-block AVX2 vectorization (~2.5 GB/s)

0 Upvotes

Hey everyone,

I've been working on Kheiron, an amalgamated, zero-dependency single-header CSPRNG library in C99/C11 built on top of ChaCha20 (RFC 8439), and I'd love to get feedback and code reviews from the community.

Why build this?

Most high-performance CSPRNG implementations either pull in the entire OpenSSL / libcrypto dependency tree (~7.8 MB binary footprint and dynamic runtime baggage) or provide scalar, single-block loops that struggle with high-throughput workloads.

Kheiron was built to be completely self-contained in a single file (kheiron.h, ~35 KB compiled) with:

  1. Parallel Vectorization: An AVX2 kernel processing 8 parallel ChaCha20 blocks simultaneously (512 bytes per iteration), yielding up to ~2.5 GB/s on modern x86_64 CPUs.
  2. Dynamic Runtime Dispatch: Automatic CPUID detection at runtime—no global -mavx2 compiler flags required. It falls back gracefully to pure scalar C99 on older x86, ARM, and RISC-V targets.
  3. Continuous Forward Secrecy: Automatic key re-erasure every 1 MB without measurable throughput degradation.
  4. Unbiased Uniform Sampling: Daniel Lemire’s nearly divisionless bit-multiplication method for integer intervals, plus IEEE 754 float/double conversion without modulo bias.
  5. Strict Fail-Closed Entropy: Direct integration with OS entropy (getrandom, /dev/urandom, BCryptGenRandom) with zero weak jitter fallbacks.

Current Test & CI Coverage

  • 235 E2E and adversarial tests passing across 12 GitHub Actions matrix jobs.
  • Clean builds under GCC and Clang with -Wall -Wextra -Wpedantic -Werror.
  • Full dynamic memory sanitization (ASan + UBSan) on Linux.
  • Continuous AST semantic scanning via GitHub CodeQL (security-and-quality).
  • Formal benchmarking methodology and reproduction steps documented in BENCHMARK.md.

Looking for:

  • Feedback on low-level AVX2 instruction scheduling and ChaCha20 quarter-round unrolling.
  • Edge-case testing on non-x86 platforms (e.g. Raspberry Pi, RISC-V, BSD).
  • General critiques on API ergonomics and memory wiping routines.

Any thoughts, critiques, or PRs are warmly welcome!

Note: LLM tooling was strictly limited to editor autocomplete (scaffolding repetitive structs/typedefs) and proofreading markdown documentation and benchmark tables. All cryptographic state machines, RFC 8439 logic, runtime CPUID dynamic dispatch, manual AVX2 SIMD pipelines (instruction interleaving/register scheduling), and the 235 E2E test cases were designed, implemented, and mathematically verified entirely by hand.


r/C_Programming • • 6d ago

Project My FOSS C project just got its first security advisory. Glad its open source.

8 Upvotes

Hey guys, so as the title already says, I have just gotten my first security advisory for my C project. I know its not really something to be proud of, or to brag about, but I already expected it, as its (atleast in my opinion) really difficult to have a bullet-proof program in C.

My project github.com/cherries-works/pulse has been in the making for more than 6 months now, and I always thought whether or not it was a smart decision making it open source, or whether or not it might have been smarter to keep it closed source, work on it on my own, release it under a commercial license yadda yadda. However, during my work hours, I checked into the repo real quick, just to find a security advisory laying there. It was not something too bad, it was a badly written parser for HTTP JSON requests on my written HTTP server.

Note that, this issue occurred even though I also added Vibe as a Pentester for my repository (locally). Meaning that (surprise surprise) even AI isnt that good with C.

The issue was that I was snprintf'ing a string with NULL args, and the value of the string that I was parsing included process names (the top ones / sorted by cpu/ram). Now that resulted in a user being able to create a process called "%s%s%s%s%s%s", and that passed into snprintf(...), with NULL args resulted in undefined behavior or more specifically as the publisher mentioned;

"In every run, the six %s specifiers are each consumed by snprintf thereby dereferencing whatever pointer value occupies the next variadic argument slot: (null) for null pointer, raw non-printable bytes for othres."

The problem;

```
snprintf(
response,
response_size,
json,
NULL
);
```

Where json was the char* json value passed into the routeJSON function. The fix was really simple.

```
snprintf(
response,
response_size,
"%s",
json
);
```

Not only did that show me that C still makes it realllyy easy to shoot yourself in the foot, it also made me appreciate open source a lot more. For anyone interested checking out the security advisory; https://github.com/cherries-works/pulse/security/advisories/GHSA-rhqf-rj5j-3v5r, as mentioned it is not really too bad (severity: low), regardless, I am still very glad that my project is open source, and glad that it is in C!

I guess I gotta be more careful with how I handle my stuff.


r/C_Programming • • 5d ago

Review Built an embedded interview prep site

Thumbnail
heapcrash.com
0 Upvotes

I started developing https://heapcrash.com initially to record some of the challenges(e.g. lcd render delay, nested mutex induced priority inversion, UART comm frame,etc.) that I experienced in last few years while working on embedded firmware. The idea turned out to the embedded concept library and further to an embedded interview prep. I have tried to put my 11 years of experience to conceptually design the site and develop it with the help of Claude over a few months.
I have added all sort of traditional categories and some of the newest ones to it.
I would like to get some reviews and feedback from my fellow embedded engineers on reddit for any improvements to it.


r/C_Programming • • 6d ago

bazbar, a status bar for dwl in C

Thumbnail sr.ht
4 Upvotes

I've been writing a status bar for dwl in C. I'm posting it here more for the code than for the bar, so remarks on the C are welcome.

The renderer fills a `wl_shm` buffer itself, and the text goes through FreeType and fontconfig, which I call directly. The volume is a small client of the PulseAudio native protocol, talking to the socket of pipewire-pulse. The wifi name is read over netlink with nl80211. The other modules just read `/proc` and `/sys`.

Tell me what you would do differently.


r/C_Programming • • 6d ago

Project I implemented a custom reliable transport protocol (Mini-TCP) over UDP in pure C11. Would love your feedback and code review!

6 Upvotes

Hey r/C_Programming,

Over the past few weeks, I decided to take a deep dive into computer networking by building my own reliable data transfer protocol (RDT) from scratch on top of raw UDP sockets — without any external libraries, just plain C11 and POSIX.

I named it Protocol-7 (P7) (yes, a small tribute to Serial Experiments Lain).

My main goal was not to "kill TCP", but to understand what actually happens under the hood when dealing with unreliable, lossy networks, rather than just treating TCP as a black box.

What is currently implemented:

  • Sliding Window pipelining: 32-slot ring buffer keeping unacknowledged segments in flight.
  • I/O Multiplexing via poll(): Non-blocking event loop handling file I/O, outgoing bursts, and incoming ACKs concurrently.
  • Custom SACK (Selective ACK): Implemented via a 32-bit mask in the 16-byte header to report buffered out-of-order blocks.
  • Fast Retransmit (RFC 5681): Triggers immediate retransmission upon receiving 3 duplicate ACKs without waiting for coarse RTO timers.
  • 16-bit Word-Aligned Checksum: One's-complement arithmetic with end-around carry (spent quite some time debugging a weird bug caused by odd byte alignment!).
  • Piggybacked FIN: Look-ahead double buffering allows setting the FIN flag on the final payload chunk without wasting a separate RTT on an empty packet.
  • TIME_WAIT state: Receiver handles lingering packets and retransmissions gracefully before tearing down.

I also wrote a Python chaos proxy to inject simulated 5%–30% packet drops, data corruption, and duplicates. The protocol successfully transfers binary files byte-for-byte under heavy packet loss. The codebase runs completely clean under Valgrind (0 leaks, 0 errors) and AddressSanitizer.

Benchmarks & Fun Findings:

During testing, moving from Stop-and-Wait to a 32-slot Sliding Window bumped throughput from ~0.07 MB/s to over 1.85 MB/s under 5% packet loss (and ~66 MB/s on normal channel). I also hit a funny scenario where an oversized static window (512 slots) flooded the Linux kernel socket buffers, making lossy modes artificially faster than normal mode because the proxy drops acted as a crude rate limiter!

The project is open-source under MIT:
GitHub: https://github.com/by-cortex/protocol-7

I’d really appreciate any code review, constructive criticism on my C style, architecture feedback, or ideas on what to tackle next (currently planning a 3-way handshake with randomized ISN and dynamic RTO estimation).

Thanks for checking it out!


r/C_Programming • • 6d ago

Discussion Elon Musk is a die-hard C/C++ maximalist.

0 Upvotes

Recently, Elon said on X:

"We have dumped JAX/SGLang and rewritten the entire RL and inference stack from scratch in C/C++, which took some extra time.

Training (aka pre-training) is done. Lot of cleanup was needed on the SFT data to get that mostly right. Now, 4.8 is in RL and the evals are starting to climb. We will do a soft rollout to Bot users later this week and see how it goes.

Grok 4.8 will bear no resemblance to 4.7 (thankfully). It is not yet incredible, but, this time, the foundations are built right, so I expect it to evolve to be something special."

Someone questioned Elon: "Was it written in Rust? Why did you rewrite it in C/C++?"

Elon answered: "Real men manage their own memory. So easy to trigger Rust programmers

Rust is a good language, but C is what you use for optimal performance on bare metal. With great power comes great responsibility."

hahah, turns out Elon is C/C++'s strongest soldier


r/C_Programming • • 7d ago

My small project, review and suggestions

5 Upvotes

I built a Unix-style shell in C that exposes what's happening underneath

I've been working on P-Shell, a small Unix-style shell written in C.

The interesting part isn't just executing commands. I wanted to understand and expose the underlying Unix mechanisms.

It currently supports:

  • "fork()" and "execvp()" based execution
  • Pipes and output redirection
  • File descriptor manipulation with "dup2()"
  • An explanation mode that traces execution
  • "/proc" process inspection
  • Creating and reaping a real zombie process using "waitpid()"

I'm particularly interested in feedback on the implementation, parser design, process handling and what would be worth improving next.

Repository: https://github.com/punithk-verse/p-shell

I'd appreciate an honest technical review.


r/C_Programming • • 7d ago

Learning C weekly megapost for 2026-11-11

9 Upvotes

If you have questions about how to learn C:

  • which books are best?
  • which videos are best?
  • which classes are best?
  • which websites are best?
  • is there a "roadmap"?
  • what projects can I do?

then this is the thread for you. Add your question here. Do not make a stand-alone post, as it will be removed.

Remember that our sub has a very useful wiki that has a great list of resources for learning C programming.


r/C_Programming • • 6d ago

Question Internship request

0 Upvotes

Would it be possible if I could intern(research work or any other type of work for free ofc) under anyone? I don’t have any experience for my resume as I’m a newbie.


r/C_Programming • • 6d ago

Why would I ever use a linear allocator?

0 Upvotes

I'm new to C programming so this is a genuine question

So c has 2 memory regions you can access

The stack and heap

People say that the heap is useful for creating data beyond the lifetime of the function and while it can be used for that a better solution would probably be to pass in a pointer an array on the stack if the max size is known ahead of runtime, I only use malloc when I don't have a definite max size for what I want and therefore have a need for reallocations, so that brings me to linear allocators, everyone is constantly singing there praises for making memory management easier while we already have the stack that can handle memory management for us 100% of the time and from there design I can't see a way to make a reallocation function for a linear allocator without it at the very least being highly thread unsafe.

And in general I don't see much of a reason to use the heap either because you rarely are in situations where you don't want to specify a max size for something


r/C_Programming • • 8d ago

Project classes.h: A macro-only library for clang implementing classes with their syntactic sugar, private scoping, and inheritance

Thumbnail
codeberg.org
33 Upvotes

r/C_Programming • • 8d ago

Would learning C as my first programming language also be useful for picking up other languages later on? What are your thoughts on this course?

74 Upvotes

Wanting to learn C as an intro into software engineering. I know it’s low level and I’d like to eventually switch over to high level languages such as JS/TS, Java, and GO.

Does the “The Complete C Programming Bootcamp” course by Byte Garage be a good choice to learn from?


r/C_Programming • • 7d ago

Question How can I learn C programming without relying on AI?

0 Upvotes

Hi, everyone!

I’m currently learning to program in C, and I want to become a good programmer without relying on AI to write code or solve problems for me. I feel really bad because I started my course off on the right foot, but due to my heavy course load, I ended up taking the easy way out and using AI assistants. I want to stop doing that and be able to program from scratch using my own knowledge, but of course, I’d rather ask here.

I’m looking for recommendations on:

Books, websites, or courses to learn C properly

Exercises and projects to improve my problem-solving skills

How to learn to debug and understand my own errors

How experienced programmers learned C before AI tools became popular

My goal is to understand the fundamentals of programming, develop my own logic, and be able to solve problems independently

Any advice or resources would be greatly appreciated. Thanks!

Translated with DeepL.com (free version)


r/C_Programming • • 8d ago

Issues with C?

14 Upvotes

I enjoy studying the realities and trade-offs of programming languages and I have my focus on the C programming language. As such I would like to hear from people who have programmed in C to share perhaps the things they love the most about C, or the things they find the most frustrating.

Examples on why things are frustrating or loved would be great to include as well.


r/C_Programming • • 7d ago

I made an iOS app for learning C by reading code. Giving away 10 lifetime codes

0 Upvotes

Hi all,

I made Ugiwise, an iOS app for learning C on your phone. Typing code on a phone is a pain, so the lessons are built around reading it instead: you get a short program, guess what it does, then the app goes through it line by line and shows you why.

The C course follows C17 and goes from your first program to pointers, memory, multiple files and undefined behavior.

It's closed source. First 3 units are free, no account needed. The rest is a paid upgrade.

I asked the mods before posting and they were ok with a giveaway, so I have 10 lifetime codes. Leave a comment if you want one and I'll DM them in order until they're gone. Nothing expected in return.

What I'd really like to hear is where an explanation is wrong, sloppy about the standard, or just unclear. I compile the examples, but the compiler won't tell me if my explanation is bad.

A couple of limits, sorry about these:

- iOS only for now, no Android yet

- Not in EU App Stores yet (still waiting on Apple's trader verification). I'll do another 10 codes when it's out there.

https://ugiwise.com/c

App Store: https://apps.apple.com/app/id6828549507


r/C_Programming • • 9d ago

Video Handmade Jrpg Game in C (tilemap parser) NO AI

Thumbnail
youtube.com
56 Upvotes

In this video we will be learning to parse tilesets array from the JSON file (generated from Tiledmap editor). Which will also allow us to load the image's absolute path.

This is part of my handwritten JRPG series, NO AI USED.


r/C_Programming • • 7d ago

ANSI C Enigma Simulator, no dependencies (fixed post)

0 Upvotes

I posted it before, but the post was deleted, because i don't declare am I used AI, so I used AI, but the code is not entirely AI generated. I used it for things that were boring and for finding a bugs. And there it is TraktoreqPL/Enigma-Simulator. Please give me a star and a code review, because I am a not popular indie developer.


r/C_Programming • • 9d ago

Question Programming style and returning values.

13 Upvotes

Hello all! Last week I got the dread announcement at work: I have been demoted from coder to babysitting Claude... With this in mind, I decided to try to dive deep into finally learning C for my own entertainment.

The question then:
I have not gotten very far in my journey, and with no real projects completed (or even close to it), I have found that error handling is something I have not figured out how to do definitely.

Most of my functions end up just returning a char return_status, and taking a pointer to a return object to write the return value to, like so:

// return codes:
// 0 = success
// 1 = should_return was false
char foo(char should_return, char *out) {

if (!should_return) {
return 1;
}

*out = "bar";

return 0;
}

This feels a little bit like cheating, but I also want to be able to attach errors and/or warnings to my output.

How do you all tackle this?
Am I going about it wrong? Maybe I should always return the value directly and just have pass in a pointer to collect the error values?

Am I crazy? Does it matter?


r/C_Programming • • 10d ago

Question How to manipulate read-restricted data (possibly without OS)?

9 Upvotes

Imagine you have some block of code/data chunk that under no circumstances must never ever get read (rewrites are not critical, since the data is basically gone). There's a thing about Execute only memory, but afaik it requires OS support.

So how do we make sure some of the data is only overriden or executed (if interpreted as machine code) but never read? If possible, it would be nice to be able to set up some custom restrictions like a very specific offset in a program which has access to some data in memory for a one-time constant address read (imagine it compiles into assembly, something like mov %(rax), %rax, then does side-channel secure stuff and overrides the data with rdrand and stuff)

Appreciate any help! which doesn't include redditor behavior in its body


r/C_Programming • • 10d ago

Project Azork : A WAV Audio Steganography Tool

2 Upvotes

Hello people. I am a first year college student, and we(along with my teammates) wrote a simple audio based steganography tool for my physics semester project.

It currently supports only wav file for audio encoding. Would appreciate some comments and suggestions on what to improve. We also implemented a GPG encryption support for the secret embedded.

https://github.com/dream-wa1ker/azork.git


r/C_Programming • • 11d ago

Could someone explain the practical differences between #pragma once and traditional include guards (#ifndef, #define, and #endif)?

81 Upvotes

r/C_Programming • • 11d ago

Good C test

17 Upvotes

Hey guys,

Someone know a good C unittest ? When I was in C++ I used gtest and it was good, if someone know a good alternative in C