The only way to ensure this is by not letting them leave, so yes, they do need to lock them up to ensure their security.
Egypt has no interest in taking gaza which is why Israel feels the need to keep them locked up. The gazans are indigenous to israel which is why they are israels responsibility until someone else takes them. Obviously it would be nice for israel if the prisoners never tried to break out but that isnt a realistic outcome, and Israel knows it. If youre going to set up a prison camp you need to heavily guard the border or bad things will happen. Im not saying the initial invasion afterwards is immoral, it was just a bad decision that wouldnt have been needed if the israelis just protected the border. It was a bad decision because it predictably led to numerous atrocities which was exactly what hamas wanted. Israel is without a doubt less safe now then they were on oct 6 when they were close to opening diplomatic relations with all the middle east countries other than iran.
The best solution for Gaza is actually for them to form a union with Egypt, with which they share a border, a language, and common culture, and which has an area that’s almost 3000x the size of Gaza, much of it empty.
The Egyptian government may obviously need to keep Hamas imprisoned, but they should allow free movement to ordinary Gazan civilians.