SlideShare uma empresa Scribd logo
1 de 36
Baixar para ler offline
Cryptography in PHP:
some use cases

by Enrico Zimuel (enrico@zend.com)

Senior Software Engineer
Zend Framework Core Team
Zend Technologies Ltd



                        PHPTour Lille 2011 – 25 November
                 http://afup.org/pages/phptourlille2011/
                                                           © All rights reserved. Zend Technologies, Inc.
About me

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




                         © All rights reserved. Zend Technologies, Inc.
Summary

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




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




                     © All rights reserved. Zend Technologies, Inc.
Mcrypt extension

●   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




                     © All rights reserved. Zend Technologies, Inc.
Hash extension

●   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


                © All rights reserved. Zend Technologies, Inc.
OpenSSL extension

●   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)




                     © All rights reserved. Zend Technologies, Inc.
Which algorithm to use?

●   Some suggestions:
       ▶   Symmetric encryption:
               Blowfish / Twofish
               ●


             ●
               Rijndael (AES, FIST 197 standard
                since 2001)
       ▶ Hash: SHA-256, 384, 512


       ▶   Public key: RSA



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

●
    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”




                     © All rights reserved. Zend Technologies, Inc.
When cryptography fails...




       © All rights reserved. Zend Technologies, Inc.
Use cases



 © All rights reserved. Zend Technologies, Inc.
Use case 1: store a password


●
    Scenario:
       ▶   Web applications with a protect area
       ▶   Username and password to login
●
    Problem:
       ▶   How to safely store a password?




                    © All rights reserved. Zend Technologies, Inc.
Hash a password

●
    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)




                           © All rights reserved. Zend Technologies, Inc.
bcrypt

●
    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




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

●
     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)




                        © All rights reserved. Zend Technologies, Inc.
bcrypt workload benchmark

                                           $workload                        time in sec
                                                   10                           0.1
                                                    11                          0.2
                                                   12                           0.4
                                                   13                           0.7
                                                   14                           1.5
Suggestion:
                                                   15                           3
Spend > 1 sec
                                                   16                           6
                                                   17                           12
                                                   18                          24.3
                                                   19                          48.7
 OS: Linux kernel 2.6.38
CPU: Intel Core2, 2.1Ghz                           20                          97.3
 RAM: 2 GB - PHP: 5.3.6                            21                         194.3

                           © All rights reserved. Zend Technologies, Inc.
bcrypt output

 ●
      Example of bcrypt's output:

$2a$14$c2Rmc2Fka2hmamhzYWRmauBpwLLDFKNPTfmCeuMHV
nMVaLatNlFZO


  ●
      $2a$14$, bcrypt with workload 14
  ●
      c2Rmc2Fka2hmamhzYWRmau is the salt
  ●   BpwLLDFKNPTfmCeuMHVnMVaLatNlFZO, is the hash
      output (60 btyes)


                     © All rights reserved. Zend Technologies, Inc.
bcrypt authentication

●
    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!';
}}




                   © All rights reserved. Zend Technologies, Inc.
Use case 2: generate random data in PHP


●
    Scenario:
       ▶   Generate random passwords for
                ● Login systems
                ●
                  API systems
●
    Problem:
       ▶   How to generate random data in PHP?




                     © All rights reserved. Zend Technologies, Inc.
Random number generators




      © All rights reserved. Zend Technologies, Inc.
PHP vs. randomness

●   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()
       ▶




                       © All rights reserved. Zend Technologies, Inc.
rand() is real random?

Pseudo-random bits                                       rand() in PHP on Windows




                                                            From random.org website

                     © All rights reserved. Zend Technologies, Inc.
Use case 3: encrypt data

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




                     © All rights reserved. Zend Technologies, Inc.
Symmetric encryption

●   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 the $mode and $iv parameters?




                       © All rights reserved. Zend Technologies, Inc.
Encryption mode

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




                      © All rights reserved. Zend Technologies, Inc.
CBC
              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.
IV

●
    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




                       © All rights reserved. Zend Technologies, Inc.
Encryption is not enough

●   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)



                       © All rights reserved. Zend Technologies, Inc.
HMAC

●
    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




                      © All rights reserved. Zend Technologies, Inc.
Encryption + authentication

●
    Three possible ways:
       ▶   Encrypt-then-authenticate
       ▶   Authenticate-then-encrypt
       ▶   Encrypt-and-authenticate
●   We use encrypt-then-authenticate, as
    suggested by Schneier in [1]




                     © All rights reserved. Zend Technologies, Inc.
Demo: encrypt session data

