Menu
Is free
check in
the main  /  Navigators / How to encrypt files in PHP. Protection of PHP scripts from analysis and modification

How to encrypt files in PHP. Protection of PHP scripts from analysis and modification

Any information can be encrypted and decipher, including with using PHP.. This language has many capabilities of data encryption from simple, up to complex.

Consider the basic methods of encryption

base64. - allows you to encrypt and decrypt the data by the MIME BASE64 algorithm. It does not use keys and is often used to hide references to PHP.

Examples:
// Enciprate text
$ text \u003d "link";
Echo Base64_ENCODE ($ text); // will issue: pgegahjlzj0iiyi + 0khrgdgl0lvqutcwpc9hpg \u003d\u003d
// Decriprovka
Echo Base64_Decode ("pgegahjlzj0iiyi + 0khrgdgl0lvqutcwpc9hpg \u003d\u003d");
?>

As we can see, we used first the Base64_ENCode operation and received the cipher: Pgegahjlzj0iyi + 0khrgdgl0lvqutcwpc9hpg \u003d\u003dAnd then put it in Base64_Decode and got the link back.

mD5 - allows you to hash data unilaterally. That is, unlike Base64, you can no longer decrypt them back. Often, MD5 is used to store passwords in the database, but recently encrypted MD5 combination has become easy to find in decoding tables, courtesy of many sites and algorithms. Therefore, to store MD5 passwords to better replace the algorithms on blowfish.

Example:

// Enciprate text
Echo MD5 ("Combination");
?>

Encryption by key

And the last example of encryption / decryption, which I wanted to tell uses the key (as a password). That is, you transmit a unique key to the encryption function, the code is encrypted with it. To decrypt, you must provide the features of an encrypted code and a key that you know only. An example of using functions at the bottom of the code.

FUNCTION __ENCODE ($ Text, $ Key) (



$ ENC_TEXT \u003d BASE64_ENCODE (MCRYPT_GENERIC ($ TD, $ IV. $ text));
MCRYPT_GENERIC_DEINIT ($ TD);
MCRYPT_MODULE_CLOSE ($ TD);
RETURN $ ENC_TEXT; ))
Function Strtohex ($ String) (
$ hex \u003d "";
for ($ i \u003d 0; $ i< strlen($string); $i++) { $hex .= dechex(ord($string[$i])); }
Return $ Hex; )
FUNCTION __DECODE ($ Text, $ Key) (
$ TD \u003d MCRYPT_MODULE_OPEN ("Tripledes", "", "CFB", "");
$ IV_SIZE \u003d MCRYPT_ENC_GET_IV_SIZE ($ TD);
$ iv \u003d mcrypt_create_iv (MCRYPT_ENC_GET_IV_SIZE ($ TD), MCRYPT_RAND);
If (mcrypt_generic_init ($ TD, $ Key, $ IV)! \u003d -1) (
$ decode_text \u003d substr (MDecrypt_Generic ($ TD, BASE64_DECODE ($ text)), $ iv_size);
MCRYPT_GENERIC_DEINIT ($ TD);
MCRYPT_MODULE_CLOSE ($ TD);
Return $ Decode_Text; ))
FUNCTION HEXTOSTR ($ Hex) (
$ string \u003d "";
for ($ i \u003d 0; $ i< strlen($hex)-1; $i+=2) { $string .= chr(hexdec($hex[$i].$hex[$i+1])); }
RETURN $ STRING; )

$ str \u003d "Buns that need to encrypt!
By key";
$ code \u003d STRTOHEX (__ ENCODE ($ STR, "My # Key-DO-36-simvolov"));
Echo "Encrypted code:" $ Code. "
";

$ str \u003d __decode (HEXTOSTR ($ Code), "My # Key-DO-36-simvolov");
ECHO "Decrypted code:" $ str. "
";
?>

You can encrypt with HTML content. The key length must be no more than 36 characters.

This method can be used to encrypt some data and placing them in a TXT file or database, and getting with a key decryption.

Of course, any code can be decrypted / hack and this is no exception, so use reliable encryption methods.

Suppose data exchange is required between two servers. To secure data from listening to traffic, the data is encrypted. Well, for example, the transfer of action inside the botnet. This is what is essentially an encryption, but is called coding and known functions are used to decode such a code.

As another example of the pseudo-enjoyment, I will give an example of "encryption" passwords in the database of one CMS - passwords are not encrypted in MD5 () or, but simply encoded via Base64. Those. When draining the base, the hacker will not be a job to decipher all passwords through the built-in PHP function BASE64_DECODE ().

We also need to transmit data without worrying that someone can intercept the text and decipher it. The PHP has a popular MCRYPT data encryption package, which provides two-way encryption features (that is, the data is actually encrypting and decoding).

