Momentum operator is defined as:
$$\hat{p}=\frac{\hbar}{i}\frac{d}{dx}$$
This means that if you want to get the momentum from the wavefunction $\psi$, you must apply the momentum operator to the wavefunction. Let's define the wavefunction as:
$$\psi=A\exp\left[\frac{i}{\hbar}\left(px-Et\right)\right]$$
It is easy to see that:
$$\frac{\hbar}{i}\frac{d}{dx}\psi=p\psi$$
If you want to get $p^2$ you have to apply the momentum operator to the wavefunction twice.
$$\hat{p}^2\psi=\hat{p}\hat{p}\psi=\frac{\hbar}{i}\frac{d}{dx}\left(\frac{\hbar}{i}\frac{d}{dx}\psi\right)=p\left(\frac{\hbar}{i}\frac{d}{dx}\psi\right)=p^2\psi$$
So the $\hat{p}^2$ operator is:
$$\hat{p}^2=\left(\frac{\hbar}{i}\frac{d}{dx}\right)\left(\frac{\hbar}{i}\frac{d}{dx}\right)=\left(\frac{\hbar}{i}\right)^2\frac{d^2}{dx^2}=-\hbar^2\frac{d^2}{dx^2}$$