●   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




                      © All rights reserved. Zend Technologies, Inc.
Conclusion (1)

●
    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)




                      © All rights reserved. Zend Technologies, Inc.
Conclusion (2)

●
    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




                     © All rights reserved. Zend Technologies, Inc.
References

(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



                          © All rights reserved. Zend Technologies, Inc.
Thank you!

●
    Comments and feedbacks:
      ▶   enrico@zend.com




                    © All rights reserved. Zend Technologies, Inc.

Mais conteúdo relacionado

Mais procurados

Wtf is happening_inside_my_android_phone_public
Wtf is happening_inside_my_android_phone_publicWtf is happening_inside_my_android_phone_public
Wtf is happening_inside_my_android_phone_public
Jaime Blasco
 
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
Area41
 
Java Symmetric
Java SymmetricJava Symmetric
Java Symmetric
phanleson
 

Mais procurados (20)

Wtf is happening_inside_my_android_phone_public
Wtf is happening_inside_my_android_phone_publicWtf is happening_inside_my_android_phone_public
Wtf is happening_inside_my_android_phone_public
 
introduction to jsrsasign
introduction to jsrsasignintroduction to jsrsasign
introduction to jsrsasign
 
Testing NodeJS Security
Testing NodeJS SecurityTesting NodeJS Security
Testing NodeJS Security
 
Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)
 
Hacking NodeJS applications for fun and profit
Hacking NodeJS applications for fun and profitHacking NodeJS applications for fun and profit
Hacking NodeJS applications for fun and profit
 
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
 
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
 
XSS Countermeasures in Grails
XSS Countermeasures in GrailsXSS Countermeasures in Grails
XSS Countermeasures in Grails
 
mimikatz @ rmll
mimikatz @ rmllmimikatz @ rmll
mimikatz @ rmll
 
Угадываем пароль за минуту
Угадываем пароль за минутуУгадываем пароль за минуту
Угадываем пароль за минуту
 
Root via sms. 4G security assessment
Root via sms. 4G security assessment Root via sms. 4G security assessment
Root via sms. 4G security assessment
 
Securing your MySQL server
Securing your MySQL serverSecuring your MySQL server
Securing your MySQL server
 
Securing TodoMVC Using the Web Cryptography API
Securing TodoMVC Using the Web Cryptography APISecuring TodoMVC Using the Web Cryptography API
Securing TodoMVC Using the Web Cryptography API
 
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
 
Grails vs XSS: Defending Grails against XSS attacks
Grails vs XSS: Defending Grails against XSS attacksGrails vs XSS: Defending Grails against XSS attacks
Grails vs XSS: Defending Grails against XSS attacks
 
BalCCon2k18 - Towards the perfect cryptocurrency wallet
BalCCon2k18 - Towards the perfect cryptocurrency walletBalCCon2k18 - Towards the perfect cryptocurrency wallet
BalCCon2k18 - Towards the perfect cryptocurrency wallet
 
Java Symmetric
Java SymmetricJava Symmetric
Java Symmetric
 
Developer's Guide to JavaScript and Web Cryptography
Developer's Guide to JavaScript and Web CryptographyDeveloper's Guide to JavaScript and Web Cryptography
Developer's Guide to JavaScript and Web Cryptography
 
OWASP Much ado about randomness
OWASP Much ado about randomnessOWASP Much ado about randomness
OWASP Much ado about randomness
 
Passwords#14 - mimikatz
Passwords#14 - mimikatzPasswords#14 - mimikatz
Passwords#14 - mimikatz
 

Destaque

Owasp top 10
Owasp top 10Owasp top 10
Owasp top 10
markstory
 

Destaque (8)

Deploying PHP apps on the cloud
Deploying PHP apps on the cloudDeploying PHP apps on the cloud
Deploying PHP apps on the cloud
 
Data is dead. Long live data!
Data is dead. Long live data! Data is dead. Long live data!
Data is dead. Long live data!
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
Owasp top 10
Owasp top 10Owasp top 10
Owasp top 10
 
Optimizing performance
Optimizing performanceOptimizing performance
Optimizing performance
 
Resolving problems & high availability
Resolving problems & high availabilityResolving problems & high availability
Resolving problems & high availability
 
Unit testing for project managers
Unit testing for project managersUnit testing for project managers
Unit testing for project managers
 
5 Cryptography Part1
5 Cryptography Part15 Cryptography Part1
5 Cryptography Part1
 

Semelhante a Cryptography in PHP: Some Use Cases

Course_Presentation cyber --------------.pptx
Course_Presentation cyber --------------.pptxCourse_Presentation cyber --------------.pptx
Course_Presentation cyber --------------.pptx
ssuser020436
 
