/r/cryptography

Photograph via snooOG

For people interested in the mathematical and theoretical side of modern cryptography.

From Greek κρύπτω krýpto "hidden" and the verb γράφω gráfo "to write" or λέγειν legein "to speak".

Cryptography is the practice of establishing a secure connection between two parties in the presence of a third party whom you don't want to be able to read your messages.

Cryptographers design algorithms and protocols, which do exactly this (and many other things). They also use a lot of time looking for security holes in existing protocols to make sure they can still be trusted. This is called cryptanalysis.

If you want a formal introduction to cryptography, you should read An Introduction to Mathematical Cryptography. The creator of the sub also approve of the Udacity course Applied Cryptography - A Science of Secrets.


A combined karma of at least 10 is required to post or comment in this sub.


Cryptocurrency talk is only allowed if it's to discuss the cryptography subparts of it.


We won't do your homework for you. It is however allowed to help you understand material and or the questions.


we won't solve your ciphers unless you provide us with an algorithm. If anyone sends you a code or a cipher without telling you how they encrypted it, don't bother posting it on this subreddit - your post will get deleted. We redirect you to /r/breakmycode or /r/codes. Thank you for your understanding and for following the rules.


Related Subreddits:

/r/cryptography

74,801 Subscribers

1

Are there any places I can test my cryptography?

Hey there, sorry if this gets asked a lot. I'm interested in writing my own programs in C for encrypting/decrypting information as a hobby, and was wondering is there a website or a tool that can try to break my cryptography and tell me how good it is?

1 Comment
2024/12/03
03:04 UTC

2

How do you send someone a PGP key ? Is airdropping a PGP key secure?

Even if you share your PGP key in person, it’s so long how do you share that without texting it? Is airdropping safe to share the key through files on iPhones? What about sending a key to an android?

7 Comments
2024/12/02
14:05 UTC

11

Are there companies that do research on theoretical cryptography?

I am curious if the only path for someone that likes research on theoretical cryptography is the academic one or if there are companies that do that.

6 Comments
2024/12/01
23:14 UTC

1

Cipher Question

I have a question about Ciphers that I hope someone can help me on. Is it possible if i know the start of a cipher and the output at the end but not knowing what cipher was used, is there a way of finding out what cipher was used, ai testing or something,like that. Sorry if that sounds confusing. VMT

3 Comments
2024/12/01
20:45 UTC

8

Cryptography Jobs for Maths PhD Graduate

Dear Cryptography people,

Is it possible for me to get a job in cryptography ?

Some background : I have just finished a PhD in number theory, before that I did an undergraduate degree in physics. I did well in both these subjects and have published a paper in each. As I came to the end of my PhD I started thinking about jobs, having abandoned the idea of academia, cryptography seemed like a sensible option. I find the mathematics in cryptography easy, such as number theory and elliptic curves, group theory, linear algebra, I have also studied quantum mechanics and quantum computing related to today's advances in post-quantum cryptography. I have some experience with coding, having used Python and MATLAB, I understand the fundamentals and can program ciphers like RSA for example, but coding isn't my speciality.

I started looking into cryptography seriously a few months ago, I read books, watched lectures, made a Github with my own implementations of cryptographic algorithms, thought the subject really interesting and engaging. But the more I look into finding jobs in cryptography the more disheartened I become and the more impossible it seems.

What I am asking is for you cryptography people to give me an honest opinion about my chances in this field.

From what I've read, the impression I get is that 99% of cryptography jobs are in industry and 99% of those jobs have nothing to do with maths or physics at all. It is almost entirely software engineering, cybersecurity, network security etc. If that's the way it is, then there isn't much I can do. My thought is that if the skills I have gained in maths, physics and research are of no real value in cryptography, then I should stop trying to get into it.

I understand there are jobs in research in cryptography but these seem exceedingly rare and are highly competitive, much more likely to be given to people with degrees specifically in cryptography, or computer science, or at least with a few years of experience in the field. I don't mind starting in an entry level position and working my way up, but even these positions seem impossible to get into. Almost all entry level positions in cryptography need years of experience in IT, expertise in C, knowledge of acronyms I've never even heard of.

