r/explainlikeimfive • • 9h ago

Technology ELI5: Public/Private Key Encryption

How does public/private key encryption actually work? I have a serious mental block about this. I've searched and read other explanations and I'm still not getting it, so I'm really hoping for some kind of simplified examples that involve actual math and values. I just watched a video about SSH with key login, so maybe that specific example would help.

I generate a public key and then save it to the server, but I'm transmitting that key when I log into the server, and that has to be in plain text, so how is that secure? What is it that stops someone from reading my key and then just logging in as me?

Edit: Thanks everyone. 1) Understood, I made an error here and you don't transmit the key (I was thinking about how you establish encrypted communications with a website, but that's not the question I asked) 2) I somehow missed that when you generate a key it's both a private key and a public key. The private key part was what I was missing.

28 Upvotes

78 comments sorted by

•

u/nudave 9h ago

I have had this exact question. I hope my comment doesn't get deleted for simply linking a video, but this video (and part 2) does exactly what you want - go through one style of public key encryption (RSA) using very small prime numbers to give you the example of how it works:

https://www.youtube.com/watch?v=4zahvcJ9glg

It is the only thing that was able to get me to wrap my head around how "two prime numbers that no one else knows" can form a private key while "those same two numbers multiplied together" can form the public key. The short, short answer is "modular exponentiation." The video doesn't quite ELI...5, but it definitely is good to ELI'm someone who did okay in high school math but doesn't understand this issue at all.

•

u/bluecete 8h ago

This was super helpful, thank you!

•

u/No_Perspective_44 9h ago

Calling both strings "keys" isn't very intuitive. I prefer the "lock" and "key" analogy. The public key is a lock, the private key is the actual key.

Running with the analogy, the server says "if you're really who you say you are, you can open this locked box". It can safely send the box to you, where you unlock it in private so the key stays secure, and then you send the opened box back. It knows that only the keyholder could open the lock, meaning you are who you say you are, so you can log in.

•

u/boring_pants 5h ago

The problem is they can both play both roles. You can use the public key to encrypt a message which can be decrypted with the private key and vice versa.

They are both keys.

•

u/No_Tamanegi 9h ago

The public key is a lock, the private key is the actual key.

That's actually really helpful. I've always understood modern encryption by way of the "lockbox with space for two locks" analogy, but I never really understood how the public key worked in that scheme.

•

u/MattytheWireGuy 8h ago

No ita not two padlocks, it's like having a box of padlocks sitting next to your mailbox and anybody can lock up a message with one of those padlocks, but only you know the combination to unlock the padlock. Technically someone could guess the padlock code or attempt to pick the lock, but the padlock is built in such a way that that could take millions of years to successfully do it.

there is another aspect of it, though that you can prove to somebody else that you know the private code without actually showing them the private code

•

u/Fixes_Computers 2h ago

After reading a bunch of these, I think of it as one lock with two keys.

It doesn't matter which key is used to lock it. You can only unlock it with the other key.

At some point, a decision is made which key is public and which is private. "Everyone" has the public key. Only you have the private key.

If you lock it, anyone else can unlock it and know it was from you. Similarly, if one of them locks it, they know only you can unlock it.

•

u/nicuramar 9h ago

Yeah, but in public/private encryption, either key can encrypt for the other one to decrypt. And this is used for signatures.

•

u/flatfinger 8h ago

I think it would be more helpful to use the term "recipe" rather than "cryptographic key". Feeding a document to a public signature recipe will yield a lock that will only accept a key that produced by feeding the private recipe a copy of the same document.

•

u/MattytheWireGuy 8h ago edited 8h ago

Thats a hash not a key They live in the same world but they are not the same thing.

That said, hashes are typically signed with the private key but they do completely different things.

•

u/flatfinger 8h ago

The "lock operating device" that the public recipe produces from the document is the "lock operating device" that the private recipe produces from the document. The "lock operating device" isn't a "cryptographic key", but what other term would one use for something that is put into a lock to see if it's accepted.

•

u/jimtsurugi 7h ago

In this context, your recipe is the algorithm or cipher. Instructions on how to use the public secret to encrypt something, or use the private secret to decrypt something that was encrypted with the public secret.

Fun Fact: The keys are cryptographically interchangeable, in that each key can only decrypt something encrypted with the other key. We label one as private so that you always keep the same one secret.

•

u/flatfinger 6h ago

Someone who signs a document needs to produce something that can be validated by something else. One might view a signature authentication method as a recipe for converting a collection of bits that represents a cryptographic private key into a "device" that can in turn convert a document into a signature, but it's just as simple to view as a recipe the procedure "feed this collection of bits into a specified cryptosystem to get a means of converting documents into signatures".

•

u/jimtsurugi 6h ago

In your analogy, is the key is part of the device, or is the key input along with the data into the device?

•

u/flatfinger 5h ago

The key is the collection of bits identifying the signature, and the lock would be a means of determining whether to accept or reject the key.

