pinenacl 0.1.3-dev.1

  • Readme
  • Changelog
  • Installing
  • 79

PineNaCl #

pub package

PineNaCl is a Dart implementation of the TweetNaCl the world's first auditable high-security cryptographic library.

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 #

  1. Add the following into the pubspec.yaml of your dart package:
  pinenacl: ^0.1.3-dev.1
  1. You can install now from the command line with pub:
$ pub get
  1. In your Dart code, you can use the similar:
import 'package:pinenacl/api.dart';
import 'package:pinenacl/public.dart';

Features #

PineNaCl reuses a lot of terminologies, concepts, sections of documents and implements examples and some features from, the before mentioned PyNaCl's publicly available

Implemented features:

  • ECDH (with Curve25519) for key exchange
    • Public-key Encryption
      • Box (public-key authenticated encryption) and
      • SealedBox
    • Private-key encryption
      • SecretBox (private-key authenticated encryption)
  • EdDSA for Digital signatures (signing).
    • 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.

Low-level Functions supported by PineNaCl #

This library supports all 25 of the C NaCl functions, that can be used to build NaCl applications.

  1. crypto_box = crypto_box_curve25519xsalsa20poly1305
  2. crypto_box_open
  3. crypto_box_keypair
  4. crypto_box_beforenm
  5. crypto_box_afternm
  6. crypto_box_open_afternm
  7. crypto_core_salsa20
  8. crypto_core_hsalsa20
  9. crypto_hashblocks = crypto_hashblocks_sha512
  10. crypto_hash = crypto_hash_sha512
  11. crypto_onetimeauth = crypto_onetimeauth_poly1305
  12. crypto_onetimeauth_verify
  13. crypto_scalarmult = crypto_scalarmult_curve25519
  14. crypto_scalarmult_base
  15. crypto_secretbox = crypto_secretbox_xsalsa20poly1305
  16. crypto_secretbox_open
  17. crypto_sign = crypto_sign_ed25519
  18. crypto_sign_keypair
  19. crypto_sign_open
  20. crypto_stream = crypto_stream_xsalsa20
  21. crypto_stream_salsa20
  22. crypto_stream_salsa20_xor
  23. crypto_stream_xor
  24. crypto_verify_16
  25. crypto_verify_32

However a simple NaCl application would only need the following six high-level NaCl API functions.

  • crypto_box for public-key authenticated encryption;
  • crypto_box_open for verification and decryption;
  • crypto_box_keypair to create a public key (scalarmult k with basepoint B=9) for key exchange.

Similarly for signatures

  • crypto_sign,
  • crypto_sign_open, and
  • crypto_sign_keypair, to create signing keypair for signing (scalarmult k with basepoint B=(x, 4/5))

Extension to the TweetNaCl #

The following NaCl library's high-level functions are implemented as the extension to the TweetNaCl library.

  1. crypto_auth - HMAC-SHA-512 (NaCl uses HMAC-SHA-512/256)
  2. crypto_auth_verify
  3. scalar_base - for retriving public key A, e.g. A = kB.

Examples #

PineNaCl comes /w the following examples:

Public Key Encryption example #

Implemented from PyNaCl's example


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.

-- PyNaCl

import 'package:pinenacl/api.dart';
import 'package:pinenacl/public.dart' show PrivateKey;

void main() {
  // Generate Bob's private key, which must be kept secret
  final skbob = PrivateKey.generate();

  // Bob's public key can be given to anyone wishing to send
  // Bob an encrypted message
  final pkbob = skbob.publicKey;

  // Alice does the same and then Alice and Bob exchange public keys
  final 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 key
  final 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 message
  final 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);


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.


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.

-- PyNaCl

import 'package:pinenacl/public.dart' show SealedBox, PrivateKey;

void main() {

  // Generate Bob's private key, which must be kept secret
  final 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);
  assert(message == String.fromCharCodes(plainText));

A Secret Key Encryption example #

Implemented from PyNaCl's example


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.

-- PyNaCl

import 'package:pinenacl/api.dart';
import 'package:pinenacl/secret.dart' show SecretBox;