I'm really not sure where to look or where to start anymore, I love mathematics and I think I'm pretty good at it, I would love to use it to do cryptography, but if I'm just totally wrong about this field and would be better suited to search in other areas it would be useful to know. If cryptography is in fact a wise choice of career path for me, any advice on jobs suited to my skills, or where to start looking would be much appreciated !

11 Comments
2024/12/01
13:09 UTC

2

How to Pursue Further Studies and Research in Cryptography?

Hi. I’m about to finish my undergraduate studies in Computer Science, with a double major in Mathematics by the end of this year. I developed a strong interest in cryptography during my 3rd year after taking an introductory Cryptography course (from the CS department) and a Number Theory course (from the Math department). Loved the little algorithms and proofs in the latter course.

This made me want to explore the research side of cryptography, especially its intersection with mathematics, but there aren’t any professors specializing in cryptography at my university beyond introductory level.

What steps can I take to dive deeper into this field and potentially contribute to research? I really don’t want this interest to fade away, and I’d love your guidance.

Thank you in advance!

14 Comments
2024/11/30
16:52 UTC

6

Hashing

Im new to IT and even basic levels of cryptography and have been recently learning about how hashing and salting work. I wanted to hash a certain password but I’m not sure where to actually perform this function. Is it a certain program or website I use? Sorry if this is a dumb question, I still have a lot to learn.

24 Comments
2024/11/30
02:04 UTC

0

New and improved TUKP

DISCLAIMER : the following creation was purely made for fun, and i do not plan on ever using it. I am aware that this is practically unusable and far from unbreakable but i do not care because my goal was to see how secure i could make a cryptography method with my small knowledge, and slowly improving it while learning. This was made with 0 concern toward actual use.

So a few days ago i shared here a cryptographic method I came up with, TUKP (Theorical Unique Key Protocol). It has 2 variants : C-TUKP (C for Classic), for pre-quantum cryptography and Q-TUKP (Q for Quantum) for post-quantum cryptography. Based on the CONSTRUCTIVE criticism I recieved, I tried to improve it, so here it is (A1 sending a message to A2) :

The protocol begins with A1 performing a key exchange using either ECDH (c25519 elliptic curve) or Kyber. A1 generates a random private key and computes the corresponding public key P1=G×a1P1=G×a1 (for ECDH) or uses Kyber for post-quantum exchange. A1 sends P1P1 to A2 along with the length of the message he wants to encode and a signature of SHA−3(P1) encrypted using A1’s private key via EdDSA (C-UKP) or Sphinc++ (Q-UKP).

Upon receiving P1 and the signature, A2 decrypts the signature using A1’s public key and verifies it against SHA−3(P1). If the verification is successful, A2 generates their own private key, computes their public key P2, and sends P2 back to A1. He the sends his signature of SHA−3(P2) encrypted using A2’s private key via EdDSA (C-UKP) or Sphinc++ (Q-UKP).

Both A1 and A2 now compute the shared secret K using their respective private keys and the other party's public key. A1 computes K=P2×a1K=Pa1 (or the equivalent in Kyber), and A2 computes K=P1×a2K=Pa2. Both now have the same shared secret K.

Next, A1 and A2 independently run the shared secret K through the HKDF to derive a cryptographically secure key of the needed length (it needs to be as long as the message) and a signing key Ks(random length).

A1 encrypts the message M by XORing each byte of M with the corresponding byte of the derived key (OTP), producing the ciphertext C. Then, A1 generates a signature for the ciphertext by applying KMAC to the concatenation of the signing key and the encrypted message, creating a signature S=KMAC(Ks∣∣C). A1 sends both the ciphertext C and the signature S to A2. I would like to add a nonce (against replay attacks) to the KMAC, but I dont know how to make it so that both sides have the same.

Upon receiving the ciphertext and the signature, A2 performs the same KMAC operation with the shared secret and the ciphertext to check the validity of the signature. If the signature matches, A2 XORs the ciphertext C with the derived key to recover the original message M.

It's important to precise that, to ensure the OTP's security, a new key needs to be created for every message, and the ECDH/Kyber needs to be redone each time (making this method to practical AT ALL). We also need to securely get rid of old keys.

I know this isn't actual OTP, since the key exchange protocol is technically breakable, but it's the most secure implementation of OTP I could come up with. (actually unbreakable OTP is impossible, because you need to share the keys which is not 100% secure).