•

u/GendoIkari_82 9h ago

I give you a public key, which acts like a rule to apply when encrypting your message. "Add an X after every character". So when you want to send me "Hello", instead you now send me "HXeXlXlXoX". Only I know the private key, which is a secret rule like "Remove every other character from the message". So when I receive your "HXeXlXlXoX", I can apply my secret rule and end up with "Hello".

So like that but way more complicated. The point is that the public key allows a message to be encrypted in such a way that only the private key can decrypt it.

•

u/MattytheWireGuy 8h ago

Id argue it actually isnt much more complicated than that. What makes it nearly impossible to determine is that factoring a number into two distinct primes is completely brute force. Creating the public key is simple multiplication but reversing it could take millions of years to guess the two primes.

•

u/wrosecrans 8h ago edited 7h ago

That's pretty much exactly where people get stuck learning it.

The simple math operations you use in an "ELI5" type high level conceptual answer are easy to reverse. So with a simple explanation, it "feels" like the public key should be enough information to decrypt any message encrypted by that key. Explaining why the operation is asymmetric pretty much requires "and then just look at the raw math of the real operations" which the student is either ready to dive into, or absolutely isn't.

•

u/MattytheWireGuy 8h ago

Yeah I think the issue people overlook is that factoring isnt necessarily easy and there isnt an equation to do it other than choosing two cofactors and putting them through the equation to create the key. If you back up to just simple division, you still have the major road block of factoring which requires either rote knowledge or brute forcing.

•

u/hotel2oscar 8h ago

And you can also flip it: any message encrypted by the private key can only be decrypted by the public key. That's how you prove you wrote the message and is used to sign things digitally.

•

u/msthe_student 9h ago

Your public key is calculated from your private key, in such a way that your private key can't be calculated from your public key. When authenticating, a challenge-response mechanism is used, where the correct response can only be calculated by someone who has your private key.

•

u/nicuramar 9h ago

The public and private key are calculated together, the public key isn’t calculated from the private, typically.

•

u/JivanP 8h ago

That is completely false. For example, in systems that rely on cyclic groups over a ring, such as RSA (multiplicative group of integers modulo a product of two primes, over the ring of integers) and ECC (additive group of elliptic curve points over the ring of integers), the public key is defined as the group-combination of the group generator and the secret key.

•

u/Temporary_Pie2733 7h ago

Isn’t the main difference between the private key and the public key which you choose to keep public and which you choose to keep private? Or is that only true when the generated exponents have roughly the same size? (I know a smaller exponent is usually preferred for the public key to make encryption more efficient, but I don’t know if that’s required for other security reasons.)

•

u/JivanP 7h ago edited 6h ago

Isn’t the main difference between the private key and the public key which you choose to keep public and which you choose to keep private?

In RSA, yes. In general, no.

In both RSA and ECC, the public key is derived from the secret key. However, in RSA specifically, the public key consists only of the public exponent, whereas the secret key consists of a secret exponent and the trapdoor values (the prime factors of the modulus being used). The mathematical roles of the public exponent and the secret exponent are interchangeable, and if the trapdoor values are known, then either one can be derived from the other. The fundamental thing that RSA's security relies on is the difficulty of deriving the secret exponent from the public exponent. The only good ways we know of to do this are to know the trapdoor values, or to use Shor's algorithm, which exploits the periodicity of finite cyclic groups. The multiplicative group of integers modulo a number, which is what RSA uses, is a finite cyclic group.

In ECC, the role of the modulus is replaced by the "order" (number of elements) of an elliptic curve group. The order itself is prime or near-prime (a small multiple of a prime), not a product of two very large primes like the modulus of RSA. ECC doesn't rely on the same trapdoor mechanism as RSA. The public key is derived directly from the secret key (they are both elliptic curve points), and the fundamental thing we're relying on for the security of the scheme is the difficulty of computing the secret curve point from the public curve point. The only good way we know of to do this is Shor's algorithm; factoring the order is not helpful, and in fact the factors are publicly known. The elliptic curve groups used by ECC are finite cyclic groups, so Shor's algorithm applies to them also.

