I have a new job coming up soon and want to increase my PHP knowledge.
This is my first attempt at creating and using a class. I just want to know if it's the correct way to do things.
It's very basic: a simple encrypt / decrypt of a string with a salt.
/**
* Encryption Class
*
* Use for encrypting / decrypting a string securely
*
*/
class stringEncryption
{
// generate random string if the variable in a encrypt / decrypt is set as false
public function generateRandomString($length = 10) {
return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}
// encrypts the string
public function encryptString($string, $salt)
{
//if there is no salt, generate one
if (!$salt)
{
$salt = self::generateRandomString();
}
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $string, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
// decrypt the string
public function decryptString($string, $salt)
{
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($string), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
}
This is how I have created 2 objects and encrypted / decrypted
include 'libs/PHP_Classes/class.encryption.php';
// Password BEFORE encryption
$passwordBefore = "TestPassword";
$salt = "8i3bf92f";
echo "Current Password: $passwordBefore<br>";
// object to handle the new password to be encrypted
$safePassword = new stringEncryption;
// object to handle the decryption of a password
$decrypt = new stringEncryption;
// create the encrypted password
$encryptedPassword = $safePassword->encryptString($passwordBefore, $salt);
// decrypt the password
$decryptedPassword = $decrypt->decryptString($encryptedPassword, $salt);
// show the password with encryption
echo "Encrypted: $encryptedPassword<br />";
// show the password decrypted
echo "Decrypted: $decryptedPassword";
PDO? \$\endgroup\$self::generateRandomString();is a static method call, whereas the signature:public function generateRandomStringis a non-static method. That's bad, mkay \$\endgroup\$