It's important to precise that, to ensure the OTP's security, a new key needs to be created for every message, and the ECDH/Kyber needs to be redone each time (making this method to practical AT ALL)

Please let me know what you think and how I could Improve it : ).

Also, can someone explain in a bit more detail EdDSA, kyber and sphincs++ ? I know what they do, but I don't exactly know how the work in the inside.

8 Comments
2024/11/29
22:03 UTC

1

Today quantum-safe replacement for RSA?

Hi. We developed some software a decade ago using RSA for identity management (some sort of certificates for login) and also for secure transmission to a server knowing the private key and client-software using the public key (used hybrid with AES 256). I think it is time to upgrade our software to use some quantum-safe algorithms instead of RSA soon. I did some research and I think there is some general insecurity about the best algorithms. Even NIST has not yet decided for a finalist.

So, for today, is there some valid recommendation to an algorithm that

a) is most likely quantum-safe and

b) does not force us to implement new protocols (just add a new cipher)?

The ideal candidate would be some algorithm also using private/public keys and allows us to encrypt at least 1024 bits of data. More or less some direct RSA replacement.

I like to prevent the need for some dual encryption, hybrid models, additional overhead or major protocol changes (except maybe some more CPU power or RAM needed, which is okay).

Any hints on that?

PS. Some sites suggest ML-KEM (Kyper). Does that fit my needs?

15 Comments
2024/11/29
13:39 UTC

3

I have one big question related to Known Key in AES CTR

Genrally the security of AES CTR stream cipher is depending on 2 things as far as my understanding:

  • Generation of secure shared key.
  • Generation of random NONCEs.

So my question is, If I have a most random mechanism to generate most random NONCEs for every message sent so for which consider simply that my NONCEs are secure and in this case what attacks might be possible if the Shared Key is breached which will be used for encrypting NONCE+Counter through AES ECB in AES CTRrather which produces keystream, What happens in this scenario considering my NONCEs are most random as possible and secure but my shared key breached?

16 Comments
2024/11/28
18:43 UTC

25

NIST Published Report Outlining Migration to Post-Quantum Cryptography

https://nvlpubs.nist.gov/nistpubs/ir/2024/NIST.IR.8547.ipd.pdf

It's most pressing to migrate asymmetric encryption schemes because of "Store now, decrypt later" attacks, which don't apply to signature schemes. While this is also mentioned throughout their report, I was surprised to see that this is not reflected in their deprecation timeline.

For example, they will disallow both the Signature Scheme ECDSA with 128 bits of security and the Encryption Algorithm ECDH with 128 bits of security by 2035. I would argue that ECDH should be migrated and disallowed much earlier than ECDSA. Such a deprecation timeline might lead to confusion and bad priorization of transition efforts.

EDIT:

Thanks to u/tomrlutong's encouragement, I've decided to write out my concerns and sent them an email to provide feedback. I know there are much more notable people than me that are going to comment on this, but I thought the experience might be interesting. Here is what I wrote: https://bsky.app/profile/pascscha.ch/post/3lc6cdmonvs2i

6 Comments
2024/11/28
16:28 UTC

2

Theoretical encryption method

So just before we begin, I made this just for fun and I obviously don’t plan to use it in any way. (Also i’m a begginner). So anyway, i tried to come up with the most secure encryption protocol i could think of with my very small knowledge of the subject and without any concern for practicity. And I came up with UKP (Unique Key Protocol)(banger name, ik).

It’s really nothing crazy tbh : Everytime 1 want to send a message to 2, we first use ECDH: he generates a random point G on the c25519 elliptic curve And sends it to 2. He then generate a random private a that has the same length as the message and sends P1=G•a (where • is the ECC scalar multiplication). When 2 receive both, he generates a random private b and sends P2=G•b. They then get the secret key K=P2•a(for 1)=P1•b(for 2). They then perform OTP : 1 XOR each bit of the message with each bit of the key and sends the created cipher to 2, as well as a signature, which is HMAC-sha3(Secret key || original message) to make sure the message wasnt modified. 2 then XOR the cipher with the key to get the original message and HMAC-sha3(secret key || decrypted message) and compare it to the signature : if they are the same, the message wasn’t modified.

So this is C-UKP (Classic UKP), and I also came up with Q-UKP(Quantum UKP) that use Kyber instead of ECDH because according to my small researches, kyber is th most secure post quantum key exchange algorythm, but I’ll only talk about C-UKP since idk how kyber works.