Php Inside - confoo 2011 - Derick Rethans
Php Inside -  confoo 2011 - Derick RethansPhp Inside -  confoo 2011 - Derick Rethans
Php Inside - confoo 2011 - Derick Rethans
Bachkoutou Toutou
 

Semelhante a Cryptography in PHP: Some Use Cases (20)

Strong cryptography in PHP
Strong cryptography in PHPStrong cryptography in PHP
Strong cryptography in PHP
 
Cryptography in PHP: use cases
Cryptography in PHP: use casesCryptography in PHP: use cases
Cryptography in PHP: use cases
 
Cryptography with Zend Framework
Cryptography with Zend FrameworkCryptography with Zend Framework
Cryptography with Zend Framework
 
Как мы сделали PHP 7 в два раза быстрее PHP 5 / Дмитрий Стогов (Zend Technolo...
Как мы сделали PHP 7 в два раза быстрее PHP 5 / Дмитрий Стогов (Zend Technolo...Как мы сделали PHP 7 в два раза быстрее PHP 5 / Дмитрий Стогов (Zend Technolo...
Как мы сделали PHP 7 в два раза быстрее PHP 5 / Дмитрий Стогов (Zend Technolo...
 
How to scale PHP applications
How to scale PHP applicationsHow to scale PHP applications
How to scale PHP applications
 
How to Manage Cloud Infrastructures using Zend Framework
How to Manage Cloud Infrastructures using Zend FrameworkHow to Manage Cloud Infrastructures using Zend Framework
How to Manage Cloud Infrastructures using Zend Framework
 
Turbocharging php applications with zend server (workshop)
Turbocharging php applications with zend server (workshop)Turbocharging php applications with zend server (workshop)
Turbocharging php applications with zend server (workshop)
 
Quick start on Zend Framework 2
Quick start on Zend Framework 2Quick start on Zend Framework 2
Quick start on Zend Framework 2
 
Course_Presentation cyber --------------.pptx
Course_Presentation cyber --------------.pptxCourse_Presentation cyber --------------.pptx
Course_Presentation cyber --------------.pptx
 
Turbocharging php applications with zend server
Turbocharging php applications with zend serverTurbocharging php applications with zend server
Turbocharging php applications with zend server
 
PBKDF2: Storing Sensitive Data Securely in Android Applications
PBKDF2: Storing Sensitive Data Securely in Android ApplicationsPBKDF2: Storing Sensitive Data Securely in Android Applications
PBKDF2: Storing Sensitive Data Securely in Android Applications
 
Php Inside - confoo 2011 - Derick Rethans
Php Inside -  confoo 2011 - Derick RethansPhp Inside -  confoo 2011 - Derick Rethans
Php Inside - confoo 2011 - Derick Rethans
 
Vulnerabilities of machine learning infrastructure
Vulnerabilities of machine learning infrastructureVulnerabilities of machine learning infrastructure
Vulnerabilities of machine learning infrastructure
 
Costruire un sito e-commerce in alta affidabilità con Magento e Zend Server C...
Costruire un sito e-commerce in alta affidabilità con Magento e Zend Server C...Costruire un sito e-commerce in alta affidabilità con Magento e Zend Server C...
Costruire un sito e-commerce in alta affidabilità con Magento e Zend Server C...
 
Debugging PHP with xDebug inside of Eclipse PDT 2.1
Debugging PHP with xDebug inside of Eclipse PDT 2.1Debugging PHP with xDebug inside of Eclipse PDT 2.1
Debugging PHP with xDebug inside of Eclipse PDT 2.1
 
Engineering an Encrypted Storage Engine
Engineering an Encrypted Storage EngineEngineering an Encrypted Storage Engine
Engineering an Encrypted Storage Engine
 
Sơ lược kiến trúc hệ thống Zing Me
Sơ lược kiến trúc hệ thống Zing MeSơ lược kiến trúc hệ thống Zing Me
Sơ lược kiến trúc hệ thống Zing Me
 
A Gentle Introduction to GPU Computing by Armen Donigian
A Gentle Introduction to GPU Computing by Armen DonigianA Gentle Introduction to GPU Computing by Armen Donigian
A Gentle Introduction to GPU Computing by Armen Donigian
 
Securing your Cloud Environment v2
Securing your Cloud Environment v2Securing your Cloud Environment v2
Securing your Cloud Environment v2
 
Project Casquatch: An Open Source Java Abstraction Framework for Cassandra Da...
Project Casquatch: An Open Source Java Abstraction Framework for Cassandra Da...Project Casquatch: An Open Source Java Abstraction Framework for Cassandra Da...
Project Casquatch: An Open Source Java Abstraction Framework for Cassandra Da...
 

Mais de Zend by Rogue Wave Software

Mais de Zend by Rogue Wave Software (20)

Develop microservices in php
Develop microservices in phpDevelop microservices in php
Develop microservices in php
 
Speed and security for your PHP application
Speed and security for your PHP applicationSpeed and security for your PHP application
Speed and security for your PHP application
 
Building and managing applications fast for IBM i
Building and managing applications fast for IBM iBuilding and managing applications fast for IBM i
Building and managing applications fast for IBM i
 
Building web APIs in PHP with Zend Expressive
Building web APIs in PHP with Zend ExpressiveBuilding web APIs in PHP with Zend Expressive
Building web APIs in PHP with Zend Expressive
 
To PHP 7 and beyond
To PHP 7 and beyondTo PHP 7 and beyond
To PHP 7 and beyond
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
 
The Sodium crypto library of PHP 7.2 (PHP Day 2018)
The Sodium crypto library of PHP 7.2 (PHP Day 2018)The Sodium crypto library of PHP 7.2 (PHP Day 2018)
The Sodium crypto library of PHP 7.2 (PHP Day 2018)
 
Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)
 
Middleware web APIs in PHP 7.x
Middleware web APIs in PHP 7.xMiddleware web APIs in PHP 7.x
Middleware web APIs in PHP 7.x
 
Ongoing management of your PHP 7 application
Ongoing management of your PHP 7 applicationOngoing management of your PHP 7 application
Ongoing management of your PHP 7 application
 
Developing web APIs using middleware in PHP 7
Developing web APIs using middleware in PHP 7Developing web APIs using middleware in PHP 7
Developing web APIs using middleware in PHP 7
 
The Docker development template for PHP
The Docker development template for PHPThe Docker development template for PHP
The Docker development template for PHP
 
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
 
Developing apps faster
Developing apps fasterDeveloping apps faster
Developing apps faster
 
Keeping up with PHP
Keeping up with PHPKeeping up with PHP
Keeping up with PHP
 
Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i  Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i
 
Getting started with PHP on IBM i
Getting started with PHP on IBM iGetting started with PHP on IBM i
Getting started with PHP on IBM i
 
Continuous Delivery e-book
Continuous Delivery e-bookContinuous Delivery e-book
Continuous Delivery e-book
 
Standard CMS on standard PHP Stack - Drupal and Zend Server
Standard CMS on standard PHP Stack - Drupal and Zend ServerStandard CMS on standard PHP Stack - Drupal and Zend Server
Standard CMS on standard PHP Stack - Drupal and Zend Server
 
Dev & Prod - PHP Applications in the Cloud
Dev & Prod - PHP Applications in the CloudDev & Prod - PHP Applications in the Cloud
Dev & Prod - PHP Applications in the Cloud
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Cryptography in PHP: Some Use Cases

  • 1. Cryptography in PHP: some use cases by Enrico Zimuel (enrico@zend.com) Senior Software Engineer Zend Framework Core Team Zend Technologies Ltd PHPTour Lille 2011 – 25 November http://afup.org/pages/phptourlille2011/ © All rights reserved. Zend Technologies, Inc.
  • 2. About me • Software Engineer since 1996 – Assembly x86, C/C++, Java, Perl, PHP • Enjoying PHP since 1999 • PHP Engineer at Zend since 2008 • ZF Core Team from April 2011 • Author of two italian books about Email: enrico@zend.com Twitter: @ezimuel applied cryptography • B.Sc. Computer Science and Economics from University of Pescara (Italy) © All rights reserved. Zend Technologies, Inc.
  • 3. Summary ● Cryptography in PHP ● Some use cases: ▶ Safe way to store passwords ▶ Generate pseudo-random numbers ▶ Encrypt/decrypt sensitive data ● Demo: encrypt PHP session data © All rights reserved. Zend Technologies, Inc.
  • 4. Cryptography in PHP ● crypt() ● Mcrypt ● Hash ● OpenSSL © All rights reserved. Zend Technologies, Inc.
  • 5. 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 ● Note: don't use PHP 5.3.7 (bug #55439) © All rights reserved. Zend Technologies, Inc.
  • 6. Mcrypt extension ● 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 © All rights reserved. Zend Technologies, Inc.
  • 7. Hash extension ● 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 © All rights reserved. Zend Technologies, Inc.
  • 8. OpenSSL extension ● 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) © All rights reserved. Zend Technologies, Inc.
  • 9. Which algorithm to use? ● Some suggestions: ▶ Symmetric encryption: Blowfish / Twofish ● ● Rijndael (AES, FIST 197 standard since 2001) ▶ Hash: SHA-256, 384, 512 ▶ Public key: RSA © All rights reserved. Zend Technologies, Inc.
  • 10. Cryptography vs. Security ● 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” © All rights reserved. Zend Technologies, Inc.
  • 11. When cryptography fails... © All rights reserved. Zend Technologies, Inc.
  • 12. Use cases © All rights reserved. Zend Technologies, Inc.
  • 13. Use case 1: store a password ● Scenario: ▶ Web applications with a protect area ▶ Username and password to login ● Problem: ▶ How to safely store a password? © All rights reserved. Zend Technologies, Inc.
  • 14. Hash a password ● 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) © All rights reserved. Zend Technologies, Inc.
  • 15. bcrypt ● 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 © All rights reserved. Zend Technologies, Inc.
  • 16. bcrypt in PHP ● 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) © All rights reserved. Zend Technologies, Inc.
  • 17. bcrypt workload benchmark $workload time in sec 10 0.1 11 0.2 12 0.4 13 0.7 14 1.5 Suggestion: 15 3 Spend > 1 sec 16 6 17 12 18 24.3 19 48.7 OS: Linux kernel 2.6.38 CPU: Intel Core2, 2.1Ghz 20 97.3 RAM: 2 GB - PHP: 5.3.6 21 194.3 © All rights reserved. Zend Technologies, Inc.
  • 18. bcrypt output ● Example of bcrypt's output: $2a$14$c2Rmc2Fka2hmamhzYWRmauBpwLLDFKNPTfmCeuMHV nMVaLatNlFZO ● $2a$14$, bcrypt with workload 14 ● c2Rmc2Fka2hmamhzYWRmau is the salt ● BpwLLDFKNPTfmCeuMHVnMVaLatNlFZO, is the hash output (60 btyes) © All rights reserved. Zend Technologies, Inc.
  • 19. bcrypt authentication ● 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!'; }} © All rights reserved. Zend Technologies, Inc.
  • 20. Use case 2: generate random data in PHP ● Scenario: ▶ Generate random passwords for ● Login systems ● API systems ● Problem: ▶ How to generate random data in PHP? © All rights reserved. Zend Technologies, Inc.
  • 21. Random number generators © All rights reserved. Zend Technologies, Inc.
  • 22. PHP vs. randomness ● 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() ▶ © All rights reserved. Zend Technologies, Inc.
  • 23. rand() is real random? Pseudo-random bits rand() in PHP on Windows From random.org website © All rights reserved. Zend Technologies, Inc.
  • 24. Use case 3: encrypt data ● Scenario: ▶ We want to store some sensitive data (e.g. credit card numbers) ● Problem: ▶ How to encrypt this data in PHP? © All rights reserved. Zend Technologies, Inc.
  • 25. Symmetric encryption ● 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 the $mode and $iv parameters? © All rights reserved. Zend Technologies, Inc.
  • 26. Encryption mode ● Symmetric encryption mode: ▶ ECB, CBC, CFB, OFB, NOFB or STREAM ● We are going to use the CBC that is the most used and secure (as suggested by Schneier in [1]) ● Cipher-Block Chaining (CBC) mode of operation was invented in 1976 by IBM © All rights reserved. Zend Technologies, Inc.
  • 27. CBC 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.
  • 28. IV ● 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 © All rights reserved. Zend Technologies, Inc.
  • 29. Encryption is not enough ● 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) © All rights reserved. Zend Technologies, Inc.
  • 30. HMAC ● 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 © All rights reserved. Zend Technologies, Inc.
  • 31. Encryption + authentication ● Three possible ways: ▶ Encrypt-then-authenticate ▶ Authenticate-then-encrypt ▶ Encrypt-and-authenticate ● We use encrypt-then-authenticate, as suggested by Schneier in [1] © All rights reserved. Zend Technologies, Inc.
  • 32. Demo: encrypt session data ● 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 © All rights reserved. Zend Technologies, Inc.
  • 33. Conclusion (1) ● 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) © All rights reserved. Zend Technologies, Inc.
  • 34. Conclusion (2) ● 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 © All rights reserved. Zend Technologies, Inc.
  • 35. References (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 © All rights reserved. Zend Technologies, Inc.
  • 36. Thank you! ● Comments and feedbacks: ▶ enrico@zend.com © All rights reserved. Zend Technologies, Inc.