Google Authenticator is an alternative to SMS for 2Step verification, installing an app on Android where the codes will be sent.

It works without any connectivity; it even works on plane mode. This is what I don't get. How is it possible that it works without connectivity? How do the mobile phone and the server sync to know which code is valid at that very moment?

Google Authenticator supports both the HOTP and TOTP algorithms for generating one-time passwords.

With HOTP, the server and client share a secret value and a counter, which are used to compute a one time password independently on both sides. Whenever a password is generated and used, the counter is incremented on both sides, allowing the server and client to remain in sync.

TOTP essentially uses the same algorithm as HOTP with one major difference. The counter used in TOTP is replaced by the current time. The client and server remain in sync as long as the system times remain the same. This can be done by using the Network Time protocol.

The secret key (as well as the counter in the case of HOTP) has to be communicated to both the server and the client at some point in time. In the case of Google Authenticator, this is done in the form of a QRCode encoded URI. See: KeyUriFormat for more information.
