SlideShare a Scribd company logo
1 of 54
Download to read offline
Cryptography
       In PHP
For The Average Developer
Cryptography
● Keeping Data Secure
  ○ Safe From Viewing
  ○ Safe From Tampering
  ○ Safe From Forgery
● Not A Silver Bullet
  ○ XSS
  ○ SQLI
  ○ Social Engineering
● Very Hard To Do
  ○ Any bug will cause problems
The First Rule
of Cryptography
Don't Do It!
Leave It
  For
Experts
Random!
The Foundation of Cryptography

● Classified Under Three Types:
  ○ Weak
    ■ For non-cryptographic usages
  ○ Strong
    ■ For cryptographic usages where security does
       not depend on the strength of randomness
  ○ Cryptographically Secure
    ■ For cryptographic usage when security does
       depend on the strength of randomness
Vulnerabilities of
           Randomness
● Bias
  ○ Certain values tend to occur more often making it
    easier to predict future numbers
● Predictability
  ○ Knowing past numbers helps predict future
    numbers
● Poisoning
  ○ Ability to alter future random number generation
Weak Random in PHP
Not to be used for cryptographic usages!!!

●   rand()
●   mt_rand()
●   uniqid()
●   lcg_value()
Strong Random in PHP
●   mcrypt_create_iv()
    ○ MCRYPT_DEV_URANDOM

● openssl_random_pseudo_bytes()


●   /dev/urandom
    ○ For *nix systems only
Cryptographically Secure
●   mcrypt_create_iv()
    ○ MCRYPT_DEV_RANDOM

● openssl_random_pseudo_bytes()
  ○ Maybe

●   /dev/random
    ○ For *nix systems only
NEVER
 Use Weak
For Security
NEVER
 Use CS
When Not
 Needed
If In Doubt
 Use Strong
Randomness
Encryption vs Hashing
● Encryption
  ○ Encoding
  ○ 2 Way / Reversible
  ○ Putting a lock on a box
● Hashing
  ○ Signing
  ○ 1 Way / Non-Reversible
  ○ Taking a person's finger-print
Encryption
Seriously,
Don't Do It!
Terms
● Key
  ○ Secure string of data


● Plain-Text
  ○ The text you want to keep secret


● Cipher-Text
  ○ The encrypted output
Two Basic Types
● Symmetric Encryption
  ○ Like a Pad-Lock with a shared key
  ○ The only secret is the key
  ○ Both sides must have the same key
● Asymmetric Encryption
  ○ Like a pair of Pad-Locks
    ■ The "lock" is the public key
  ○ The only secret is the private key
  ○ Both sides have their own key
Symmetric Encryption 101
● Number:
  01

Scratch That

● Numbers:
  01 04 01 54 95 42 64 12
Symmetric Encryption 101
 Let's Add A "Secret" Number!


01 04 01 54 95 42 64 12

+10

11 14 11 64 05 52 74 22
Secret Numbers
● We just invented the Caesar Cipher
  ○ Commonly known as "ROT13"


● But There Are Problems:
  ○ Vulnerable To Statistical Attacks
  ○ Vulnerable To Brute Forcing
    ■ Only 100 possible secret numbers!
Symmetric Encryption 101
 I Know: Let's Add A Different Number!


01 04 01 54 95 42 64 12

+10 43 21 95 42 67 31 83

11 47 22 49 37 09 95 95
How It Works
We can generate the pads in two ways
● Randomly
  ○ If we only use once, perfect security
    ■ Known as a one-time-pad
  ○ If we use multiple times, same as caesar
    cipher
● With A Function
  ○ Give one or two inputs
    ■ A key, and an "input"
  ○ Generates a "stream" of pseudo random
    numbers
Ciphers
● Take 2 inputs
  ○ A secret key
  ○ An "input"


● Produces Pseudo-Random Output
  ○ Looks random (statistically)
  ○ Is deterministic
     ■ Reproducible given same inputs
Modes
● Multiple ways to use the keystream


● Each way is known as a "Mode"


● Some are secure
  ○ Others are not
ECB
Electronic Code Book

● Uses plain-text as "input"


● Uses output as cipher-text


