问题
A JavaEE application uses Jasypt simple encryptor to encrypt usernames stored in a MySQL database using JPA.
As the usernames are encrypted, can't make the username column unique. (Refer to use cases below.)
A search can be performed before saving a new username to avoid duplicates, but there is a theoretical possibility of creating multiple users names simultaneously.
Encrypt('username','key') = 'EncryptedUsername'
Decrypt('EncryptedUsername','key') = 'username'
Case 1 - Already in the database
Username1 = 'a'
Key1 = '1'
EncryptedValue1 = 'XXXX' (suppose)
Case 2 - Going to add a new username
Username2 = 'b'
Key2 = '2'
EncryptedValue2 = 'XXXX' (suppose)
Case 3 - Going to add another new username
Username3 = 'a'
Key3 = '3'
EncryptedValue3 = 'YYYY' (suppose)
Case 2 must be allowed.
case 3 must not be allowed
I can not achieve that by making the field I store the encrypted value unique.
If I make it unique, it will not allow adding new username 'b' in case 2. That is wrong as existing username 'a' is different from the new username 'b'.
In case 3, it will also allow adding the 'a' as a username as the encrypted values are different.
How can we make sure the user name remains unique despite encryption?
回答1:
Use an application scope bean to search for the provided username. If the new username is not found, create a user with the new username. If the username found, ask for another one from the user. As there is only one place to carry out this function, there will be no duplicates.
来源:https://stackoverflow.com/questions/57833606/making-a-value-of-an-encrypted-field-unique