RSA Key generation: How is multiplicative inverse computed?
Modular inverse can be computed with Extended Euclidian Algorithm, as other answers suggest.

I will answer your second question - why an attacker can't get private key? The problem here is that the private exponent is the modular inverse of the public one, but modulo $\phi(n)$, not $n$:

$d \equiv e^{-1} \pmod{\phi(n)}$

Attacker does not know $\phi(n) = (p-1)(q-1)$ here and there's no known way to compute it without factorizing $n=pq$.

You can notice that these numbers differ only by $p + q - 1$ but this fact itself does not help much because $p+q=O(\sqrt{n})$ and the simplest trial division algorithm for factorization works with the same complexity (it is far from feasible). Of course there are much more advanced factorization methods but they are also far from factorizing large RSA modulus.