Strong Cryptography in PHP

by Enrico Zimuel (enrico@zend.com)

Senior Software Engineer
Zend Framework Core Team
Zend Technologies Ltd



Dutch PHP Conference, 21th May 2011

                                      © All rights reserved. Zend Technologies, Inc.
About me
           ●   Software Engineer since 1996
           ●   Enjoying PHP since 1999
           ●   PHP Engineer at Zend Technologies,
                 in the Zend Framework Team
           ●   Author of two books on security and
                 cryptography (in italian)
           ●   B.Sc. (Hons) in Computer Science and
                Economics
           ●   Blog on Programming in PHP:
                 http://www.zimuel.it/blog




                 © All rights reserved. Zend Technologies, Inc.
Strong cryptography



  Strong cryptography is the usage of
cryptographic systems or components that
     are considered highly resistant to
           cryptanalytic attacks




              © All rights reserved. Zend Technologies, Inc.
A metric of security?
●   How we can say that an encryption algorithm
    is considered highly resistant to cryptanalytic
    attacks?
●   It's difficult to answer to this question. We
    don't have a simple metric of security.
●   We have to consider:
       ▶   Brute forcing attacks
       ▶   Theoretical attacks
       ▶   Implementation attacks


                      © All rights reserved. Zend Technologies, Inc.
A metric of security? (2)
●   Brute forcing attacks
       ▶   Space key is 2n, where n is the byte size of
             the key. If n=128, K= 3,4 * 1038
●   Theoretical attacks
       ▶   Break the encryption with mathematical
             attacks.
       ▶   Reduce the space key, for AES 256bit, an
             attack can reduce K to 299.5
●   Implementation attacks
       ▶   Based on the implementation

                       © All rights reserved. Zend Technologies, Inc.
Is DES still secure?
●   EFF DES cracker ("Deep
    Crack") is a computer built by
    the Electronic Frontier
    Foundation (EFF) in 1998 to
    perform a brute force search
    of DES cipher's key space
●   The Deep Crack decrypted a
    56 bit DES cryptogram in only
    56 hours of work. In the
    1998!




                     © All rights reserved. Zend Technologies, Inc.
Examples of strong cryptography
●   Strong:
       ▶   PGP, OpenPGP, GnuPG
       ▶   AES, Blowfish, Twofish
       ▶   RSA (key ≥ 2048 bit)
●   Not strong:
       ▶   DES
       ▶   WEP (Wired Equivalent Privacy)
       ▶   SSL 40 bit, international version
       ▶   All the classic ciphers (Enigma, ROT13, Vigenère,
              etc)


                         © All rights reserved. Zend Technologies, Inc.
Not only encryption
●   Strong cryptography is not only related to
    encryption.
●   It can also be used to describe hashing and
    unique identifier
●   In this usage, the term means difficult to
    guess




                    © All rights reserved. Zend Technologies, Inc.
Cryptography vs. Security
●   Cryptography doesn't means security
●   Encryption is not enough
●   “Security is a
    process, not a
    product”
        Bruce Schneier




                     © All rights reserved. Zend Technologies, Inc.
Complexity vs. Security




●   There are no complex
    systems that are secure.
●   “Complexity is the wrost
    enemy of security, and it
    always comes in the form of
    features or options”

       N. Ferguson, B. Schneier

                             © All rights reserved. Zend Technologies, Inc.
Cryptography in PHP




      © All rights reserved. Zend Technologies, Inc.
Cryptography in PHP
●   crypt()
●   Mcrypt
●   Hash
●   OpenSSL




              © All rights reserved. Zend Technologies, Inc.
crypt()
 ●   One-way string hashing
 ●   Support strong cryptography
        ▶   bcrypt, sha-256, sha-512
 ●   PHP 5.3.0 – bcrypt support
 ●   PHP 5.3.2 – sha-256/512




                      © All rights reserved. Zend Technologies, Inc.
Mcrypt
●   Mcrypt is an interface to the mcrypt library,
    which supports a wide variety of block
    algorithms
●   It support the following encryption algorithms:
       ▶   3DES, ARCFOUR, BLOWFISH, CAST, DES,
             ENIGMA, GOST, IDEA (non-free),
             LOKI97, MARS, PANAMA, RIJNDAEL, RC2,
             RC4, RC6, SAFER, SERPENT, SKIPJACK,
             TEAN, TWOFISH, WAKE, XTEA



                    © All rights reserved. Zend Technologies, Inc.
Hash
●   The Hash extension requires no external libraries
    and is enabled by default as of PHP 5.1.2.
●   This extension replace the old mhash extension
●   With this extension you can generate hash values
    or HMAC (Hash-based Message Authentication
    Code)
●   Supported hash algorithms: MD4, MD5, SHA1,
    SHA256, SHA384, SHA512, RIPEMD, RIPEMD,
    WHIRLPOOL, GOST, TIGER, HAVAL, etc




                    © All rights reserved. Zend Technologies, Inc.
OpenSSL
●   The OpenSSL extension uses the functions of the
    OpenSSL project for generation and verification of
    signatures and for sealing (encrypting) and
    opening (decrypting) data
●   You can use OpenSSL to protect data using public
    key cryptography with the RSA algorithm.




                    © All rights reserved. Zend Technologies, Inc.
Use standard algorithms

                                                 ● AES (RIJNDAEL), FIST 197
                                                   standard since 2001
                                                 ● BLOWFISH

                                                 ● TWOFISH

                                                 ● SHA-256, 384, 512

                                                 ● RSA




             © All rights reserved. Zend Technologies, Inc.
Examples and
Best practices




   © All rights reserved. Zend Technologies, Inc.
Example: encrypt with AES (CBC mode)

$ivSize= mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,
 $ivSize= mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,
                             MCRYPT_MODE_CBC);
                              MCRYPT_MODE_CBC);