●   VERY BROKEN!!!
ECB
CBC
Cipher Block Chaining
● Uses an "Initialization Vector"
  ○   Helps "randomize" the plain-text
  ○   Ensures no non-unique blocks
  ○   Does NOT need to be secret
● Chains each block together
  ○ Propagating the generated "randomness"
● Plain-Text Must Be Padded
  ○ To a multiple of block-size
● Secure!
CBC
CFB
Cipher FeedBack
● Uses an "Initialization Vector"

● Plain-Text never enters cipher
  ○ Does not need to be padded


● "Decrypt" Is Never Used

● Secure!
CFB
Ciphers
● AES 128 & 256
  ○ Standard
     ■ NIST Approved
  ○ Also Known As RIJNDAEL-128
     ■ 128 here refers to "block size"
  ○ Very Strong
  ○ Note, the number after AES is *key size*
● Blowfish
● TwoFish
● Serpent
Authentication
How do you know it wasn't tampered
with / came from your friend?
● HMAC
  ○   Hash-based Message Authentication Code
● USE A SEPARATE KEY!
● Encrypt-Then-MAC
  ○ Always MAC after encryption
All Together
    Now!
Encrypt
$key = 'xxxxxxxxxxxxxxxx';
$authKey = 'XXXXXXXXXXXXXX';
$plain = 'This is plain text that I am going to encrypt';


$size = mcrypt_get_iv_size(
     MCRYPT_RIJNDAEL_128,
     MCRYPT_MODE_CFB
);


$iv = mcrypt_create_iv(
     $size,
     MCRYPT_DEV_URANDOM
);
$cipherText = mcrypt_encrypt(
    MCRYPT_RIJNDAEL_128,
     $key,
     $plain,
     MCRYPT_MODE_CFB,
     $iv
);
$auth = hash_hmac('sha512', $cipherText, $authKey, true);
$encrypted = base64_encode($iv . $cipherText . $auth);
Decrypt
$key = 'xxxxxxxxxxxxxxxx';
$authKey = 'XXXXXXXXXXXXXX';


$size = mcrypt_get_iv_size(
     MCRYPT_RIJNDAEL_128,
     MCRYPT_MODE_CFB
);
$encrypted = base64_decode($encrypted);
$iv = substr($encrypted, 0, $size);
$auth = substr($encrypted, -64);
$cipherText = substr($encrypted, $size, -64);
if ($auth != hash_hmac('sha512', $cipherText, $authKey, true)) {
     // Auth Failed!!!
     return false;
}
$plainText = mcrypt_decrypt(
    MCRYPT_RIJNDAEL_128,
     $key,
     $cipherText,
     MCRYPT_MODE_CFB,
     $iv
);
Please Don't Do It!
● Notice How Much Code It Took
  ○ Without error checking
● Notice How Complex It Is
  ○ Without flexibility
● Notice How Easy To Screw Up
  ○ Without Key Storage
● Notice How Many Decisions To Make
If you MUST,
Use a Library
Common Encryption Needs
●   Between Client / Server
    ○ Use SSL
    ○ Really, just use SSL
    ○ I'm not kidding, just use SSL
●   Storage
    ○ Use disk encryption
    ○ Use database encryption
Really,
Don't Do It!
Encryption Resources
● Zend Framework Encryption
  ○ Very good and complete lib
  ○ ZF2
    ■ ZendCryptBlockCipher
● PHP Sec Lib
  ○ phpseclib.sourceforge.net
  ○ Pure PHP
● Not Many Others
  ○ Beware of online tutorials!!!
Password
 Storage
Passwords
  Should Be
 HASHED!
Not Encrypted!
Password Hashes
● Use A Salt
  ○ Defeats Rainbow Tables
  ○ Makes Each Hash a "Proof Of Work"
  ○ Should be random!
    ■ Strong Randomness
● Should Be SLOW!
  ○ Salt is not enough
  ○ Salted SHA256: 11 BILLION per second
  ○ bcrypt: 3200 per second
Good Algorithms

crypt($password, $salt);
pbkdf2($password, $salt, $i);
password_hash(
    $password,
    PASSWORD_BCRYPT
);
$passLib->hash($password);
$phpass->hashPassword($pass);
Cost Parameter
● Target: 0.25 - 0.5 Seconds
  ○ As slow as you can afford

