如何解密由ENCRYPT函数加密的字符串?无对应DECRYPT函数
ENCRYPT() Function? Hey there, let's break this down clearly—first off, a critical point: MySQL's ENCRYPT() function doesn't have a corresponding DECRYPT() function, and for good reason.
Why There's No Decryption Method
ENCRYPT() is built on top of the Unix crypt() utility, which is a one-way hash function, not a symmetric encryption algorithm. Unlike AES or DES encryption (which are reversible with the right key), one-way hashes are designed to be mathematically impossible to reverse-engineer back to the original plaintext. Its primary use case is storing sensitive data like passwords, where you only need to verify if a provided input matches the stored hash, not retrieve the original value.
What You Can Do Instead
If your goal is to verify whether a plaintext value matches the encrypted string, you can do this by re-hashing the input with the same salt used in the original encryption:
- Extract the salt from the encrypted string: Traditional
crypt()implementations use the first 2 characters of the hash as the salt (this varies slightly by system, but it's the standard for most Unix-based systems). - Hash the candidate plaintext with this extracted salt using
ENCRYPT(). - Compare the result to the stored encrypted string.
Example query to verify a password:
-- Let's say your stored encrypted string is 'saXJZ7t7S3X0Q' SELECT ENCRYPT('user_input_password', SUBSTRING('saXJZ7t7S3X0Q', 1, 2)) = 'saXJZ7t7S3X0Q' AS password_match;
If the result is 1, the input matches the original plaintext; 0 means it doesn't.
Important Notes
- Brute-force/rainbow tables: The only way to "recover" the original plaintext is via brute-force guessing (trying every possible combination) or rainbow tables (precomputed hash-to-plaintext mappings). This isn't true decryption—it's just guessing, and it's only feasible for short or weak plaintext values.
- Security warning:
ENCRYPT()is not considered secure for modern applications. It relies on system-specificcrypt()implementations, which may use outdated, weak hashing algorithms. For new projects, use stronger alternatives likeSHA2()with a unique salt per entry, or MySQL's dedicated password hashing functions (likePASSWORD()in older versions, though it's deprecated in MySQL 8.0+).
内容的提问来源于stack exchange,提问作者Ali Mehdi