$iv= mcrypt_create_iv($ivSize, MCRYPT_RAND);
 $iv= mcrypt_create_iv($ivSize, MCRYPT_RAND);

$encrypted= mcrypt_encrypt(
 $encrypted= mcrypt_encrypt(
    MCRYPT_RIJNDAEL_128,
     MCRYPT_RIJNDAEL_128,
    $key,
     $key,
    $data,
     $data,
    MCRYPT_MODE_CBC,
     MCRYPT_MODE_CBC,
    $iv
     $iv
);
 );



                   © All rights reserved. Zend Technologies, Inc.
Example: decrypt with AES (CBC mode)

$data= mcrypt_decrypt(
 $data= mcrypt_decrypt(
    MCRYPT_RIJNDAEL_128,
     MCRYPT_RIJNDAEL_128,
    $key,
     $key,
    $encrypted,
     $encrypted,
    MCRYPT_MODE_CBC,
     MCRYPT_MODE_CBC,
    $iv
     $iv
);
 );


 ●   What is the IV?
 ●   How to generate the key?

                    © All rights reserved. Zend Technologies, Inc.
Initialization vector (IV)

 ●   In cryptography, an Initialization
     Vector (IV) is a fixed-size input to a
     cryptographic primitive that is typically
     required to be random or pseudorandom
 ●   The IV is not a secret, you can send it
     in plaintext
 ●   Usually IV is stored before the encrypted
     message


                  © All rights reserved. Zend Technologies, Inc.
CBC needs IV
               The Plaintext (input) is divided into blocks


         Block 1                    Block 2                               Block 3




                                                                                    ...


        Block 1                      Block 2                              Block 3



  The Ciphertext (output) is the concatenation of the cipher-blocks

                         © All rights reserved. Zend Technologies, Inc.
Message Authentication Code (MAC)
●
    Use always a MAC to authenticate your encryption
    data




                    © All rights reserved. Zend Technologies, Inc.
Hash-based MAC (HMAC) in PHP
●   In PHP we can generate an HMAC using the
    hash_hmac() function:

    hash_hmac($algo, $msg, $key);

    $algo is the hash algorithm to use (i.e. sha256)
    $msg is the message
    $key is the secret for the HMAC
●   Combining with encryption:
       ▶   Encrypt and after HMAC of the encrypted
             message
       ▶   HMAC of the message and after encryption

                      © All rights reserved. Zend Technologies, Inc.
How build the key?
●   New key: pseudo-random
      ▶   Use openssl_random_pseudo_bytes()
            (PHP 5.3.0)
      ▶   DO NOT USE rand() or mt_rand()
●   Don't use the user password as a key
      ▶   Hash with a salt + iteration (stretching)
      ▶   To prevent dictionary based attacks
            Try http://md5.rednoize.com/




                     © All rights reserved. Zend Technologies, Inc.
Pseudo random key

function pseudoRandomKey($size) {{
 function pseudoRandomKey($size)
     if(function_exists('openssl_random_pseudo_bytes')) {{
      if(function_exists('openssl_random_pseudo_bytes'))
        $rnd == openssl_random_pseudo_bytes($size, $strong);
         $rnd    openssl_random_pseudo_bytes($size, $strong);
        if($strong === TRUE)
         if($strong === TRUE)
          return $rnd;
           return $rnd;
     }}
     $sha=''; $rnd='';
      $sha=''; $rnd='';
     for ($i=0;$i<$size;$i++) {{
      for ($i=0;$i<$size;$i++)
        $sha= hash('sha256',$sha.mt_rand());
         $sha= hash('sha256',$sha.mt_rand());
        $char= mt_rand(0,62);
         $char= mt_rand(0,62);
        $rnd.= chr(hexdec($sha[$char].$sha[$char+1]));
         $rnd.= chr(hexdec($sha[$char].$sha[$char+1]));
     }}
     return $rnd;
      return $rnd;
}}


                        © All rights reserved. Zend Technologies, Inc.
