Slide 1

Slide 1 text

Criptografia com PHP @vcampitelli CRIPTOGRAFIA CRIPTOGRAFIA COM PHP COM PHP 1

Slide 2

Slide 2 text

Criptografia com PHP @vcampitelli QUEM SOU EU? QUEM SOU EU? Vinícius Campitelli • MT4 Tecnologia • @MediaPost • Curseduca • senhasegura vcampitelli.github.io 2

Slide 3

Slide 3 text

Criptografia com PHP @vcampitelli O QUE É O QUE É CRIPTOGRAFIA? CRIPTOGRAFIA? 3 . 1

Slide 4

Slide 4 text

Criptografia com PHP @vcampitelli é a prática e o estudo de técnicas para comunicação segura na presença de terceiros é a construção e análise de protocolos que previnam terceiros de ler mensagens privadas 3 . 2

Slide 5

Slide 5 text

Criptografia com PHP @vcampitelli Texto claro → Texto cifrado 3 . 3

Slide 6

Slide 6 text

Criptografia com PHP @vcampitelli TIPOS DE TIPOS DE CRIPTOGRAFIA CRIPTOGRAFIA 4

Slide 7

Slide 7 text

Criptografia com PHP @vcampitelli SIMÉTRICA SIMÉTRICA 5 . 1

Slide 8

Slide 8 text

Criptografia com PHP @vcampitelli Utiliza uma mesma chave para criptografar e descriptografar os textos Exemplos AES 3DES RC4 Blowfish 5 . 2

Slide 9

Slide 9 text

Criptografia com PHP @vcampitelli CIFRAS CIFRAS 5 . 3

Slide 10

Slide 10 text

Criptografia com PHP @vcampitelli CIFRAS EM BLOCO CIFRAS EM BLOCO Algoritmo determinístico que usa uma chave para transformar um bloco em um texto cifrado AES Blocos de 128 bits Chaves de 128, 192 ou 256 bits 5 . 4

Slide 11

Slide 11 text

Criptografia com PHP @vcampitelli MODOS DE OPERAÇÃO MODOS DE OPERAÇÃO Mecanismo que irá dividir a mensagem em blocos e aplicar a cifra a cada um Exemplos ECB CBC CTR GCM (PHP 7.1) 5 . 5

Slide 12

Slide 12 text

Criptografia com PHP @vcampitelli Tux original Tux original Tux aplicando-se CBC / CTR Tux aplicando-se CBC / CTR Tux aplicando-se ECB Tux aplicando-se ECB NÃO USE ECB! NÃO USE ECB! 5 . 6

Slide 13

Slide 13 text

Criptografia com PHP @vcampitelli CIFRAS DE FLUXO (STREAM) CIFRAS DE FLUXO (STREAM) Algoritmo que opera em um bit/byte de cada vez Chave "infinita" de dados pseudo-randômicos Indicado quando não se sabe o tamanho do dado Algoritmos RC4, mais conhecido mas inseguro : projeto para escolher novos algoritmos eSTREAM 5 . 7

Slide 14

Slide 14 text

Criptografia com PHP @vcampitelli ASSIMÉTRICA ASSIMÉTRICA 6 . 1

Slide 15

Slide 15 text

Criptografia com PHP @vcampitelli Chave privada: utilizada para criptografar (escrever) Chave pública: utilizada para descriptografar (ler) Algoritmos RSA Curvas Elípticas 6 . 2

Slide 16

Slide 16 text

Criptografia com PHP @vcampitelli Provê encriptação e autenticação Utilizada para estabelecer conexões seguras em ambientes inseguros Principais utilizações SSH SSL/TLS (certificados digitais) PGP 6 . 3

Slide 17

Slide 17 text

Criptografia com PHP @vcampitelli PROBLEMA: TROCA DE CHAVES PROBLEMA: TROCA DE CHAVES Algoritmo Diffie–Hellman Algoritmo Diffie–Hellman 6 . 4

Slide 18

Slide 18 text

Criptografia com PHP @vcampitelli

Slide 19

Slide 19 text

Criptografia com PHP @vcampitelli Fonte: Fonte: Wikipedia Wikipedia 6 . 5

Slide 20

Slide 20 text

Criptografia com PHP @vcampitelli GERADORES DE GERADORES DE ALEATORIEDADE ALEATORIEDADE 7 . 1

Slide 21

Slide 21 text

Criptografia com PHP @vcampitelli PHP 7 random_int() random_bytes() PHP 5.3+ openssl_random_pseudo_bytes() PHP 5.x paragonie/random_compat 7 . 2

