Security concern with TOTP I am pretty new to cryptography and I have been studying up on TOTP (Time Based OTP) and while I have learnt how the computation works, I'm unable to figure out why using TOTP makes a system more secure.

Here's what I have understood. TOTP is used for 2FA, so the first factor would be your username and password. This as we know is not very secure in itself and hence we use the second factor, here the OTP.

So with TOTP, there is a secret key that both the server and the client have. So my question is that if an attacker has gained access to this secret, would he not be able to generate the OTP just as easily as the client software on my system because HOTP(key,counter) will remain the same for all? So to ensure TOTP is helpful, I have to make sure that the secret key with the client is safe? Let's say I'm making a software that is to be used by the public which uses TOTP based authentication. So will I be attaching a different secret to each of the clients and maintaining a database on the server end to match the secret server side?

If not, what's a safe way to have the same secret on both client and the server in this case?
So my question is that if an attacker has gained access to this secret, would he not be able to generate the OTP just as easily as the client software on my system because HOTP(key,counter) will remain the same for all? 


Yes, if an attacker learns your shared secret, he can calculate OTPs whenever she wants. But this is very unlikely, since every secret is unique (no reuse, like with a password) and never transmitted (apart from the initial agreement) a direct hack of the server or the client's token is the only possibility of obtaining it.


  So to ensure TOTP is helpful, I have to make sure that the secret key with the client is safe? 


Correct.


  Let's say I'm making a software that is to be used by the public which
  uses TOTP based authentication. So will I be attaching a different
  secret to each of the clients and maintaining a database on the server
  end to match the secret server side?


Yes. Every user has a different key on your service. If you store it in a database or obtain via some deterministic calculation from a master secret is up to your implementation.