Build a key from a user password
●    Hash the password with a random salt +
     stretching

    $salt= pseudoRandomKey(128);
     $salt= pseudoRandomKey(128);
    $hash='';
     $hash='';
    for ($i=0;$i<HASH_CYCLE_LIMIT;$i++) {
     for ($i=0;$i<HASH_CYCLE_LIMIT;$i++) {
        $hash= hash('sha512',$hash.$salt.$password);
         $hash= hash('sha512',$hash.$salt.$password);
    }}


 ●   HASH_CYCLE_LIMIT depends on the CPU speed, should
     take between 200 to 1000 ms
         ▶   Intel Core 2 at 2.1Ghz, LIMIT≃ 20'000 (500 ms)

                          © All rights reserved. Zend Technologies, Inc.
Safely store a password (bcrypt)
 ●   Hash the password using bcrypt (PHP 5.3.0)

$salt = substr(str_replace('+', '.',
 $salt = substr(str_replace('+', '.',
                base64_encode($salt)), 0, 22);
                 base64_encode($salt)), 0, 22);
$hash= crypt($password,'$2a$'.$cost.'$'.$salt);
 $hash= crypt($password,'$2a$'.$cost.'$'.$salt);

 ●
     where $cost is the base-2 logarithm of the iteration count
     (Blowfish). Must be in range 04-31.
 ●   How to check if a password is valid or not:

$hash==crypt($password,$hash)
 $hash==crypt($password,$hash)


                        © All rights reserved. Zend Technologies, Inc.
Safely store a password (sha256)
function securePassword ($password, $salt) {
 function securePassword ($password, $salt) {
    $hash='';
     $hash='';
    for ($i=0;$i<SHA_LIMIT_LOOP;$i++) {
     for ($i=0;$i<SHA_LIMIT_LOOP;$i++) {
        $hash= hash('sha256',$hash.$salt.$password);
         $hash= hash('sha256',$hash.$salt.$password);
    }}
    return base64_encode($salt).'$'.$hash;
     return base64_encode($salt).'$'.$hash;
}}
●   For instance, $password= 'thisIsTheSecretPassword' and $salt=
    'hsjYeg/bxn()%3jdhsGHq0'

    aHNqWWVnL2J4bigpJTNqZGhzR0hxMA==$a9c810e9c722af719adabcf5
    0db8a0b4cd0d14e07eddbb43e5f47bde620a3c13

    Green= salt, Red= encrypted password



                           © All rights reserved. Zend Technologies, Inc.
Check if a password is valid
function validPassword ($password, $hash) {{
 function validPassword ($password, $hash)
    $delimiter= strpos($hash,'$');
     $delimiter= strpos($hash,'$');
    if ($delimiter===false) {{
     if ($delimiter===false)
        return false;
         return false;
    }}
    $salt= base64_decode(substr($hash,0,$delimiter));
     $salt= base64_decode(substr($hash,0,$delimiter));
    $tHash='';
     $tHash='';
    for ($i=0;$i<SHA_LIMIT_LOOP;$i++) {{
     for ($i=0;$i<SHA_LIMIT_LOOP;$i++)
        $tHash= hash('sha256',$tHash.$salt.$password);
         $tHash= hash('sha256',$tHash.$salt.$password);
    }}
    return (base64_encode($salt).'$'.$tHash==$hash);
     return (base64_encode($salt).'$'.$tHash==$hash);
}}




                     © All rights reserved. Zend Technologies, Inc.
Generate public and private keys

$privateKey = openssl_pkey_new(array(
 $privateKey = openssl_pkey_new(array(
   'private_key_bits' => 2048,
     'private_key_bits' => 2048,
   'private_key_type' => OPENSSL_KEYTYPE_RSA
     'private_key_type' => OPENSSL_KEYTYPE_RSA
));
 ));

openssl_pkey_export_to_file($privateKey,,
 openssl_pkey_export_to_file($privateKey
'/path/to/privatekey', $passphrase);
 '/path/to/privatekey', $passphrase);

$keyDetails = openssl_pkey_get_details($privateKey);
 $keyDetails = openssl_pkey_get_details($privateKey);
file_put_contents('/path/to/publickey',
 file_put_contents('/path/to/publickey',
$keyDetails['key']);
 $keyDetails['key']);



                   © All rights reserved. Zend Technologies, Inc.
Encrypt/decrypt using RSA
// encrypt
 // encrypt
$pubKey= openssl_pkey_get_public('pubkeyfile');
 $pubKey= openssl_pkey_get_public('pubkeyfile');
openssl_public_encrypt($plaintext,
 openssl_public_encrypt($plaintext,
                        $encrypted,
                         $encrypted,
                         $pubKey);
                          $pubKey);

// decrypt
 // decrypt
$privateKey= openssl_pkey_get_private('privkeyfile',
 $privateKey= openssl_pkey_get_private('privkeyfile',
             $passphrase);
              $passphrase);
openssl_private_decrypt($encrypted,
 openssl_private_decrypt($encrypted,
                         $plaintext,
                          $plaintext,
                          $privateKey);
                           $privateKey);



                   © All rights reserved. Zend Technologies, Inc.
Public-key cryptography to encrypt data
 ●   In general, the public-key cryptography is not
     used directly to encrypt data.
 ●   Public-key cryptography is computationally heavy,
     that means the algorithms are very slow!
 ●   We can use hybrid systems:
        ▶   public key + block chipers




                      © All rights reserved. Zend Technologies, Inc.
Example of hybrid system: PGP


 Plaintext
                         Block cipher                                  Ciphertext




             RND   Session key (random)
                                                                                     Message



 Receiver's                       RSA                                  Encrypted
 Public key                                                            Session key




                      © All rights reserved. Zend Technologies, Inc.
Some resources (books and papers)
●   N.Ferguson, B.Schneier, and T. Kohno, “Cryptography
      Engineering” John Wiley & Sons, 2010
●   N. Ferguson, B.Schneier, “Pratical Cryptography” Wiley,
      2003
●   C. Snyder, M.Southwell, “Pro PHP Security”, Apress, 2005
●   Chris Chiflett, “Essential PHP Security”, O'Reilly, 2006
●   Norman D. Jorstad, Landgrave T. Smith, Jr. “Cryptographic
      Algorithm Metrics”, Institute for Defense Analyses, 1997
●   Z. Benenson, U. Kühn, S.Lucks, “Cryptographic Attack
       Metrics” Dependability Metrics 2005




                         © All rights reserved. Zend Technologies, Inc.
Some resources (web)
●   PHP Cryptography Extensions,
      http://www.php.net/manual/en/refs.crypto.php
●   crypt(), http://nl.php.net/manual/en/function.crypt.php
●   Cracking MD5 and SHA-1, http://md5.rednoize.com/
●   A Guide to Cryptography in PHP,
      http://www.devx.com/webdev/Article/37821
●   How To Safely Store A Password,
      http://codahale.com/how-to-safely-store-a-password/
●   Zimuel's blog, Strong Cryptography in PHP
●   Zimuel's blog, Encrypt Session data in PHP



                        © All rights reserved. Zend Technologies, Inc.
Thank you!
●    Twitter:
          ▶   @ezimuel
●   Blog:
          ▶   http://www.zimuel.it/blog
●   GitHub:
          ▶   https://github.com/ezimuel


    © Copyright of the pictures used in this presentation:
    • TotalFail.blogspot.com

    • Windows Azure: Building a Secure Backup System

    • Borja Sotomayor “Globus Toolkit 4 Programmer's Tutorial”




                             © All rights reserved. Zend Technologies, Inc.
Questions?




             © All rights reserved. Zend Technologies, Inc.

More Related Content

PDF
Cryptography in PHP: use cases
PDF
Cryptography For The Average Developer - Sunshine PHP
PDF
Password Security
ODP
Password Security
PPT
9 password security
ODP
Applying Security Algorithms Using openSSL crypto library
PDF
Cryptography For The Average Developer
PPT
OpenPGP/GnuPG Encryption
Cryptography in PHP: use cases
Cryptography For The Average Developer - Sunshine PHP
Password Security
Password Security
9 password security
Applying Security Algorithms Using openSSL crypto library
Cryptography For The Average Developer
OpenPGP/GnuPG Encryption

What's hot (20)

PPTX
Secret key cryptography
PPTX
Cryptography 101
PPT
Old Linux Security Talk
PDF
Cryptography in PHP: Some Use Cases
PPT
Kleptography
PPT
introduction to cryptography
PPTX
Cryptography
PDF
Ch12 Encryption
PPTX
Cryptography - Simplified - Asymmetric Encryption
PDF
Gpg basics
PPT
PDF
Asymmetric Cryptography
PDF
Encryption Boot Camp on the JVM
PPTX
Cryptography for Absolute Beginners (May 2019)
PDF
OpenSSL Basic Function Call Flow
PPTX
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
PPTX
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
PPTX
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
PPTX
Cryptographic Algorithms: DES and RSA
Secret key cryptography
Cryptography 101
Old Linux Security Talk
Cryptography in PHP: Some Use Cases
Kleptography
introduction to cryptography
Cryptography
Ch12 Encryption
Cryptography - Simplified - Asymmetric Encryption
Gpg basics
Asymmetric Cryptography
Encryption Boot Camp on the JVM
Cryptography for Absolute Beginners (May 2019)
OpenSSL Basic Function Call Flow
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
Cryptographic Algorithms: DES and RSA
Ad

Similar to Strong cryptography in PHP (20)

