The trick is to set both \leftskip and \rightskip to have infinite stretchable space that cancel each other out. For the last line, the \parfillskip will also be used, so you can cancel the effect of \rightskip. Basically, you just have to write
\leftskip=0pt plus 1fil %
\rightskip=0pt plus -1fil %
\parfillskip=0pt plus 1fil %
where you want to use this formatting. You can usually omit the \parfillskip definition, as the above value is usually the default. Here’s a complete example, showing the effect on section headings.
\documentclass[11pt]{article}
\usepackage{lipsum}
\usepackage{sectsty}
\sectionfont{\leftskip=0pt plus 1fil \rightskip=0pt plus -1fil}
\begin{document}
\section*{This is a short heading}
\lipsum[4]
\section*{This a long (but not an extremely long) heading, spanning span two lines}
\lipsum[10]
\section*{This an extremely long heading, even longer than the one above, and spanning not one, not two, but three lines}
\lipsum[2]
\end{document}

Note that all lines except the last are justified, as in the normal LaTeX classes, which might look ugly, with large interword spaces. To make them ragged-right instead, use
\leftskip=0pt plus 1fil %
\rightskip=0pt plus 1fill %
\parfillskip=0pt plus -1fill %
However, if the last line is very short, you do risk that the first word in the last line starts to the right of the last word(s) in the preceding line(s), making the last line appear not to be connected to the rest of section heading.
In other words, either having the first part of the section heading justified or having it ragged-right may cause ugly headings, so you might want to reconsider this formatting choice.
For the header, just use the same commands. Example, using the fancyhdr package (and a numbered and slightly longer section title):
\fancyhead{}
\fancyhead[L]{\leftskip=0pt plus 1fil \rightskip=0pt plus -1fil \leftmark}
With the default settings of fancyhdr, but using numbered sections, it looks like this:

For the ToC, the code to use depends on which classes (book/Koma-Script/memoir/…) and/or packages (tocloft/titletoc/…) you use, but I would strongly recommend just using a shorter version of the title instead. Example:
\section[Extremely long heading]{This an extremely long heading, even longer than the one above, and it's spanning not one, not two, but three lines}
The short version will by default also be used in the header.