Ashraful, 22, and 18-year-old Rahim batted through the post-lunch session as Bangladesh, trailing by 389 runs on the first innings, went to tea on the third day at 261-5.
Ashraful was unbeaten on 102, his fourth Test century and the third against Sri Lanka. He has so far hit 10 boundaries.
Rahim, called on to replace long-serving wicket-keeper Khaled Mashud for this match because of his batting abilities, justified his selection with 79 not out containing nine fours and a six.
The unbeaten stand is just four runs away from equalling Bangladesh's best ever partnership of 187 by Habibul Bashar and Shahriar Nafees for the second wicket against Australia in Fatullah last year.
It was a remarkable fightback by Bangladesh after they were shot out for 62 in the first innings, but the tourists still need 128 runs more to make the hosts bat a second time.
Sri Lanka won last week's first Test at the Sinhalese Sports Club by an innings and 234 runs to take the lead in the three-match series.
Ashraful and Rahim came together when former captain Bashar was dismissed 40 minutes after the start of the day's play to reduce Bangladesh to 78-5.
Bangladesh added nine runs to their overnight score of 69-4 when Dilhara Fernando shattered Bashar's stumps.
Ashraful brought up the 50-run partnership by driving Lasith Malinga through the covers and then also posted the century stand with another boundary off Fernando.
At the other end, Rahim hit two fours off Chaminda Vaas and then stepped out to loft Muttiah Muralitharan for an audacious six over the long-on fence.
The prolific Muralitharan, who is 21 wickets away from equalling retired Australian leg-spinner's world record tally of 708, has failed to strike in 24 overs.