Slide 22

Slide 22 text

Criptografia com PHP @vcampitelli MÁS PRÁTICAS MÁS PRÁTICAS rand() e mt_rand() não são criptogra camente seguros 7 . 3

Slide 23

Slide 23 text

Criptografia com PHP @vcampitelli VETORES DE VETORES DE INICIALIZAÇÃO INICIALIZAÇÃO 8 . 1

Slide 24

Slide 24 text

Criptografia com PHP @vcampitelli Utilizados para "inicializar" os algoritmos openssl_cipher_iv_length() para buscar o tamanho do IV para cada algoritmo openssl_get_cipher_methods() para descobrir os algoritmos disponíveis 8 . 2

Slide 25

Slide 25 text

Criptografia com PHP @vcampitelli EXEMPLO EXEMPLO random_bytes random_bytes( (openssl_cipher_iv_length openssl_cipher_iv_length( ('aes-256-ctr' 'aes-256-ctr') )) ); ; // Q��A|Gh���C �M // Q��A|Gh���C �M 8 . 3

Slide 26

Slide 26 text

Criptografia com PHP @vcampitelli MÁS PRÁTICAS GERAIS MÁS PRÁTICAS GERAIS mcrypt: desatualizada desde 2008 Fazer seu próprio algoritmo 9 . 1

Slide 27

Slide 27 text

Criptografia com PHP @vcampitelli NA PRÁTICA NA PRÁTICA 9 . 2

Slide 28

Slide 28 text

Criptografia com PHP @vcampitelli string string openssl_encrypt openssl_encrypt( ( string string $data $data , , string string $method $method , , string string $key $key [ [, , int int $options $options = = 0 0 [ [, , string string $iv $iv = = "" "" [ [, , string string & &$tag $tag = = NULL NULL [ [, , string string $aad $aad = = "" "" [ [, , int int $tag_length $tag_length = = 16 16 ] ]] ]] ]] ]] ] ) ) 9 . 3

Slide 29

Slide 29 text

Criptografia com PHP @vcampitelli $key $key = = openssl_random_pseudo_bytes openssl_random_pseudo_bytes( (32 32) ); ; // chave de 256 bits // chave de 256 bits $iv $iv = = openssl_random_pseudo_bytes openssl_random_pseudo_bytes( ( openssl_cipher_iv_length openssl_cipher_iv_length( ('aes-256-ctr' 'aes-256-ctr') ) ) ); ; $data $data = = 'Olá, PHP Conference 2017!' 'Olá, PHP Conference 2017!'; ; $encrypted $encrypted = = openssl_encrypt openssl_encrypt( ($data $data, , 'aes-256-ctr' 'aes-256-ctr', , $key $key, , 0 0, , $iv $iv) ); ; // LKdTM372XbDEYP6UnAWbhChZ7wxbaOt+6qg= // LKdTM372XbDEYP6UnAWbhChZ7wxbaOt+6qg= 9 . 4

Slide 30

Slide 30 text

Criptografia com PHP @vcampitelli string string openssl_decrypt openssl_decrypt( ( string string $data $data , , string string $method $method , , string string $key $key [ [, , int int $options $options = = 0 0 [ [, , string string $iv $iv = = "" "" [ [, , string string $tag $tag = = "" "" [ [, , string string $aad $aad = = "" "" ] ]] ]] ]] ] ) ) 9 . 5

Slide 31

Slide 31 text

Criptografia com PHP @vcampitelli // $key e $iv devem ser os mesmos usados no openssl_encrypt() // $key e $iv devem ser os mesmos usados no openssl_encrypt() // Uma forma de passar o IV é enviá-lo junto com o texto cifrado // Uma forma de passar o IV é enviá-lo junto com o texto cifrado // Por exemplo: $data = $iv . $crypt; // Por exemplo: $data = $iv . $crypt; $ivLength $ivLength = = openssl_cipher_iv_length openssl_cipher_iv_length( ('aes-256-ctr' 'aes-256-ctr') ); ; $iv $iv = = substr substr( ($data $data, , 0 0, , $ivLength $ivLength) ); ; $crypt $crypt = = substr substr( ($data $data, , $ivLength $ivLength) ); ; openssl_decrypt openssl_decrypt( ($crypt $crypt, , 'aes-256-ctr' 'aes-256-ctr', , $key $key, , 0 0, , $iv $iv) ); ; 9 . 6

Slide 32

Slide 32 text