void main() {
  final key = Utils.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(message.codeUnits);

  final decrypted = box.decrypt(encrypted);

  final ctext = encrypted.ciphertext;

  assert(ctext.length == message.length + SecretBox.macBytes);

  final plaintext = String.fromCharCodes(decrypted.plaintext);
  assert(message == plaintext);

Digital Signatures example #

Implemented from PyNaCl's example


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.

-- PyNaCl

import 'package:convert/convert.dart';
import 'package:pinenacl/signing.dart';

void main() {
  /// Signer’s perspective (SigningKey)
  // Generate a new random signing key
  final signingKey = SigningKey.generate();

  final message = 'People see the things they want to see...';
  // Sign a message with the signing key
  final signed = signingKey.sign(message.codeUnits);

  //  Obtain the verify key for a given signing key
  final verifyKey = signingKey.verifyKey;

  // Serialize the verify key to send it to a third party
  // TODO: implements similar: verifyKey.encode(Bech32Encoder(hrp: 'ed25519_pk'));
  final verifyKeyHex = hex.encode(verifyKey);

  /// Verifier’s perspective (VerifyKey)
  // TODO: implements similar: VerifyKey.decode(verifyKeyHex, decoder: HexEncoder());
  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.message, signed.signature);

  // Alter the signed message text
  signed[0] ^= signed[0] + 1;

  try {
    // Forged message.
  } on Exception catch(e) {
    print('Successfully cought: $e');

Hashing example #

Implemented from PyNaCl's example

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.

-- PyNaCl

Blake2b #

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.


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.

-- PyNaCl


void main() {

  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 generator
  final 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.


  • [ ] Implement proper Error/Exception handling.
  • [ ] Implement encoding/decoding) classes.
  • [ ] Add more unit tests.
  • [ ] Refactor to much simpler code.
  • [ ] Simplify or refactor the APIs and modules' dependencies.
  • [ ] Remove [fixnum] and [convert] pakages' dependency.

Thanks and Credits #

License #

0.1.0-dev.1 #

  • The initial draft version.

0.1.0 #

  • Added the byte-length official SHA-512 test vectors.
  • Added hashing example
  • Allowed personalisation paramater to be less then 16 bytes long by zero-padding to 16 bytes.

0.1.1-dev.1 #

  • Added the Curve25519's official DH (Diffie-Hellman) test vector.
  • Added the Wycheproof's X25519 test vectors.

0.1.1-dev.2 #

  • Refactored the EncryptionMessage classes

0.1.1 #

  • Refactored the library for using a simplified API.
  • Refactored AsymmetricKey and AsymmetricPrivateKey classes.
  • Refactored ByteList to be unmodofiable
  • Refactored EncrytpionMessage based classes e.g. EncryptedMessage, SealedMessage and SignedMessage.
  • Refactored SigningKey and VerifyKey by adding Sign and Verify interfaces.
  • Bumped version to 0.1.1

0.1.2-dev.1 #

  • Added Class diagrams.
  • Added ByteList's immutability tests.

0.1.2-dev.2 #

  • Added TweetNaclExt (Extension) class, that implements the HMAC-SHA-512's based crypto_auth and crypto_auth_verify functions of the NaCl library (does not exists in TweetNaCl).
  • Added HMAC-SHA-512.
  • Added HMAC-SHA-512 unit tests.
  • Added some TweetNaCl's tests.
  • Cleaned some code.
  • Fixed exports.
  • Renamed _EncryptionMessage class to SuffixByteList.
  • Fixed ByteList's constructor

0.1.2-dev.3 #

  • Added SHA-256.
  • Added SHA-256 unit tests with the official testvectors.
  • Fixed some typos.
  • Added scalar_base for Ed25519Bip32 compatibility
  • Added Encoding classes.
  • Renamed ed25519_vectors.json (RFC8032's EdDSA) to eddsa_ed25519_vectors.json.

0.1.2-dev.4 #

  • Refactored SuffixByteList class to Suffix mixin.
  • Updated (added HMAC, SHA-256)
  • Refactored the Encoding classes.
  • Swapped Bech32 to the github version, as pub package does not have custom length for messages.

0.1.2 #

  • Complete refactor of the API and the base classes.
  • Added API class diagrams.
  • Swapped Bech32 back to the latest and working pub package.
  • Refactored the decode factories.

0.1.3-dev.1 #

  • Added constructor for EncryptedMessage class, see ilap/pinenacl-dart#3

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  pinenacl: ^0.1.3-dev.1

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:pinenacl/api.dart';
import 'package:pinenacl/crypto/blake2b.dart';
import 'package:pinenacl/crypto/hmac_sha512.dart';
import 'package:pinenacl/crypto/poly1305.dart';
import 'package:pinenacl/crypto/sha_256.dart';
import 'package:pinenacl/crypto/tweetnacl.dart';
import 'package:pinenacl/crypto/tweetnacl_ext.dart';
import 'package:pinenacl/encoding.dart';
import 'package:pinenacl/hashing.dart';
import 'package:pinenacl/public.dart';
import 'package:pinenacl/secret.dart';
import 'package:pinenacl/signing.dart';
import 'package:pinenacl/utils.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Mar 10, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.5

Health suggestions

Format lib/src/api/key_encryption.dart.

Run dartfmt to format lib/src/api/key_encryption.dart.

Maintenance suggestions

Package is pre-release. (-5 points)

Pre-release versions should be used with caution; their API can change in breaking ways.

Maintain an example.

None of the files in the package's example/ directory matches known example patterns.

Common filename patterns include main.dart, example.dart, and pinenacl.dart. Packages with multiple examples should provide example/

For more information see the pub package layout conventions.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
bech32 ^0.1.2 0.1.2
convert ^2.0.2 2.1.1
fixnum ^0.10.9 0.10.11
Transitive dependencies
charcode 1.1.3
typed_data 1.1.6
Dev dependencies
pedantic ^1.8.0+1
test ^1.0.0