The shape matching very much matters beyond just being made for a hub with the same ball size.
The parameters are overall length, major diameter, ball track profile, location of the ball track within the overall length, presence or absence of sealing elements and/or ability to have any pressed metal shields transplanted.
Generally speaking we're past the age of common and easy Shimano cone replacements, especially for older hubs. Third party support has also dwindled. There are exceptions.
Edit after the question edit to make it clear that this is about balls, not cones:
It's an excellent question and also the subject of some degree of lore and conflicting opinions among bike mechanics.
Ball bearings sold for repairs on bikes do vary a lot in hardness. One confusing thing is that bearing grade is a measure of sphericity (the grade number is the maximum deviation from sphericity in millionths of an inch), but it tends to also be true that the higher grade (lower number) bearings sold in the bike industry are fancier, harder steel. I believe the way the numbers fall is that common grade 200-300 balls are HRc 60min and the fancier stainless and/or chromium alloys can land in the 65-67 range, which is a big difference. Some mechanics will tell you that using higher grade is a bad idea in hubs that aren't meant for it, because it can tear up the cup and cone surfaces if they weren't hard enough to match. Others will tell you don't worry about it, and just use the nicer BBs because the actual price difference is negligible for the quantity in question. All else equal, better roundness means better longevity and performance.
I think it's likely possible that there are hubs in the world with humble enough hardness numbers on the cups and cones that one could theoretically make bad things happen by putting ultra-hard balls in. For this reason, since it would be an unfortunate thing to ruin a hub you were trying to maintain, I recommend sticking to the conventional wisdom of saving grade 25 for nicer hubs. Within Shimano's line I tend to use them for about 105 and better on the road side and SLX/LX and better on the mountain. When doing a more basic hub, use 300s like they came with.
However, the science here goes deeper and to be honest it's one of those bearing engineer topics that bike people really are badly equipped to answer. The truth is that there's probably some way of calculating the maximum safe difference in hardness between the cups/cones and the bearings, and then to actually use that information you'd need to measure the hardness of the cups/cones you have in front of you since it's not published (though it's relatively easy to buy bearing balls of known hardness).