Orientação gerada a partir de informações públicas. Apenas para referência.
Pinenacl é uma implementação em Dart da API PyNaCl, aproveitando a biblioteca criptográfica leve e segura TweetNaCl. Oferece uma interface simples para operações criptográficas comuns, como criptografia, descriptografia, assinatura e geração de chaves. Projetado para desempenho e segurança, suporta múltiplas plataformas, incluindo Android, iOS, Web, macOS, Windows e Linux. Ideal para desenvolvedores que precisam de criptografia robusta em aplicações Flutter sem depender de código nativo.
Casos de uso
Armazenamento de dados seguro
Mensagens criptografadas de ponta a ponta
Assinaturas digitais
Gerenciamento de token de autenticação
Gerenciamento de configuração seguro
Principais recursos
segurança baseada no TweetNaCl
Compatibilidade multiplataforma
API simples semelhante ao PyNaCl
Leve e rápido
Suporta criptografia de chave pública e simétrica
Indicado para
Aplicativos Flutter que exigem criptografia forte
Desenvolvedores familiarizados com o PyNaCl
Aplicações que lidam com dados de usuário sensíveis
Projetos que precisam de criptografia independente de plataforma
Integrações de backend voltadas para segurança
Considerações
Requer entendimento de conceitos criptográficos
Não adequado para cargas de trabalho criptográficas de alto volume
Limitado ao conjunto de recursos do TweetNaCl
Sem gerenciamento de chaves embutido
Depende da correção da biblioteca externa
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
This dart implementation based on the tweetnacl-dart library, but it's slightly rewritten and extended by some higher level API implementations, similar to the PyNaCl library's APIs and concepts, for real-life applications.
Thes library has the aim of
improving the
usability, by implementing high-level and simple-to-use APIs,
security and speed, by using the dart implementation of the high-security TweetNaCl library.
and providing a simple API for creating real-life applications easier.
Installing
Add the following into the pubspec.yaml of your dart package:
dependencies:pinenacl:^0.6.0
You can install now from the command line with pub:
PineNaCl reuses a lot of terminologies, concepts, sections of documents and implements examples and some features from, the before mentioned PyNaCl's publicly available readthedocs.io.
Implemented features:
ECDH (with Curve25519) for key exchange (authenticated encryptions)
Public-key Encryption
Box (public-key authenticated encryption) and
SealedBox
Private-key encryption
SecretBox (private-key authenticated encryption)
EdDSA for Digital signatures (signing). It is complete (they are valid for all points on the curve) and deterministic i.e. no unique random nonce is required.
Ed25519 Signatures i.e. Curve25519 with SHA-512.
Hashing and message authentication
SHA-256,
SHA-512, the default hashing algorithm of the original TweetNaCl
BLAKE2b for KDF and MAC (not implemented in TweetNaCl).
HMAC-SHA512.
Password based key derivation and password hashing.
PBKDF2 with HMAC-SHA512, iterating the HMAC-SHA512 many times on a combination of the password and a random salt.
Low-level Functions supported by PineNaCl
This library supports all 25 of the C NaCl functions, that can be used to build NaCl applications.
Imagine Alice wants something valuable shipped to her. Because it’s valuable, she wants to make sure it arrives securely (i.e. hasn’t been opened or tampered with) and that it’s not a forgery (i.e. it’s actually from the sender she’s expecting it to be from and nobody’s pulling the old switcheroo).
One way she can do this is by providing the sender (let’s call him Bob) with a high-security box of her choosing. She provides Bob with this box, and something else: a padlock, but a padlock without a key. Alice is keeping that key all to herself. Bob can put items in the box then put the padlock onto it. But once the padlock snaps shut, the box cannot be opened by anyone who doesn’t have Alice’s private key.
Here’s the twist though: Bob also puts a padlock onto the box. This padlock uses a key Bob has published to the world, such that if you have one of Bob’s keys, you know a box came from him because Bob’s keys will open Bob’s padlocks (let’s imagine a world where padlocks cannot be forged even if you know the key). Bob then sends the box to Alice.
In order for Alice to open the box, she needs two keys: her private key that opens her own padlock, and Bob’s well-known key. If Bob’s key doesn’t open the second padlock, then Alice knows that this is not the box she was expecting from Bob, it’s a forgery.
This bidirectional guarantee around identity is known as mutual authentication.
import'package:pinenacl/api.dart';
import'package:pinenacl/public.dart'showPrivateKey;
voidmain() {
// Generate Bob's private key, which must be kept secretfinal skbob = PrivateKey.generate();
// Bob's public key can be given to anyone wishing to send// Bob an encrypted messagefinal pkbob = skbob.publicKey;
// Alice does the same and then Alice and Bob exchange public keysfinal skalice = PrivateKey.generate();
final pkalice = skalice.publicKey;
// Bob wishes to send Alice an encrypted message so Bob must make a Box with// his private key and Alice's public keyfinal bobBox = Box(myPrivateKey: skbob, theirPublicKey: pkalice);
// This is our message to send, it must be a bytestring as Box will treat it// as just a binary blob of data.final message = 'There is no conspiracy out there, but lack of the incentives to drive the people towards the answers.';
// TweetNaCl can automatically generate a random nonce for us, making the encryption very simple:// Encrypt our message, it will be exactly 40 bytes longer than the// original message as it stores authentication information and the// nonce alongside it.final encrypted = bobBox.encrypt(message.codeUnits);
// Finally, the message is decrypted (regardless of how the nonce was generated):// Alice creates a second box with her private key to decrypt the messagefinal aliceBox = Box(myPrivateKey: skalice, theirPublicKey: pkbob);
// Decrypt our message, an exception will be raised if the encryption was// tampered with or there was otherwise an error.final decrypted = aliceBox.decrypt(encrypted);
print(String.fromCharCodes(decrypted.plaintext));
}
SealedBox
The SealedBox class encrypts messages addressed to a specified key-pair by using ephemeral sender’s keypairs, which will be discarded just after encrypting a single plaintext message.
This kind of construction allows sending messages, which only the recipient can decrypt without providing any kind of cryptographic proof of sender’s authorship.
Warning
By design, the recipient will have no means to trace the ciphertext to a known author, since the sending keypair itself is not bound to any sender’s identity, and the sender herself will not be able to decrypt the ciphertext she just created, since the private part of the key cannot be recovered after use.
import'package:pinenacl/public.dart'showSealedBox, PrivateKey;
voidmain() {
// Generate Bob's private key, which must be kept secretfinal skbob = PrivateKey.generate();
final pkbob = skbob.publicKey;
// Alice wishes to send a encrypted message to Bob,// but prefers the message to be untraceable// she puts it into a secretbox and seals it.final sealedBox = SealedBox(pkbob);
final message = 'The world is changing around us and we can either get ''with the change or we can try to resist it';
final encrypted = sealedBox.encrypt(message.codeUnits);
// Bob unseals the box with his privatekey, and decrypts it.final unsealedBox = SealedBox(skbob);
final plainText = unsealedBox.decrypt(encrypted);
print(String.fromCharCodes(plainText));
assert(message == String.fromCharCodes(plainText));
}
Secret key encryption (also called symmetric key encryption) is analogous to a safe. You can store something secret through it and anyone who has the key can open it and view the contents. SecretBox functions as just such a safe, and like any good safe any attempts to tamper with the contents are easily detected.
Secret key encryption allows you to store or transmit data over insecure channels without leaking the contents of that message, nor anything about it other than the length.
import'package:pinenacl/api.dart';
import'package:pinenacl/x25519.dart'showSecretBox;
voidmain() {
print('\n### Secret Key Encryption - SecretBox Example ###\n');
final key = PineNaClUtils.randombytes(SecretBox.keyLength);
final box = SecretBox(key);
final message =
'Change is a tricky thing, it threatens what we find familiar with...';
final encrypted = box.encrypt(Uint8List.fromList(message.codeUnits));
final decrypted = box.decrypt(encrypted);
final ctext = encrypted.cipherText;
assert(ctext.length == message.length + SecretBox.macBytes);
final plaintext = String.fromCharCodes(decrypted);
print(plaintext);
assert(message == plaintext);
}
You can use a digital signature for many of the same reasons that you might sign a paper document. A valid digital signature gives a recipient reason to believe that the message was created by a known sender such that they cannot deny sending it (authentication and non-repudiation) and that the message was not altered in transit (integrity).
Digital signatures allow you to publish a public key, and then you can use your private signing key to sign messages. Others who have your public key can then use it to validate that your messages are actually authentic.
import'package:convert/convert.dart';
import'package:pinenacl/signing.dart';
voidmain() {
/// /// Signer’s perspective (SigningKey)///// Generate a new random signing keyfinal signingKey = SigningKey.generate();
final message = 'People see the things they want to see...';
// Sign a message with the signing keyfinal signed = signingKey.sign(message.codeUnits);
// Obtain the verify key for a given signing keyfinal verifyKey = signingKey.verifyKey;
// Serialize the verify key to send it to a third partyfinal verifyKeyHex = hex.encode(verifyKey);
/// /// Verifier’s perspective (VerifyKey)/// final verifyKey2 = VerifyKey.fromHexString(verifyKeyHex);
assert(verifyKey == verifyKey2);
print('The "$message" is successfully verified');
// Check the validity of a message's signature// The message and the signature can either be passed separately or// concatenated together. These are equivalent:
verifyKey.verify(signed);
verifyKey.verify(signed.message, signed.signature);
// Alter the signed message text
signed[0] ^= signed[0] + 1;
try {
// Forged message.
verifyKey.verify(signed);
} onExceptioncatch(e) {
print('Successfully cought: $e');
}
}
Cryptographic secure hash functions are irreversible transforms of input data to a fixed length digest.
The standard properties of a cryptographic hash make these functions useful both for standalone usage as data integrity checkers, as well as black-box building blocks of other kind of algorithms and data structures.
All of the hash functions exposed in hashing can be used as data integrity checkers.
As already hinted above, traditional cryptographic hash functions can be used as building blocks for other uses, typically combining a secret-key with the message via some construct like the HMAC one.
The blake2b hash function can be used directly both for message authentication and key derivation, replacing the HMAC construct and the HKDF one by setting the additional parameters key, salt and person.
Warning
Please note that key stretching procedures like HKDF or the one outlined in Key derivation are not suited to derive a cryptographically-strong key from a low-entropy input like a plain-text password or to compute a strong long-term stored hash used as password verifier.
...
voidmain() {
final hasher = Hash.blake2b;
print('Hash example\nH(\'\'): ${hex.encode(hasher(''))}');
Message authentication
To authenticate a message, using a secret key, the blake2b function must be called as in the following example.
/// It can ganarate a MAC to be sure that the message is not forged.final msg = '256 BytesMessage' * 16;
// the simplest way to get a cryptographic quality authKey// is to generate it with a cryptographic quality// random number generatorfinal authKey = Utils.randombytes(64);
final mac = hasher(msg, key: authKey);
print('MAC(msg, authKey): ${hex.encode(mac)}.\n');
Key derivation
The blake2b algorithm can replace a key derivation function by following the lines of:
print('Key derivation example');
final masterKey = Utils.randombytes(64);
final derivationSalt = Utils.randombytes(16);
final personalisation = Uint8List.fromList('<DK usage>'.codeUnits);
final subKey = hasher('', key: masterKey, salt: derivationSalt, personalisation: personalisation);
print('KDF(\'\', masterKey, salt, personalisation): ${hex.encode(subKey)}');
By repeating the key derivation procedure before encrypting our messages, and sending the derivationSalt along with the encrypted message, we can expect to never reuse a key, drastically reducing the risks which ensue from such a reuse.
TODOS
[ ] Important: refactor for working in 32-bit systems and browser (js).
[ ] Implement proper Error/Exception handling.
[x] Implement encoding/decoding) classes.
[x] Add more unit tests.
[x] Refactor to much simpler code.
[x] Simplify or refactor the APIs and modules' dependencies.
[x] Remove [bech32], [hex] and [convert] pakages dependency.
[x] Remove [fixnum] pakage dependency.
[x] Add Ed25519 to X25519 function, to allow Ed25519 to be used in
authenticated encryption too, see note below.
[ ] Refactor hashers to have some similar methods such: init(), update(), finalize() etc.
[x] Refactor key derivation function to be able to use diff hmacs.
[x] Optimise SHA-256 for faster execution. Done 5 time faster now 0.41 sec instead of 3.1 sec for 256K iterations.
[ ] Optimise SHA-512 for faster execution.
[x] Add some benchmark files.
[ ] IMPORTANT. refactor, rewrite source code for security auditing.
Note: Ed25519 keys that are used only for digital signatures (EdDSA), can be
converted to Curve25519/X25519 key (that is used only for authenticated encryption i.e.
ECDH), therefore the same key pairs can be used for
digital signatures (EdDSA), as it's already used, using crypto_sign and