Other schemes use other problems that are believed to be difficult to solve, such as the LWE ("learning with errors") problem used by ML-KEM (a.k.a. CRYSTALS-Kyber) and ML-DSA (a.k.a. CRYSTALS-Dilithium), and the one-wayness of (i.e. difficulty of inverting/reversing) cryptographic hash functions that is used by SLH-DSA (SPHINCS+). The nature of the keys, how they're derived, and how they're used, is highly scheme-specific and does not resemble RSA or ECC at all. LWE-based and hash-based schemes such as these are dubbed quantum-resistant, because there are no known ways of solving those problems, not even with a quantum computer. Videos 3, 4, and 5 of this playlist give an excellent overview of LWE if you want the mathematical details, this 40-minute lecture by Another Roof goes through some worked examples, and this other 40-minute lecture by Another Roof goes over SLH-DSA (which, despite the video's title, is a digital signature scheme, not an encryption scheme).

•

u/garagedragon 9h ago edited 9h ago

You do not transmit any keys when you login to the server. As a simple example, the server sends you a random number (the "challenge", often tied to the current time in practice) and you use your private key (which never leaves your machine) to sign this number, and send the number and it's signature back to the server. The server can then use your public key to verify the signature, and it's a property of the system that the only effective way to produce a signature that can be verified by the public key, is to know the private key. That means the server can conclude that you, who produced a valid signature, are in possession of the right private key, without ever directly seeing it.

Even with everything in plaintext, nothing that goes over the wire is useful for an attacker. Even if the attacker records your signed number, it's only useful if the server challenges them with the same original number when they try to connect, and you can make that vanishingly unlikely just by making the number, say, 64 bits long. If the number contains the current date/time, then it will never show up again and the attacker won't be able to use the recorded signature ever. (This is called a "replay attack.")

Usually the next step after this is the server uses your public key to encrypt data it sends you, and the decryption can only be performed by the private key. Again nothing useful to the attacker goes over the wire, because the private key never leaves your device and the encrypted data is useless without that.

•

u/bluecete 9h ago

Thank you. I think this helps the most. I suppose I mixed up my situations here, because over SSH you're not transferring the key in plaintext, because you have to login first (with a password). But there are situations where you are transmitting your public key, right? Like otherwise how do you ensure that communication with any random website is encrypted. Though, that's probably out of scope for this question.

I think what always got me is that whenever I read about this they always talk about generating a public key and somewhere along the line the fact that you are simultaneously producing a private key is just glossed over (or I missed it).

So basically when I run the command to generate a key, I'm really generating two keys. I send the public one to the server (over an encrypted connection, because we're talking SSH and I previously logged in). Now I don't have to use the password because it has my public key. When I walk to talk to the server it looks up my personal public key, generates something that only I can decrypt (with my private key) and once I do that, I've proven who I am and we can continue to exchange data.

•

u/KarlSethMoran 9h ago

You don't care about sending the public key securely. It's public. For what's it worth, you can put it in your email signature or on your LinkedIn profile.

You only need to keep your private key secure.

•

u/garagedragon 8h ago edited 8h ago

Yes, you produce the pair at the same time. SSH is entirely able to login directly with a keypair, and no password. This is arguably more secure because it's impossible to spoof, whereas an attacker could attack passwords by things like reversing hashes or brute-forcing the server with a botnet, particularly because passwords are almost always human-generated and therefore less random than keypairs. (Normal websites are getting on this too, directly logging in with a keypair is what a "passkey" is.)

