Here is how you would do it using the standard add-on package VariationalMethods, which is meant for calculations like this:
Clear[m, k, c, x, t];
T = 1/2 m x'[t]^2;
V = 1/2 k x[t]^2;
L = T - V;
Needs["VariationalMethods`"]
hamiltonianEq =
h == FirstIntegral[t] /. Last[FirstIntegrals[L, {x[t]}, t]]
(* ==> h == 1/2 (k x[t]^2 + m Derivative[1][x][t]^2) *)
momentumEq = p[x] == VariationalD[L, x'[t], t]
(* ==> p[x] == m Derivative[1][x][t] *)
h /.
First[Solve[Eliminate[{hamiltonianEq, momentumEq}, x'[t]], h]]
(* ==> (p[x]^2 + k m x[t]^2)/(2 m) *)
Here, I defined two equations defining the Hamiltonian and momentum using the capabilities of the VariationalMethods package, and then used Eliminate to combine these equations into the final result.
The result is in simplified form, but you can also split it into two terms (which is more standard), by adding Apart@ in front of it.
For time-dependent Hamiltonians:
The above works for Hamiltonians that are equal to the conserved energy, as is the case in the question. However, it's easy to modify the definition of hamiltonianEq above so that it also works in general, following the definition given in the question. You would replace the first equation by
hamiltonianEq = h == x'[t] VariationalD[L, x'[t], t] - L
The rest stays the same.