1. Go to this page and download the library: Download sierratecnologia/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/ */
sierratecnologia / crypto example snippets
// bootstrap/app.php (somente para Lumen)
$app->withFacades(); // Habilitar Facades
// Registrar o Service Provider
$app->register(SierraTecnologia\Crypto\CryptoProvider::class);
// src/CryptoProvider.php:44-56
public function register()
{
$this->app->singleton('Crypto', function () {
return new Crypto();
});
$loader = AliasLoader::getInstance();
$loader->alias('Crypto', \SierraTecnologia\Crypto\Services\Crypto::class);
}
// app/Models/Customer.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use SierraTecnologia\Crypto\Traits\Encryptable;
class Customer extends Model
{
use Encryptable;
protected $fillable = [
'name', 'email', 'cpf', 'phone', 'address'
];
/**
* Campos que serão criptografados automaticamente
*/
protected $encrypted = [
'email',
'cpf',
'phone'
];
}
// Controller
class CustomerController extends Controller
{
public function store(Request $request)
{
$customer = Customer::create([
'name' => $request->name,
'email' => $request->email, // criptografado automaticamente
'cpf' => $request->cpf, // criptografado automaticamente
'phone' => $request->phone, // criptografado automaticamente
]);
return response()->json($customer); // dados descriptografados no JSON
}
}
use Crypto;
// Controller
class PasswordResetController extends Controller
{
public function sendResetLink(Request $request)
{
$user = User::where('email', $request->email)->first();
// Criptografar ID do usuário para URL
$token = Crypto::urlEncode($user->id . '|' . time());
$resetUrl = url("/password/reset/{$token}");
// Enviar email com o link
Mail::to($user)->send(new PasswordResetMail($resetUrl));
return response()->json(['message' => 'Link enviado!']);
}
public function resetPassword(Request $request, $token)
{
try {
// Descriptografar token da URL
$decrypted = Crypto::urlDecode($token);
[$userId, $timestamp] = explode('|', $decrypted);
// Verificar se não expirou (ex: 1 hora)
if (time() - $timestamp > 3600) {
return response()->json(['error' => 'Token expirado'], 400);
}
$user = User::findOrFail($userId);
$user->password = Hash::make($request->password);
$user->save();
return response()->json(['message' => 'Senha alterada!']);
} catch (\Exception $e) {
return response()->json(['error' => 'Token inválido'], 400);
}
}
}
use Crypto;
// Aplicação A (API) - Criptografar
class ApiController extends Controller
{
public function generateToken(User $user)
{
$payload = json_encode([
'user_id' => $user->id,
'email' => $user->email,
'expires_at' => now()->addHours(24)->timestamp,
]);
// Usar criptografia compartilhável
$token = Crypto::shareableEncrypt($payload);
return response()->json(['token' => $token]);
}
}
// Aplicação B (Admin) - Descriptografar
class AdminController extends Controller
{
public function validateToken(Request $request)
{
try {
// Descriptografar token da outra aplicação
$decrypted = Crypto::shareableDecrypt($request->token);
$payload = json_decode($decrypted, true);
if ($payload['expires_at'] < now()->timestamp) {
return response()->json(['error' => 'Token expirado'], 401);
}
$user = User::find($payload['user_id']);
return response()->json(['user' => $user]);
} catch (\Exception $e) {
return response()->json(['error' => 'Token inválido'], 401);
}
}
}
try {
$decrypted = Crypto::decrypt($encrypted);
} catch (\Exception $e) {
\Log::warning('Falha ao descriptografar', [
'error' => $e->getMessage(),
// NÃO logue o valor criptografado ou descriptografado
]);
return response()->json(['error' => 'Dados inválidos'], 400);
}
// Serviço A: Market (E-commerce)
use SierraTecnologia\Crypto\Traits\Encryptable;
class Payment extends Model
{
use Encryptable;
protected $encrypted = ['credit_card_number', 'cvv'];
}
// Serviço B: MediaManager (Gestão de Arquivos)
use Crypto;
class FileMetadata extends Model
{
public function setOwnerDataAttribute($value)
{
$this->attributes['owner_data'] = Crypto::shareableEncrypt(json_encode($value));
}
}
// Serviço C: Informate (Relatórios)
use Crypto;
class Report
{
public function generateCustomerReport($customerId)
{
$customer = Customer::find($customerId);
// Descriptografar dados para relatório
return [
'name' => $customer->name,
'email' => Crypto::decrypt($customer->encrypted_email),
'cpf' => Crypto::decrypt($customer->encrypted_cpf),
];
}
}
namespace App\Encryption;
use SierraTecnologia\Crypto\Encryption\CryptoEncrypterInterface;
class CustomEncrypter implements CryptoEncrypterInterface
{
protected $key;
protected $algorithm;
public function __construct($key, $algorithm = 'aes-256-gcm')
{
$this->key = $key;
$this->algorithm = $algorithm;
}
public function encrypt($value)
{
// Implementação customizada usando AES-GCM
$iv = random_bytes(16);
$tag = '';
$encrypted = openssl_encrypt(
$value,
$this->algorithm,
$this->key,
OPENSSL_RAW_DATA,
$iv,
$tag
);
return base64_encode($iv . $tag . $encrypted);
}
public function decrypt($value)
{
$decoded = base64_decode($value);
$iv = substr($decoded, 0, 16);
$tag = substr($decoded, 16, 16);
$encrypted = substr($decoded, 32);
return openssl_decrypt(
$encrypted,
$this->algorithm,
$this->key,
OPENSSL_RAW_DATA,
$iv,
$tag
);
}
public function uuid()
{
return \Ramsey\Uuid\Uuid::uuid4()->toString();
}
}
// app/Providers/AppServiceProvider.php
use App\Encryption\CustomEncrypter;
public function register()
{
$this->app->singleton('CustomCrypto', function () {
return new CustomEncrypter(config('app.key'));
});
}
// Uso
$encrypted = app('CustomCrypto')->encrypt('dados sensíveis');
namespace App\Services;
use SierraTecnologia\Crypto\Services\Crypto as BaseCrypto;
class ExtendedCrypto extends BaseCrypto
{
/**
* Criptografar com timestamp para expiração automática
*/
public static function encryptWithExpiry($value, $ttlSeconds = 3600)
{
$expiresAt = time() + $ttlSeconds;
$payload = json_encode([
'data' => $value,
'expires_at' => $expiresAt,
]);
return parent::encrypt($payload);
}
/**
* Descriptografar e verificar expiração
*/
public static function decryptWithExpiry($encrypted)
{
$decrypted = parent::decrypt($encrypted);
$payload = json_decode($decrypted, true);
if ($payload['expires_at'] < time()) {
throw new \Exception('Dados expirados');
}
return $payload['data'];
}
}
// app/Providers/CryptoServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\ExtendedCrypto;
class CryptoServiceProvider extends ServiceProvider
{
public function register()
{
// Sobrescrever binding do Crypto
$this->app->singleton('Crypto', function () {
return new ExtendedCrypto();
});
}
}
// config/app.php
'providers' => [
// ...
App\Providers\CryptoServiceProvider::class, // adicionar após o CryptoProvider original
],
namespace App\Traits;
use Crypto;
trait EncryptableWithAudit
{
use \SierraTecnologia\Crypto\Traits\Encryptable;
/**
* Override setAttribute para adicionar auditoria
*/
public function setAttribute($key, $value)
{
if (in_array($key, $this->encrypted ?? [])) {
// Registrar auditoria antes de criptografar
\Log::info("Campo {$key} será criptografado", [
'model' => static::class,
'id' => $this->id,
'user' => auth()->id(),
]);
}
return parent::setAttribute($key, $value);
}
}
// ❌ Dados sensíveis armazenados em texto plano
class Order extends Model
{
protected $fillable = ['customer_email', 'credit_card', 'amount'];
}
// Risco: Dados expostos em caso de breach no banco de dados
// ✅ Dados sensíveis criptografados automaticamente
use SierraTecnologia\Crypto\Traits\Encryptable;
class Order extends Model
{
use Encryptable;
protected $fillable = ['customer_email', 'credit_card', 'amount'];
protected $encrypted = ['customer_email', 'credit_card'];
}
// Benefício: Conformidade com PCI-DSS, proteção em caso de breach
// Modelo de Tenant
use SierraTecnologia\Crypto\Traits\Encryptable;
class Tenant extends Model
{
use Encryptable;
protected $encrypted = [
'api_key',
'webhook_secret',
'database_password',
'smtp_password',
];
}
// Compartilhar dados entre serviços
use Crypto;
class TenantProvisioningService
{
public function provisionTenant($tenantId)
{
$tenant = Tenant::find($tenantId);
// Gerar token compartilhável para worker
$token = Crypto::shareableEncrypt(json_encode([
'tenant_id' => $tenant->id,
'api_key' => $tenant->api_key, // já descriptografado pelo trait
'provisioned_at' => now()->timestamp,
]));
// Enviar para fila de provisionamento
dispatch(new ProvisionTenantJob($token));
}
}
// Worker (outra aplicação)
class ProvisionTenantJob implements ShouldQueue
{
public function handle($token)
{
$data = json_decode(Crypto::shareableDecrypt($token), true);
// Provisionar recursos do tenant
$this->createDatabase($data['tenant_id']);
$this->configureApi($data['api_key']);
}
}
// Serviço de Autenticação Principal
use Crypto;
class AuthService
{
public function generateSessionToken(User $user)
{
$payload = [
'user_id' => $user->id,
'email' => $user->email,
'roles' => $user->roles->pluck('name'),
'expires_at' => now()->addHours(24)->timestamp,
'session_id' => Crypto::uuid(),
];
return Crypto::shareableEncrypt(json_encode($payload));
}
public function validateToken($token)
{
try {
$payload = json_decode(Crypto::shareableDecrypt($token), true);
if ($payload['expires_at'] < now()->timestamp) {
throw new \Exception('Token expirado');
}
return $payload;
} catch (\Exception $e) {
throw new \Exception('Token inválido');
}
}
}
// Middleware para validação em todas as aplicações
class ValidateCryptoToken
{
public function handle($request, Closure $next)
{
$token = $request->bearerToken();
try {
$payload = app(AuthService::class)->validateToken($token);
$request->merge(['auth_payload' => $payload]);
} catch (\Exception $e) {
return response()->json(['error' => 'Não autorizado'], 401);
}
return $next($request);
}
}
namespace SierraTecnologia\Crypto\Services;
use SierraTecnologia\Crypto\Encryption\CryptoEncrypter;
/**
* Classe de serviço para operações de criptografia.
*
* Esta classe fornece uma interface simplificada para
* criptografia e descriptografia de dados sensíveis.
*
* @package SierraTecnologia\Crypto\Services
* @author SierraTecnologia Team <[email protected]>
*/
class ExampleService
{
/**
* Instância do encrypter.
*
* @var CryptoEncrypter
*/
protected CryptoEncrypter $encrypter;
/**
* Construtor do serviço.
*
* @param CryptoEncrypter $encrypter Instância do encrypter
*/
public function __construct(CryptoEncrypter $encrypter)
{
$this->encrypter = $encrypter;
}
/**
* Criptografa um valor.
*
* @param string $value Valor a ser criptografado
* @return string Valor criptografado
* @throws \Exception Se a criptografia falhar
*/
public function encrypt(string $value): string
{
if (empty($value)) {
throw new \InvalidArgumentException('Valor não pode ser vazio');
}
return $this->encrypter->encrypt($value);
}
}