So yeah, this is the most secure protocol I could think of : since OTP is unbreakable if the key is 100% random and the same length as the message, all the security is on ECDH (or kyber), which is i believe pretty damn secure.

But the obvious catch : it is absolutely unusable for actual use : 1st, we need to perform ECDH EVERYTIME 1 message is sent, which is quite long and complicated with large keys, and 2cnd, because we use OTP, the keys are as long as the message, which can quickly be way too much. And there are probably other catchs idk about.

So yeah, let me know what you guys think !

9 Comments
2024/11/28
07:52 UTC

0

Is Vagabond Code a real thing?

I have found a code in a hawkeye comic called vagabond code. He states that it is a code used by carnies and hobos and I was wondering if it is a real thing because I haven't been able to find anything about it. One of the examples was a circle with two arrows through it. You can also google images of it pretty easily.

2 Comments
2024/11/27
02:57 UTC

68

PSA: SHA-256 is not broken

You would think this goes without saying, but given the recent rise in BTC value, this sub is seeing an uptick of posts about the security of SHA-256.

Let's start with the obvious: SHA-2 was designed by the National Security Agency in 2001. This probably isn't a great way to introduce a cryptographic primitive, especially give the history of Dual_EC_DRBG, but the NSA isn't all evil. Before AES, we had DES, which was based on the Lucifer cipher by Horst Feistel, and submitted by IBM. IBM's S-box was changed by the NSA, which of course raised eyebrows about whether or not the algorithm had been backdoored. However, in 1990 it was discovered that the S-box the NSA submitted for DES was more resistant to differential cryptanalysis than the one submitted by IBM. In other words, the NSA strengthed DES, despite the 56-bit key size.

However, unlike SHA-2, before Dual_EC_DRBG was even published in 2004, cryptographers voiced their concerns about what seemed like an obvious backdoor. Elliptic curve cryptography at this time was well-understood, so when the algorithm was analyzed, some choices made in its design seemed suspect. Bruce Schneier wrote on this topic for Wired in November 2007. When Edward Snowden leaked the NSA documents in 2013, the exact parameters that cryptographers suspected were a backdoor was confirmed.

So where does that leave SHA-2? On the one hand, the NSA strengthened DES for the greater public good. On the other, they created a backdoored random number generator. Since SHA-2 was published 23 years ago, we have had a significant amount of analysis on its design. Here's a short list (if you know of more, please let me know and I'll add it):

If this is too much to read or understand, here's a summary of the currently best cryptanalytic attacks on SHA-2: preimage resistance breaks 52 out of 64 rounds for SHA-256 and 57 out of 80 rounds for SHA-512 and pseudo-collision attack breaks 46 out of 64 rounds for SHA-256. What does this mean? That all attacks are currently of theoretical interest only and do not break the practical use of SHA-2.

In other words, SHA-2 is not broken.

We should also talk about the size of SHA-256. A SHA-256 hash is 256 bits in length, meaning it's one of 2^256 possibilities. How large is that number? Bruce Schneier wrote it best. I won't hash over that article here, but his summary is worth mentoning:

brute-force attacks against 256-bit keys will be infeasible until computers are built from something other than matter and occupy something other than space.

However, I don't need to do an exhaustive search when looking for collisions. Thanks to the Birthday Problem, I only need to search roughly √(2^(256)) = 2^128 hashes for my odds to reach 50%. Surely searching 2^128 hashes is practical, right? Nope. We know what current distributed brute force rates look like. Bitcoin mining is arguably the largest distributed brute force computing project in the world, hashing roughly 2^94 SHA-256 hashes annually. How long will it take the Bitcoin mining network before their odds reach 50% of finding a collision? 2^128 hashes / 2^94 hashes per year = 2^34 years or 17 billion years. Even brute forcing SHA-256 collisions is out of reach.

16 Comments
2024/11/26
15:22 UTC

5

Master's Degree Guidance

Hi all! I'm interested in entering the Cryptography job field (cryptographer, cryptanalyst, etc.), but I have no idea how I should go about it.

My current bachelor's degree is in Computer Security Technology and I currently work in the GRC field. During my coursework I took two Cryptography courses (Introduction to Cryptography and Applied Cryptography).

