I have a field that can contain an EIN or SSN but I want to mask it when I display them in the view. Here’s the code I used to do that. Basically I just count the number of dashes. If there is only one it’s an EIN and if there are two it’s an SSN. I select the correct mask and then append the last four of the string.
are you really handling SSNs? If so I’d suggest storing only the mask in the database, if you need to verify them store a password_hash of the SSN as well so you can verify it like any other password. Storing SSNs stack on so many potential issues and data handling/storage requirements it’s usually not worth it if you don’t absolutely have to.
I remember one time talking to my cable company provider that was setting up my account that the lady over the phone asked my for my SSN. I almost gave it to her, but then I quickly said I not going to you my SSN as you don’t need it to do for what you are doing. A quick pause she finally said “Well give me a hint for your password then”.