Transmitting your public key is fine - it's public after all - but it's less useful than it sounds because if the server hasn't seen that key before, then sure, it can set up encryption with you, but it doesn't know you from Alice. It doesn't know if you're presenting the "right" public key, because it has no comparison. Websites get around this with "certificates" which are effectively signed attestations from someone you do know (the root authorities, who's public keys are stored in your OS and browser) that this public key belongs to this person, but those aren't usually used in SSH

"Anonymous" encryption even without any previously exchanged keys can be done with something called Diffie-Hellman key exchange, which effectively sets up a temporary keypair for just that one communication and uses that to setup the encrypted tunnel. I expect this is what SSH does when you login with a password, but I don't know off-hand.

In practice, if the server has your public key already, you do a combination of both - you sign the DH outputs with your private key but then use those outputs to set up the tunnel, and the server does the same. This ensures you both know you're talking to the right person (Mallory would not be able to produce signatures) but also protects you from an attacker who records the conversation and then steals your long-lived keys later. If you'd directly used your long-lived keys to set up the tunnel, the attacker would be able to decrypt them after stealing your private keys.

•

u/suvlub 9h ago

What is it that stops someone from reading my key

Nothing.

and then just logging in as me?

The fact that you are using asymmetrical cypher and the key you've just sent is used to encrypt while a different key you never ever must give to anybody is used to decrypt. The attacker could send you a secret message if he wanted to, but that's it.

•

u/Temporary_Pie2733 7h ago

There is a point worth mentioning here; since anyone could have your public key, you can’t assume that the remote end is who they say they are just because they can decode your signed challenge. That’s where host keys come in, so that you can verify that the challenge comes from the host it claims to be. 

•

u/No_Tamanegi 9h ago edited 9h ago

This is a very rudimentary explanation but its the one that's always helped me understand it. You want to send someone who lives in your city a secure message. So you create a lockbox that has space for two padlocks. You place the message inside the lockbox and place your padlock (which you have a key to) on the box, and you send them the lockbox. The key to your padlock is your private key.

When they receive the box, they place their padlock on the box. It is locked with their private key. Then they return the box to you.

When you receive the box, you unlock and remove your padlock, but the lockbox is still locked with their private key. You send the box back to them.

When they receive the lockbox the second time, they are able to unlock their own padlock with their private key and receive your message. Most importantly, both parties are able to make secure transactions without compromising their own personal security.

As I've learned from other commenters, in this analogy, your public key is actually your padlock, and your private key is the key that opens your padlock. Its a cumbersome process when dealing with physical security, but with digital messages it works largely the same way, only in a minimal amount of time.

•

u/Rikudou_Sage 9h ago

That's kinda wrong. Better analogy would be I send you a lock (public key) and a box, you put a message in the box and then lock it. You send it back to me, I open it with my key (private key).

You (nor anyone else) ever had the means to unlock it after you locked it.

•

u/No_Tamanegi 9h ago

Its the same idea, yours is simplified.

•

u/britishmetric144 9h ago

Imagine that I want to send you the message "Reddit sucks", but I want to encrypt it so that no one can steal it.

You broadcast your public key. In this case, it's "type everything two characters to the left, and wrap around if not possible".

What I send to you is "Wqaaye itzhl."

If you apply the same public key, it won't work. You'll get "Pokkrq yenfj."

But you know that your private key is "type everything two characters to the right, and wrap around if not possible".

So when you decrypt what I send you, you get back the original "Reddit sucks".

The benefit is that if you can keep your private key a secret, you can distribute your public key everywhere without losing security.

---

I used a simple example here to make it easier to understand. But, with mathematics, there are functions for which it would take a supercomputer more than the lifetime of the universe to reverse, which proivies the security.

•

u/MattytheWireGuy 8h ago

Well that's true with traditional computers, quantum computers don't have the same roadblocks to factoring and that's why new encryption methods that can't be calculated by a quantum computer are being developed. It's also why the US and other nation states are archiving all the encrypted traffic on the internet, they believe they will be able to decrypt all of it sooner or later.

•

u/aqualad33 9h ago

Private key systems only have one key, that key both scrambles and unscrambles the data. Right now we have an extremely secure private key system AES256. The problem though is how do you get this key to the other person without anyone else seeing it? Because if they see your key, then they can also unscramble your data.

Here's where public key systems come in. They typically are harder to make as secure. Or in order to make them as secure you sacrifice efficiency. However, they come with 2 keys instead. One that scrambles data, and one that unscrambles data. You can share the one that scrambles data with the general public and its totally fine if everyone sees that key. You hold onto your unscrambling key and that's the one you have to protect.

Now anyone can scramble message and send you these scrambled messages that only you can unscramble. Often times what they will be sending you is a key to a private key system so you two can just switch to that instead and just use the better system now that you have gotten past the road block of how do you exchange the key securely.

•

u/itsflowzbrah 9h ago
  1. You generate a Public and private key locally
  2. You give the public key to the server and tell it "anything that has the corresponding private key for this public key can log in". Since its the public key its fine if someone steals it. They still dont have the private key that identifies you.
  3. When you log in, you tell the server, "hey, i want to log in with public key ID 123". The server then encrypts a message with that public key. Only the private key can decrypt it. Youre the only person with the private key.
  4. You decrypt the message using your private key. Hash the resulting plaintext. And send the hash back to the server.
  5. The server verifies that the hash you provided is the correct hash for the message it sent in step 3.

The only way you can get that hash, is if you have the private key so the server can trust that you are who you say you are.

•

u/erroneousbosh 9h ago

Think about how a lock works, just a shitty wafer lock like on a mailbox. You put the key in and it pushes little brass plates with holes in them up and down against springs. If you put the right key in, all the plates line up with the lock cylinder and it turns freely, so you can lock and unlock it.

Okay now can you imagine making it a bit bigger and on one side you put a ratchet that stops the key unlocking if it's not the right cut but will let it turn to lock, and on the other another ratchet stopping it locking but will let it turn to unlock?

Now let's take it a bit further and involve a very clever Swiss person who can make all kinds of cool locks. If you lock it with one key it can only be unlocked with the other. Got it?

You can then post a picture of the "public" key online and we all make copies of it. You keep your private key a secret. You can give away part of the key's pattern just enough so you and I can prove we each have a copy of a matching pair, but only you know the secret part of your private key.

I make a copy, you send me a cashbox that you've locked, I open it, and it can only have been locked by you. I put my reply in the box and lock it, and only you can open it.

If you wanted it to be totally secure so only you and I see the messages, you make a copy of my public key, lock your message in a cashbox with your private key (so only you could have locked it but anyone can open it) and then lock that in a bigger box with my public key (so anyone could have locked it but only I can open it).

•

u/2wicky 9h ago

Lets say you have small secure box with a lock. It accepts two keys. One public key can only lock it and one private key can only open it.

So when someone wants to send you a message, you send the unlocked box with the public key that can lock it. When they receive the box, they write their message, place it in the box, then use the key to lock the box. Once the box is locked, they can't use that same key to unlock it. Neither can anyone else that may have made copies of that key.

They then send the box back to you.

You still have the second private key that can now unlock that box and read the message inside it. This key, you need to keep secret, meaning you never share it with anyone. Otherwise, anyone that has a copy of your private key could intercept any boxes sent your way, unlock it and read your messages.

•

u/CheezitsLight 9h ago

Short answer is to the question is and your password. The password is encrypted with the public key which only the server can decrypt with the private key. Since no one else has your password it's secure.

•

u/MattytheWireGuy 9h ago edited 9h ago

imagine it like Legos the public key for sending you encrypted messages is similar to someone handing you a fully assembled Lego project and asking you if it looks the same as the picture on the box. The private key side would be like them, handing you a completely disassembled box of Legos and you have to create that project. The only way you can do that is if you have a secret set of instructions for doing it.

checking if the completed Lego project matches the box is super easy trying to re-create it from 10,000 loose bricks is the complete opposite.

in cryptography like this, it’s extremely difficult to determine the prime numbers that the private key is based on using only public information but if you have the prime numbers, you can create a public key out them in milliseconds while it could take millions of years to properly factor the public key.

•

u/SirPriseTheEigth 9h ago edited 9h ago

Imagine an equation like y = mx + c. Given x and y, it’s (computationally) difficult (essentially impossible) to figure out what m and c are. It becomes much more difficult the larger x,y,m,c become. In this scenario m and c are the private key (if I know m and c I can solve for any y given x) and x is the public key. This is quite heavily simplified (although not far off the LWE problem) and elliptic curves are slightly more complex…

•

u/MercuryInCanada 9h ago

Public key is like your mailbox address. Anyone can look it up and send you mail (encrypted messages) that the post offices (the internet) delivers to the mail slot in your front door. Because it's your mailbox you can the (secret) key to unlock the door and get your mail.

The public address provides public instructions on what math to do to the mail, while the secret key is the input to reverse all that math quickly,because trying to get the secret key out of the public key is very hard.

Now onto your second question. When you transmit that key to the server you've already engaged with more cryptography. The session is protected through some protocol that your machine and the serve execute to protect your messages. In these protocols the parties you digital signatures algorithms to sign the messages as a way to claim that the message came from the holder of the secret signing key tied to what's called a certificate. The certificate is basically the signature public verification key.

Again all this is backed with math that says just knowing the public verification key and some examples of the signatures that key verifies does not let anyone recover the secret key. The certificate is issued to your machine by a certificate authority whose job is to generate and distribute then to new machines.

•

u/pixel293 9h ago

With your private key you can "sign something" meaning you can generate a 256bit(?) hash of some data using your private key. Someone with your public key can verify that signature to check that whoever created it used your private key.

Someone can also use your public key to encrypt something, and only someone with your private key can decrypt it.

Using those methods a server can verify that the person connecting had the private key.

•

u/nicuramar 9h ago

What actually happens is that either key can encrypt something for the other to decrypt.

•

u/pixel293 8h ago

While that is possible, it is not standard, the public key is public, so what is the point of the encryption when anyone with the public key can read it? Hence, usually the private key is just used for signing something to prove it came from someone.

•

u/chillaxin-max 8h ago

Signing is done by encrypting (a hash of) the message with the private key. The signature is verified by decrypting the signature with the public key and confirming that the result is the (hashed) message

•

u/Temporary_Pie2733 8h ago

It’s better say that each key can transform data in a way that only the other key can reverse. When transformed by the public key, we call that transformation encrypting, and only you with your private key can decrypt it. When transformed by the private key, we call that transformation signing and anyone with your public key can verify that only you could have produced the signature. 

•

u/Lallner 9h ago edited 8h ago

The security of the original public/private key cryptosystems were based on the difficulty of factoring large numbers, so let's start there. Let p and q be prime numbers, and N =pq (N equals the product of p times q). It is much easier to compute N if you know p and q than it is to solve for p and q if you know N. Here's a real-life example. N = 4,235,339 is the product of two prime numbers, p and q. Finding p, q, and computing N=pq is computationally trivial. But I challenge you to solve for p and q given N (without using AI). You basically have to try trial division by dividing N by every prime number up to the square root of N. For VERY LARGE primes p and q, this becomes computationally infeasible in a reasonable amount of time. For the purposes of this explanation, N could serve as my public key, meaning I can publish it to the world, but p and q are my private key which remains secret even though I published N=pq. If you want to know how to use this mathematical property to create a complete cryptosystem, let mw know and I will elaborate, but it gets into more advanced number theory using discrete logs.

•

u/biggles1994 8h ago

A public private key encryption is two parts.

If you encrypt with the private key, only the public key can unlock it.

If you encrypt with the public key, only the private key can unlock it.

You cannot lock with private and unlock with private, or vice/versa, and you cannot deduce one key from knowing the other.

You shout from the rooftops your public key, everyone on the internet knows that this public key belongs to X person.

This means if you encrypt something with your private key, everyone can unlock it with your public key, and they know that you are the only person who could have locked it. This is signing to prove you sent something.

Similarly if someone wants to send you a message, they can encrypt it with your public key and only you can then reveal the message with your private key which nobody else knows.

If you want to send something to another person, you use their public key and encrypt the message and send it to them, safe in the knowledge that only they can unlock it.

Similarly if you receive an encrypted message and your friends public key unlocks it, you know that message just have come from your friend.

The hard part is how you trust that a public key belongs to a specific person/entity, as public key spoofing can be a thing, but that’s a different issue.

•

u/FishBrainn 8h ago

Both are keys that lock and unlock, but with a rule: when you lock with one, you can unlock with the other.

Your public key is for everyone: your parents, siblings, the clerk at the store, everyone gets a copy of your public key.

Your private key is for you and you alone. You share it with no one.

So, I have two packages. I lock the first one with my public key. This means I need my private key to unlock it. Or consider this: use the public key of the store clerk. This way, you can only unlock it with the private key of the store clerk. This guarantees that only the person with the private key can unlock it.

Package two I will lock with my private key. This way, everyone can see I and only I has locked the package. "Can you open the package? That means you have sent it"

And to further expand this: what happens if I use both keys?

•

u/d1722825 8h ago

In the SSH case you are not really using the public key cryptography to encrypt things, but to create digital signatures.

You could think about digital signatures as wax seals on paper. You can easily check if the pattern in the wax matches a pattern drew on a piece a paper, but it is hard to form or shape a piece of metal to produce the right pattern if you press it into molten wax.

In that case you could give out the drawings of the pattern of your wax seal to anyone (eg. to the SSH server) without any fear, because nobody would be able to recreate the original seal.

But you could use your seal to create original wax seals on any piece of letter, and anybody who has the drawings of the pattern could check that no one but you could make that.

If you want to authenticate to an SSH server with keys, first you share your public key with the server (or with anyone if you wish), it is useless for anything except verifying that a digital signature have been made with your private key.

Then when you want to log in, you use your private key to sign a "yes, I really wish to login" message and send that to the server. This message doesn't contain your private key, and your private key can not be recovered from it. Then the server checks the list of trusted publik keys, and verifies that this message was signed by a private key corresponding to one of the trusted public key on that list.


Note that this has nothing to do with encryption or confidentiality.

To hide the contents of the communication, SSH uses public key cryptography to create an encrypted channel between the two machines, but that is done even if you use password to login.

https://en.wikipedia.org/wiki/Key-agreement_protocol

•

u/Mr_Engineering 8h ago edited 8h ago

There are two sides to public/private cryptography, secrecy and authentication.

As far as secrecy is concerned, any message encrypted using a public key can only be decrypted using the corresponding private key. If I give you my public key, and you encrypt a message with it, only I can read that message. Clients and servers use this method of asymmetric encryption to secretly negotiate a shared symmetric encryption key which is much faster.

As far as authenticity is concerned, a digital signature can be generated for any digital sequence using a private key, and then have its integrity verified using the corresponding public key. This is used to create a chain of trust to ensure that data has not been modified since it was originally generated by its original author.

•

u/Raiddinn1 8h ago

Two parties A and B both generate their own private and public keys.

Both sides just hand the other side their public keys.

Both sides encrypt some phrase like "Information wants to be free" using their own private key and the public key of the other side.

Both sides send the encoded phrase to the other side to act as a signature each of them can store internally.

Each side will send information using the public key of the other side along with the signature.

Each person in the world knows the public key of both parties, only A and B have the signature stuff. So if person C tries to send something using the public key of A while pretending to be B, but without the signature of B, then the message will be disregarded. It would appear valid, but we couldn't trust the sender is who they say they are.

•

u/BiomeWalker 7h ago

We call them both keys, but they're actually both locks and keys.

You want to send a message to someone, and you want only them to be able to read it, but that can be tricky.

RSA encryption is one of the common choices today that uses public/private keys, and it has a simple relationship between its keys.

Your computer generates a pair of really, really, really really large prime numbers, those serve as the private key. It then multiplies them together, which makes the public key.

Now that we have them, let's go over their use. The actual inner workings are way beyond ELI5, but how they're used isn't hard to understand.

Each key can be used to "lock" (encrypt) a file (all files are just large binary numbers) in a way that requires the other key to unlock (decrypt).

Important note here, the private key can be used to generate the public key, but taking a public key and getting the private one requires factoring a number with over 600 digits (when written in decimal, 2048 in binary) which has a time requirement in the range of millennia to accomplish.

The initial exchange of keys is often "backed" by what's called a "certificate authority", which has a way of signing the keys you get. This looks like creating an additional segment to the file which the public key will verify could only be generated with the secret key.

How does your computer know to trust that initial signature? Your OS came with the knowledge to verify it, including the required public keys to initially talk to the CA.

•

u/finn_tate644 6h ago

Honestly, the math isn't what's blocking most people. It's that explanations blend two different jobs into one. Locking works like handing out open padlocks: anyone can snap one shut on a box, but only your key opens it. SSH login is the other job, signing: the server hands you a fresh note, you stamp it with a stamp only you own, and it checks the mark against the stamp pattern you gave it earlier, so your private key never leaves your laptop.

•

u/boring_pants 5h ago

The trick is that you have a pair of keys. Thanks to mathematical trickery it's possible to come up with a pair of encryption keys which complement each others. You can use the first key to encrypt a message which can then be decrypted only using the second key. And you can use the second key to encrypt a message which can then be encrypted only by the first key.

Once you have that all you have to do is share one key with the person you want to talk to (the public key), and keep the other to yourself (the private key).

If they want to talk to you, they use your public key (which you hand out freely, so anyone can use it) to encrypt a message. Everyone can do this, but only you can decrypt the message, because only you have the private key.

Of course, you can't really send an encrypted message back using only this, because if you were to encrypt a message using your private key everyone who has access to your public key can decrypt it, and your public key is available to everyone.

So instead, what happens is that when someone wants to talk to you they encrypt the message as described above, *but the message contains another encryption key.

And no one except you and the sender have access to that encryption key, so you can use that to respond to them.

•

u/Slight_Albatross_860 5h ago

Public key = result of multiplication (over simplified but works) of prime numbers like 7 and 11

Private key = the prime numbers 7 and 11 which make up the public key.

The idea is that it is easy to calculate the public key but much more time consuming to calculate the original prime numbers. When the prime numbers are about length of 2000 bits, normal computers take many lifetimes to resolve the private key from public key.

•

u/MultiFazed 9h ago

I'm transmitting that key when I log into the server,

That's not correct. To over-simplify a bit, you're encrypting some message with your private key and sending that encrypted message to the server. The server then uses your public key that you sent them earlier to decrypt the message. If the decryption is successful, that means that you have the private key that is paired to that public key, which means that you're you.

•

u/chaossabre 6h ago

Still not quite right. You encrypt your message (login request) with the server's public key, so that only the server can decrypt it using their private key. If you encrypted it with your private key then anyone including attackers can decrypt it with your public key.

•

u/aviddd 9h ago edited 9h ago
  1. A public key can only encrypt, not decrypt
  2. Only the matching private key can decrypt.
  3. The private key can also add a "signature" to a chunk of data, which means anyone with the public key can prove the data was vouched for by the private key and not altered in any way.
  4. When you attempt to log in the SSH server generates a one-time challenge "password" and encrypts it with your public key. You decrypt it with your private key, and send it back encrypted with the server's public key.

This is a simplification but I hope it gives you a starting point

•

u/nicuramar 9h ago

This isn’t true. Either can encrypt for the other to decrypt and vice versa.

•

u/aviddd 8h ago

"this is a simplification". In common use the "Public" key is not treated as a secret.

•

u/MultiFazed 8h ago

However, the private key is used to encrypt the hash of messages to be used as a signature, which is validated by using the public key to decrypt it.

It's just not useful to encrypt entire messages with the private key.

•

u/aviddd 8h ago

That’sa good explanation but you may have to explain the concept of a hash to OP

•

u/BananaBird1 8h ago

Both can be used to reverse the hashing of the other, but when you encode a message with the private key it is not an encryption.

The private key contains enough information to reverse engineer the public key, but not the other way. So if you provide someone with the private key so they can encode a message for you to read with the public key, any third party intercepting your communication can find the public key and read the message as well.

Encryption is defined not just by a hash encoding, but by the security it provides. If you have to publicly share the key to decode a message in order to communicate, it is not an encryption.

This is why it is inherently asymmetric. The private key holder can read messages encrypted for them that just knowing the public key cannot decode, but cannot send encrypted messages. Only hashed signatures readable by anyone proving they hold the private key.

•

u/JivanP 8h ago

This depends entirely on the specific scheme in use. Not all asymmetric schemes have the same kind of mathematical relationship between secret key and public key as in RSA.

•

u/Temporary_Pie2733 7h ago

Either key can transform data in a way that can only be reversed by the other. When the public key does the transformation, we call it encryption. When the private key does the transformation signing, we call it signing. 

•

u/Henry5321 9h ago

The public key can decrypt content encrypted by the private key and the private key can decrypt content encrypted by the public key.

If you share the public key, all someone can do is verify you have the private key.

It’s called a public key because everyone can have your public key and use it to verify you. But no one can use the public key to impersonate you.

•

u/cajunjoel 9h ago

This is wrong. The public key can encrypt, but not decrypt. Only the private key can decrypt a message encrypted with its public key

•

u/zeekar 9h ago

I believe it depends entirely on which specific public-key cryptosystem you're using. Some really are symmetric, where both keys work both ways, but only in conjunction with the other. That is, only the public key can decrypt a message encrypted with the private and vice-versa.

In fact, in some systems it may not matter which key is chosen to be public and which private, as long as you only ever reveal one of them! But in other systems you do very much care which is which, since the nature of the math/algorithm means exposing the private key would also reveal the public key. That's not a problem as long as you assign them those roles, but it's a disaster if you get them the wrong way around.

•

u/Rikudou_Sage 9h ago

You can, at least with RSA. Not much reason to do that but you can.

Edit: Base64 of the encrypted string with a private key I just made:

iTNC4DJY/cXgLrgKysYGz14Qe06yDsJ1As7sU8Wkt9HDULks0RV8249u/lIQg9A9PI+D0qNS8KYR
i98/qnnE0bKNRRh8cCYWB607UV6F502+DWV6t6ghBAe787/hlT8XgIH0q2tDEPnPBhCV2QGCr+6I
lX1+31jsNTC/xOxwmNdtH2UDloV7l28Yta/paGRO6oI8/s8vYINgm03J278lxqSW6fUsXD03byku
pb9TFacoWsKPOO96nOFpsPGMc4olz22unEjrWNWt+TiSecIk5Y5/zcSFBazx+kykEWAESDBigUEM
bQEUsTcPILlzhsMovSozhr/CXgTvq/pie2/DeQ==

Here's the public key:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs1zSlmiaGEO5Sek6m7hX
7W0V+cIiQjSktokhHHLSDqX/bBJ1pEZAirOCCha32GsvB4plQzh+6XpH1rr4V7+F
AlCcLuP2HdXgroTRh4QUMSvHPAdDgkRAuYJ7LpL2nP1itC2stAeIamAxBsszXrPr
Kqa4RV8wPSf5nTpsDsTrsn4eqp/ND3Dv878Ru026MTCycxQQNhWsO3v0n6/QCOgg
Png4wj7265fsHnhKoM6wwJRglH4iaWHqRFqSlAmv7AblljwVLC6DJ7ENiC0at+Ev
hmw6cpG2M97zKYHTEFMxIUqcOP09v1Z0zxZ2gbv7l2VR2AjydA7+HSxXQ/06mEt+
TwIDAQAB
-----END PUBLIC KEY-----

•

u/MultiFazed 8h ago
VFv6e4Zox+oM+Z0AvBpg+pTWmvg1NJ3tvYsH53GTbDAB0flA8C+WkSwFzFMTDBDXbUcg8I8vdOhuHZOjvqFxTWavC06uavOIMuikkFPFSM2w6FNrz4obtM03/xUWJ7SXTGU0goXep+vQJ7o/CaIfo9/d+JwRtMgyhSCXNGOP6Xy6qMWY3PmhySuHrYwmoSO1kJhpuifBjKJ27M7x7nIYqnuGuIwt46huEpxTUnI8WxODolIlKumWYqloFDFuj2fPQztEgPNheWUMGwVw0LsbH19ZHqoJRNq/WclXUeTip/HYFm8RewQaRuNsQ9MySPmGzyE1x93moNMphcpATkIQRw==

•

u/Rikudou_Sage 8h ago
qX1wOlPUxk2NT2FRi32Pfwj+Qtikm1TCA8Csf7EAVrwWrKSIk3zruIq0ea1acSWXhxRxyHU1QtwI
STRAZ+tIRBTPs2bu1+QcPayO6bMVLBvcOnzhRX3vxUH67GO5MPRCjCB3JX6ENL6XcjHeIP0LDkvi
9NZwoBtVFl98K5bXkEvQtZrUCECK88kV6hcEa4yMe0Q00hmW6nOqv7qbXOBLxUqObxcuDEWBfdz6
bttZk0onX+5ZAZSiyp0AxIiEHAppb0kcUQbpPGOHFjRb2Ds8TZpFsegZHXYpBmq2hoLC3x9IkFpo
2sw8Cu/bWshdlpubMebP071iIUG5mnidmHgL+w==

•

u/nudave 9h ago

This is wrong. With some (not all) public key systems, the public and private key are complete inverses of each other. Something encrypted with public can be decrypted with private; something encrypted with private can be decrypted with public. RSA is like this, for instance.

This has the benefit of allowing for signature. If I take a hash of a message, then "encrypt" that hash with my private key, the recipient can "decrypt" the hash with my public key, hash the message themselves, and (if the hashes match) verify that I was the one who sent the message.

•

u/MultiFazed 9h ago

The public key can encrypt, but not decrypt.

You could absolutely decrypt the full message with the public key if it were encrypted with the private key. RSA libraries simply just don't expose that as an option because there's no benefit to doing it. Everyone has access to the public key, after all.

Instead, the standard is to create a "signature" by generating a hash of the message and encrypting that with the private key. But when you verify the signature, you're decrypting it with the public key exactly the same way you'd use it to decrypt a full message.