Criptografia com PHP @vcampitelli HASHING HASHING 10 . 1

Slide 33

Slide 33 text

Criptografia com PHP @vcampitelli é uma função que mapeia dados de tamanho arbitrário para dados de tamanho xo 10 . 2

Slide 34

Slide 34 text

Criptografia com PHP @vcampitelli TIMING ATTACKS TIMING ATTACKS Side-channel attack Side-channel attack que analisa o tempo de execução que analisa o tempo de execução de algoritmos de criptografia de algoritmos de criptografia 10 . 3

Slide 35

Slide 35 text

Criptografia com PHP @vcampitelli string string hash hash( ( string string $algo $algo , , string string $data $data [ [, , bool bool $raw_output $raw_output = = false false ] ]) ) hash hash( ('sha256' 'sha256', , 'phpconf@2017' 'phpconf@2017') ); ; // f32b98cc1a6ed7e0614e5ee8fdf8142ea6b9b12a8c487aa6e269d220d93669 // f32b98cc1a6ed7e0614e5ee8fdf8142ea6b9b12a8c487aa6e269d220d93669 10 . 4

Slide 36

Slide 36 text

Criptografia com PHP @vcampitelli bool bool hash_equals hash_equals( ( string string $known_string $known_string , , string string $user_string $user_string ) ) $userHash $userHash = = hash hash( ('sha256' 'sha256', , $postedData $postedData) ); ; if if ( (hash_equals hash_equals( ($storedHash $storedHash, , $userHash $userHash) )) ) { { . .. .. . } } 10 . 5

Slide 37

Slide 37 text

Criptografia com PHP @vcampitelli string string password_hash password_hash( ( string string $password $password , , int int $algo $algo [ [, , array array $options $options ] ] ) ) password_hash password_hash( ('phpconf@2017' 'phpconf@2017', , PASSWORD_DEFAULT PASSWORD_DEFAULT, , [ ['cost' 'cost' = => > 12 12] ]) ); ; // $2y$12$m.GZEOwitahX7JIq7ulvWeR54AMT/SEg1TVh74iijsjTXT0LZRQ2q // $2y$12$m.GZEOwitahX7JIq7ulvWeR54AMT/SEg1TVh74iijsjTXT0LZRQ2q 10 . 6

Slide 38

Slide 38 text

Criptografia com PHP @vcampitelli bool bool password_verify password_verify( ( string string $password $password , , string string $hash $hash ) ) if if ( (password_verify password_verify( ($postedPassword $postedPassword, , $storedHash $storedHash) )) ) { { . .. .. . } } 10 . 7

Slide 39

Slide 39 text

Criptografia com PHP @vcampitelli ARGON2 NO PHP 7.2 ARGON2 NO PHP 7.2 Vencedor do (2015) Versão Argon2i, otimizada para side-channel attacks Constante PASSWORD_ARGON2I Opções memory_cost: memória máxima (bytes) time_cost: tempo máximo para o cálculo threads: número de threads Password Hashing Competition 10 . 8

Slide 40

Slide 40 text

Criptografia com PHP @vcampitelli MÁS PRÁTICAS MÁS PRÁTICAS md5() - colisões e velocidade sha1() - colisão ( ) === - timing attack shattered.io 10 . 9

Slide 41

Slide 41 text

Criptografia com PHP @vcampitelli ASSINATURAS ASSINATURAS 11 . 1

Slide 42

Slide 42 text

Criptografia com PHP @vcampitelli esquema matemático para demonstrar a autenticidade de uma mensagem 11 . 2

Slide 43

Slide 43 text

Criptografia com PHP @vcampitelli OPENSSL OPENSSL Disponível a partir do PHP 5.3 Algoritmos disponíveis: ou openssl_get_md_methods() http://php.net/manual/en/openssl.signature- algos.php 11 . 3

Slide 44

Slide 44 text

Criptografia com PHP @vcampitelli bool bool openssl_sign openssl_sign( ( string string $data $data , , string string & &$signature $signature , , mixed mixed $priv_key_id $priv_key_id [ [, , mixed mixed $signature_alg $signature_alg = = OPENSSL_ALGO_SHA1 OPENSSL_ALGO_SHA1 ] ] ) ) $privateKey $privateKey = = openssl_pkey_get_private openssl_pkey_get_private( ('file:///path/to/key.pem' 'file:///path/to/key.pem') ) openssl_sign openssl_sign( ($data $data, , $signature $signature, , $privateKey $privateKey, , OPENSSL_ALGO_SHA256 OPENSSL_ALGO_SHA256) ) // $signature = j�C^�)�L}� K���^ �~C3���l��&�l.��.�(� // $signature = j�C^�)�L}� K���^ �~C3���l��&�l.��.�(� // Para converter, usar base64_encode() ou bin2hex() // Para converter, usar base64_encode() ou bin2hex() 11 . 4

Slide 45

Slide 45 text

Criptografia com PHP @vcampitelli int int openssl_verify openssl_verify( ( string string $data $data , , string string $signature $signature , , mixed mixed $pub_key_id $pub_key_id [ [, , mixed mixed $signature_alg $signature_alg = = OPENSSL_ALGO_SHA1 OPENSSL_ALGO_SHA1 ] ] ) ) $pubKey $pubKey = = openssl_pkey_get_public openssl_pkey_get_public( ('file://path/to/cert.pem' 'file://path/to/cert.pem') ); ; openssl_verify openssl_verify( ($data $data, , $signature $signature, , $pubKey $pubKey, , 'sha256WithRSAEncrypti 'sha256WithRSAEncrypti // Retorna 1 ou 0 se a assinatura for válida ou não // Retorna 1 ou 0 se a assinatura for válida ou não // Caso haja algum erro, retorna -1 // Caso haja algum erro, retorna -1 11 . 5

Slide 46

Slide 46 text

Criptografia com PHP @vcampitelli HMAC HMAC Hash-based Message Authentication Code Algoritmos disponíveis: hash_hmac_algos() 11 . 6

Slide 47

Slide 47 text

Criptografia com PHP @vcampitelli string string hash_hmac hash_hmac( ( string string $algo $algo , , string string $data $data , , string string $key $key [ [, , bool bool $raw_output $raw_output = = false false ] ] ) ) hash_hmac hash_hmac( ('sha256' 'sha256', , 'PHP Conference 2017' 'PHP Conference 2017', , '+0FcB5@#:vb;%' '+0FcB5@#:vb;%') ); ; // 8486e5da2bd373ac77af77f966088aedeec2481f73c32c82cead64715be5a4 // 8486e5da2bd373ac77af77f966088aedeec2481f73c32c82cead64715be5a4 11 . 7

Slide 48

Slide 48 text

Criptografia com PHP @vcampitelli bool bool hash_equals hash_equals( ( string string $known_string $known_string , , string string $user_string $user_string ) ) hash_equals hash_equals( ($hashFromDb $hashFromDb, , hash hash( ('sha256' 'sha256', , $postedData $postedData) )) ); ; 11 . 8

Slide 49

Slide 49 text

Criptografia com PHP @vcampitelli MÁS PRÁTICAS MÁS PRÁTICAS md5() - colisões e velocidade sha1() - colisão ( ) === - timing attack shattered.io 11 . 9

Slide 50

Slide 50 text

Criptografia com PHP @vcampitelli UTILIDADES UTILIDADES 12 . 1

Slide 51

Slide 51 text

Criptografia com PHP @vcampitelli CRYPTOOL CRYPTOOL CrypTool CrypTool

Slide 52

Slide 52 text

Criptografia com PHP @vcampitelli 12 . 2

Slide 53

Slide 53 text

Criptografia com PHP @vcampitelli LIBSODIUM LIBSODIUM Biblioteca moderna para criptografia, assinaturas e hashing Incorporada no PHP 7.2 ( ) manual PHP 7.2: The First Programming Language to Add Modern Cryptography to its Standard Library 12 . 3

Slide 54

Slide 54 text

Criptografia com PHP @vcampitelli GERANDO CHAVES SIMÉTRICAS SEGURAS GERANDO CHAVES SIMÉTRICAS SEGURAS pwgen pwgen - -sy1 sy1 32 32 12 . 4

Slide 55

Slide 55 text

Criptografia com PHP @vcampitelli GERANDO PAR DE CHAVES RSA GERANDO PAR DE CHAVES RSA openssl genrsa openssl genrsa - -out out private private. .key key 2048 2048 # Generating RSA private key, 2048 bit long modulus # Generating RSA private key, 2048 bit long modulus openssl rsa openssl rsa - -in in private private. .key key - -outform outform PEM PEM - -pubout pubout - -out out public public. .pem pem # writing RSA key # writing RSA key 12 . 5

Slide 56

Slide 56 text

Criptografia com PHP @vcampitelli OBRIGADO! OBRIGADO! GitHub: Twitter: Slides: Vagas: @vcampitelli @vcampitelli vcampitelli.github.io [email protected] 13