🙂

Simple String EnCrypt + DeCrypt function.

Sometimes you need some simple way to avoid stuff is read by someone else.
Some texts you want to keep private.
Can be if you save information in files, at a server with limited options for file protection.

If your need of security is not that high,
this script makes it a bit more difficult to get to your information.
Most people would never be able to decode your text.
If you have stuff that needs high security, you should use other tools.
Sure is possible to add more complicated operations,
but I wanted to keep it small, fast and simple.

This little function will use a Secret Key to encrypt text.
And you would have to use same Key to decrypt it back.
There is only one function for both encrypt/decrypt.
And you call it the same way always.

Script below will output:

Key: mysecretkey
To be or not to be, that is the question
Yv3gf2jf+kvy9gj#p`8+qqlm3lp2q|n%hx|`qj}k
To be or not to be, that is the question

I think it is easy to see how to use this function.
Here is my code:

<?php
// String EnCrypt + DeCrypt function
// Author: halojoy, July 2006
function convert($str,$ky=''){
if($ky=='')return $str;
$ky=str_replace(chr(32),'',$ky);
if(strlen($ky)<8)exit('key error');
$kl=strlen($ky)<32?strlen($ky):32;
$k=array();for($i=0;$i<$kl;$i++){
$k[$i]=ord($ky{$i})&0x1F;}
$j=0;for($i=0;$i<strlen($str);$i++){
$e=ord($str{$i});
$str{$i}=$e&0xE0?chr($e^$k[$j]):chr($e);
$j++;$j=$j==$kl?0:$j;}
return $str;
}
///////////////////////////////////

// Secret key to encrypt/decrypt with
$key='mysecretkey'; // 8-32 characters without spaces

// String to encrypt
$string1='To be or not to be, that is the question';

// EnCrypt string
$string2=convert($string1,$key);

// DeCrypt back
$string3=convert($string2,$key);

