Diffie-Hellman key exchange: Why is $(g^{k_1} \bmod n )^{k_2} \bmod n \equiv (g^{k_2} \mod n)^{k_1} \bmod n$ In a Diffie-Hellman key exchange, with a generator $g$ and a modulo $n$, and two keys $k_1$ and $k_2$, why is 

$(g^{k_1} \bmod n )^{k_2} \bmod n \equiv (g^{k_2} \mod n)^{k_1} \bmod n$
let $a=g^{k_1} \pmod n$ and $b=g^{k_2} \pmod n$. We want to prove that $a^{k_2} \equiv b^{k_1} \pmod n$. By congruence definition, $\exists t_1 \in \mathbb{Z}/\,a=nt_1+g^{k_1}$ and $\exists t_2 \in \mathbb{Z}/\,b=nt_2+g^{k_2}$. We want to prove that $(nt_1+g^{k_1})^{k_2} \equiv (nt_2+g^{k_2})^{k_1} \pmod n$. By binomial theorem, we have $(nt_1+g^{k_1})^{k_2} = \sum _{i=0}^{k_2} \binom{k_2}{i}\times(nt_1)^i\times(g^{k_1})^{k_2-i}$ and $(nt_2+g^{k_2})^{k_1} = \sum _{j=0}^{k_1} \binom{k_1}{j}\times(nt_2)^j\times(g^{k_2})^{k_1-j}$. The only time where $nt_1$ and $nt_2$ disapear is when $i=0$ and $j=0$, otherwise the two sums are $\equiv 0 \pmod n$. Thus, $(nt_1+g^{k_1})^{k_2} \equiv \binom{k_2}{0}\times(nt_1)^0\times(g^k_1)^{k_2-0} \equiv g^{k_1k_2} \pmod n$ and $(nt_2+g^{k_2})^{k_1} \equiv \binom{k_1}{0}\times(nt_2)^0\times(g^k_2)^{k_1-0} \equiv g^{k_2k_1} \pmod n$. Hence, $g^{k_1k_2} \equiv g^{k_2k_1} \pmod n$.