PHP code example of tourze / tls-crypto

1. Go to this page and download the library: Download tourze/tls-crypto library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tourze / tls-crypto example snippets


use Tourze\TLSCrypto\CryptoFactory;

// 创建随机数生成器
$random = CryptoFactory::createRandom();

// 生成16字节的随机数
$randomBytes = $random->getRandomBytes(16);

// 生成1-100范围内的随机整数
$randomInt = $random->getRandomInt(1, 100);

use Tourze\TLSCrypto\CryptoFactory;

// 创建SHA-256哈希函数
$hash = CryptoFactory::createHash('sha256');

// 计算哈希值
$data = 'Hello, World!';
$hashValue = $hash->hash($data);

// 使用增量哈希
$context = $hash->createContext();
$hash->updateContext($context, 'Hello, ');
$hash->updateContext($context, 'World!');
$hashValue = $hash->finalizeContext($context);

use Tourze\TLSCrypto\CryptoFactory;

// 创建基于SHA-256的HMAC
$hmac = CryptoFactory::createMac('hmac-sha256');

// 计算HMAC
$data = 'Message to authenticate';
$key = $random->getRandomBytes(32);
$mac = $hmac->compute($data, $key);

// 验证HMAC
$isValid = $hmac->verify($data, $mac, $key);

use Tourze\TLSCrypto\CryptoFactory;

// 创建AES-256-GCM加密算法
$cipher = CryptoFactory::createCipher('aes-256-gcm');

// 生成随机密钥和IV
$random = CryptoFactory::createRandom();
$key = $random->getRandomBytes($cipher->getKeyLength());
$iv = $random->getRandomBytes($cipher->getIVLength());

// 加密数据
$plaintext = 'Secret message';
$aad = 'Additional authenticated data';
$tag = null;
$ciphertext = $cipher->encrypt($plaintext, $key, $iv, $aad, $tag);

// 解密数据
$decrypted = $cipher->decrypt($ciphertext, $key, $iv, $aad, $tag);

use Tourze\TLSCrypto\CryptoFactory;

// 创建基于SHA-256的HKDF
$kdf = CryptoFactory::createKdf('hkdf-sha256');

// 导出密钥
$secret = 'Master secret';
$salt = 'Salt value';
$info = 'Key expansion';
$length = 32; // 导出32字节的密钥材料
$derivedKey = $kdf->derive($secret, $salt, $info, $length);