How to properly AES encrypt a string, deriving the key from the same string? Let's say someone has a list of names, e.g.:

'Batman'
'Batman'
'Super Man'


I am auditing this list, but I'm not allowed full access to all names. So they must be encrypted.

I should be able to:


Determine that one name appears twice in the list, and that one appears once
Get a clear text name (from the list owner) and use it as key to decrypt its encrypted version


One approach is for the list owner to encrypt the names with a pre-determined iv, and a pre-determined algorithm for generating a key. Just to illustrate, a simple algorithm could be to append 0's until the key is 32 bits:

batman_cipher    = SymmetricEncryption::Cipher.new(key: 'Batman00000000000000000000000000',
                                                   iv: '1234567890ABCDEF',
                                                   cipher_name: 'aes-128-cbc')
super_man_cipher = SymmetricEncryption::Cipher.new(key: 'Super Man00000000000000000000000',
                                                   iv: '1234567890ABCDEF',
                                                   cipher_name: 'aes-128-cbc')

batman_cipher.encrypt('Batman')         # =&gt; 'TYBaLlaS/8QogiyBt77LVQ=='
super_man_cipher.encrypt('Super Man')   # =&gt; 'aSrFGzbWjwXGpEf0VU8t4Q=='


The encrypted list would be:

'TYBaLlaS/8QogiyBt77LVQ=='
'TYBaLlaS/8QogiyBt77LVQ=='
'aSrFGzbWjwXGpEf0VU8t4Q=='


The only way for me to get the clear text names would be to guess or to ask the list owner for one of the names so I could test it:

batman_cipher.decrypt('TYBaLlaS/8QogiyBt77LVQ==') # =&gt; 'Batman'


My question: Unless there is a better approach, what would be the best strategy to strengthen the security, e.g. generating secure keys?

It seems that there are no specific security implications in deriving a key from the string you want to encrypt. And the best strategy I can find elsewhere is to hash the string and truncate its output to 32 bits
My question: Unless there is a better approach, what would be the best strategy to strengthen the security, e.g. generating secure keys?


When you want to derive key for cipher, do use a KDF, ciphers require high-entropy key on all it's length to avoid potential weaknesses. Also, this way you avoid any problems with strings longer than your key size is.

But it appears that you don't need encryption at all. You can just get hash for every item. Then you can check list for duplicates, and request for original text, which then you can validate because you have hash. This is very same as encryption, except you can theoretically get collisions (but if you find collision in modern hash, that would be something special - nobody yet managed it).