MCRYPT version 2.4.7 Supports the following symmetric encryption algorithms: Blowfish, RC2, SAFER-SK64 XTEA, CAST-256, RC4, SAFER-SK128, DES, RC4-IV, Serpent, Enigma, Rijndael-128, Threeway, Rijndael-192, TripleDes, Loki97, Rijndael-256, Twofish, Panama, Saferplus, etc. More about each algorithm is written in Wikipedia.

Since symmetrical encryption is used, the key must be known to both sides and is kept secret.

Example encryption and decryption string

mCRYPT_MODULE_OPEN ("Des", "", "ECB", "")
This feature opens the algorithm module and the mode used. For this example, the DES algorithm in ECB mode.

$ Key \u003d Substr ($ key, 0, mcrypt_enc_get_key_size ($ TD));
The maximum key size must be obtained by calling the mcrypt_enc_get_key_size () function, and each value is less than the obtained.

$ s \u003d mcrypt_generic ($ TD, $ Source);
When encrypted, the data is filled with zero bytes to guarantee the data length in N * Blocksize. Blocksize block size is determined by the algorithm (for DES size block 64). Therefore, when decoding at the end of the line, "\\ 0" may appear, which are deleted by the Trim () function

One of the main truths of cryptography states that it is not necessary to invent anything in this area if you are not a professional. This is a partly true, for all the best has long been invented, laid out and used not one ten years in the field information technologies. The other side of the truth is that the development of some field of knowledge occurs only with a constant influx of fresh ideas and original solutions in it.

As for obvious reasons, we will not be caught on the giants of industrial cryptography like AES, and plunge, so to speak, into its own cryptographic surveys with blackjack and joy.

Partly because it is interesting, partly because simulating something and comparing this with recognized standards, clearly see contrast, effective solutions and frank omissions, you understand what you can strive to improve efficiency.

But rather water.

Suppose our web application is written on PHP, needs to be reversible encryption and we believe that in the forces to write your cipher system.

So, write own system reversible encryption with a private and public key, which will have the following signs of a little firm protected cryptographic algorithm:

  1. The presence of noise symbols in the final cipher.
  2. Information in each channel The sender-addressee will be encrypted in a private key, and the conformity function will be unique for each key.
  3. Each message will receive a digest code - a kind of unique code that is a function from a private key and source message. This is required in order to achieve the uniqueness of the conformity function "The original symbol<=> The encoded character "is not only for the" Sender-Address "channel, but also for each individual message.

    Thus, even if it is known that the correspondence of coded and source characters is known for a specific message by applying cryptographic analysis, for example, frequency analysis, this does not give any preferences in the study of another message.

  4. To complicate frequency analysis, we will encode each source message symbol with two cipher symbols.
So what happened.

Actually, the final result can be viewed.

The SyMcoder class includes encryption and decryption methods.

Encryption performs the Code () method that accepts the original message at the entrance.

Here a message on the generated matching table in Tab_coded creates an encrypted message diluted along the edges and inside the noise symbols.

Noise symbols, by the way, are unique to each channel sender-addressee, as it is generated using the channel key, but not unique to messages. Symbols used for encryption in Code_Symbols are some punctuation marks and symbols of the type%, @, etc.

Each encoded symbol accounts for two characters from Code_Symbols for obvious reasons that they are several times less than encoded symbols.

Create_Tab_Coded Compliance Table is built using a host key translating a message to an array with an amount of elements equal to the number of elements in the code symbol array. The position of the start-up of two-grains codes is also always different and is associated with the channel key. This makes it possible to be sure that the algorithm for bypassing the encoded symbols and compliance with the code symbols is always (well or guaranteed often) will be different.

For example, the message "Hi, the world" being encoded, looks like this:

[Email Protected]@=!=-.?&1.#&?=:.:.1%!&-%@[Email Protected]%~&1^#=?%%.!%+.?.~=?..&?%&&:%~.#%@&1&1.#=?.#.?.!&1==&=.-=!

But the same message encoded again:

Digest-A00BF11D - \u003d:.? \u003d: &!.?. 1 & - \u003d: \u003d?.? \u003d.?! & \u003d%! \u003d -% @ \u003d!% ~. \u003d ^ #. 1 %%. !% + \u003d: [Email Protected]==%&&1%~.1%@[Email Protected][Email Protected]=:&1.==:=!.1&:

It can be seen that the digest of the same message coincides, but the cipher becomes different - noise symbols are added arbitrary compliance and in any order for each new encryption.

Messages have redundancy, which decreases as the message volume increases, in the limit to reach 10% noise (for the shortest messages, noise reaches 90% and higher than percent), the minimum length of the encrypted message is 116 characters. One of some minuses this method encryption - increasing coded messages at least twice.