PDF
Cryptography with Zend Framework
PDF
Password (in)security
PPTX
PBKDF2: Storing Sensitive Data Securely in Android Applications
PPTX
Unit-III_3R-CRYPTO_2021-22_VSM.pptx
PPT
Eight simple rules to writing secure PHP programs
PPTX
Cryptography
PPTX
Data Security Essentials - JavaOne 2013
PPTX
Crypto failures every developer should avoid
PPTX
Crypto failures every developer should avoid
PPTX
Encryption techniques
PDF
Encryption Boot Camp at JavaZone 2010
PPTX
Technology, Process, and Strategy
PPTX
How to do Cryptography right in Android Part One
PPTX
Course_Presentation cyber --------------.pptx
PPTX
Project Casquatch: An Open Source Java Abstraction Framework for Cassandra Da...
PPTX
Q Con New York 2015 Presentation - Conjur
PDF
How to Manage Cloud Infrastructures using Zend Framework
PDF
Crypkit 1
PDF
Challenges Building Secure Mobile Applications
PPTX
Vulnerabilities of machine learning infrastructure
Cryptography with Zend Framework
Password (in)security
PBKDF2: Storing Sensitive Data Securely in Android Applications
Unit-III_3R-CRYPTO_2021-22_VSM.pptx
Eight simple rules to writing secure PHP programs
Cryptography
Data Security Essentials - JavaOne 2013
Crypto failures every developer should avoid
Crypto failures every developer should avoid
Encryption techniques
Encryption Boot Camp at JavaZone 2010
Technology, Process, and Strategy
How to do Cryptography right in Android Part One
Course_Presentation cyber --------------.pptx
Project Casquatch: An Open Source Java Abstraction Framework for Cassandra Da...
Q Con New York 2015 Presentation - Conjur
How to Manage Cloud Infrastructures using Zend Framework
Crypkit 1
Challenges Building Secure Mobile Applications
Vulnerabilities of machine learning infrastructure
Ad

More from Enrico Zimuel (20)

PDF
Integrare Zend Framework in Wordpress
PDF
Quick start on Zend Framework 2
PDF
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
PDF
A quick start on Zend Framework 2
PDF
Zend Framework 2 quick start
PDF
PHP goes mobile
PDF
Zend Framework 2
PDF
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)
PDF
Manage cloud infrastructures using Zend Framework 2 (and ZF1)
PDF
Framework software e Zend Framework
PDF
How to scale PHP applications
PDF
Velocizzare Joomla! con Zend Server Community Edition
PDF
Zend_Cache: how to improve the performance of PHP applications
PDF
XCheck a benchmark checker for XML query processors
PDF
Introduzione alle tabelle hash
PDF
Crittografia quantistica: fantascienza o realtà?
PDF
Introduzione alla crittografia
PDF
Crittografia è sinonimo di sicurezza?
PDF
Sviluppo di applicazioni sicure
PDF
Misure minime di sicurezza informatica
Integrare Zend Framework in Wordpress
Quick start on Zend Framework 2
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
A quick start on Zend Framework 2
Zend Framework 2 quick start
PHP goes mobile
Zend Framework 2
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)
Manage cloud infrastructures using Zend Framework 2 (and ZF1)
Framework software e Zend Framework
How to scale PHP applications
Velocizzare Joomla! con Zend Server Community Edition
Zend_Cache: how to improve the performance of PHP applications
XCheck a benchmark checker for XML query processors
Introduzione alle tabelle hash
Crittografia quantistica: fantascienza o realtà?
Introduzione alla crittografia
Crittografia è sinonimo di sicurezza?
Sviluppo di applicazioni sicure
Misure minime di sicurezza informatica

Recently uploaded (20)

PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PPT
Module 1.ppt Iot fundamentals and Architecture
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PPTX
observCloud-Native Containerability and monitoring.pptx
PPTX
Chapter 5: Probability Theory and Statistics
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Unlock new opportunities with location data.pdf
PPTX
Web Crawler for Trend Tracking Gen Z Insights.pptx
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
CloudStack 4.21: First Look Webinar slides
PDF
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
PPTX
Modernising the Digital Integration Hub
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPT
What is a Computer? Input Devices /output devices
PDF
Architecture types and enterprise applications.pdf
PDF
August Patch Tuesday
DOCX
search engine optimization ppt fir known well about this
PPTX
Tartificialntelligence_presentation.pptx
Group 1 Presentation -Planning and Decision Making .pptx
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Module 1.ppt Iot fundamentals and Architecture
sustainability-14-14877-v2.pddhzftheheeeee
observCloud-Native Containerability and monitoring.pptx
Chapter 5: Probability Theory and Statistics
A comparative study of natural language inference in Swahili using monolingua...
Unlock new opportunities with location data.pdf
Web Crawler for Trend Tracking Gen Z Insights.pptx
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
WOOl fibre morphology and structure.pdf for textiles
CloudStack 4.21: First Look Webinar slides
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
Modernising the Digital Integration Hub
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
What is a Computer? Input Devices /output devices
Architecture types and enterprise applications.pdf
August Patch Tuesday
search engine optimization ppt fir known well about this
Tartificialntelligence_presentation.pptx

