Simple String EnCrypt + DeCrypt function
Page 1 of 3 123 LastLast
Results 1 to 15 of 37

Thread: Simple String EnCrypt + DeCrypt function

  1. #1
    phpMaster
    Join Date
    Jun 2005
    Location
    Europe
    Posts
    2,983

    resolved Simple String EnCrypt + DeCrypt function



    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:
    Code:
    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 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";
    ?>
    Apache/2.4.7 (Win64) PHP/5.5.9 MySQL/5.6.16 phpMyAdmin/4.1.7

  2. #2
    Senior Member
    Join Date
    Apr 2003
    Location
    Silver Lake
    Posts
    4,845
    Neato! what is this doing?

    PHP Code:
    $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.
    Last edited by sneakyimp; 07-26-2006 at 05:18 PM.
    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  3. #3
    NMaOtBG bpat1434's Avatar
    Join Date
    Oct 2004
    Location
    Around 255.255.255.0
    Posts
    7,850
    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.

  4. #4
    phpMaster
    Join Date
    Jun 2005
    Location
    Europe
    Posts
    2,983
    Quote Originally Posted by sneakyimp
    Neato! what is this doing?
    PHP Code:
    $k[$i] = ord($ky{$i}) & 0x1F
    -----------
    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()
    -----------

    Last edited by halojoy; 07-27-2006 at 12:36 AM.
    Apache/2.4.7 (Win64) PHP/5.5.9 MySQL/5.6.16 phpMyAdmin/4.1.7

  5. #5
    Member rocklv's Avatar
    Join Date
    Jan 2003
    Location
    china
    Posts
    42
    It's cool! I love it!

  6. #6
    phpMaster
    Join Date
    Jun 2005
    Location
    Europe
    Posts
    2,983
    Quote Originally Posted by rocklv
    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

    .
    Apache/2.4.7 (Win64) PHP/5.5.9 MySQL/5.6.16 phpMyAdmin/4.1.7

  7. #7
    Junior Member
    Join Date
    Jul 2006
    Posts
    11
    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*

  8. #8
    phpMaster
    Join Date
    Jun 2005
    Location
    Europe
    Posts
    2,983
    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 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;
    }

    ?>
    Apache/2.4.7 (Win64) PHP/5.5.9 MySQL/5.6.16 phpMyAdmin/4.1.7

  9. #9
    phpMaster
    Join Date
    Jun 2005
    Location
    Europe
    Posts
    2,983
    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

    Apache/2.4.7 (Win64) PHP/5.5.9 MySQL/5.6.16 phpMyAdmin/4.1.7

  10. #10
    Senior Member
    Join Date
    Aug 2006
    Posts
    110
    Quote Originally Posted by halojoy
    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.
    My Portfolio
    (x)HTML / CSS / PHP / MySQL for very cheap.

  11. #11
    phpMaster
    Join Date
    Jun 2005
    Location
    Europe
    Posts
    2,983
    Quote Originally Posted by cheerio
    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.
    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#p`8+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
    .
    Apache/2.4.7 (Win64) PHP/5.5.9 MySQL/5.6.16 phpMyAdmin/4.1.7

  12. #12
    PHP Witch laserlight's Avatar
    Join Date
    Apr 2003
    Location
    Singapore
    Posts
    13,555
    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 Code:
    <?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.
    Last edited by laserlight; 08-27-2006 at 07:02 AM.
    Use Bazaar for your version control system
    Read the PHP Spellbook
    Learn How To Ask Questions The Smart Way

  13. #13
    Member rocklv's Avatar
    Join Date
    Jan 2003
    Location
    china
    Posts
    42
    Quote Originally Posted by halojoy
    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,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

  14. #14
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,855
    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 Code:
    <?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($key0$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
        
    $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 just as easy to have something decent - e.g.RC4? If you want half-assed then base64_encode(strrev(gzencode($key.$text,9))) is plenty half-assed) because I already know the answer:

    Quote Originally Posted by sci.crypt FAQ
    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.
    Last edited by Weedpacket; 09-12-2006 at 10:34 PM. Reason: A couple of optimisations
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  15. #15
    phpMaster
    Join Date
    Jun 2005
    Location
    Europe
    Posts
    2,983
    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
    Apache/2.4.7 (Win64) PHP/5.5.9 MySQL/5.6.16 phpMyAdmin/4.1.7

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •