Cryptography in PHP: use cases

Enrico Zimuel
Enrico ZimuelSenior Software Engineer at Zend Technologies
October 2011




Cryptography in PHP:
use cases
Enrico Zimuel
Zend Technologies
About me
                                                      October 2011

                           • Enrico Zimuel (ezimuel)
                           • Software Engineer since 1996
                             – Assembly x86, C/C++, Java, Perl, PHP
                           • Enjoying PHP since 1999
                           • Senior PHP Engineer at Zend
                               Technologies since 2008
                           • Author of two italian books about
Email: enrico@zend.com
                               applied cryptography
                           • B.Sc. Computer Science and
                               Economics from University of
                               Pescara (Italy)
Summary
                                         October 2011




●   Cryptography in PHP
●   Some use cases:
    ●   Safe way to store passwords
    ●   Generate pseudo-random numbers
    ●   Encrypt/decrypt sensitive data
●   Demo: encrypt PHP session data
Cryptography in PHP
                     October 2011




● crypt()
● Mcrypt


● Hash


● OpenSSL
crypt()
                                   October 2011




●   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
●   Note: don't use PHP 5.3.7 (bug #55439)
Mcrypt
                                            October 2011




●   Mcrypt is an interface to the mcrypt library
●   Supports 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
Hash
                                    October 2011




●   Enabled by default from PHP 5.1.2
●   Hash or HMAC (Hash-based Message
    Authentication Code)
●   Supported hash algorithms: MD4, MD5,
    SHA1, SHA256, SHA384, SHA512,
    RIPEMD, RIPEMD, WHIRLPOOL, GOST,
    TIGER, HAVAL, etc
OpenSSL
                                        October 2011




●   The OpenSSL extension uses the functions of
    the OpenSSL project for generation and
    verification of signatures and for sealing
    (encrypting) and opening (decrypting) data
●   Public key cryptography (RSA algorithm)
Which algorithm?
                                      October 2011




●   Some suggestions:
    ●   Symmetric encryption:
         – Blowfish / Twofish
         – Rijndael (AES, FIST 197 standard
           since 2001)
    ●   Hash: SHA-256, 384, 512
    ●   Public key: RSA
Cryptography vs. Security

                                        October 2011




●   Cryptography doesn't mean security
●   Encryption is not enough
●   Bruce Schneier quotes:
    ●   “Security is only as strong as the
        weakest link”
    ●   “Security is a process, not a product”
Cryptography vs. Security

                   October 2011
October 2011




Use cases
Use case 1: store a password

                                    October 2011




●   Scenario:
    ● Web applications with a protect area
    ● Username and password to login


●   Problem: how to safely store a password?
Hash a password
                                                      October 2011




●   Basic ideas, use of hash algorithms:
    ●   md5($password) – not secure
        –   Dictionary attack (pre-built)
    ●   md5($salt . $password) – better but still insecure
        –   Dictionary attacks:
             ● 700'000'000 passwords a second using CUDA (budget

               of 2000 $, a week)
             ● Cloud computing, 500'000'000 passwords a second

               (about $300/hour)
bcrypt
                                            October 2011




●   Better idea, use of bcrypt algorithm:
    ●   bcrypt prevent the dictionary attacks
        because is slow as hell
    ●   Based on a variant of Blowfish
    ●   Introduce a work factor, which allows you to
        determine how expensive the hash function
        will be
bcrypt in PHP
                                                         October 2011




    ●   Hash the password using bcrypt (PHP 5.3+)

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


●
        $salt is a random string (it is not a secret!)
●
        $workload is the bcrypt's workload (from 10 to 31)
bcrypt workload benchmark
                           $workload   time in sec
                                                 October 2011
                              10           0.1
                              11           0.2
                              12           0.4
                              13           0.7
                              14           1.5
Suggestion:
Spend ≈ 1 sec (or more)       15           3
                              16           6
                              17           12
                              18          24.3
                              19          48.7
                              20          97.3
                              21         194.3
 OS: Linux kernel 2.6.38
CPU: Intel Core2, 2.1Ghz      22         388.2
RAM: 2 GB - PHP: 5.3.6        …            …
bcrypt output
                                                October 2011




  ●   Example of bcrypt's output:
$2a$14$c2Rmc2Fka2hmamhzYWRmauBpwLLDFKNPTfmCeuMHVnMVaLatNlFZO



  ●   c2Rmc2Fka2hmamhzYWRmau is the salt
  ●   Workload: 14
  ●   Length of 60 btyes
bcrypt authentication
                                    October 2011




●   How to check if a $userpassword is valid
    for a $hash value?

if ($hash==crypt($userpassword,$hash)) {
 if ($hash==crypt($userpassword,$hash)) {
   echo 'The password is correct';
    echo 'The password is correct';
} else {
 } else {
   echo 'The password is not correct!';
    echo 'The password is not correct!';
}}
Use case 2: generate random
            data in PHP
                                    October 2011




●   Scenario:
    ●   Generate random passwords for
         – Login systems
         – API systems
    ●   Problem: how to generate random data
        in PHP?
Random number generators
                  October 2011
PHP vs. randomness
                                         October 2011




●   How generate a pseudo-random value in PHP?
●   Not good for cryptography purpose:
    ●   rand()
    ●   mt_rand()
●   Good for cryptography (PHP 5.3+):
    ●   openssl_random_pseudo_bytes()
rand() is real random?
                                     October 2011



Pseudo-random bits   rand() in PHP on Windows




                             From random.org website
Use case 3: encrypt data
                                      October 2011




●   Scenario:
    ● We want to store some sensitive data
      (e.g. credit card numbers)
●   Problem:
    ●   How to encrypt this data in PHP?
Symmetric encryption
                                          October 2011




●   Using Mcrypt extension:
    ●
        mcrypt_encrypt(string $cipher,string $key,
        string $data,string $mode[,string $iv])
    ●
        mcrypt_decrypt(string $cipher,string $key,
        string $data,string $mode[,string $iv])
●   What are these $mode and $iv parameters?
Encryption mode
                                          October 2011




●   Symmetric encryption mode:
    ●   ECB, CBC, CFB, OFB, NOFB or STREAM
●   We are going to use the CBC that is the most
    used and secure
●   Cipher-Block Chaining (CBC) mode of operation
    was invented in 1976 by IBM
CBC
                                                             October 2011

              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
IV
                                               October 2011




●   Initialization Vector (IV) is a fixed-size input that
    is typically required to be random or pseudo
●   The IV is not a secret, you can send it in
    plaintext
●   Usually IV is stored before the encrypted
    message
●   Must be unique for each encrypted message
Encryption is not enough
                                               October 2011




●   We cannot use only encryption to store sensitive
    data, we need also authentication!
●   Encryption doesn't prevent alteration of data
    ●   Padding Oracle Attack (Vaudenay, EuroCrypt 2002)
●   We need to authenticate:
    ●   MAC (Message Authentication Code)
    ●   HMAC (Hash-based Message Authentication
        Code)
HMAC
                                           October 2011




●   In PHP we can generate an HMAC using the
    hash_hmac() function:

    hash_hmac ($algo, $msg, $key)

    $algo is the hash algorithm to use (e.g. sha256)
    $msg is the message
    $key is the key for the HMAC
Encryption + authentication
                                    October 2011




●   Three possible ways:
    ● Encrypt-then-authenticate
    ● Authenticate-then-encrypt


    ● Encrypt-and-authenticate


●   We will use encrypt-then-authenticate,
    as suggested by Schneier in [1]
Demo: encrypt session data

                                             October 2011




●   Specific PHP session handler to encrypt
    session data using files
●   Use of AES (Rijndael 128) + HMAC (SHA-256)
●   Pseudo-random session key
●   The encryption and authentication keys are
    stored in a cookie variable
●   Source code:
    https://github.com/ezimuel/PHP-Secure-Session
Conclusion (1)
                                            October 2011




●   Use standard algorithms for cryptography:
    ●   AES (Rijndael 128), SHA-* hash family, RSA
●   Generate random data using the function:
    ●   openssl_random_pseudo_bytes()
●   Store passwords using bcrypt:
    ●   crypt($password, '$2a$'.$workload.'$'.$salt)
Conclusion (2)
                                         October 2011




●   For symmetric encryption:
    ●   Use CBC mode with a different random IV
        for each encryption
    ●   Always authenticate the encryption data
        (using HMAC): encrypt-then-authenticate
●   Use HTTPS (SSL/TLS) to protect the
    communication client/server
References
                                                    October 2011



(1) N. Ferguson, B. Schneier, T. Kohno, “Cryptography
   Engineering”, Wiley Publishing, 2010
(2) Serge Vaudenay, “Security Flaws Induced by CBC Padding
   Applications to SSL, IPSEC, WTLS”, EuroCrypt 2002
●   Web:
    ●   PHP cryptography extensions
    ●   How to safely store a password
    ●   bcrypt algorithm
    ●   SHA-1 challenge
    ●   Nvidia CUDA
    ●   Random.org
Thank you!
                                  October 2011




●   Vote this talk:
    ●   http://joind.in/3748
●   Comments and feedbacks:
    ●   enrico@zend.com
1 of 36

Recommended

Cryptography For The Average Developer - Sunshine PHP by
Cryptography For The Average Developer - Sunshine PHPCryptography For The Average Developer - Sunshine PHP
Cryptography For The Average Developer - Sunshine PHPAnthony Ferrara
23.9K views64 slides
Password Storage and Attacking in PHP by
Password Storage and Attacking in PHPPassword Storage and Attacking in PHP
Password Storage and Attacking in PHPAnthony Ferrara
7.3K views60 slides
Strong cryptography in PHP by
Strong cryptography in PHPStrong cryptography in PHP
Strong cryptography in PHPEnrico Zimuel
5.7K views38 slides
Cryptography For The Average Developer by
Cryptography For The Average DeveloperCryptography For The Average Developer
Cryptography For The Average DeveloperAnthony Ferrara
2.2K views54 slides
9 password security by
9   password security9   password security
9 password securitydrewz lin
5.2K views37 slides
Password (in)security by
Password (in)securityPassword (in)security
Password (in)securityEnrico Zimuel
10.5K views38 slides

More Related Content

What's hot

Secure password - CYBER SECURITY by
Secure password - CYBER SECURITYSecure password - CYBER SECURITY
Secure password - CYBER SECURITYSupanShah2
577 views10 slides
Cryptography in PHP: Some Use Cases by
Cryptography in PHP: Some Use CasesCryptography in PHP: Some Use Cases
Cryptography in PHP: Some Use CasesZend by Rogue Wave Software
10.6K views36 slides
How does cryptography work? by Jeroen Ooms by
How does cryptography work?  by Jeroen OomsHow does cryptography work?  by Jeroen Ooms
How does cryptography work? by Jeroen OomsAjay Ohri
976 views3 slides
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose) by
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)Svetlin Nakov
522 views45 slides
Cryptography for Absolute Beginners (May 2019) by
Cryptography for Absolute Beginners (May 2019)Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)Svetlin Nakov
1.9K views40 slides
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019) by
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Svetlin Nakov
2.5K views57 slides

What's hot(20)

Secure password - CYBER SECURITY by SupanShah2
Secure password - CYBER SECURITYSecure password - CYBER SECURITY
Secure password - CYBER SECURITY
SupanShah2577 views
How does cryptography work? by Jeroen Ooms by Ajay Ohri
How does cryptography work?  by Jeroen OomsHow does cryptography work?  by Jeroen Ooms
How does cryptography work? by Jeroen Ooms
Ajay Ohri976 views
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose) by Svetlin Nakov
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
Svetlin Nakov522 views
Cryptography for Absolute Beginners (May 2019) by Svetlin Nakov
Cryptography for Absolute Beginners (May 2019)Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)
Svetlin Nakov1.9K views
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019) by Svetlin Nakov
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Svetlin Nakov2.5K views
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018) by Svetlin Nakov
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
Svetlin Nakov3K views
Wtf is happening_inside_my_android_phone_public by Jaime Blasco
Wtf is happening_inside_my_android_phone_publicWtf is happening_inside_my_android_phone_public
Wtf is happening_inside_my_android_phone_public
Jaime Blasco2.8K views
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у... by Positive Hack Days
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Positive Hack Days2.5K views
DEFCON 23 - Eijah - crypto for hackers by Felipe Prado
DEFCON 23 - Eijah - crypto for hackersDEFCON 23 - Eijah - crypto for hackers
DEFCON 23 - Eijah - crypto for hackers
Felipe Prado76 views
Applying Security Algorithms Using openSSL crypto library by Priyank Kapadia
Applying Security Algorithms Using openSSL crypto libraryApplying Security Algorithms Using openSSL crypto library
Applying Security Algorithms Using openSSL crypto library
Priyank Kapadia5.9K views
Applied cryptanalysis - stream ciphers by Vlad Garbuz
Applied cryptanalysis - stream ciphersApplied cryptanalysis - stream ciphers
Applied cryptanalysis - stream ciphers
Vlad Garbuz528 views
Apache Commons ソースリーディングの会:Codec by moai kids
Apache Commons ソースリーディングの会:CodecApache Commons ソースリーディングの会:Codec
Apache Commons ソースリーディングの会:Codec
moai kids3.3K views
Challenges Building Secure Mobile Applications by Masabi
Challenges Building Secure Mobile ApplicationsChallenges Building Secure Mobile Applications
Challenges Building Secure Mobile Applications
Masabi1.1K views
VisualWorks Security Reloaded - STIC 2012 by Martin Kobetic
VisualWorks Security Reloaded - STIC 2012VisualWorks Security Reloaded - STIC 2012
VisualWorks Security Reloaded - STIC 2012
Martin Kobetic801 views
OpenSSL Basic Function Call Flow by William Lee
OpenSSL Basic Function Call FlowOpenSSL Basic Function Call Flow
OpenSSL Basic Function Call Flow
William Lee5.2K views

Similar to Cryptography in PHP: use cases

Crypto & Crpyocurrencies Intro by
Crypto & Crpyocurrencies IntroCrypto & Crpyocurrencies Intro
Crypto & Crpyocurrencies IntroTal Shmueli
1.4K views67 slides
Redis - for duplicate detection on real time stream by
Redis - for duplicate detection on real time streamRedis - for duplicate detection on real time stream
Redis - for duplicate detection on real time streamCodemotion
3.8K views38 slides
Redis for duplicate detection on real time stream by
Redis for duplicate detection on real time streamRedis for duplicate detection on real time stream
Redis for duplicate detection on real time streamRoberto Franchini
7.5K views38 slides
All Your Password Are Belong To Us by
All Your Password Are Belong To UsAll Your Password Are Belong To Us
All Your Password Are Belong To UsCharles Southerland
800 views55 slides
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft... by
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft..."Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...Dataconomy Media
414 views30 slides
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES by
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESPyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESAlessandro Molina
777 views29 slides

Similar to Cryptography in PHP: use cases(20)

Crypto & Crpyocurrencies Intro by Tal Shmueli
Crypto & Crpyocurrencies IntroCrypto & Crpyocurrencies Intro
Crypto & Crpyocurrencies Intro
Tal Shmueli1.4K views
Redis - for duplicate detection on real time stream by Codemotion
Redis - for duplicate detection on real time streamRedis - for duplicate detection on real time stream
Redis - for duplicate detection on real time stream
Codemotion3.8K views
Redis for duplicate detection on real time stream by Roberto Franchini
Redis for duplicate detection on real time streamRedis for duplicate detection on real time stream
Redis for duplicate detection on real time stream
Roberto Franchini7.5K views
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft... by Dataconomy Media
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft..."Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
Dataconomy Media414 views
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES by Alessandro Molina
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESPyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
Alessandro Molina777 views
Module: drand - the Distributed Randomness Beacon by Ioannis Psaras
Module: drand - the Distributed Randomness BeaconModule: drand - the Distributed Randomness Beacon
Module: drand - the Distributed Randomness Beacon
Ioannis Psaras211 views
Cryptography with Zend Framework by Enrico Zimuel
Cryptography with Zend FrameworkCryptography with Zend Framework
Cryptography with Zend Framework
Enrico Zimuel3.3K views
Netflix Open Source Meetup Season 4 Episode 2 by aspyker
Netflix Open Source Meetup Season 4 Episode 2Netflix Open Source Meetup Season 4 Episode 2
Netflix Open Source Meetup Season 4 Episode 2
aspyker19.4K views
Advanced SOHO Router Exploitation XCON by Lyon Yang
Advanced SOHO Router Exploitation XCONAdvanced SOHO Router Exploitation XCON
Advanced SOHO Router Exploitation XCON
Lyon Yang2.2K views
NSC #2 - Challenge Solution by NoSuchCon
NSC #2 - Challenge SolutionNSC #2 - Challenge Solution
NSC #2 - Challenge Solution
NoSuchCon1.6K views
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for... by Alexandre Moneger
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
Alexandre Moneger892 views
inside-linux-kernel-rng-presentation-sept-13-2022.pdf by xiso
inside-linux-kernel-rng-presentation-sept-13-2022.pdfinside-linux-kernel-rng-presentation-sept-13-2022.pdf
inside-linux-kernel-rng-presentation-sept-13-2022.pdf
xiso11 views
"Developing a multicurrency, multisignature wallet" by Alex Melville by ICOVO
"Developing a multicurrency, multisignature wallet" by Alex Melville  "Developing a multicurrency, multisignature wallet" by Alex Melville
"Developing a multicurrency, multisignature wallet" by Alex Melville
ICOVO371 views
Deploying PHP on PaaS: Why and How? by Docker, Inc.
Deploying PHP on PaaS: Why and How?Deploying PHP on PaaS: Why and How?
Deploying PHP on PaaS: Why and How?
Docker, Inc.692 views
Dnssec tutorial-crypto-defs by AFRINIC
Dnssec tutorial-crypto-defsDnssec tutorial-crypto-defs
Dnssec tutorial-crypto-defs
AFRINIC331 views
OSDC 2016 - Ingesting Logs with Style by Pere Urbon-Bayes by NETWAYS
OSDC 2016 - Ingesting Logs with Style by Pere Urbon-BayesOSDC 2016 - Ingesting Logs with Style by Pere Urbon-Bayes
OSDC 2016 - Ingesting Logs with Style by Pere Urbon-Bayes
NETWAYS137 views
Type safe, versioned, and rewindable stream processing with Apache {Avro, K... by Hisham Mardam-Bey
Type safe, versioned, and rewindable stream processing  with  Apache {Avro, K...Type safe, versioned, and rewindable stream processing  with  Apache {Avro, K...
Type safe, versioned, and rewindable stream processing with Apache {Avro, K...
Hisham Mardam-Bey1.4K views

More from Enrico Zimuel

Integrare Zend Framework in Wordpress by
Integrare Zend Framework in WordpressIntegrare Zend Framework in Wordpress
Integrare Zend Framework in WordpressEnrico Zimuel
6.6K views38 slides
Quick start on Zend Framework 2 by
Quick start on Zend Framework 2Quick start on Zend Framework 2
Quick start on Zend Framework 2Enrico Zimuel
12.5K views42 slides
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecniche by
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecnicheIntroduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecnicheEnrico Zimuel
1.9K views15 slides
A quick start on Zend Framework 2 by
A quick start on Zend Framework 2A quick start on Zend Framework 2
A quick start on Zend Framework 2Enrico Zimuel
16.5K views52 slides
Zend Framework 2 quick start by
Zend Framework 2 quick startZend Framework 2 quick start
Zend Framework 2 quick startEnrico Zimuel
9.6K views45 slides
PHP goes mobile by
PHP goes mobilePHP goes mobile
PHP goes mobileEnrico Zimuel
3.3K views24 slides

More from Enrico Zimuel(20)

Integrare Zend Framework in Wordpress by Enrico Zimuel
Integrare Zend Framework in WordpressIntegrare Zend Framework in Wordpress
Integrare Zend Framework in Wordpress
Enrico Zimuel6.6K views
Quick start on Zend Framework 2 by Enrico Zimuel
Quick start on Zend Framework 2Quick start on Zend Framework 2
Quick start on Zend Framework 2
Enrico Zimuel12.5K views
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecniche by Enrico Zimuel
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecnicheIntroduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
Enrico Zimuel1.9K views
A quick start on Zend Framework 2 by Enrico Zimuel
A quick start on Zend Framework 2A quick start on Zend Framework 2
A quick start on Zend Framework 2
Enrico Zimuel16.5K views
Zend Framework 2 quick start by Enrico Zimuel
Zend Framework 2 quick startZend Framework 2 quick start
Zend Framework 2 quick start
Enrico Zimuel9.6K views
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1) by Enrico Zimuel
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)
Enrico Zimuel3.5K views
Manage cloud infrastructures using Zend Framework 2 (and ZF1) by Enrico Zimuel
Manage cloud infrastructures using Zend Framework 2 (and ZF1)Manage cloud infrastructures using Zend Framework 2 (and ZF1)
Manage cloud infrastructures using Zend Framework 2 (and ZF1)
Enrico Zimuel1.9K views
Framework software e Zend Framework by Enrico Zimuel
Framework software e Zend FrameworkFramework software e Zend Framework
Framework software e Zend Framework
Enrico Zimuel1.1K views
How to scale PHP applications by Enrico Zimuel
How to scale PHP applicationsHow to scale PHP applications
How to scale PHP applications
Enrico Zimuel29.5K views
Velocizzare Joomla! con Zend Server Community Edition by Enrico Zimuel
Velocizzare Joomla! con Zend Server Community EditionVelocizzare Joomla! con Zend Server Community Edition
Velocizzare Joomla! con Zend Server Community Edition
Enrico Zimuel2K views
Zend_Cache: how to improve the performance of PHP applications by Enrico Zimuel
Zend_Cache: how to improve the performance of PHP applicationsZend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applications
Enrico Zimuel6.4K views
XCheck a benchmark checker for XML query processors by Enrico Zimuel
XCheck a benchmark checker for XML query processorsXCheck a benchmark checker for XML query processors
XCheck a benchmark checker for XML query processors
Enrico Zimuel819 views
Introduzione alle tabelle hash by Enrico Zimuel
Introduzione alle tabelle hashIntroduzione alle tabelle hash
Introduzione alle tabelle hash
Enrico Zimuel662 views
Crittografia quantistica: fantascienza o realtà? by Enrico Zimuel
Crittografia quantistica: fantascienza o realtà?Crittografia quantistica: fantascienza o realtà?
Crittografia quantistica: fantascienza o realtà?
Enrico Zimuel763 views
Introduzione alla crittografia by Enrico Zimuel
Introduzione alla crittografiaIntroduzione alla crittografia
Introduzione alla crittografia
Enrico Zimuel733 views
Crittografia è sinonimo di sicurezza? by Enrico Zimuel
Crittografia è sinonimo di sicurezza?Crittografia è sinonimo di sicurezza?
Crittografia è sinonimo di sicurezza?
Enrico Zimuel648 views
Sviluppo di applicazioni sicure by Enrico Zimuel
Sviluppo di applicazioni sicureSviluppo di applicazioni sicure
Sviluppo di applicazioni sicure
Enrico Zimuel390 views
Misure minime di sicurezza informatica by Enrico Zimuel
Misure minime di sicurezza informaticaMisure minime di sicurezza informatica
Misure minime di sicurezza informatica
Enrico Zimuel690 views

Recently uploaded

Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveNetwork Automation Forum
49 views35 slides
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsShapeBlue
172 views13 slides
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueShapeBlue
149 views7 slides
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...ShapeBlue
93 views13 slides
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... by
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...ShapeBlue
48 views17 slides
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ by
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericShapeBlue
58 views9 slides

Recently uploaded(20)

Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by ShapeBlue
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystems
ShapeBlue172 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue149 views
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue93 views
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... by ShapeBlue
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
ShapeBlue48 views
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ by ShapeBlue
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
ShapeBlue58 views
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue154 views
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... by ShapeBlue
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
ShapeBlue128 views
"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays49 views
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by ShapeBlue
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
ShapeBlue114 views
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ... by ShapeBlue
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
ShapeBlue97 views
DRBD Deep Dive - Philipp Reisner - LINBIT by ShapeBlue
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBIT
ShapeBlue110 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue191 views
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue by ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue134 views
The Power of Heat Decarbonisation Plans in the Built Environment by IES VE
The Power of Heat Decarbonisation Plans in the Built EnvironmentThe Power of Heat Decarbonisation Plans in the Built Environment
The Power of Heat Decarbonisation Plans in the Built Environment
IES VE67 views
Extending KVM Host HA for Non-NFS Storage - Alex Ivanov - StorPool by ShapeBlue
Extending KVM Host HA for Non-NFS Storage -  Alex Ivanov - StorPoolExtending KVM Host HA for Non-NFS Storage -  Alex Ivanov - StorPool
Extending KVM Host HA for Non-NFS Storage - Alex Ivanov - StorPool
ShapeBlue56 views
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue178 views
NTGapps NTG LowCode Platform by Mustafa Kuğu
NTGapps NTG LowCode Platform NTGapps NTG LowCode Platform
NTGapps NTG LowCode Platform
Mustafa Kuğu287 views
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue by ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
ShapeBlue147 views

Cryptography in PHP: use cases

  • 1. October 2011 Cryptography in PHP: use cases Enrico Zimuel Zend Technologies
  • 2. About me October 2011 • Enrico Zimuel (ezimuel) • Software Engineer since 1996 – Assembly x86, C/C++, Java, Perl, PHP • Enjoying PHP since 1999 • Senior PHP Engineer at Zend Technologies since 2008 • Author of two italian books about Email: enrico@zend.com applied cryptography • B.Sc. Computer Science and Economics from University of Pescara (Italy)
  • 3. Summary October 2011 ● Cryptography in PHP ● Some use cases: ● Safe way to store passwords ● Generate pseudo-random numbers ● Encrypt/decrypt sensitive data ● Demo: encrypt PHP session data
  • 4. Cryptography in PHP October 2011 ● crypt() ● Mcrypt ● Hash ● OpenSSL
  • 5. crypt() October 2011 ● 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 ● Note: don't use PHP 5.3.7 (bug #55439)
  • 6. Mcrypt October 2011 ● Mcrypt is an interface to the mcrypt library ● Supports 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
  • 7. Hash October 2011 ● Enabled by default from PHP 5.1.2 ● Hash or HMAC (Hash-based Message Authentication Code) ● Supported hash algorithms: MD4, MD5, SHA1, SHA256, SHA384, SHA512, RIPEMD, RIPEMD, WHIRLPOOL, GOST, TIGER, HAVAL, etc
  • 8. OpenSSL October 2011 ● The OpenSSL extension uses the functions of the OpenSSL project for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data ● Public key cryptography (RSA algorithm)
  • 9. Which algorithm? October 2011 ● Some suggestions: ● Symmetric encryption: – Blowfish / Twofish – Rijndael (AES, FIST 197 standard since 2001) ● Hash: SHA-256, 384, 512 ● Public key: RSA
  • 10. Cryptography vs. Security October 2011 ● Cryptography doesn't mean security ● Encryption is not enough ● Bruce Schneier quotes: ● “Security is only as strong as the weakest link” ● “Security is a process, not a product”
  • 13. Use case 1: store a password October 2011 ● Scenario: ● Web applications with a protect area ● Username and password to login ● Problem: how to safely store a password?
  • 14. Hash a password October 2011 ● Basic ideas, use of hash algorithms: ● md5($password) – not secure – Dictionary attack (pre-built) ● md5($salt . $password) – better but still insecure – Dictionary attacks: ● 700'000'000 passwords a second using CUDA (budget of 2000 $, a week) ● Cloud computing, 500'000'000 passwords a second (about $300/hour)
  • 15. bcrypt October 2011 ● Better idea, use of bcrypt algorithm: ● bcrypt prevent the dictionary attacks because is slow as hell ● Based on a variant of Blowfish ● Introduce a work factor, which allows you to determine how expensive the hash function will be
  • 16. bcrypt in PHP October 2011 ● Hash the password using bcrypt (PHP 5.3+) $salt = substr(str_replace('+', '.', $salt = substr(str_replace('+', '.', base64_encode($salt)), 0, 22); base64_encode($salt)), 0, 22); $hash = crypt($password,'$2a$'.$workload.'$'.$salt); $hash = crypt($password,'$2a$'.$workload.'$'.$salt); ● $salt is a random string (it is not a secret!) ● $workload is the bcrypt's workload (from 10 to 31)
  • 17. bcrypt workload benchmark $workload time in sec October 2011 10 0.1 11 0.2 12 0.4 13 0.7 14 1.5 Suggestion: Spend ≈ 1 sec (or more) 15 3 16 6 17 12 18 24.3 19 48.7 20 97.3 21 194.3 OS: Linux kernel 2.6.38 CPU: Intel Core2, 2.1Ghz 22 388.2 RAM: 2 GB - PHP: 5.3.6 … …
  • 18. bcrypt output October 2011 ● Example of bcrypt's output: $2a$14$c2Rmc2Fka2hmamhzYWRmauBpwLLDFKNPTfmCeuMHVnMVaLatNlFZO ● c2Rmc2Fka2hmamhzYWRmau is the salt ● Workload: 14 ● Length of 60 btyes
  • 19. bcrypt authentication October 2011 ● How to check if a $userpassword is valid for a $hash value? if ($hash==crypt($userpassword,$hash)) { if ($hash==crypt($userpassword,$hash)) { echo 'The password is correct'; echo 'The password is correct'; } else { } else { echo 'The password is not correct!'; echo 'The password is not correct!'; }}
  • 20. Use case 2: generate random data in PHP October 2011 ● Scenario: ● Generate random passwords for – Login systems – API systems ● Problem: how to generate random data in PHP?
  • 21. Random number generators October 2011
  • 22. PHP vs. randomness October 2011 ● How generate a pseudo-random value in PHP? ● Not good for cryptography purpose: ● rand() ● mt_rand() ● Good for cryptography (PHP 5.3+): ● openssl_random_pseudo_bytes()
  • 23. rand() is real random? October 2011 Pseudo-random bits rand() in PHP on Windows From random.org website
  • 24. Use case 3: encrypt data October 2011 ● Scenario: ● We want to store some sensitive data (e.g. credit card numbers) ● Problem: ● How to encrypt this data in PHP?
  • 25. Symmetric encryption October 2011 ● Using Mcrypt extension: ● mcrypt_encrypt(string $cipher,string $key, string $data,string $mode[,string $iv]) ● mcrypt_decrypt(string $cipher,string $key, string $data,string $mode[,string $iv]) ● What are these $mode and $iv parameters?
  • 26. Encryption mode October 2011 ● Symmetric encryption mode: ● ECB, CBC, CFB, OFB, NOFB or STREAM ● We are going to use the CBC that is the most used and secure ● Cipher-Block Chaining (CBC) mode of operation was invented in 1976 by IBM
  • 27. CBC October 2011 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
  • 28. IV October 2011 ● Initialization Vector (IV) is a fixed-size input that is typically required to be random or pseudo ● The IV is not a secret, you can send it in plaintext ● Usually IV is stored before the encrypted message ● Must be unique for each encrypted message
  • 29. Encryption is not enough October 2011 ● We cannot use only encryption to store sensitive data, we need also authentication! ● Encryption doesn't prevent alteration of data ● Padding Oracle Attack (Vaudenay, EuroCrypt 2002) ● We need to authenticate: ● MAC (Message Authentication Code) ● HMAC (Hash-based Message Authentication Code)
  • 30. HMAC October 2011 ● In PHP we can generate an HMAC using the hash_hmac() function: hash_hmac ($algo, $msg, $key) $algo is the hash algorithm to use (e.g. sha256) $msg is the message $key is the key for the HMAC
  • 31. Encryption + authentication October 2011 ● Three possible ways: ● Encrypt-then-authenticate ● Authenticate-then-encrypt ● Encrypt-and-authenticate ● We will use encrypt-then-authenticate, as suggested by Schneier in [1]
  • 32. Demo: encrypt session data October 2011 ● Specific PHP session handler to encrypt session data using files ● Use of AES (Rijndael 128) + HMAC (SHA-256) ● Pseudo-random session key ● The encryption and authentication keys are stored in a cookie variable ● Source code: https://github.com/ezimuel/PHP-Secure-Session
  • 33. Conclusion (1) October 2011 ● Use standard algorithms for cryptography: ● AES (Rijndael 128), SHA-* hash family, RSA ● Generate random data using the function: ● openssl_random_pseudo_bytes() ● Store passwords using bcrypt: ● crypt($password, '$2a$'.$workload.'$'.$salt)
  • 34. Conclusion (2) October 2011 ● For symmetric encryption: ● Use CBC mode with a different random IV for each encryption ● Always authenticate the encryption data (using HMAC): encrypt-then-authenticate ● Use HTTPS (SSL/TLS) to protect the communication client/server
  • 35. References October 2011 (1) N. Ferguson, B. Schneier, T. Kohno, “Cryptography Engineering”, Wiley Publishing, 2010 (2) Serge Vaudenay, “Security Flaws Induced by CBC Padding Applications to SSL, IPSEC, WTLS”, EuroCrypt 2002 ● Web: ● PHP cryptography extensions ● How to safely store a password ● bcrypt algorithm ● SHA-1 challenge ● Nvidia CUDA ● Random.org
  • 36. Thank you! October 2011 ● Vote this talk: ● http://joind.in/3748 ● Comments and feedbacks: ● enrico@zend.com