Created
December 29, 2024 10:25
-
-
Save ozanhazer/203842aedced77f61c97ed2676c3fcbc to your computer and use it in GitHub Desktop.
crypt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
program EncryptPassword; | |
uses | |
SysUtils, IdHashMessageDigest, IdGlobal; | |
function EncryptPassword(const Password: string): string; | |
var | |
Salt: string; | |
MD5: TIdHashMessageDigest5; | |
Hash: string; | |
begin | |
// Generate a salt (this will use a time-based seed, similar to the PHP example) | |
Salt := '$1$' + Copy(MD5Hash(IntToStr(GetTickCount())), 1, 8) + '$'; | |
// Create an MD5 hash object | |
MD5 := TIdHashMessageDigest5.Create; | |
// Combine password with salt and hash it | |
Hash := MD5.HashStringAsHex(Salt + Password); | |
// Return the salt + hash (similar to crypt() output) | |
Result := Salt + Hash; | |
MD5.Free; | |
end; | |
function CheckPassword(const InputPassword, StoredEncryptedPassword: string): Boolean; | |
var | |
Salt, StoredHash, InputHash: string; | |
MD5: TIdHashMessageDigest5; | |
begin | |
// Extract the salt from the stored encrypted password (first 12 chars) | |
Salt := Copy(StoredEncryptedPassword, 1, 12); | |
// Create MD5 hash object | |
MD5 := TIdHashMessageDigest5.Create; | |
// Re-encrypt the input password using the same salt | |
InputHash := MD5.HashStringAsHex(Salt + InputPassword); | |
// Extract the stored hash (from the 13th character onward) | |
StoredHash := Copy(StoredEncryptedPassword, 13, Length(StoredEncryptedPassword) - 12); | |
// Compare the generated hash with the stored hash | |
Result := InputHash = StoredHash; | |
MD5.Free; | |
end; | |
var | |
Password, EncryptedPassword, UserInput: string; | |
begin | |
// Get the password to encrypt | |
Write('Enter a password: '); | |
ReadLn(Password); | |
// Encrypt the password | |
EncryptedPassword := EncryptPassword(Password); | |
WriteLn('Encrypted password: ', EncryptedPassword); | |
// Check the password | |
Write('Enter password to check: '); | |
ReadLn(UserInput); | |
if CheckPassword(UserInput, EncryptedPassword) then | |
WriteLn('Password is correct!') | |
else | |
WriteLn('Incorrect password!'); | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment