SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PPTX
Generative AI, WiDS 2023.pptx
Colleen Farrelly
 
PDF
Microservices and SOA
Capgemini
 
PDF
Introduction to ChatGPT & how its implemented in UiPath
sharonP24
 
PPTX
What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...
Simplilearn
 
PDF
Use Case Patterns for LLM Applications (1).pdf
M Waleed Kadous
 
ODP
Big Data Testing Strategies
Knoldus Inc.
 
PDF
Let's talk about GPT: A crash course in Generative AI for researchers
Steven Van Vaerenbergh
 
PDF
Running Apache NiFi with Apache Spark : Integration Options
Timothy Spann
 
PPTX
Introduction to Apache Kafka
AIMDek Technologies
 
PDF
How to migrate an application in IBM APIc, and preserve its client credential
Shiu-Fun Poon
 
PDF
Pig Tutorial | Twitter Case Study | Apache Pig Script and Commands | Edureka
Edureka!
 
PDF
Intelligent Auto-scaling of Kafka Consumers with Workload Prediction | Ming S...
HostedbyConfluent
 
PPTX
Introduction to Hadoop and Hadoop component
rebeccatho
 
PPTX
Using AI for Learning.pptx
GDSCUOWMKDUPG
 
PDF
Generative AI For Everyone on AWS.pdf
Manjunatha Sai
 
PPTX
Introduction to Hadoop
Dr. C.V. Suresh Babu
 
PDF
Six Signs You Need Platform Engineering
Weaveworks
 
PDF
Share point 2019 installation guide
Rudresh Tiwari
 
PPTX
Introduction to Microservices
MahmoudZidan41
 
PDF
Apache Hadoop and HBase
Cloudera, Inc.
 
Generative AI, WiDS 2023.pptx
Colleen Farrelly
 
Microservices and SOA
Capgemini
 
Introduction to ChatGPT & how its implemented in UiPath
sharonP24
 
What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...
Simplilearn
 
Use Case Patterns for LLM Applications (1).pdf
M Waleed Kadous
 
Big Data Testing Strategies
Knoldus Inc.
 
Let's talk about GPT: A crash course in Generative AI for researchers
Steven Van Vaerenbergh
 
Running Apache NiFi with Apache Spark : Integration Options
Timothy Spann
 
Introduction to Apache Kafka
AIMDek Technologies
 
How to migrate an application in IBM APIc, and preserve its client credential
Shiu-Fun Poon
 
Pig Tutorial | Twitter Case Study | Apache Pig Script and Commands | Edureka
Edureka!
 
Intelligent Auto-scaling of Kafka Consumers with Workload Prediction | Ming S...
HostedbyConfluent
 
Introduction to Hadoop and Hadoop component
rebeccatho
 
Using AI for Learning.pptx
GDSCUOWMKDUPG
 
Generative AI For Everyone on AWS.pdf
Manjunatha Sai
 
Introduction to Hadoop
Dr. C.V. Suresh Babu
 
Six Signs You Need Platform Engineering
Weaveworks
 
Share point 2019 installation guide
Rudresh Tiwari
 
Introduction to Microservices
MahmoudZidan41
 
Apache Hadoop and HBase
Cloudera, Inc.
 

Similar to Cryptography in PHP: use cases (20)

PDF
Cryptography in PHP: Some Use Cases
Zend by Rogue Wave Software
 
PPTX
Crypto & Crpyocurrencies Intro
Tal Shmueli
 
PDF
Password (in)security
Enrico Zimuel
 
PDF
Strong cryptography in PHP
Enrico Zimuel
 
PDF
Redis for duplicate detection on real time stream
Roberto Franchini
 
PDF
Redis - for duplicate detection on real time stream
Codemotion
 
ODP
All Your Password Are Belong To Us
Charles Southerland
 
PDF
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
Dataconomy Media
 
PDF
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
Alessandro Molina
 
PDF
Module: drand - the Distributed Randomness Beacon
Ioannis Psaras
 
PDF
Cryptography with Zend Framework
Enrico Zimuel
 
PDF
Netflix Open Source Meetup Season 4 Episode 2
aspyker
 
PPTX
Advanced SOHO Router Exploitation XCON
Lyon Yang
 
PDF
NSC #2 - Challenge Solution
NoSuchCon
 
PPTX
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
Alexandre Moneger
 
PDF
inside-linux-kernel-rng-presentation-sept-13-2022.pdf
xiso
 
PDF
Cryptography Attacks and Applications
UTD Computer Security Group
 
PDF
"Developing a multicurrency, multisignature wallet" by Alex Melville
ICOVO
 
PDF
Advances in Open Source Password Cracking
n|u - The Open Security Community
 
PDF
Deploying PHP on PaaS: Why and How?
Docker, Inc.
 
Cryptography in PHP: Some Use Cases
Zend by Rogue Wave Software
 
Crypto & Crpyocurrencies Intro
Tal Shmueli
 
Password (in)security
Enrico Zimuel
 
Strong cryptography in PHP
Enrico Zimuel
 
Redis for duplicate detection on real time stream
Roberto Franchini
 
Redis - for duplicate detection on real time stream
Codemotion
 
All Your Password Are Belong To Us
Charles Southerland
 
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
Dataconomy Media
 
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
Alessandro Molina
 
Module: drand - the Distributed Randomness Beacon
Ioannis Psaras
 
Cryptography with Zend Framework
Enrico Zimuel
 
Netflix Open Source Meetup Season 4 Episode 2
aspyker
 
Advanced SOHO Router Exploitation XCON
Lyon Yang
 
NSC #2 - Challenge Solution
NoSuchCon
 
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
Alexandre Moneger
 
inside-linux-kernel-rng-presentation-sept-13-2022.pdf
xiso
 
Cryptography Attacks and Applications
UTD Computer Security Group
 
"Developing a multicurrency, multisignature wallet" by Alex Melville
ICOVO
 
Advances in Open Source Password Cracking
n|u - The Open Security Community
 
Deploying PHP on PaaS: Why and How?
Docker, Inc.
 
Ad

More from Enrico Zimuel (20)

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

Recently uploaded (20)

PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 

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: [email protected] 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: ● [email protected]