I LOVED these courses (especially Applied Cryptography) and really want to expand upon this and enter the field by getting a Master's degree but I'm confused. Do I get a Master's in Mathematics? Applied Mathematics? Computer Science?

Any guidance is appreciated!

Note: I am in the US!

10 Comments
2024/11/26
12:22 UTC

3

Zero Knowledge Proof for proxy servers ?

General question about something that seems intuitively impossible (but tbh that’s most of zkp for me)

I have a setup where a browser sends requests via proxy server to an end destination and the proxy returns the request but the proxy MAY also (lie, drop the request, return malicious content etc). Is there a way to set this up where the proxy returns the content to the browser and creates a zkp that anyone can verify that proves it faithfully proxied the request without leaking information about the request, destination, or response ?

Intuitively to me, this is impossible as any response could be valid since a verifier does not know the destination or the request but unsure if someone has a better formulation here

TIA for any thoughts

14 Comments
2024/11/26
05:19 UTC

0

naor & shamir integration with IA

Hey everyone, im looking for a project about visual cryptography of NAOR & SHAMIR integrate with IA (ML model or something ), any feedback please ?

1 Comment
2024/11/25
15:43 UTC

2

Equation for FHE cyphertext length

Hi all. I am digging into FHE and I am trying to locate a formula or equation that can provide the cyphertext length for a given input sequence, FHE scheme and number of FHE operations desired. As I understand it these are the three variables that impact the result. Thanks!

2 Comments
2024/11/24
19:50 UTC

12

Time-Lock-Cryptography

Hey everyone,

I’m looking for an easy and reliable way to time-lock access to a file or important information for the next 5 years.

In the past, I’ve faced situations where having access too soon led to decisions I later regretted.

A time-lock could help me avoid repeating the same mistakes, so I’m exploring options now.

I’m not keen on overly technical or complicated setups and would prefer something user-friendly.

Are there any trusted services where I can securely upload an encrypted .txt file or implement a similar solution?

If anyone has experience or ideas for simple and secure time-locking methods, I’d really appreciate hearing your thoughts.

Looking forward to your suggestions!

30 Comments
2024/11/23
15:20 UTC

2

Is this 256 bit hash based, OTS scheme secure?

Variables:

M -> message

Skey -> random secret key

nonce -> Number used only once.

Sig -> Signature (256-bit)

H(x) -> One way hash function (256-bit)

Signature generation:

Sig = H(Skey || H(M) || nonce)

It's very simple that I believe someone already thought of this and given it name.

Given Sig, M and nonce, Skey should be relatively unrecoverable for a one way hash function, H(). Maybe some rehashing itself makes bruteforcing hard.