● Depends on hardware
  ○ Test it!

● Good Defaults:
  ○ BCrypt: 10
  ○ PBKDF2: 10,000
Simplified
Password
 Hashing
New API for 5.5
●   string password_hash($pass,         $algo, array $options =
    array() )

    ○   Generates Salt, hashes password
●   bool password_verify($pass, $hash)
    ○   Verifies Hash with Password
●   bool password_needs_rehash($hash,   $algo, array $options = array())

    ○   Determines if the hash is the same as
        specified by algo and options
●   array password_get_info($hash)
     ○ Returns information about the hash
Example
function register($user, $password) {
    $hash = password_hash($password, PASSWORD_BCRYPT);
    $this->store($user, $hash);
}

function login($user, $password) {
    $hash = $this->fetchHash($user);
    if (password_verify($password, $hash)) {
        if (password_needs_rehahs($hash, PASSWORD_BCRYPT)) {
            $hash = password_hash($password, PASSWORD_BCRYPT);
            $this->store($user, $hash);
        }
        $this->startSession();
        return true;
    }
    return false;
}
Hashing Resources
● PHP 5.5 API
  ○ wiki.php.net/rfc/password_hash
● Password Compat
  ○ PHP 5.5 Compatibility
  ○ github/ircmaxell/password_compat
● PasswordLib
  ○ 5.3+, Multiple Algorithms, Portable
  ○ github/ircmaxell/PHP-PasswordLib
● PHPASS
  ○ PHP 4+
  ○ openwall.com/phpass
Seriously,
Hire an Expert!
You Have Been
  Warned
Questions?

 Comments?

Snide Remarks?
Anthony Ferrara
    @ircmaxell
blog.ircmaxell.com
me@ircmaxell.com
   joind.in/7939

More Related Content

What's hot

Encryption Boot Camp on the JVM
Encryption Boot Camp on the JVMEncryption Boot Camp on the JVM
Encryption Boot Camp on the JVMMatthew McCullough
 
Password Security
Password SecurityPassword Security
Password SecurityAlex Hyer
 
Secure password - CYBER SECURITY
Secure password - CYBER SECURITYSecure password - CYBER SECURITY
Secure password - CYBER SECURITYSupanShah2
 
Password Security
Password SecurityPassword Security
Password SecurityCSCJournals
 
DEFCON 23 - Eijah - crypto for hackers
DEFCON 23 - Eijah - crypto for hackersDEFCON 23 - Eijah - crypto for hackers
DEFCON 23 - Eijah - crypto for hackersFelipe Prado
 
Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015Derrick Isaacson
 
Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)Svetlin Nakov
 
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contractsOWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contractsOWASP
 
Hacker News vs. Slashdot—Reputation Systems in Crowdsourced Technology News
Hacker News vs. Slashdot—Reputation Systems in Crowdsourced Technology NewsHacker News vs. Slashdot—Reputation Systems in Crowdsourced Technology News
Hacker News vs. Slashdot—Reputation Systems in Crowdsourced Technology NewsChristoph Matthies
 
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)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)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Svetlin Nakov
 
Securing your Bitcoin wallet
Securing your Bitcoin walletSecuring your Bitcoin wallet
Securing your Bitcoin walletRon Reiter
 
apidays LIVE New York - WT* is JWT? by Maciej Treder
apidays LIVE New York -  WT* is JWT? by Maciej Trederapidays LIVE New York -  WT* is JWT? by Maciej Treder
apidays LIVE New York - WT* is JWT? by Maciej Trederapidays
 
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)
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)Svetlin Nakov
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developersMichel Schudel
 

What's hot (17)

Encryption Boot Camp on the JVM
Encryption Boot Camp on the JVMEncryption Boot Camp on the JVM
Encryption Boot Camp on the JVM
 
Password Security
Password SecurityPassword Security
Password Security
 
Cryptography in PHP: Some Use Cases
Cryptography in PHP: Some Use CasesCryptography in PHP: Some Use Cases
Cryptography in PHP: Some Use Cases
 
