Yes, it is legal. Look up ghostwriters, who are people that secretly write books for others. If you are seeking to hire a ghostwriter, they are very expensive and are payed per word. A 200-page book could cost $30,000 to have someone write it for you.
Usually, ghostwriting is only partial- the claimed author writes most of the book, while the ghostwriter edits it.
Some famous ghostwritten books include the entire Nancy Drew series (she does not exist).
Motivations for hiring a ghostwriter might be a famous person (who is not a very good writer) seeking to make an “autobiography”. When people send fanmail to some famous group, the reply is often ghostwritten, because the actual person is too busy to reply to hundreds of letters.
Ghostwriting in an academic situation, while legal, is most certainly a violation of the honor code and can result in the expulsion of the person from the college/school.
If you do decide to hire a ghostwriter, make sure that he signs a non-disclosure agreement and can not sue you for compensation if your book becomes wildly successful (which it probably won’t).