I am using base64 for encryption and decryption.
But for some values, encrypted data is not decrypting properly and add special characters. Using current key, word 'skype' is not encrypting and decrypting correctly instead special characters appear on decrypting.
Can anyone please tell me, what the problem is? (code is simple available on Google but I have checked blogs and forum, can't find any such thing related to this issue, which means problem is in my code)
encrypt.php
<?php
$id= $_GET['id'];
$encrypted = encrypt($id, "check");
echo $encrypted ;
function encrypt($string, $key)
{
$result = '';
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}
return base64_encode($result);
}
?>
decrypt.php
<?php
$id= $_GET['id'];
$decrypted = decrypt($id, "check");
echo $decrypted ;
function decrypt($string, $key)
{
$result = '';
$string = base64_decode($string);
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}
return $result;
}
?>
asked Sep 25, 2014 at 9:59
K.Liaqat
1431 gold badge3 silver badges15 bronze badges
1 Answer 1
Basically...
- Base64 isn't encryption, it's encoding. (Linked article explains the difference between various bits of cryptography and programming vocabulary.)
- If you're not a crypto expert, you shouldn't really be deploying home-grown cryptography code.
- Use a PHP cryptography library instead of trying to write your own (until you become an expert).
- If you need to know the lower-level internals beyond "use a library": read updated cryptographic right answers (and the original: cryptographic right answers).
answered Feb 24, 2016 at 21:09
Scott Arciszewski
34.3k17 gold badges94 silver badges212 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-php
for($i=0; $i<strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, ($i % strlen($key))-1, 1); $char = chr(ord($char)+ord($keychar)); $result.=$char; }for "encrypting"mk5?!? Do you meanmd5? No,md5is a hashing algorithm. It's one-way (you can't get the cow back from the beefburger), and flawed