Decoding consists in reverse translation of the code icon - the source symbol with noise cut from the message. What could be as a key? In principle, any string is unique for each pair of the appearance of the recipient.

For example, if you create a messenger with encryption of messages, in this case the simplest option of the closed key can be MD5 ($ user_id_1. $ SALT. $ User_id_2), then the key will be unique for each message channel.

(PHP 4, PHP 5, PHP 7)

crypt - One-Way String Hashing

Warning

This Function Is Not (YET) Binary Safe!

Description.

crypt. (string $ Str. [, string $ Salt. ]): String

crypt () Will Return A Hashed String Using the Standard Unix des -Based Algorithm or Alternative Algorithms That May Be Available On The System.

The Salt Parameter Is Optional. However, crypt () Creates a Weak Hash Without The Salt. PHP 5.6 OR LATER RAISE AN E_NOTICE ERROR WITHOUT IT. Make Sure to Specify A Strong Enough Salt for Better Security.

password_hash () Uses A Strong Hash, Generates a Strong Salt, and Applies Proper Rounds Automatically. password_hash () IS A Simple. crypt () Wrapper and compatible with existing password hashes. Use Of. password_hash () is encouraged.

Some Operating Systems Support More Than One Type of Hash. In Fact, Sometimes The Standard Des-Based Algorithm IS Replaced by An MD5-Based Algorithm. The Hash Type IS Triggered by The Salt Argument. Prior to 5.3, PHP Would Determine The Available Algorithms At Install-Time Based On The System "S Crypt (). If no Salt Is Provided, PHP Will AUTO-Generate Either Standard Two Character (Des) Salt, or a twelve character ( MD5), Depending on The Availability of MD5 Crypt (). PHP Sets a Constant Named Crypt_Salt_Length. Which Indicates The Longest Valid Salt Allowed by The Available Hashes.

The Standard Des-Based crypt () Returns The Salt As The First Two Characters of the Output. It Also Only Use The First Eight Characters of Str, SO Longer Strings That Start Will Generate The Same Result (Will Generate the Salt IS Used).

On Systems Where The Crypt () Function Supports Multiple Hash Types, The Following Constants Are Set to To 0 or 1 Depending on Whether The Given Type Is Available:

  • Crypt_std_des. - Standard Des-Based Hash With a Two Character Salt from the Alphabet. ./0-9a-za-z. USING INVALID CHARACTS IN THE SALT WILL CAUSE CRYPT () TO FAIL.
  • Crypt_Ext_Des. - Extended Des-Based Hash. The "Salt" is a 9-Character String Consisting of An Underscore Followed by 4 Bytes of Iteration Count and 4 Bytes of Salt. These Are Encoded As Printable Characters, 6 Bits Per Character, Least Significant Character First. The Values \u200b\u200b0 to 63 Are Encoded AS ./0-9a-za-z ". USING INVALID CHARACTS IN THE SALT WILL CAUSE CRYPT () TO FAIL.
  • Crypt_md5. - MD5 HASHING WITH A TWELVE CHARACTER SALT STARTING WITH $ 1 $
  • Crypt_blowfish - Blowfish HASHING WITH A SALT AS FOLLOWS: "$ 2A $", "$ 2x $" Or "$ 2y $", A Two Digit Cost Parameter, "$", and 22 Characters from the Alphabet "./0-9A- Za-z ". Using Characters Outside of this Range in the Salt Will Cause Crypt () to return a Zero-Length String. The TWO DIGIT COST PARAMETER IS THE BASE-2 LOGARITHM OF THE ITERATION COUNT FOR THE THE UNGORITHM OF THE ITERATION COUNT FOR THE THE UNGORITHMETER AND MUST BAS IN RANGE 04-31, VALUES OUTSIDE THIS RANGE WILL CAUSE CRYPT () TO FAIL. Versions of PHP Before 5.3.7 Only Support "$ 2A $" AS The Salt Prefix: PHP 5.3.7 Introduced The New Prefixes to Fix a Security Weakness in the Blowfish Implementation. Please Refer to For Full Details of the Security Fix, But to Summarise, developers targeting only PHP 5.3.7 and Later Should Use $ 2y $ "in Preference to" $ 2a $ ".
  • Crypt_sha256. - Sha-256 Hash with a Sixteen Character Salt Prefixed WITH $ 5 $. If The Salt String Starts WITH "Rounds \u003d
  • Crypt_sha512. - SHA-512 HASH WITH A SIXTEEN CHARACTER SALT PREFIXED WITH $ 6 $. If The Salt String Starts WITH "Rounds \u003d $ ", The Numeric Value of N IS Used to Indicate How Many Times The Hashing Loop Should Be Executed, Much Like The Cost Parameter on Blowfish. The Default Number of Rounds Is 5000, there is a minimum of 1000 and a maximum of 999.999,999. Any Selection of N Outside This Range Will Be Truncated to the Nearest Limit.