Secure password - CYBER SECURITY
Secure password - CYBER SECURITYSecure password - CYBER SECURITY
Secure password - CYBER SECURITY
 
Password Security
Password SecurityPassword Security
Password Security
 
DEFCON 23 - Eijah - crypto for hackers
DEFCON 23 - Eijah - crypto for hackersDEFCON 23 - Eijah - crypto for hackers
DEFCON 23 - Eijah - crypto for hackers
 
Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015
 
Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)
 
Passwords presentation
Passwords presentationPasswords presentation
Passwords presentation
 
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contractsOWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
OWASP Poland Day 2018 - Damian Rusinek - Outsmarting smart contracts
 
Hacker News vs. Slashdot—Reputation Systems in Crowdsourced Technology News
Hacker News vs. Slashdot—Reputation Systems in Crowdsourced Technology NewsHacker News vs. Slashdot—Reputation Systems in Crowdsourced Technology News
Hacker News vs. Slashdot—Reputation Systems in Crowdsourced Technology News
 
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
 
Securing your Bitcoin wallet
Securing your Bitcoin walletSecuring your Bitcoin wallet
Securing your Bitcoin wallet
 
apidays LIVE New York - WT* is JWT? by Maciej Treder
apidays LIVE New York -  WT* is JWT? by Maciej Trederapidays LIVE New York -  WT* is JWT? by Maciej Treder
apidays LIVE New York - WT* is JWT? by Maciej Treder
 
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)
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developers
 

Similar to Cryptography For The Average Developer

Cryptography with Zend Framework
Cryptography with Zend FrameworkCryptography with Zend Framework
Cryptography with Zend FrameworkEnrico Zimuel
 
AES-GCM common pitfalls and how to work around them.pptx
AES-GCM common pitfalls and how to work around them.pptxAES-GCM common pitfalls and how to work around them.pptx
AES-GCM common pitfalls and how to work around them.pptxskantos
 
Password (in)security
Password (in)securityPassword (in)security
Password (in)securityEnrico Zimuel
 
Thwarting The Surveillance in Online Communication by Adhokshaj Mishra
Thwarting The Surveillance in Online Communication by Adhokshaj MishraThwarting The Surveillance in Online Communication by Adhokshaj Mishra
Thwarting The Surveillance in Online Communication by Adhokshaj MishraOWASP Delhi
 
Bitcoin Keys, Addresses & Wallets
Bitcoin Keys, Addresses & WalletsBitcoin Keys, Addresses & Wallets
Bitcoin Keys, Addresses & WalletsChristopher Allen
 
Cool Crypto Concepts CodeOne SFO
Cool Crypto Concepts CodeOne SFOCool Crypto Concepts CodeOne SFO
Cool Crypto Concepts CodeOne SFORoy Wasse
 
ContainerDays Boston 2016: "Hiding in Plain Sight: Managing Secrets in a Cont...
ContainerDays Boston 2016: "Hiding in Plain Sight: Managing Secrets in a Cont...ContainerDays Boston 2016: "Hiding in Plain Sight: Managing Secrets in a Cont...
ContainerDays Boston 2016: "Hiding in Plain Sight: Managing Secrets in a Cont...DynamicInfraDays
 
Encryption Deep Dive
Encryption Deep DiveEncryption Deep Dive
Encryption Deep DiveDiego Pacheco
 
Crypto & Crpyocurrencies Intro
Crypto & Crpyocurrencies IntroCrypto & Crpyocurrencies Intro
Crypto & Crpyocurrencies IntroTal Shmueli
 
Using Cryptography Properly in Applications
Using Cryptography Properly in ApplicationsUsing Cryptography Properly in Applications
Using Cryptography Properly in ApplicationsGreat Wide Open
 
Crypto OpSec - How to Securely Store Bitcoin and Other Crypto Assets
Crypto OpSec - How to Securely Store Bitcoin and Other Crypto AssetsCrypto OpSec - How to Securely Store Bitcoin and Other Crypto Assets
Crypto OpSec - How to Securely Store Bitcoin and Other Crypto AssetsThatCrypto
 
When Crypto Attacks! (Yahoo 2009)
When Crypto Attacks! (Yahoo 2009)When Crypto Attacks! (Yahoo 2009)
When Crypto Attacks! (Yahoo 2009)Nate Lawson
 
Cryptography for developers
Cryptography for developersCryptography for developers
Cryptography for developersKai Koenig
 
Cs166 mynote
Cs166 mynoteCs166 mynote
Cs166 mynoteKaya Ota
 
Data Security Essentials - JavaOne 2013
Data Security Essentials - JavaOne 2013Data Security Essentials - JavaOne 2013
Data Security Essentials - JavaOne 2013javagroup2006
 
All Your Password Are Belong To Us
All Your Password Are Belong To UsAll Your Password Are Belong To Us
All Your Password Are Belong To UsCharles Southerland
 

Similar to Cryptography For The Average Developer (20)

Cryptography 101
Cryptography 101Cryptography 101
Cryptography 101
 
Cryptography with Zend Framework
Cryptography with Zend FrameworkCryptography with Zend Framework
Cryptography with Zend Framework
 
AES-GCM common pitfalls and how to work around them.pptx
AES-GCM common pitfalls and how to work around them.pptxAES-GCM common pitfalls and how to work around them.pptx
AES-GCM common pitfalls and how to work around them.pptx
 
Password (in)security
Password (in)securityPassword (in)security
Password (in)security
 
Thwarting The Surveillance in Online Communication by Adhokshaj Mishra
Thwarting The Surveillance in Online Communication by Adhokshaj MishraThwarting The Surveillance in Online Communication by Adhokshaj Mishra
Thwarting The Surveillance in Online Communication by Adhokshaj Mishra
 
Cryptography 202
Cryptography 202Cryptography 202
Cryptography 202
 
Passwords
PasswordsPasswords
Passwords
 
Bitcoin Keys, Addresses & Wallets
Bitcoin Keys, Addresses & WalletsBitcoin Keys, Addresses & Wallets
Bitcoin Keys, Addresses & Wallets
 
Cool Crypto Concepts CodeOne SFO
Cool Crypto Concepts CodeOne SFOCool Crypto Concepts CodeOne SFO
Cool Crypto Concepts CodeOne SFO
 
ContainerDays Boston 2016: "Hiding in Plain Sight: Managing Secrets in a Cont...
ContainerDays Boston 2016: "Hiding in Plain Sight: Managing Secrets in a Cont...ContainerDays Boston 2016: "Hiding in Plain Sight: Managing Secrets in a Cont...
ContainerDays Boston 2016: "Hiding in Plain Sight: Managing Secrets in a Cont...
 
Encryption Deep Dive
Encryption Deep DiveEncryption Deep Dive
Encryption Deep Dive
 
Crypto & Crpyocurrencies Intro
Crypto & Crpyocurrencies IntroCrypto & Crpyocurrencies Intro
Crypto & Crpyocurrencies Intro
 
Using Cryptography Properly in Applications
Using Cryptography Properly in ApplicationsUsing Cryptography Properly in Applications
Using Cryptography Properly in Applications
 
Passwords
PasswordsPasswords
Passwords
 
Crypto OpSec - How to Securely Store Bitcoin and Other Crypto Assets
Crypto OpSec - How to Securely Store Bitcoin and Other Crypto AssetsCrypto OpSec - How to Securely Store Bitcoin and Other Crypto Assets
Crypto OpSec - How to Securely Store Bitcoin and Other Crypto Assets
 
When Crypto Attacks! (Yahoo 2009)
When Crypto Attacks! (Yahoo 2009)When Crypto Attacks! (Yahoo 2009)
When Crypto Attacks! (Yahoo 2009)
 
Cryptography for developers
Cryptography for developersCryptography for developers
Cryptography for developers
 
Cs166 mynote
Cs166 mynoteCs166 mynote
Cs166 mynote
 
Data Security Essentials - JavaOne 2013
Data Security Essentials - JavaOne 2013Data Security Essentials - JavaOne 2013
Data Security Essentials - JavaOne 2013
 
All Your Password Are Belong To Us
All Your Password Are Belong To UsAll Your Password Are Belong To Us
All Your Password Are Belong To Us
 