// Test output
echo '<span style="font-family:Courier">'."\n";
echo 'Key: '.$key.'<br>'."\n";
echo $string1.'<br>'."\n";
echo $string2.'<br>'."\n";
echo $string3.'<br>'."\n";
echo '</span>'."\n";
?>
    6 days later

    Neato! what is this doing?

    $k[$i] = ord($ky{$i}) & 0x1F;
    

    i'm not familiar with $var{$i] notation. And isn't the & doing a binary shift?

    I'd love to hear a rough explanation of what it's doing.

    Also, from wikipedia:

    In cryptography, Kerckhoffs' principle (also called Kerckhoffs' assumption, axiom or law) was stated by Auguste Kerckhoffs in the 19th century: a cryptosystem should be secure even if everything about the system, except the key, is public knowledge. It was reformulated (perhaps independently) by Claude Shannon as "the enemy knows the system". In that form it is called Shannon's maxim. It is widely embraced by cryptographers, in opposition to security through obscurity.

    How do you think your function holds up under 'Shannon's maxim?' Any thoughts on how one might conceal the key within a PHP project?

    EDIT: I know the idea wasn't exactly RSA encryption. I was just curious about what thoughts anyone might have on what ol kerckhoff said in the context of a php project.

    Also, it might be confusing while writing code...is the output of your function encrypted or decrypted? perhaps separate encrypt and decrypt into separate functions that don't contain the substring 'crypt'. if we're doing security by obscurity, might as well make it that much more obscure so a simple grep won't find the decrypt routine? i have no idea if this is helpful.

      keep the key outside the root directory....

      I used a class someone else made on here to encrypt an entire file of SQL dump info for storage across multiple servers. One server crash prompted me to do it 🙂 It uses the mcrypt functions, but works well. You can send the Initialization Vector (IV) with the encrypted stuff... but the key I keep out of the served document root. Just one more security measure. Not full-proof, but will help in times.

        sneakyimp wrote:

        Neato! what is this doing?

        [code=php]$k[$i] = ord($ky{$i}) & 0x1F;[/code]

        Also, from wikipedia:
        How do you think your function holds up under 'Shannon's maxim?' Any thoughts on how one might conceal the key within a PHP project?

        EDIT: I know the idea wasn't exactly RSA encryption. I was just curious about what thoughts anyone might have on what ol kerckhoff said in the context of a php project.

        Also, it might be confusing while writing code...is the output of your function encrypted or decrypted?

        $k[$i] = ord($ky{$i}) & 0x1F;
        This has to do with me not wanting control characters ( like chr(10) LF )
        to be effected by script.

        It prepares the key to be used, by setting bits 5-7 to zero

        and only using bit 0-4 ( decimal 0-31)

        I have no idea if it will hold up.
        And I dont aim to make it hold up to any advanced security standard

        ( read my first post, with my thoughts of use )

        I wrote this script, for the following use:
        1. Take some text - encrypt it -> save it to flatfile.
        2. Read flatfile -> decrypt it -> display/use text.

        Flatfiles can sometimes be read, if your server does not support 'Deny Access',
        so good if my texts can not be read easily.

        If you want to have two separate functions:
        Just make 2 copies of my convert($text, $secret_key) function.

        Then you name one: encrypt() and the other: decrypt()

        🙂

          8 days later
          rocklv wrote:

          It's cool! I love it! 🙂

          Thanks, rocklv.

          I think there are times this little function is useful and handy tool.

          Like with passwords, you should make sure you can remember your secret key
          and preferably put it OUTSIDE OF of phpscript,
          maybe in some include folder php where not so easy to find it.

          You have any such small scripts or functions, rocklv?
          I see you are from China and have been member in phpbuilder since 2003 !!!!
          Long time ...

          🙂
          regards from Sweden ( summer now )
          halojoy

          .

            The actually character swapping/encoding part of the script is awsome. I tried doing this type of thing in Visual Basic at one time. Actually worked, but you had to use a codeword to encode and the same codeword to decode. But I basically had to define an array with the whole alphabet, then another array with the "encoded" alphabet, which would switch round depending on the codeword and do it that way. You managed it in about 100 less lines than me lol!

            So yeah, simple but very good.

            Works the same as mine, but in a lot less lines and probably bug free, since mine had capitalization problems. Nice one thumbs up

              hi
              thanks for that

              there has to be 100 of different ways
              to code a similiar encrypt/decrypt function

              this code of mine is not at all easy to read or understand for an average person
              but that is also a part of the thing:
              ... the less anybody knows or would bother to find out how it works

              ... the less the chance to crack the code and read my text strings

              If anybody wants me to
              I will post a better commented version, with proper $variable names
              and explain it line by line
              how it works
              and my thinking while creating this script.

              Here is the original code from my first post:

              <?php
              // String EnCrypt + DeCrypt function
              // Author: halojoy, July 2006
              
              function convert($str,$ky=''){
              if($ky=='')return $str;
              $ky=str_replace(chr(32),'',$ky);
              if(strlen($ky)<8)exit('key error');
              $kl=strlen($ky)<32?strlen($ky):32;
              $k=array();for($i=0;$i<$kl;$i++){
              $k[$i]=ord($ky{$i})&0x1F;}
              $j=0;for($i=0;$i<strlen($str);$i++){
              $e=ord($str{$i});
              $str{$i}=$e&0xE0?chr($e^$k[$j]):chr($e);
              $j++;$j=$j==$kl?0:$j;}
              return $str;
              }
              
              ?>
                19 days later

                I am thinking of making an even better such
                Encrypt / Decrypt function.

                I post back here when I have got something nice to add.
                I am quite busy now, but hope to get to it, in near future.

                Any bug reports, modification suggestions and
                anyone happy using this function with good results
                are welcome to post here.
                Would be nice for me to know!

                halojoy

                🙂

                  halojoy wrote:

                  I am thinking of making an even better such
                  Encrypt / Decrypt function.

                  I post back here when I have got something nice to add.
                  I am quite busy now, but hope to get to it, in near future.

                  Any bug reports, modification suggestions and
                  anyone happy using this function with good results
                  are welcome to post here.
                  Would be nice for me to know!

                  halojoy

                  🙂

                  Hey, this is really cool! I've never learned about encryption/decryption, i guess now would be a good time to learn. I'm looking forward to seeing that commented version with easy variable names. :rolleyes:

                    cheerio wrote:

                    Hey, this is really cool! I've never learned about encryption/decryption, i guess now would be a good time to learn. I'm looking forward to seeing that commented version with easy variable names. :rolleyes:

                    I will se what I can get together. With my commented version.
                    I think I still remember how I did 😃 😃
                    As I mention above there are many methods for this.
                    My method is almost as simple as it gets, to make a text imposible to read.
                    And the beauty of my function is that
                    if you run function a second time on your text, using secret keyword,
                    the text will come back!

                    See first post:
                    Keyword: mysecretkey
                    Original String:
                    To be or not to be, that is the question

                    First run(encrypt)
                    Yv3gf2jf+kvy9gj#p8+qqlm3lp2q|n%hx|qj}k
                    Second run(decrypt)

                    To be or not to be, that is the question

                    Now, give the second string to any clever php programmer (without keyword!)
                    and se if he can tell what the original text is .... 🙂

                    I guess many of php people here, would say my method is too simple,
                    and be very critical about my code. Because they 'know' how 'unsafe' it is.
                    And yet, they wouldnt even try to decrypt this string.
                    Because they know, they wont make it 😃

                    halojoy
                    .

                      I've never learned about encryption/decryption, i guess now would be a good time to learn.

                      I suggest reading:
                      Cryptography FAQ
                      Handbook of Applies Cryptography
                      An Overview of Cryptography

                      I'm looking forward to seeing that commented version with easy variable names.

                      With some minor changes:

                      <?php
                      // String EnCrypt + DeCrypt function
                      // Author: halojoy, July 2006
                      // Modified and commented by: laserlight, August 2006
                      
                      function convert($text, $key = '') {
                      	// return text unaltered if the key is blank
                      	if ($key == '') {
                      		return $text;
                      	}
                      
                      // remove the spaces in the key
                      $key = str_replace(' ', '', $key);
                      if (strlen($key) < 8) {
                      	exit('key error');
                      }
                      // set key length to be no more than 32 characters
                      $key_len = strlen($key);
                      if ($key_len > 32) {
                      	$key_len = 32;
                      }
                      
                      $k = array(); // key array
                      // fill key array with the bitwise AND of the ith key character and 0x1F
                      for ($i = 0; $i < $key_len; ++$i) {
                      	$k[$i] = ord($key{$i}) & 0x1F;
                      }
                      
                      // perform encryption/decryption
                      for ($i = 0, $j = 0; $i < strlen($text); ++$i) {
                      	$e = ord($text{$i});
                      	// if the bitwise AND of this character and 0xE0 is non-zero
                      	// set this character to the bitwise XOR of itself and the jth key element
                      	// else leave this character alone
                      	if ($e & 0xE0) {
                      		$text{$i} = chr($e ^ $k[$j]);
                      	}
                      	// increment j, but ensure that it does not exceed key_len-1
                      	$j = ($j + 1) % $key_len;
                      }
                      return $text;
                      }
                      
                      echo convert('To be or not to be, that is the question', 'mysecretkey');
                      ?>

                      I guess many of php people here, would say my method is too simple,
                      and be very critical about my code. Because they 'know' how 'unsafe' it is.

                      You have already warned that your cryptosystem is not intended for use where strong encryption is required, so there really is nothing to criticise concerning its security.

                        16 days later
                        halojoy wrote:

                        You have any such small scripts or functions, rocklv?
                        I see you are from China and have been member in phpbuilder since 2003 !!!!
                        Long time ...

                        Hi halojoy,

                        I use pack to create small enCrypt/deCrypt function&#65292;but I think yours are better.
                        Well, I started to use PHP from 2002, being a long time. I am still a coder, wish to be a guru like you 🙂

                          Commenting on the code: in the loop, $j is pointless, as it's just $i%$key_len (and using strlen($text) in the loop iterator is also a needless waste of clock cycles).

                          The original code is horribly laid out (why? Was there an obfuscated PHP contest I didn' hear about?) - laserlight's reformatting makes it legible.

                          It's unnecessary to turn the key into an array; leaving it as a string also works and avoids the need to convert back and forth with ord() and chr().

                          Using exit() to kill the entire script just because the key is too short is nasty (and this is real, live code?).

                          It's possible for an ASCII 127 (delete) character to get into the cipherstream; for example if the plaintext character is 'n' and the corresponding character in the key is 'q'. This may not be desirable behaviour.

                          The purpose of the masking with 0x1f and 0xe0 is to keep the first three bits of each byte untouched; this is done to both the key and the plaintext, so only 62.5% of the plaintext is encoded.

                          In fact, since all the bitwise operations can be carried out on strings, just for a giggle I had a go at rewriting the algorithm using only strings and avoiding loops.

                          <?php
                          // String EnCrypt + DeCrypt function
                          // Author: halojoy, July 2006
                          // Modified and commented by: laserlight, August 2006
                          //
                          // Exploratory implementation using bitwise ops on strings; Weedpacket September 2006
                          
                          function convert($text, $key = '') {
                              // return text unaltered if the key is blank
                              if ($key == '') {
                                  return $text;
                              }
                          
                          // remove the spaces in the key
                          $key = str_replace(' ', '', $key);
                          if (strlen($key) < 8) {
                              exit('key error');
                          }
                          // set key length to be no more than 32 characters
                          $key_len = strlen($key);
                          if ($key_len > 32) {
                              $key_len = 32;
                          }
                          
                          // A wee bit of tidying in case the key was too long
                          $key = substr($key, 0, $key_len);
                          
                          // We use this a couple of times or so
                          $text_len = strlen($text);
                          
                          // fill key with the bitwise AND of the ith key character and 0x1F, padded to length of text.
                          $lomask = str_repeat("\x1f", $text_len); // Probably better than str_pad
                          $himask = str_repeat("\xe0", $text_len);
                          $k = str_pad("", $text_len, $key); // this one _does_ need to be str_pad
                          
                          // {en|de}cryption algorithm. The whole thing. Right here.
                          $text = (($text ^ $k) & $lomask) | ($text & $himask);
                          
                          return $text;
                          }
                          
                          echo convert('To be or not to be, that is the question', 'mysecretkey');
                          echo "\n";
                          
                          ?>
                          

                          As for the cryptography; not a lot to say. I already know the answers to my main questions (like, why bother whacking out something half-assed when it's easier to use something decent? If you want half-assed then base64_encode(strrev(gzencode($key.$text,9))) is plenty half-assed) because I already know the answer:

                          sci.crypt FAQ wrote:

                          3.7. Why are many people still using cryptosystems that are relatively easy to break?

                          Some don't know any better. Often amateurs think they can design secure systems, and are not aware of what an expert cryptanalyst could do. And sometimes there is insufficient motivation for anybody to invest the work needed to crack a system.

                          In this case, the only justification would appear to be "insufficient motivation": no-one actually cares about your secrets enough to bother. Basically, after taking into account all the crippling that was done either to make the thing easy to break or just to fix each little bug as it cropped up there's not much more to add beyond what has already been said about it since its invention 450 years ago.

                            hi
                            I cant believe this.
                            I try to minimize my functions from having any stuff not necessary.

                            Question:
                            Weedpacket,
                            have you tried to run my script
                            without the $j loop?

                            In this case I want to update my script
                            using your version.
                            This will speed up my script, especially when very long texts/strings.

                            thank you
                            halojoy


                            PS.
                            if you havent tried your version and debugged it
                            we can just leave it.
                            it is not interesting for me, as my version is tested
                            to work perfectly alright
                            - an idea or hypotes has to be tested, to become something else than just an assumption
                            and of practical use for anyone

                              This cipher is probably extremely weak*. Why would you want to use it in lieu of a proper encryption system, such as the symmetric algorithms provided by mcrypt or the asymmetric ones provided by openssl?

                              What is the use-case for having stuff encrypted / decrypted by PHP anyway?

                              Mark

                              • Based on my minimal understanding of cryptography; it is trivial to determine (part of ) key if you know even part of the plaintext message. This is presumably not the case with "strong" ciphers.

                                Weedpacket,
                                have you tried to run my script
                                without the $j loop?

                                Read carefully: Weedpacket pointed out that $j was pointless, not that the loop in which $j was used was pointless.

                                Consider:

                                // String EnCrypt + DeCrypt function
                                // Author: halojoy, July 2006
                                // Modified and commented by: laserlight, August 2006
                                
                                function convert($text, $key = '') {
                                    // return text unaltered if the key is blank
                                    if ($key == '') {
                                        return $text;
                                    }
                                
                                // remove the spaces in the key
                                $key = str_replace(' ', '', $key);
                                if (strlen($key) < 8) {
                                    exit('key error');
                                }
                                // set key length to be no more than 32 characters
                                $key_len = strlen($key);
                                if ($key_len > 32) {
                                    $key_len = 32;
                                }
                                
                                $k = array(); // key array
                                // fill key array with the bitwise AND of the ith key character and 0x1F
                                for ($i = 0; $i < $key_len; ++$i) {
                                    $k[$i] = ord($key{$i}) & 0x1F;
                                }
                                
                                // perform encryption/decryption
                                for ($i = 0; $i < strlen($text); ++$i) {
                                    $e = ord($text{$i});
                                    // if the bitwise AND of this character and 0xE0 is non-zero
                                    // set this character to the bitwise XOR of itself
                                    // and the ith key element, wrapping around key length
                                    // else leave this character alone
                                    if ($e & 0xE0) {
                                        $text{$i} = chr($e ^ $k[$i % $key_len]);
                                    }
                                }
                                return $text;
                                }
                                  MarkR wrote:

                                  What is the use-case for having stuff encrypted / decrypted by PHP anyway?

                                  I can think of two:

                                  1. You don't entirely trust everyone who has access to your user database, so you hash the passwords stored therein. Once those passwords have been obtained, they could be impersonated not only at the site in question but (given a bit of data mining) at other sites on which the users are registered with the same password (people have a tendency to repeat passwords). Of course, brute-forcing the hashes is likely to turn up quite a few of those passwords anyway, but the only defence against that is for users not to pick easy passwords in the first place. (It should go without saying that hash algorithms are not designed for "secure storage" of passwords.)

                                  2. Write-only storage that is intended only for later access offsite. This assumes that no-one can obtain the plaintext prior to its encryption, and requires the use of an asymmetric cipher for which the decrypt key is kept offsite.

                                  Obviously, halojoy's code serves neither case.

                                  halojoy wrote:

                                  especially when very long texts/strings.

                                  Ooh, that sounds like fun; can we see one of these very long texts/strings?

                                    a year later

                                    Hey guyz,

                                    I am facing a problem in encryption using you code in php.

                                    Key: ABC12345key
                                    String: 321321321321
                                    Encrypt: 202" "'':6+0
                                    Decrypt :321321321321

                                    As you can see its working fine, but when I try to insert data in database its creating MySQL error, because the encrypted code has (') and (") quotations.

                                    Please help me! 😕

                                    Thanks,
                                    Salman Mustafa

                                      use [man]mysql_real_escape_string/man on the encrypted text.....