Huck Finn has to pretend to be Tom Sawyer because he realizes that the family that is holding Jim is none other than the family of Tom Sawyer. Because he wants to maintain easy access to Jim so he can free him, he takes on Tom's identity so that he'll be welcomed like family while devising his plan.
As with most lies, this one that Huck creates spurs several other lies, and Tom, as a result, has to lie about his identity also.
The boys keep their secret regarding who is who until the end of the book where they manage to free Jim from the shack. While running away, Tom (the real Tom) is shot and nearly killed. Finally, in the end, the boys tell Aunt Sally and Uncle Silas who is who and why they did it.