Robert Farmer scored 15 seconds from time to secure Great Britain the point they needed to win the gold medal and promotion to play in the top level of the World Championship for the first time since 1994.
GB, ranked 24th in the world and the tournament’s bottom seeds, needed a point to win promotion but were trailing 2-0 with 10 minutes remaining.
A Robert Dowd goal was followed by a penalty-shot save by Ben Bowns before Farmer sent GB into dreamland with the equalising goal with only 15.8 seconds remaining.
GB went on to win the game 3-2 by securing a penalty-shot victory and will be joined in the top flight by Italy, while Kazakhstan win the bronze medal.
The hosts went ahead on the powerplay as Christopher Bodo put a doorstep rebound past Bowns at 3:31.
Bowns made a great glove save from Balint Magosi’s shot and then produced an out-of-this-world pad save to deny Balazs Sebok as he slid across his crease to shut the door.
Britain made a positive start to the second period and great speed from Liam Kirk set up Dallas Ehrhardt, but his shot from left point was saved by Adam Vay.
Dowd had two chances in quick succession while Mark Richardson was denied by Vay’s pad from close range.
Hungary went 2-0 ahead early in the third period as the puck went past Bowns off Csanad Erdely’s shoulder from just out in front (41:53), a goal given after a lengthy video review.
Paul Swindlehurst and Brett Perlini had chances to close the gap before Dowd spun on the spot and fired the puck through traffic on a rebound to reduce the arrears at 50:55.
Bowns saved his second penalty shot of the tournament as he denied Janos Hari and it proved a decisive turning point.
With 15 seconds remaining Farmer wriggled free and his low shot slid under Vay to secure GB the point they needed.
GB went on to win the penalty shootout 2-1 with goals from Farmer and Ben O’Connor to crown a memorable night.
Head coach, Pete Russell, said: “We dared to dream and we did it. I just cannot believe it.
“This team is very special and what we have pulled off is absolutely unbelievable.
“We did not give up and showed true British spirit to pull that one out of the bag.
“I am so proud of every single one of them and we will now play the best teams in the world next year.
“Our team work rate was immense every single night and they dug need to provide GB with one of our greatest-ever moments.”