Each week (besides the first when it was released) you get what, for the purposes of making it easier to understand, I'm going to call a chest token (not the official term by any stretch). If while you have a token you or someone you queued with (not someone on your team, someone in your premade) gets an S rank (S- counts, idk if S+ are a thing but those would too if they exist) you will earn a chest and the token will be consumed. You can store up to 4 tokens at a time and there's a timer telling you when the next one will be given to you for a total of about 4 per month.
You can only earn a chest on a champion once per season and if you look over your champions in your profile page the ones you have gotten a chest on have a gold border and if you mouse over them it will show a gold chest to show you earned it on them. So if you get an S rank on Nasus and get a chest you can't get a chest on him for the rest of the season. If you get a S rank but don't get a chest because you've already used all your tokens it won't count and you're still eligible to get a chest on that champion later. If you didn't get the S rank, but your premade buddy did, you get the chest credit on the champion you were playing. So if you were playing jhin and your buddy was playing yi and he earns an S rank, you get credit for Jhin. This is regardless of if your buddy has earned his own chest for that champion. So if your buddy consistently gets S ranks with someone you can play different champions each time and get your chests that way. Also, as the chests are tied to mastery you can only earn them on game modes with mastery associated with them which at this point are summoner's rift (ranked or normals) and weekly game modes.
Key fragments don't have the same 4 per month limitation on them as the chests and aren't tied to mastery. Instead, you just have a random chance to earn one when you win a game. Any game mode counts, but I think it has to be matchmade against other players (so no bot games or custom games though I don't know for sure). There's talk around that there's some sort of weight attached to the random values so you don't earn way more keys than Riot feels is appropriate but I've not seen anything from Riot about that specifically so I can't say for sure.