Strong cryptography in PHP

  • 1. Strong Cryptography in PHP by Enrico Zimuel ([email protected]) Senior Software Engineer Zend Framework Core Team Zend Technologies Ltd Dutch PHP Conference, 21th May 2011 © All rights reserved. Zend Technologies, Inc.
  • 2. About me ● Software Engineer since 1996 ● Enjoying PHP since 1999 ● PHP Engineer at Zend Technologies, in the Zend Framework Team ● Author of two books on security and cryptography (in italian) ● B.Sc. (Hons) in Computer Science and Economics ● Blog on Programming in PHP: http://www.zimuel.it/blog © All rights reserved. Zend Technologies, Inc.
  • 3. Strong cryptography Strong cryptography is the usage of cryptographic systems or components that are considered highly resistant to cryptanalytic attacks © All rights reserved. Zend Technologies, Inc.
  • 4. A metric of security? ● How we can say that an encryption algorithm is considered highly resistant to cryptanalytic attacks? ● It's difficult to answer to this question. We don't have a simple metric of security. ● We have to consider: ▶ Brute forcing attacks ▶ Theoretical attacks ▶ Implementation attacks © All rights reserved. Zend Technologies, Inc.
  • 5. A metric of security? (2) ● Brute forcing attacks ▶ Space key is 2n, where n is the byte size of the key. If n=128, K= 3,4 * 1038 ● Theoretical attacks ▶ Break the encryption with mathematical attacks. ▶ Reduce the space key, for AES 256bit, an attack can reduce K to 299.5 ● Implementation attacks ▶ Based on the implementation © All rights reserved. Zend Technologies, Inc.
  • 6. Is DES still secure? ● EFF DES cracker ("Deep Crack") is a computer built by the Electronic Frontier Foundation (EFF) in 1998 to perform a brute force search of DES cipher's key space ● The Deep Crack decrypted a 56 bit DES cryptogram in only 56 hours of work. In the 1998! © All rights reserved. Zend Technologies, Inc.
  • 7. Examples of strong cryptography ● Strong: ▶ PGP, OpenPGP, GnuPG ▶ AES, Blowfish, Twofish ▶ RSA (key ≥ 2048 bit) ● Not strong: ▶ DES ▶ WEP (Wired Equivalent Privacy) ▶ SSL 40 bit, international version ▶ All the classic ciphers (Enigma, ROT13, Vigenère, etc) © All rights reserved. Zend Technologies, Inc.
  • 8. Not only encryption ● Strong cryptography is not only related to encryption. ● It can also be used to describe hashing and unique identifier ● In this usage, the term means difficult to guess © All rights reserved. Zend Technologies, Inc.
  • 9. Cryptography vs. Security ● Cryptography doesn't means security ● Encryption is not enough ● “Security is a process, not a product” Bruce Schneier © All rights reserved. Zend Technologies, Inc.
  • 10. Complexity vs. Security ● There are no complex systems that are secure. ● “Complexity is the wrost enemy of security, and it always comes in the form of features or options” N. Ferguson, B. Schneier © All rights reserved. Zend Technologies, Inc.
  • 11. Cryptography in PHP © All rights reserved. Zend Technologies, Inc.
  • 12. Cryptography in PHP ● crypt() ● Mcrypt ● Hash ● OpenSSL © All rights reserved. Zend Technologies, Inc.
  • 13. crypt() ● One-way string hashing ● Support strong cryptography ▶ bcrypt, sha-256, sha-512 ● PHP 5.3.0 – bcrypt support ● PHP 5.3.2 – sha-256/512 © All rights reserved. Zend Technologies, Inc.
  • 14. Mcrypt ● Mcrypt is an interface to the mcrypt library, which supports a wide variety of block algorithms ● It support the following encryption algorithms: ▶ 3DES, ARCFOUR, BLOWFISH, CAST, DES, ENIGMA, GOST, IDEA (non-free), LOKI97, MARS, PANAMA, RIJNDAEL, RC2, RC4, RC6, SAFER, SERPENT, SKIPJACK, TEAN, TWOFISH, WAKE, XTEA © All rights reserved. Zend Technologies, Inc.
  • 15. Hash ● The Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2. ● This extension replace the old mhash extension ● With this extension you can generate hash values or HMAC (Hash-based Message Authentication Code) ● Supported hash algorithms: MD4, MD5, SHA1, SHA256, SHA384, SHA512, RIPEMD, RIPEMD, WHIRLPOOL, GOST, TIGER, HAVAL, etc © All rights reserved. Zend Technologies, Inc.
  • 16. OpenSSL ● The OpenSSL extension uses the functions of the OpenSSL project for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data ● You can use OpenSSL to protect data using public key cryptography with the RSA algorithm. © All rights reserved. Zend Technologies, Inc.
  • 17. Use standard algorithms ● AES (RIJNDAEL), FIST 197 standard since 2001 ● BLOWFISH ● TWOFISH ● SHA-256, 384, 512 ● RSA © All rights reserved. Zend Technologies, Inc.
  • 18. Examples and Best practices © All rights reserved. Zend Technologies, Inc.
  • 19. Example: encrypt with AES (CBC mode) $ivSize= mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, $ivSize= mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); MCRYPT_MODE_CBC); $iv= mcrypt_create_iv($ivSize, MCRYPT_RAND); $iv= mcrypt_create_iv($ivSize, MCRYPT_RAND); $encrypted= mcrypt_encrypt( $encrypted= mcrypt_encrypt( MCRYPT_RIJNDAEL_128, MCRYPT_RIJNDAEL_128, $key, $key, $data, $data, MCRYPT_MODE_CBC, MCRYPT_MODE_CBC, $iv $iv ); ); © All rights reserved. Zend Technologies, Inc.
  • 20. Example: decrypt with AES (CBC mode) $data= mcrypt_decrypt( $data= mcrypt_decrypt( MCRYPT_RIJNDAEL_128, MCRYPT_RIJNDAEL_128, $key, $key, $encrypted, $encrypted, MCRYPT_MODE_CBC, MCRYPT_MODE_CBC, $iv $iv ); ); ● What is the IV? ● How to generate the key? © All rights reserved. Zend Technologies, Inc.
  • 21. Initialization vector (IV) ● In cryptography, an Initialization Vector (IV) is a fixed-size input to a cryptographic primitive that is typically required to be random or pseudorandom ● The IV is not a secret, you can send it in plaintext ● Usually IV is stored before the encrypted message © All rights reserved. Zend Technologies, Inc.
  • 22. CBC needs IV The Plaintext (input) is divided into blocks Block 1 Block 2 Block 3 ... Block 1 Block 2 Block 3 The Ciphertext (output) is the concatenation of the cipher-blocks © All rights reserved. Zend Technologies, Inc.
  • 23. Message Authentication Code (MAC) ● Use always a MAC to authenticate your encryption data © All rights reserved. Zend Technologies, Inc.
  • 24. Hash-based MAC (HMAC) in PHP ● In PHP we can generate an HMAC using the hash_hmac() function: hash_hmac($algo, $msg, $key); $algo is the hash algorithm to use (i.e. sha256) $msg is the message $key is the secret for the HMAC ● Combining with encryption: ▶ Encrypt and after HMAC of the encrypted message ▶ HMAC of the message and after encryption © All rights reserved. Zend Technologies, Inc.
  • 25. How build the key? ● New key: pseudo-random ▶ Use openssl_random_pseudo_bytes() (PHP 5.3.0) ▶ DO NOT USE rand() or mt_rand() ● Don't use the user password as a key ▶ Hash with a salt + iteration (stretching) ▶ To prevent dictionary based attacks Try http://md5.rednoize.com/ © All rights reserved. Zend Technologies, Inc.
  • 26. Pseudo random key function pseudoRandomKey($size) {{ function pseudoRandomKey($size) if(function_exists('openssl_random_pseudo_bytes')) {{ if(function_exists('openssl_random_pseudo_bytes')) $rnd == openssl_random_pseudo_bytes($size, $strong); $rnd openssl_random_pseudo_bytes($size, $strong); if($strong === TRUE) if($strong === TRUE) return $rnd; return $rnd; }} $sha=''; $rnd=''; $sha=''; $rnd=''; for ($i=0;$i<$size;$i++) {{ for ($i=0;$i<$size;$i++) $sha= hash('sha256',$sha.mt_rand()); $sha= hash('sha256',$sha.mt_rand()); $char= mt_rand(0,62); $char= mt_rand(0,62); $rnd.= chr(hexdec($sha[$char].$sha[$char+1])); $rnd.= chr(hexdec($sha[$char].$sha[$char+1])); }} return $rnd; return $rnd; }} © All rights reserved. Zend Technologies, Inc.
  • 27. Build a key from a user password ● Hash the password with a random salt + stretching $salt= pseudoRandomKey(128); $salt= pseudoRandomKey(128); $hash=''; $hash=''; for ($i=0;$i<HASH_CYCLE_LIMIT;$i++) { for ($i=0;$i<HASH_CYCLE_LIMIT;$i++) { $hash= hash('sha512',$hash.$salt.$password); $hash= hash('sha512',$hash.$salt.$password); }} ● HASH_CYCLE_LIMIT depends on the CPU speed, should take between 200 to 1000 ms ▶ Intel Core 2 at 2.1Ghz, LIMIT≃ 20'000 (500 ms) © All rights reserved. Zend Technologies, Inc.
  • 28. Safely store a password (bcrypt) ● Hash the password using bcrypt (PHP 5.3.0) $salt = substr(str_replace('+', '.', $salt = substr(str_replace('+', '.', base64_encode($salt)), 0, 22); base64_encode($salt)), 0, 22); $hash= crypt($password,'$2a$'.$cost.'$'.$salt); $hash= crypt($password,'$2a$'.$cost.'$'.$salt); ● where $cost is the base-2 logarithm of the iteration count (Blowfish). Must be in range 04-31. ● How to check if a password is valid or not: $hash==crypt($password,$hash) $hash==crypt($password,$hash) © All rights reserved. Zend Technologies, Inc.
  • 29. Safely store a password (sha256) function securePassword ($password, $salt) { function securePassword ($password, $salt) { $hash=''; $hash=''; for ($i=0;$i<SHA_LIMIT_LOOP;$i++) { for ($i=0;$i<SHA_LIMIT_LOOP;$i++) { $hash= hash('sha256',$hash.$salt.$password); $hash= hash('sha256',$hash.$salt.$password); }} return base64_encode($salt).'$'.$hash; return base64_encode($salt).'$'.$hash; }} ● For instance, $password= 'thisIsTheSecretPassword' and $salt= 'hsjYeg/bxn()%3jdhsGHq0' aHNqWWVnL2J4bigpJTNqZGhzR0hxMA==$a9c810e9c722af719adabcf5 0db8a0b4cd0d14e07eddbb43e5f47bde620a3c13 Green= salt, Red= encrypted password © All rights reserved. Zend Technologies, Inc.
  • 30. Check if a password is valid function validPassword ($password, $hash) {{ function validPassword ($password, $hash) $delimiter= strpos($hash,'$'); $delimiter= strpos($hash,'$'); if ($delimiter===false) {{ if ($delimiter===false) return false; return false; }} $salt= base64_decode(substr($hash,0,$delimiter)); $salt= base64_decode(substr($hash,0,$delimiter)); $tHash=''; $tHash=''; for ($i=0;$i<SHA_LIMIT_LOOP;$i++) {{ for ($i=0;$i<SHA_LIMIT_LOOP;$i++) $tHash= hash('sha256',$tHash.$salt.$password); $tHash= hash('sha256',$tHash.$salt.$password); }} return (base64_encode($salt).'$'.$tHash==$hash); return (base64_encode($salt).'$'.$tHash==$hash); }} © All rights reserved. Zend Technologies, Inc.
  • 31. Generate public and private keys $privateKey = openssl_pkey_new(array( $privateKey = openssl_pkey_new(array( 'private_key_bits' => 2048, 'private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA 'private_key_type' => OPENSSL_KEYTYPE_RSA )); )); openssl_pkey_export_to_file($privateKey,, openssl_pkey_export_to_file($privateKey '/path/to/privatekey', $passphrase); '/path/to/privatekey', $passphrase); $keyDetails = openssl_pkey_get_details($privateKey); $keyDetails = openssl_pkey_get_details($privateKey); file_put_contents('/path/to/publickey', file_put_contents('/path/to/publickey', $keyDetails['key']); $keyDetails['key']); © All rights reserved. Zend Technologies, Inc.
  • 32. Encrypt/decrypt using RSA // encrypt // encrypt $pubKey= openssl_pkey_get_public('pubkeyfile'); $pubKey= openssl_pkey_get_public('pubkeyfile'); openssl_public_encrypt($plaintext, openssl_public_encrypt($plaintext, $encrypted, $encrypted, $pubKey); $pubKey); // decrypt // decrypt $privateKey= openssl_pkey_get_private('privkeyfile', $privateKey= openssl_pkey_get_private('privkeyfile', $passphrase); $passphrase); openssl_private_decrypt($encrypted, openssl_private_decrypt($encrypted, $plaintext, $plaintext, $privateKey); $privateKey); © All rights reserved. Zend Technologies, Inc.
  • 33. Public-key cryptography to encrypt data ● In general, the public-key cryptography is not used directly to encrypt data. ● Public-key cryptography is computationally heavy, that means the algorithms are very slow! ● We can use hybrid systems: ▶ public key + block chipers © All rights reserved. Zend Technologies, Inc.
  • 34. Example of hybrid system: PGP Plaintext Block cipher Ciphertext RND Session key (random) Message Receiver's RSA Encrypted Public key Session key © All rights reserved. Zend Technologies, Inc.
  • 35. Some resources (books and papers) ● N.Ferguson, B.Schneier, and T. Kohno, “Cryptography Engineering” John Wiley & Sons, 2010 ● N. Ferguson, B.Schneier, “Pratical Cryptography” Wiley, 2003 ● C. Snyder, M.Southwell, “Pro PHP Security”, Apress, 2005 ● Chris Chiflett, “Essential PHP Security”, O'Reilly, 2006 ● Norman D. Jorstad, Landgrave T. Smith, Jr. “Cryptographic Algorithm Metrics”, Institute for Defense Analyses, 1997 ● Z. Benenson, U. Kühn, S.Lucks, “Cryptographic Attack Metrics” Dependability Metrics 2005 © All rights reserved. Zend Technologies, Inc.
  • 36. Some resources (web) ● PHP Cryptography Extensions, http://www.php.net/manual/en/refs.crypto.php ● crypt(), http://nl.php.net/manual/en/function.crypt.php ● Cracking MD5 and SHA-1, http://md5.rednoize.com/ ● A Guide to Cryptography in PHP, http://www.devx.com/webdev/Article/37821 ● How To Safely Store A Password, http://codahale.com/how-to-safely-store-a-password/ ● Zimuel's blog, Strong Cryptography in PHP ● Zimuel's blog, Encrypt Session data in PHP © All rights reserved. Zend Technologies, Inc.
  • 37. Thank you! ● Twitter: ▶ @ezimuel ● Blog: ▶ http://www.zimuel.it/blog ● GitHub: ▶ https://github.com/ezimuel © Copyright of the pictures used in this presentation: • TotalFail.blogspot.com • Windows Azure: Building a Secure Backup System • Borja Sotomayor “Globus Toolkit 4 Programmer's Tutorial” © All rights reserved. Zend Technologies, Inc.
  • 38. Questions? © All rights reserved. Zend Technologies, Inc.