🔐 Criptografia
Suite completa de criptografia, segurança e autenticação para aplicações Rust.
Overview
O módulo de criptografia do Arxis Core oferece implementações de última geração para:
- Funções hash criptográficas (SHA-2, SHA-3, BLAKE3)
- Criptografia simétrica (AES, ChaCha20)
- Criptografia assimétrica (RSA, Ed25519, X25519)
- Assinaturas digitais
- TLS/SSL
- JWT e OAuth
- Geração de números aleatórios criptograficamente seguros
🛡️ Auditado e Seguro: Todos os pacotes de criptografia passam por auditoria de segurança regular e seguem as melhores práticas da indústria.
avx-crypto
Pacote principal de criptografia com APIs de alto nível.
Instalação
[dependencies]
avx-crypto = "0.1.0"
Features
- hash - Funções de hash criptográfico
- cipher - Algoritmos de criptografia simétrica e assimétrica
- signature - Assinaturas digitais
- random - Gerador de números aleatórios seguros
- password - Hashing de senhas (Argon2, bcrypt)
Exemplo Básico
use avx_crypto::{hash, cipher, signature};
fn main() -> Result<(), Box> {
// Hash
let data = b"Hello, Arxis!";
let hash = hash::sha256(data);
// Criptografia simétrica
let key = cipher::generate_key();
let encrypted = cipher::encrypt(&key, data)?;
let decrypted = cipher::decrypt(&key, &encrypted)?;
// Assinatura digital
let (private_key, public_key) = signature::generate_keypair();
let signature = signature::sign(&private_key, data);
signature::verify(&public_key, data, &signature)?;
Ok(())
}
avx-hash
Implementações de funções hash criptográficas.
Algoritmos Suportados
- SHA-256, SHA-384, SHA-512 - SHA-2 family
- SHA3-256, SHA3-512 - SHA-3 family
- BLAKE3 - Hash moderno de alta performance
- HMAC - Message authentication codes
use avx_hash::{Sha256, Sha3_256, Blake3, Hmac};
// SHA-256
let hash = Sha256::digest(b"data");
// SHA3-256
let hash3 = Sha3_256::digest(b"data");
// BLAKE3
let blake = Blake3::digest(b"data");
// HMAC-SHA256
let key = b"secret_key";
let hmac = Hmac::::new(key).finalize(b"message");
avx-cipher
Algoritmos de criptografia simétrica e assimétrica.
Criptografia Simétrica
- AES-128-GCM, AES-256-GCM - Advanced Encryption Standard
- ChaCha20-Poly1305 - Stream cipher moderno
- XChaCha20-Poly1305 - ChaCha20 com nonces estendidos
use avx_cipher::{Aes256Gcm, ChaCha20Poly1305, Cipher};
// AES-256-GCM
let key = Aes256Gcm::generate_key();
let cipher = Aes256Gcm::new(&key);
let ciphertext = cipher.encrypt(b"plaintext")?;
let plaintext = cipher.decrypt(&ciphertext)?;
// ChaCha20-Poly1305
let cipher = ChaCha20Poly1305::new(&key);
let encrypted = cipher.encrypt(b"secret data")?;
Criptografia Assimétrica
- RSA - 2048, 3072, 4096 bits
- X25519 - Key exchange
- Ed25519 - Digital signatures
use avx_cipher::{Rsa, X25519};
// RSA
let (private_key, public_key) = Rsa::generate_keypair(2048)?;
let encrypted = public_key.encrypt(b"message")?;
let decrypted = private_key.decrypt(&encrypted)?;
// X25519 Key Exchange
let alice_secret = X25519::generate_secret();
let bob_secret = X25519::generate_secret();
let alice_public = alice_secret.public_key();
let bob_public = bob_secret.public_key();
let shared_secret = alice_secret.exchange(&bob_public);
avx-signature
Assinaturas digitais e verificação.
Algoritmos
- Ed25519 - Assinatura de curva elíptica (recomendado)
- ECDSA - P-256, P-384
- RSA-PSS - RSA com PSS padding
use avx_signature::{Ed25519, Signer, Verifier};
// Ed25519
let (signing_key, verifying_key) = Ed25519::generate_keypair();
let message = b"Important document";
let signature = signing_key.sign(message);
// Verificar
verifying_key.verify(message, &signature)?;
// ECDSA
use avx_signature::Ecdsa;
let (private_key, public_key) = Ecdsa::P256::generate_keypair();
let sig = private_key.sign(message);
public_key.verify(message, &sig)?;
avx-jwt
JSON Web Tokens (JWT) para autenticação e autorização.
Features
- Criar e validar JWTs
- Algoritmos HS256, HS384, HS512, RS256, ES256
- Claims customizados
- Validação de expiração
use avx_jwt::{Jwt, Algorithm, Claims};
use std::time::{SystemTime, Duration};
// Criar JWT
let secret = b"my_secret_key";
let mut claims = Claims::new();
claims.subject = Some("user123".to_string());
claims.expiration = Some(
SystemTime::now() + Duration::from_secs(3600)
);
claims.custom.insert("role".to_string(), "admin".into());
let token = Jwt::encode(&claims, secret, Algorithm::HS256)?;
// Validar JWT
let decoded = Jwt::decode(&token, secret, Algorithm::HS256)?;
println!("User: {:?}", decoded.subject);
avx-tls
TLS/SSL para comunicações seguras.
use avx_tls::{TlsConnector, TlsAcceptor};
use tokio::net::TcpStream;
// Cliente TLS
let connector = TlsConnector::new()
.with_root_certificates(&cert_store)?;
let stream = TcpStream::connect("example.com:443").await?;
let tls_stream = connector.connect("example.com", stream).await?;
// Servidor TLS
let acceptor = TlsAcceptor::new()
.with_certificate(&cert)?
.with_private_key(&key)?;
let listener = TcpListener::bind("0.0.0.0:443").await?;
let (stream, _) = listener.accept().await?;
let tls_stream = acceptor.accept(stream).await?;
avx-oauth
OAuth 2.0 e OpenID Connect.
use avx_oauth::{OAuthClient, TokenResponse};
let client = OAuthClient::new(
"client_id",
"client_secret",
"https://oauth.provider.com"
);
// Authorization Code Flow
let auth_url = client.authorization_url(
"https://myapp.com/callback",
&["read", "write"]
);
// Trocar código por token
let token: TokenResponse = client
.exchange_code("authorization_code")
.await?;
println!("Access token: {}", token.access_token);
Exemplos Avançados
Sistema de Autenticação Completo
use avx_crypto::{hash, signature};
use avx_jwt::{Jwt, Claims};
struct AuthSystem {
signing_key: signature::Ed25519PrivateKey,
verifying_key: signature::Ed25519PublicKey,
}
impl AuthSystem {
fn new() -> Self {
let (signing_key, verifying_key) =
signature::Ed25519::generate_keypair();
Self { signing_key, verifying_key }
}
fn hash_password(&self, password: &str) -> String {
hash::argon2(password.as_bytes())
}
fn verify_password(&self, password: &str, hash: &str) -> bool {
hash::verify_argon2(password.as_bytes(), hash)
}
fn create_token(&self, user_id: &str) -> Result {
let mut claims = Claims::new();
claims.subject = Some(user_id.to_string());
claims.expiration = Some(
SystemTime::now() + Duration::from_secs(86400)
);
Jwt::encode_with_key(&claims, &self.signing_key)
}
fn verify_token(&self, token: &str) -> Result {
Jwt::decode_with_key(token, &self.verifying_key)
}
}
Criptografia End-to-End
use avx_cipher::{X25519, ChaCha20Poly1305};
struct SecureChannel {
private_key: X25519Secret,
public_key: X25519Public,
}
impl SecureChannel {
fn new() -> Self {
let private_key = X25519::generate_secret();
let public_key = private_key.public_key();
Self { private_key, public_key }
}
fn encrypt_message(
&self,
recipient_public: &X25519Public,
message: &[u8]
) -> Result, Error> {
let shared_secret = self.private_key.exchange(recipient_public);
let cipher = ChaCha20Poly1305::new(&shared_secret);
cipher.encrypt(message)
}
fn decrypt_message(
&self,
sender_public: &X25519Public,
ciphertext: &[u8]
) -> Result, Error> {
let shared_secret = self.private_key.exchange(sender_public);
let cipher = ChaCha20Poly1305::new(&shared_secret);
cipher.decrypt(ciphertext)
}
}