AS of PHP 5.3.0, PHP Contains Its Own Implementation and Will Use That If The System Lacks of Support For One or More of the Algorithms.

Parameters.

The String to Be Hashed.

Caution

Using the Crypt_blowfish Algorithm, Will Result In The Str Parameter Being Truncated to a Maximum Length of 72 Characters.

An Optional Salt String to Base The Hashing On. If Not Provided, The Behaviour Is Defined by The Algorithm Implementation and Can Lead to Unexpected Results.

Return Values.

Returns The Hashed String Or A String That Is Shorter Than 13 Characters and IS Guaranteed to Differ from the Salt on Failure.

Warning

WHEN VALIDATING PASSWORDS, A STRING COMPARISON FUNCTION THAT ISN "T VULNERABLE TO TIMING ATTACKS SHOLD BE USED TO COMPARE THE OUTPUT OF OFT OF crypt () To The Previously Known Hash. PHP 5.6 Onwards Provides hash_equals () For this Purpose.

ChangeLog.

Version. Description.
5.6.5 WHEN THE FAILURE STRING "* 0" IS Given As the Salt, "* 1" Will Now Be Returned for Consistency with Other Crypt IMPLEMENTATIONS. Prior to this version, PHP 5.6 Would Incorrectly Return a des Hash.
5.6.0 Raise E_Notice Security Warning If Salt Is Omitted.
5.5.21 WHEN THE FAILURE STRING "* 0" IS Given As the Salt, "* 1" Will Now Be Returned for Consistency with Other Crypt IMPLEMENTATIONS. Prior to this version, PHP 5.5 (and Earlier Branches) Would Incorrectly Return a des Hash.
5.3.7 Added $ 2x $ And. $ 2y $ Bluefish Modes to Deal With Potential High-Bit Attacks.
5.3.2 Added SHA-256 and SHA-512 Crypt Based on Ulrich Drepper "S" IMPLEMENTATION.
5.3.2 Fixed BlowFish Behaviour On Invalid Rounds to Return "Failure" String ("* 0" or "* 1"), Instad of Falling Back to Des.
5.3.0 PHP Now Contains Its Own Implementation for the MD5 Crypt, Standard Des, Extended Des and the Blowfish Algorithms and Will Use That If The System Lacks of Support For One or More of the Algorithms.

Examples.

Example # 1. crypt () Examples.

$ hashed_password \u003d crypt ("MyPassword"); // Let The Salt Be Automatically Generated

/ * You Should Pass The Entire Results of Crypt () AS The Salt for Comparing A
Password, To Avoid Problems When Different Hashing Algorithms Are Used. (AS.
IT SAYS ABOVE, STANDARD DES-BASED PASSWORD HASHING USES A 2-CHARACTER SALT,
But MD5-Based Hashing Uses 12.) * /
if (Hash_equals ($ Hashed_Password, Crypt ($ user_input, $ hashed_password))) (
Echo "Password Verified!" ;
}
?>

Example # 2 using crypt () With HTPASSWD.

// Set The Password
$ password \u003d "mypassword";

// Get The Hash, Letting The Salt Be Automatically Generated
$ hash \u003d Crypt ($ password);
?>

Example # 3 using crypt () With Different Hash Types

/ * These Salts Are Examples Only, And Should Not Be Used Verbatim in Your Code.
You Should Generate a Distinct, Correctly-Formatted Salt for Each Password.
*/
if (crypt_std_des \u003d\u003d 1) (
Echo "Standard des:". Crypt ("Rasmuslerdorf", "RL"). "\\ n";
}

if (crypt_ext_des \u003d\u003d 1) (
Echo "Extended des:". Crypt ("Rasmuslerdorf", "_J9..RASM"). "\\ n";
}

if (crypt_md5 \u003d\u003d 1) (
Echo "MD5:". Crypt ("Rasmuslerdorf", "$ 1 $ Rasmusle $"). "\\ n";
}

if (crypt_blowfish \u003d\u003d 1) (
Echo "blowfish:". Crypt ("Rasmuslerdorf", "$ 2a $ 07 $ usesomesillyStringForsalt $"). "\\ n";
}

if (crypt_sha256 \u003d\u003d 1) (
Echo "SHA-256:". Crypt ("Rasmuslerdorf", "$ 5 $ Rounds \u003d $ 5000 UseSomesillyStringForsalt $"). "\\ n";
}

if (crypt_sha512 \u003d\u003d 1) (
Echo "SHA-512:". Crypt ("Rasmuslerdorf", "$ 6 $ rounds \u003d 5000 $ usesomesillyStringForsalt $"). "\\ n";
}
?>