More from Anthony Ferrara

Beyond design patterns phpnw14
Beyond design patterns   phpnw14Beyond design patterns   phpnw14
Beyond design patterns phpnw14Anthony Ferrara
 
Don't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo EditionDon't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo EditionAnthony Ferrara
 
Development By The Numbers - ConFoo Edition
Development By The Numbers - ConFoo EditionDevelopment By The Numbers - ConFoo Edition
Development By The Numbers - ConFoo EditionAnthony Ferrara
 
Don't Be STUPID, Grasp SOLID - DrupalCon Prague
Don't Be STUPID, Grasp SOLID - DrupalCon PragueDon't Be STUPID, Grasp SOLID - DrupalCon Prague
Don't Be STUPID, Grasp SOLID - DrupalCon PragueAnthony Ferrara
 
Don't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHPDon't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHPAnthony Ferrara
 
PHP, Under The Hood - DPC
PHP, Under The Hood - DPCPHP, Under The Hood - DPC
PHP, Under The Hood - DPCAnthony Ferrara
 
Development by the numbers
Development by the numbersDevelopment by the numbers
Development by the numbersAnthony Ferrara
 
Don't Be Stupid, Grasp Solid - MidWestPHP
Don't Be Stupid, Grasp Solid - MidWestPHPDon't Be Stupid, Grasp Solid - MidWestPHP
Don't Be Stupid, Grasp Solid - MidWestPHPAnthony Ferrara
 
Password Storage and Attacking in PHP
Password Storage and Attacking in PHPPassword Storage and Attacking in PHP
Password Storage and Attacking in PHPAnthony Ferrara
 

More from Anthony Ferrara (9)

Beyond design patterns phpnw14
Beyond design patterns   phpnw14Beyond design patterns   phpnw14
Beyond design patterns phpnw14
 
Don't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo EditionDon't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo Edition
 
Development By The Numbers - ConFoo Edition
Development By The Numbers - ConFoo EditionDevelopment By The Numbers - ConFoo Edition
Development By The Numbers - ConFoo Edition
 
Don't Be STUPID, Grasp SOLID - DrupalCon Prague
Don't Be STUPID, Grasp SOLID - DrupalCon PragueDon't Be STUPID, Grasp SOLID - DrupalCon Prague
Don't Be STUPID, Grasp SOLID - DrupalCon Prague
 
Don't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHPDon't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHP
 
PHP, Under The Hood - DPC
PHP, Under The Hood - DPCPHP, Under The Hood - DPC
PHP, Under The Hood - DPC
 
Development by the numbers
Development by the numbersDevelopment by the numbers
Development by the numbers
 
Don't Be Stupid, Grasp Solid - MidWestPHP
Don't Be Stupid, Grasp Solid - MidWestPHPDon't Be Stupid, Grasp Solid - MidWestPHP
Don't Be Stupid, Grasp Solid - MidWestPHP
 
Password Storage and Attacking in PHP
Password Storage and Attacking in PHPPassword Storage and Attacking in PHP
Password Storage and Attacking in PHP
 

Recently uploaded

Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 

Recently uploaded (20)

Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 

Cryptography For The Average Developer

  • 1. Cryptography In PHP For The Average Developer
  • 2. Cryptography ● Keeping Data Secure ○ Safe From Viewing ○ Safe From Tampering ○ Safe From Forgery ● Not A Silver Bullet ○ XSS ○ SQLI ○ Social Engineering ● Very Hard To Do ○ Any bug will cause problems
  • 3. The First Rule of Cryptography
  • 5. Leave It For Experts
  • 6. Random! The Foundation of Cryptography ● Classified Under Three Types: ○ Weak ■ For non-cryptographic usages ○ Strong ■ For cryptographic usages where security does not depend on the strength of randomness ○ Cryptographically Secure ■ For cryptographic usage when security does depend on the strength of randomness
  • 7. Vulnerabilities of Randomness ● Bias ○ Certain values tend to occur more often making it easier to predict future numbers ● Predictability ○ Knowing past numbers helps predict future numbers ● Poisoning ○ Ability to alter future random number generation
  • 8. Weak Random in PHP Not to be used for cryptographic usages!!! ● rand() ● mt_rand() ● uniqid() ● lcg_value()
  • 9. Strong Random in PHP ● mcrypt_create_iv() ○ MCRYPT_DEV_URANDOM ● openssl_random_pseudo_bytes() ● /dev/urandom ○ For *nix systems only
  • 10. Cryptographically Secure ● mcrypt_create_iv() ○ MCRYPT_DEV_RANDOM ● openssl_random_pseudo_bytes() ○ Maybe ● /dev/random ○ For *nix systems only
  • 11. NEVER Use Weak For Security
  • 12. NEVER Use CS When Not Needed
  • 13. If In Doubt Use Strong Randomness
  • 14. Encryption vs Hashing ● Encryption ○ Encoding ○ 2 Way / Reversible ○ Putting a lock on a box ● Hashing ○ Signing ○ 1 Way / Non-Reversible ○ Taking a person's finger-print
  • 17. Terms ● Key ○ Secure string of data ● Plain-Text ○ The text you want to keep secret ● Cipher-Text ○ The encrypted output
  • 18. Two Basic Types ● Symmetric Encryption ○ Like a Pad-Lock with a shared key ○ The only secret is the key ○ Both sides must have the same key ● Asymmetric Encryption ○ Like a pair of Pad-Locks ■ The "lock" is the public key ○ The only secret is the private key ○ Both sides have their own key
  • 19. Symmetric Encryption 101 ● Number: 01 Scratch That ● Numbers: 01 04 01 54 95 42 64 12
  • 20. Symmetric Encryption 101 Let's Add A "Secret" Number! 01 04 01 54 95 42 64 12 +10 11 14 11 64 05 52 74 22
  • 21. Secret Numbers ● We just invented the Caesar Cipher ○ Commonly known as "ROT13" ● But There Are Problems: ○ Vulnerable To Statistical Attacks ○ Vulnerable To Brute Forcing ■ Only 100 possible secret numbers!
  • 22. Symmetric Encryption 101 I Know: Let's Add A Different Number! 01 04 01 54 95 42 64 12 +10 43 21 95 42 67 31 83 11 47 22 49 37 09 95 95
  • 23. How It Works We can generate the pads in two ways ● Randomly ○ If we only use once, perfect security ■ Known as a one-time-pad ○ If we use multiple times, same as caesar cipher ● With A Function ○ Give one or two inputs ■ A key, and an "input" ○ Generates a "stream" of pseudo random numbers
  • 24. Ciphers ● Take 2 inputs ○ A secret key ○ An "input" ● Produces Pseudo-Random Output ○ Looks random (statistically) ○ Is deterministic ■ Reproducible given same inputs
  • 25. Modes ● Multiple ways to use the keystream ● Each way is known as a "Mode" ● Some are secure ○ Others are not
  • 26. ECB Electronic Code Book ● Uses plain-text as "input" ● Uses output as cipher-text ● VERY BROKEN!!!
  • 27. ECB
  • 28. CBC Cipher Block Chaining ● Uses an "Initialization Vector" ○ Helps "randomize" the plain-text ○ Ensures no non-unique blocks ○ Does NOT need to be secret ● Chains each block together ○ Propagating the generated "randomness" ● Plain-Text Must Be Padded ○ To a multiple of block-size ● Secure!
  • 29. CBC
  • 30. CFB Cipher FeedBack ● Uses an "Initialization Vector" ● Plain-Text never enters cipher ○ Does not need to be padded ● "Decrypt" Is Never Used ● Secure!
  • 31. CFB
  • 32. Ciphers ● AES 128 & 256 ○ Standard ■ NIST Approved ○ Also Known As RIJNDAEL-128 ■ 128 here refers to "block size" ○ Very Strong ○ Note, the number after AES is *key size* ● Blowfish ● TwoFish ● Serpent
  • 33. Authentication How do you know it wasn't tampered with / came from your friend? ● HMAC ○ Hash-based Message Authentication Code ● USE A SEPARATE KEY! ● Encrypt-Then-MAC ○ Always MAC after encryption
  • 34. All Together Now!
  • 35. Encrypt $key = 'xxxxxxxxxxxxxxxx'; $authKey = 'XXXXXXXXXXXXXX'; $plain = 'This is plain text that I am going to encrypt'; $size = mcrypt_get_iv_size( MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CFB ); $iv = mcrypt_create_iv( $size, MCRYPT_DEV_URANDOM ); $cipherText = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $key, $plain, MCRYPT_MODE_CFB, $iv ); $auth = hash_hmac('sha512', $cipherText, $authKey, true); $encrypted = base64_encode($iv . $cipherText . $auth);
  • 36. Decrypt $key = 'xxxxxxxxxxxxxxxx'; $authKey = 'XXXXXXXXXXXXXX'; $size = mcrypt_get_iv_size( MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CFB ); $encrypted = base64_decode($encrypted); $iv = substr($encrypted, 0, $size); $auth = substr($encrypted, -64); $cipherText = substr($encrypted, $size, -64); if ($auth != hash_hmac('sha512', $cipherText, $authKey, true)) { // Auth Failed!!! return false; } $plainText = mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $key, $cipherText, MCRYPT_MODE_CFB, $iv );
  • 37. Please Don't Do It! ● Notice How Much Code It Took ○ Without error checking ● Notice How Complex It Is ○ Without flexibility ● Notice How Easy To Screw Up ○ Without Key Storage ● Notice How Many Decisions To Make
  • 38. If you MUST, Use a Library
  • 39. Common Encryption Needs ● Between Client / Server ○ Use SSL ○ Really, just use SSL ○ I'm not kidding, just use SSL ● Storage ○ Use disk encryption ○ Use database encryption
  • 41. Encryption Resources ● Zend Framework Encryption ○ Very good and complete lib ○ ZF2 ■ ZendCryptBlockCipher ● PHP Sec Lib ○ phpseclib.sourceforge.net ○ Pure PHP ● Not Many Others ○ Beware of online tutorials!!!
  • 43. Passwords Should Be HASHED! Not Encrypted!
  • 44. Password Hashes ● Use A Salt ○ Defeats Rainbow Tables ○ Makes Each Hash a "Proof Of Work" ○ Should be random! ■ Strong Randomness ● Should Be SLOW! ○ Salt is not enough ○ Salted SHA256: 11 BILLION per second ○ bcrypt: 3200 per second
  • 45. Good Algorithms crypt($password, $salt); pbkdf2($password, $salt, $i); password_hash( $password, PASSWORD_BCRYPT ); $passLib->hash($password); $phpass->hashPassword($pass);
  • 46. Cost Parameter ● Target: 0.25 - 0.5 Seconds ○ As slow as you can afford ● Depends on hardware ○ Test it! ● Good Defaults: ○ BCrypt: 10 ○ PBKDF2: 10,000
  • 48. New API for 5.5 ● string password_hash($pass, $algo, array $options = array() ) ○ Generates Salt, hashes password ● bool password_verify($pass, $hash) ○ Verifies Hash with Password ● bool password_needs_rehash($hash, $algo, array $options = array()) ○ Determines if the hash is the same as specified by algo and options ● array password_get_info($hash) ○ Returns information about the hash
  • 49. Example function register($user, $password) { $hash = password_hash($password, PASSWORD_BCRYPT); $this->store($user, $hash); } function login($user, $password) { $hash = $this->fetchHash($user); if (password_verify($password, $hash)) { if (password_needs_rehahs($hash, PASSWORD_BCRYPT)) { $hash = password_hash($password, PASSWORD_BCRYPT); $this->store($user, $hash); } $this->startSession(); return true; } return false; }
  • 50. Hashing Resources ● PHP 5.5 API ○ wiki.php.net/rfc/password_hash ● Password Compat ○ PHP 5.5 Compatibility ○ github/ircmaxell/password_compat ● PasswordLib ○ 5.3+, Multiple Algorithms, Portable ○ github/ircmaxell/PHP-PasswordLib ● PHPASS ○ PHP 4+ ○ openwall.com/phpass
  • 52. You Have Been Warned
  • 54. Anthony Ferrara @ircmaxell blog.ircmaxell.com me@ircmaxell.com joind.in/7939