(It's assumed that Skey, is already established, and H is resistant to preimage attacks.)

Edit: Ok, I need to address a length extension attack vulnerability so I will be using an HMAC implementation of the hash function H() instead.

6 Comments
2024/11/23
14:46 UTC

0

Will you pay for an end to end encrypted GPT-4 type LLM

Any special cases you will use it for?

9 Comments
2024/11/22
21:18 UTC

6

Looking for book advice ^^

Îm writing about the history of cryptology for one of my university courses since i find it super interesting ^^ but im having a hard time finding scholarly sources to use so if anyone has any recommendation that would be great! <3

7 Comments
2024/11/22
15:21 UTC

4

Time Complexity of Brute Force Attacks

Hello, I'm trying to create a presentation on how quantum computing is posing a threat to modern encryption algorithms to a room full of people with little to no background in quantum computing. So, my goal is to use an analogy. I've created a custom cipher such that E(msg[i]) = (msg[i] + k_0*i + k_1) (mod 26) where obviously k_0 and k_1 can be brute forced in O(n^2) time. Now, I'm trying to think of a method to crack this algorithm in a lower complexity. It could be the case that there is no way to beat O(n^2), but there's usually a better method than brute forcing keys. Is there a clever insight that could lead to cracking this cipher in a lower complexity?

10 Comments
2024/11/20
18:51 UTC

0

AES Key generation

Hello,

Id like some constructive feedback on this Python script that generates 100 encryption keys for use with a radio that support 256 bit AES.

The histogram showed uniformity and no bias.

Thanks!

import os from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives import hashes

Constants

ROUND_COUNT = 14 # For AES-256 KEY_SIZE = 32 # 32 bytes for AES-256 BLOCK_SIZE = 16 # AES block size in bytes

Full AES S-Box

S_BOX = [ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 ]

AES Rcon

RCON = [ 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A ]

def generate_aes_key(password: bytes, salt: bytes = None, iterations: int = 1000000): if salt is None: salt = os.urandom(16) # 16-byte salt kdf = PBKDF2HMAC( algorithm=hashes.SHA512(), length=KEY_SIZE, salt=salt, iterations=iterations, ) key = kdf.derive(password) return key, salt

def sub_word(word): return [S_BOX[b] for b in word]

def rot_word(word): return word[1:] + word[:1]

def xor_words(word1, word2): return [a ^ b for a, b in zip(word1, word2)]

def key_expansion(key): key_symbols = [b for b in key] key_schedule = [] n_k = KEY_SIZE // 4 # Number of 32-bit words in the key n_r = ROUND_COUNT # Number of rounds

# Initialize the first n_k words of the key schedule with the cipher key
for i in range(n_k):
    key_schedule.append(key_symbols[4*i : 4*(i+1)])

# Generate the rest of the key schedule
for i in range(n_k, 4*(n_r+1)):
    temp = key_schedule[i - 1][:]
    if i % n_k == 0:
        temp = xor_words(sub_word(rot_word(temp)), [RCON[(i//n_k)-1], 0, 0, 0])
    elif n_k > 6 and i % n_k == 4:
        temp = sub_word(temp)
    key_schedule.append(xor_words(key_schedule[i - n_k], temp))

# Convert key schedule into a list of round keys
round_keys = [key_schedule[4*i : 4*(i+1)] for i in range(n_r+1)]
return round_keys

def add_round_key(state, round_key): return [[state[row][col] ^ round_key[row][col] for col in range(4)] for row in range(4)]

def sub_bytes(state): return [[S_BOX[byte] for byte in row] for row in state]

def shift_rows(state): shifted_state = [] for r in range(4): shifted_state.append(state[r][r:] + state[r][:r]) return shifted_state

def mix_columns(state): def xtime(a): return (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)

def mix_single_column(a):
    t = a[0] ^ a[1] ^ a[2] ^ a[3]
    u = a[0]
    a[0] ^= t ^ xtime(a[0] ^ a[1])
    a[1] ^= t ^ xtime(a[1] ^ a[2])
    a[2] ^= t ^ xtime(a[2] ^ a[3])
    a[3] ^= t ^ xtime(a[3] ^ u)
    return a

state_columns = [list(col) for col in zip(*state)]
for i in range(4):
    state_columns[i] = mix_single_column(state_columns[i])
mixed_state = [list(row) for row in zip(*state_columns)]
return mixed_state

def aes_encrypt_block(plaintext_block, round_keys): state = [list(plaintext_block[i:i+4]) for i in range(0, 16, 4)]

# Initial Round
state = add_round_key(state, round_keys[0])

# Main Rounds
for round_num in range(1, ROUND_COUNT):
    state = sub_bytes(state)
    state = shift_rows(state)
    state = mix_columns(state)
    state = add_round_key(state, round_keys[round_num])

# Final Round
state = sub_bytes(state)
state = shift_rows(state)
state = add_round_key(state, round_keys[ROUND_COUNT])

# Flatten the state to get the ciphertext block
ciphertext_block = [state[row][col] for col in range(4) for row in range(4)]
return bytes(ciphertext_block)

def pad_data(data): padding_len = BLOCK_SIZE - (len(data) % BLOCK_SIZE) padding = bytes([padding_len] * padding_len) return data + padding

def generate_and_print_keys(password: bytes, iterations: int = 1000000): for i in range(1, 101): # Generate 100 keys try: generated_key, used_salt = generate_aes_key(password, iterations=iterations) round_keys = key_expansion(generated_key) # For demonstration, the AES functions are implemented but not used here hex_key = generated_key.hex().upper() print(f"Key {i}:\nGenerated 256-bit key (hexadecimal):\n{hex_key}\n") except ValueError as ve: print(ve) input("Press Enter to exit...")

if name == "main": user_password = input("Enter password: ").encode() generate_and_print_keys(user_password)

EDIT:

Here is a pastebin

52 Comments
2024/11/20
11:08 UTC

0

Need Help with OpenSSL Benchmarking on FPGA

2 Comments
2024/11/19
09:12 UTC

1

I've finished the implementation of my end-to-end application/device security and I'm of the mind to make it available for others to review. Is that a good/bad idea?

My design principles for it stem from my security consulting I did for government. So it could be considered overkill. It’s at least bank-grade security. I’m of the mind that the model should be available to anyone to review; it doesn’t depend on secret methods that, if discovered, weaken or expose the security.

The application will run on (modern) iphones, connecting securely to backend servers.

The security architecture includes:

1. Hardware-backed key storage using Secure Enclave
2. Zero trust model for all requests
3. No shared secrets between client and server
4. Generic error responses (404) for all security failures
5. Granular encryption per nugget
6. Complete logging of security events

An example component of the model:

```mermaid
sequenceDiagram
    participant SE as Secure Enclave
    participant App as iOS App
    participant Auth as Auth Service
    participant Server
    participant DB 

    App->>Auth: Google/Apple Sign-in
    Auth-->>App: ID Token
    App->>Server: Authenticate
    Server-->>App: JWT Token

    App->>SE: Generate ECDSA Key Pair
    SE-->>App: Public Key
    App->>Server: Register Device
    Note right of App: Device ID, Public Key, JWT
    Server->>DB: Store Device Info
    Server-->>App: Registration Success
```

Is publishing it (making it available here for example) a good or bad idea? Pros? Cons?

5 Comments
2024/11/18
04:18 UTC

8

Introducing CommunisP: A Peer-to-Peer Encrypted Chat Platform Built with WebRTC and Modern Cryptography

I've been developing a project called CommunisP, a peer-to-peer (P2P) chat application that prioritizes end-to-end encryption and user privacy.

It leverages WebRTC for real-time communication and integrates robust cryptographic protocols to secure the exchange. I'm sharing it here to gather feedback, especially on the cryptographic aspects, from experts in this community.

Overview

CommunisP aims to provide a secure and private communication channel without relying on centralized servers for message storage or relay. By using WebRTC Data Channels, it establishes direct connections between peers, minimizing the potential points of failure or interception.

Cryptographic Implementation Details

Key Generation and Exchange

ECDH Key Exchange

  • Algorithm: Elliptic Curve Diffie-Hellman (ECDH)
  • Curve: P-256 (also known as prime256v1 or secp256r1)

Each peer generates an ephemeral ECDH key pair for each session. The public keys are exchanged to compute a shared secret, which forms the basis for symmetric encryption.

ECDSA for Authentication

  • Algorithm: Elliptic Curve Digital Signature Algorithm (ECDSA)
  • Curve: P-256
  • Hash Function: SHA-256

To prevent man-in-the-middle (MitM) attacks, public keys are signed using ECDSA. Each peer signs their ECDH public key with their ECDSA private key before sending it. The recipient verifies the signature using the sender's ECDSA public key, ensuring the authenticity of the key exchange.

Steps for Secure Communication Setup

  1. Key Pair Generation:
    • ECDH Key Pair: Used for deriving the shared secret.
    • ECDSA Key Pair: Used for signing the ECDH public key.
  2. Public Key Signing and Exchange:
    • The ECDH public key is signed using the ECDSA private key.
    • The signed public key and the ECDSA public key are sent to the peer.
  3. Verification:
    • The recipient verifies the ECDSA public key's authenticity by computing its SHA-256 fingerprint.
    • The ECDH public key's signature is verified using the sender's ECDSA public key.
  4. Shared Secret Derivation:
    • Using their ECDH private key and the peer's ECDH public key, both parties compute the shared secret.
  5. Symmetric Key Derivation:
    • The shared secret is used to derive a symmetric key for AES-GCM encryption.

Message Encryption and Integrity

AES-GCM Encryption

  • Algorithm: Advanced Encryption Standard in Galois/Counter Mode (AES-GCM)
  • Key Size: 256 bits (derived from the shared secret)
  • IV: 12-byte random Initialization Vector generated per message
  • Authentication Tag: 128 bits

AES-GCM is chosen for its performance and ability to provide both confidentiality and integrity in a single operation. Each message is encrypted with a unique IV to ensure semantic security.

Additional Security Measures

Public Key Fingerprints

  • Purpose: Allow users to manually verify the identity of peers via an out-of-band channel.
  • Method: Compute the SHA-256 hash of the ECDSA public key to create a fingerprint.

Ephemeral Keys

  • Rationale: Enhance forward secrecy by ensuring that compromising one session's keys doesn't affect others.
  • Implementation: Keys are generated per session and are not stored long-term.

Challenges and Considerations

Man-in-the-Middle (MitM) Attacks

While ECDSA signatures authenticate the public keys, the initial exchange still relies on a signaling server for coordination. To mitigate MitM risks:

  • Out-of-Band Verification: Users can compare public key fingerprints through a trusted channel (e.g., in person, via a phone call).
  • Trust On First Use (TOFU): Accept the key on first connection but alert users if the key changes subsequently.

Key Compromise and Forward Secrecy

  • Ephemeral Key Usage: By generating new ECDH keys for each session, we limit the exposure in case a key is compromised.
  • Future Work: Considering implementing protocols like Double Ratchet (used in Signal) to achieve perfect forward secrecy in long-running sessions.

Replay Attacks

  • Current Status: AES-GCM's use of a unique IV per message helps prevent replay attacks within a session.
  • Consideration: Implementing sequence numbers or timestamps to detect and reject replayed messages.

Denial of Service (DoS) Attacks

  • Resource Limitation: The application monitors and limits the number of concurrent connections.
  • Connection Validation: Initial handshakes involve cryptographic operations that are computationally inexpensive to minimize DoS impact.

User Experience vs. Security Trade-offs

Balancing ease of use with security is a significant challenge:

  • Key Verification: Manual fingerprint verification enhances security but may hinder user adoption.
  • Automated Trust Models: Exploring ways to streamline verification without compromising security.

Architecture Overview

Frontend

  • Technology: Plain JavaScript and HTML5.
  • Communication: WebRTC Data Channels for direct P2P messaging.
  • Encryption: All cryptographic operations use the Web Cryptography API.

Backend

  • Purpose: Minimal server used solely for signaling during the initial WebRTC connection setup.
  • Technology: Node.js with Socket.IO over secure WebSockets (WSS).
  • Role: Does not handle or store any user messages.

STUN Server

  • Function: Assists with NAT traversal to establish P2P connections.
  • Implementation: Custom STUN-like server to facilitate peer discovery.

Areas for Feedback

I am particularly interested in the community's thoughts on:

Cryptographic Protocols

  • Security of Key Exchange: Are there any vulnerabilities in the way ECDH and ECDSA are implemented together?
  • Use of AES-GCM: Is the use of AES-GCM with a random IV per message sufficient, or should additional measures be taken?
  • Key Derivation: Should a Key Derivation Function (KDF) like HKDF be used on the shared secret before using it as an AES key?

Authentication Mechanisms

  • MitM Prevention: Suggestions for improving authentication during key exchange without sacrificing usability.

  • Best Practices

  • Secure Coding in JavaScript: Recommendations for handling cryptographic operations securely in a browser environment.

  • Handling of Cryptographic Material: Ensuring keys and sensitive data are managed correctly to prevent leaks.

Future Enhancements

  • Perfect Forward Secrecy (PFS): Implementing protocols like the Double Ratchet algorithm for continuous key renewal.
  • Post-Quantum Cryptography: Thoughts on integrating post-quantum algorithms to future-proof the application.
  • Group Chats and Multi-Party Encryption: Approaches for securely extending to group communications.

Conclusion

CommunisP is an ongoing project aimed at creating a secure and private communication platform using modern cryptographic techniques. I believe that with insights from this knowledgeable community, it can be strengthened and refined.

Demo Website: CommunisP

For those interested, here's a high-level diagram of the key exchange process:

  1. Alice and Bob generate their own ECDH and ECDSA key pairs.
  2. Alice signs her ECDH public key with her ECDSA private key and sends it along with her ECDSA public key to Bob.
  3. Bob verifies the signature using Alice's ECDSA public key.
  4. Bob repeats the same process, sending his signed ECDH public key and ECDSA public key to Alice.
  5. Both Alice and Bob compute the shared secret using their ECDH private key and the other's ECDH public key.
  6. Messages are encrypted using AES-GCM with keys derived from the shared secret.
25 Comments
2024/11/15
20:20 UTC

Back To Top