Coder Social home page Coder Social logo

dchest / tweetnacl-js Goto Github PK

View Code? Open in Web Editor NEW
1.7K 44.0 293.0 4.1 MB

Port of TweetNaCl cryptographic library to JavaScript

Home Page: https://tweetnacl.js.org

License: The Unlicense

JavaScript 98.28% HTML 0.06% Makefile 0.02% C 1.51% Go 0.13%
crypto javascript authentication signature elliptic-curves secretbox djb salsa20 curve25519 eddsa

tweetnacl-js's Introduction

TweetNaCl.js

Port of TweetNaCl / NaCl to JavaScript for modern browsers and Node.js. Public domain.

Demo: https://dchest.github.io/tweetnacl-js/

Documentation

Overview

The primary goal of this project is to produce a translation of TweetNaCl to JavaScript which is as close as possible to the original C implementation, plus a thin layer of idiomatic high-level API on top of it.

There are two versions, you can use either of them:

  • nacl.js is the port of TweetNaCl with minimum differences from the original + high-level API.

  • nacl-fast.js is like nacl.js, but with some functions replaced with faster versions. (Used by default when importing NPM package.)

Audits

TweetNaCl.js has been audited by Cure53 in January-February 2017 (audit was sponsored by Deletype):

The overall outcome of this audit signals a particularly positive assessment for TweetNaCl-js, as the testing team was unable to find any security problems in the library.

Read full audit report

While the audit didn't find any bugs, there has been 1 bug discovered and fixed after the audit.

Security Considerations

It is important to note that TweetNaCl.js is a low-level library that doesn't provide complete security protocols. When designing protocols, you should carefully consider various properties of underlying primitives.

No secret key commitment

While XSalsa20-Poly1305, as used in nacl.secretbox and nacl.box, meets the standard notions of privacy and authenticity for a secret-key authenticated-encryption scheme using nonces, it is not key-committing, which means that it is possible to find a ciphertext which decrypts to valid plaintexts under two different keys. This may lead to vulnerabilities if encrypted messages are used in a context where key commitment is expected.

Signature malleability

While Ed22519 as originally defined and implemented in nacl.sign meets the standard notion of unforgeability for a public-key signature scheme under chosen-message attacks, it is malleable: given a signed message, it is possible, without knowing the secret key, to create a different signature for the same message that will verify under the same public key. This may lead to vulnerabilities if signatures are used in a context where malleability is not expected.

Hash length-extension attacks

The SHA-512 hash function, as implemented by nacl.hash, is not resistant to length-extension attacks.

Side-channel attacks

While TweetNaCl.js uses algorithmic constant-time operations, it is impossible to guarantee that they are physically constant time given JavaScript runtimes, JIT compilers, and other factors. It is also impossible to guarantee that secret data is physically removed from memory during cleanup due to copying garbage collectors and optimizing compilers.

Installation

You can install TweetNaCl.js via a package manager:

Yarn:

$ yarn add tweetnacl

NPM:

$ npm install tweetnacl

or download source code.

Examples

You can find usage examples in our wiki.

Usage

All API functions accept and return bytes as Uint8Arrays. If you need to encode or decode strings, use functions from https://github.com/dchest/tweetnacl-util-js or one of the more robust codec packages.

In Node.js v4 and later Buffer objects are backed by Uint8Arrays, so you can freely pass them to TweetNaCl.js functions as arguments. The returned objects are still Uint8Arrays, so if you need Buffers, you'll have to convert them manually; make sure to convert using copying: Buffer.from(array) (or new Buffer(array) in Node.js v4 or earlier), instead of sharing: Buffer.from(array.buffer) (or new Buffer(array.buffer) Node 4 or earlier), because some functions return subarrays of their buffers.

Public-key authenticated encryption (box)

Implements x25519-xsalsa20-poly1305.

nacl.box.keyPair()

Generates a new random key pair for box and returns it as an object with publicKey and secretKey members:

{
   publicKey: ...,  // Uint8Array with 32-byte public key
   secretKey: ...   // Uint8Array with 32-byte secret key
}

nacl.box.keyPair.fromSecretKey(secretKey)

Returns a key pair for box with public key corresponding to the given secret key.

nacl.box(message, nonce, theirPublicKey, mySecretKey)

Encrypts and authenticates message using peer's public key, our secret key, and the given nonce, which must be unique for each distinct message for a key pair.

Returns an encrypted and authenticated message, which is nacl.box.overheadLength longer than the original message.

nacl.box.open(box, nonce, theirPublicKey, mySecretKey)

Authenticates and decrypts the given box with peer's public key, our secret key, and the given nonce.

Returns the original message, or null if authentication fails.

nacl.box.before(theirPublicKey, mySecretKey)

Returns a precomputed shared key which can be used in nacl.box.after and nacl.box.open.after.

nacl.box.after(message, nonce, sharedKey)

Same as nacl.box, but uses a shared key precomputed with nacl.box.before.

nacl.box.open.after(box, nonce, sharedKey)

Same as nacl.box.open, but uses a shared key precomputed with nacl.box.before.

Constants

nacl.box.publicKeyLength = 32

Length of public key in bytes.

nacl.box.secretKeyLength = 32

Length of secret key in bytes.

nacl.box.sharedKeyLength = 32

Length of precomputed shared key in bytes.

nacl.box.nonceLength = 24

Length of nonce in bytes.

nacl.box.overheadLength = 16

Length of overhead added to box compared to original message.

Secret-key authenticated encryption (secretbox)

Implements xsalsa20-poly1305.

nacl.secretbox(message, nonce, key)

Encrypts and authenticates message using the key and the nonce. The nonce must be unique for each distinct message for this key.

Returns an encrypted and authenticated message, which is nacl.secretbox.overheadLength longer than the original message.

nacl.secretbox.open(box, nonce, key)

Authenticates and decrypts the given secret box using the key and the nonce.

Returns the original message, or null if authentication fails.

Constants

nacl.secretbox.keyLength = 32

Length of key in bytes.

nacl.secretbox.nonceLength = 24

Length of nonce in bytes.

nacl.secretbox.overheadLength = 16

Length of overhead added to secret box compared to original message.

Scalar multiplication

Implements x25519.

nacl.scalarMult(n, p)

Multiplies an integer n by a group element p and returns the resulting group element.

nacl.scalarMult.base(n)

Multiplies an integer n by a standard group element and returns the resulting group element.

Constants

nacl.scalarMult.scalarLength = 32

Length of scalar in bytes.

nacl.scalarMult.groupElementLength = 32

Length of group element in bytes.

Signatures

Implements ed25519.

nacl.sign.keyPair()

Generates new random key pair for signing and returns it as an object with publicKey and secretKey members:

{
   publicKey: ...,  // Uint8Array with 32-byte public key
   secretKey: ...   // Uint8Array with 64-byte secret key
}

nacl.sign.keyPair.fromSecretKey(secretKey)

Returns a signing key pair with public key corresponding to the given 64-byte secret key. The secret key must have been generated by nacl.sign.keyPair or nacl.sign.keyPair.fromSeed.

nacl.sign.keyPair.fromSeed(seed)

Returns a new signing key pair generated deterministically from a 32-byte seed. The seed must contain enough entropy to be secure. This method is not recommended for general use: instead, use nacl.sign.keyPair to generate a new key pair from a random seed.

nacl.sign(message, secretKey)

Signs the message using the secret key and returns a signed message.

nacl.sign.open(signedMessage, publicKey)

Verifies the signed message and returns the message without signature.

Returns null if verification failed.

nacl.sign.detached(message, secretKey)

Signs the message using the secret key and returns a signature.

nacl.sign.detached.verify(message, signature, publicKey)

Verifies the signature for the message and returns true if verification succeeded or false if it failed.

Constants

nacl.sign.publicKeyLength = 32

Length of signing public key in bytes.

nacl.sign.secretKeyLength = 64

Length of signing secret key in bytes.

nacl.sign.seedLength = 32

Length of seed for nacl.sign.keyPair.fromSeed in bytes.

nacl.sign.signatureLength = 64

Length of signature in bytes.

Hashing

Implements SHA-512.

nacl.hash(message)

Returns SHA-512 hash of the message.

Constants

nacl.hash.hashLength = 64

Length of hash in bytes.

Random bytes generation

nacl.randomBytes(length)

Returns a Uint8Array of the given length containing random bytes of cryptographic quality.

Implementation note

TweetNaCl.js uses the following methods to generate random bytes, depending on the platform it runs on:

  • window.crypto.getRandomValues (WebCrypto standard)
  • window.msCrypto.getRandomValues (Internet Explorer 11)
  • crypto.randomBytes (Node.js)

If the platform doesn't provide a suitable PRNG, the following functions, which require random numbers, will throw exception:

  • nacl.randomBytes
  • nacl.box.keyPair
  • nacl.sign.keyPair

Other functions are deterministic and will continue working.

If a platform you are targeting doesn't implement secure random number generator, but you somehow have a cryptographically-strong source of entropy (not Math.random!), and you know what you are doing, you can plug it into TweetNaCl.js like this:

nacl.setPRNG(function(x, n) {
  // ... copy n random bytes into x ...
});

Note that nacl.setPRNG completely replaces internal random byte generator with the one provided.

Constant-time comparison

nacl.verify(x, y)

Compares x and y in constant time and returns true if their lengths are non-zero and equal, and their contents are equal.

Returns false if either of the arguments has zero length, or arguments have different lengths, or their contents differ.

System requirements

TweetNaCl.js supports modern browsers that have a cryptographically secure pseudorandom number generator and typed arrays, including the latest versions of:

  • Chrome
  • Firefox
  • Safari (Mac, iOS)
  • Internet Explorer 11

Other systems:

  • Node.js

Development and testing

Install NPM modules needed for development:

$ npm install

To build minified versions:

$ npm run build

Tests use minified version, so make sure to rebuild it every time you change nacl.js or nacl-fast.js.

Testing

To run tests in Node.js:

$ npm run test-node

By default all tests described here work on nacl.min.js. To test other versions, set environment variable NACL_SRC to the file name you want to test. For example, the following command will test fast minified version:

$ NACL_SRC=nacl-fast.min.js npm run test-node

To run full suite of tests in Node.js, including comparing outputs of JavaScript port to outputs of the original C version:

$ npm run test-node-all

To prepare tests for browsers:

$ npm run build-test-browser

and then open test/browser/test.html (or test/browser/test-fast.html) to run them.

To run tests in both Node and Electron:

$ npm test

Benchmarking

To run benchmarks in Node.js:

$ npm run bench
$ NACL_SRC=nacl-fast.min.js npm run bench

To run benchmarks in a browser, open test/benchmark/bench.html (or test/benchmark/bench-fast.html).

Benchmarks

For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X, Xiaomi Redmi Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in Chrome 52/Android, and MacBook Air 2020 with Apple M1 SOC (M1) in Chromium 102/macOS.

nacl.js Intel nacl-fast.js Intel nacl.js ARM nacl-fast.js ARM nacl-fast.js M1
salsa20 1.3 MB/s 128 MB/s 0.4 MB/s 43 MB/s 268 MB/s
poly1305 13 MB/s 171 MB/s 4 MB/s 52 MB/s 248 MB/s
hash 4 MB/s 34 MB/s 0.9 MB/s 12 MB/s 76 MB/s
secretbox 1K 1113 op/s 57583 op/s 334 op/s 14227 op/s 54546 op/s
box 1K 145 op/s 718 op/s 37 op/s 368 op/s 1836 op/s
scalarMult 171 op/s 733 op/s 56 op/s 380 op/s 1882 op/s
sign 77 op/s 200 op/s 20 op/s 61 op/s 592 op/s
sign.open 39 op/s 102 op/s 11 op/s 31 op/s 300 op/s

(You can run benchmarks on your devices by clicking on the links at the bottom of the home page).

In short, with nacl-fast.js and 1024-byte messages you can expect to encrypt and authenticate more than 57000 messages per second on a typical laptop or more than 14000 messages per second on a $170 smartphone, sign about 500 and verify 300 messages per second on a laptop or 60 and 30 messages per second on a smartphone, per CPU core (with Web Workers you can do these operations in parallel), which is good enough for most applications.

Contributors

See AUTHORS.md file.

Third-party libraries based on TweetNaCl.js

Who uses it

Some notable users of TweetNaCl.js are listed on the associated wiki page.

tweetnacl-js's People

Contributors

alexendoo avatar andsdev avatar cmeone avatar dbrgn avatar dchest avatar devi avatar karlhorky avatar kevinlewi avatar lostfictions avatar marin-liovic avatar mvasilkov avatar nadimkobeissi avatar whs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tweetnacl-js's Issues

Replace console.log in tests/test.js

We need a way to log onto the web page instead of the console when running in a browser, because iPhone requires connection to computer with Xcode running to access the console. The replacement should also work in Node.

Need a better module wrapping

We need something like UMD for module wrapping with these features:

  • Global nacl/window.nacl.
  • CommonJS:
    • Node.js, with PRNG using require('crypto')
    • Browserify/Webpack using WebCrypto, not require('crypto') emulation (without this workaround).
  • AMD
  • root object inside the module, which can be null or undefined for Node, window for browsers, self (?) for webworkers in browsers (to fix #65)

Add nacl.verify() function

Add a constant-time comparison function to high-level API.

Possible names:

nacl.verifyBytes
nacl.bytesEqual
nacl.constantTimeEqual

Returns true or false.

Unsigning failing on a particular example

Firstly, I love your work. Your library is a pleasure to use. Forgive me if I've done anything stupid. I'm trying to get a simple signing example working, but the unsign always returns null (the crypto_verify_32 is failing) I've got a small test example with the latest nacl.js at:
https://jsfiddle.net/p0028d2b/
Any help is very much appreciated.

synchronous key derivation function?

I'd like to be able to use tweetnacl-js starting with user-supplied passwords, which then are inflated to 256 bits by some sort of KDF. The one I like the most is scrypt, and the best implementation I've been able to find is yours, but it is asynchronous and I need it to be synchronous (even at the expense of waiting) because there is a lot of code that follows the KDF.

Sometimes the KDF needs to be called several times before the algorithm is done, which makes asynchronous a nightmare. Is there a synchronous KDF like scrypt that you can recommend?

Add nacl-fast.js

#16 replaced Curve25519 from NaCl/ref implementation with a slower version from TweetNaCl. Let's put that faster implementation + a faster version of XSalsa20 into a drop-in nacl-fast.js.

Please update NPM version

Excellent library! Please update the version on NPM to the latest (it seems that the NPM version is missing some features)

Investigate potential bug in Node.js v0.10.28 causing test failure

t = new fg() instead of t = [] in pack25519() triggers a bug which makes sign.js test fail on a 29-byte message, e.g.:

Test #29 (Message length: 28)
! signatures don't match
JS:  AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADtDRzyhc6uz7lIroznvUFMReBqlcn0R0kYe4NMUzmSAA== 
C :  CFZpi8eA8Y6UDrTAFApIYQkztCb5WY6OO1++QmOyDb24qb1qBgmAtdy1d/VozxpDEvS86N1UyrVYVkZEqUnlDw==

I believe it is a bug in Node.js v0.10.x, because:

  • setting t to [] instead of new gf() fixes it;
  • reversing the loop copying n to t (i=16; i >=0; i--) fixes it;
  • inserting console.log(t) or console.log(n) anywhere in the function fixes it;
  • inserting console.log(sig) in test after nacl.sign fixes it.
  • directly testing the failing message (see test.js) works;
  • starting test from e.g. 10 instead of 0 fixes it;
  • running under Node.js v0.11.9 fixes it.

Since test is running a child process, I believe the bug may be caused by a race condition resulting in memory corruption (notice the first part of signature is all zeros AAAA...).

We need to investigate this further, as the probability of discovering compiler bug is smaller than the probability that our own code has a bug. Meanwhile, I chose to use the first workaround (t = []).

SPDX License

For help with npm, switch the license over to "CC0-1.0" for the public domain dedication in package.json.

TypeError: unexpected type [object String], use Uint8Array

I am working first time in security using nodejs library's and i am using example code and getting this error

/sysusers/tradeboox/node_modules/ed2curve/node_modules/tweetnacl/nacl.js:941
throw new TypeError('unexpected type ' + t + ', use Uint8Array');
^
TypeError: unexpected type [object String], use Uint8Array
at checkArrayTypes (/sysusers/tradeboox/node_modules/ed2curve/node_modules/tweetnacl/nacl.js:941:14)
at Function.nacl.sign.open (/sysusers/tradeboox/node_modules/ed2curve/node_modules/tweetnacl/nacl.js:1090:3)
at Object. (/sysusers/tradeboox/E1.js:23:30)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3

My code is

// Generate new sign key pair.
var nacl = require("/sysusers/tradeboox/node_modules/ed2curve/node_modules/tweetnacl/nacl.js");
var myKeyPair = nacl.sign.keyPair();

// Share public key with a peer.
console.log(myKeyPair.publicKey);

// Receive peer's public key.
var theirPublicKey = myKeyPair.publicKey ;
// ... receive

// Sign a message.
var message = nacl.util.decodeUTF8('Hello!');
var signedMessage = nacl.sign(message, myKeyPair.secretKey);

// Send message to peer. They can now verify it using
// the previously shared public key (myKeyPair.publicKey).
// ...

// Receive a signed message from peer and verify it using their public key.
var theirSignedMessage = 'Hello Worlds Atul Jain';
// ... receive
var theirMessage = nacl.sign.open(theirSignedMessage, theirPublicKey);
if (theirMessage) {
// ... we got the message ...
}

// Encrypt a message to their public key.
// But first, we need to convert our secret key and their public key
// from Ed25519 into the format accepted by Curve25519.
//
// Note that peers are not involved in this conversion -- all they need
// to know is the signing public key that we already shared with them.

var theirDHPublicKey = ed2curve.convertPublicKey(theirPublicKey);
var myDHSecretKey = ed2curve.convertSecretKey(myKeyPair.secretKey);

var anotherMessage = nacl.util.decodeUTF8('Keep silence');
var encryptedMessage = nacl.box(anotherMessage, theirDHPublicKey, myDHSecretKey);

// When we receive encrypted messages from peers,
// we need to use converted keys to open them.

var theirEncryptedMessage = '';
// ... receive
var decryptedMessage = nacl.box.open(theirEncryptedMessage, theirDHPublicKey, myDHSecretKey);

Safe against cryptographic attacks?

I'm building a mobile application with Javascript, and I need to know if this library employs protection against cryptographic attacks such as Side Channel Attacks (Timing Attack, Power Monitoring Attack, Differential fault analysis, Data remanence, Row hammer..), Chosen-plaintext Attacks‎ (BREACH, CRIME..). If that's not the case I will implement them myself.

no way to change constants

nacl.box.keyPair = function() {
  var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
  crypto_box_keypair(pk, sk);
  return {publicKey: pk, secretKey: sk};
};

why not use this.box.publickeybytes?

UTF-8 codec functions are named the wrong way round

Hi, in the context of UTF-8, "encode" is generally taken to mean string (of unicode characters, like in JS) -> [byte], and "decode" means [byte] -> string. Every single other API in existence has these semantics.

Even the implementation gives a clue - nacl.util.decodeUTF8 calls unescape(encodeURIComponent(s)), which is the standard JS way to encode a Unicode string into a "UTF-8 string" where each 16-bit character has only 8 semantic bits and the higher 8 bits are not set.

Please deprecate this API and create a new API with correct names, before this turns into a hilariously bad security hole.

Remove low-level API?

Do we even need nacl.lowlevel? Everything is already provided in the high-level API, which is easier and safer to use.

Rewrite high-level API

High-level API accepts plain strings or arrays of bytes for messages, base64-encoded strings or arrays of bytes for boxes, keys, and maybe nonces. Opening boxes returns strings, but then if we encrypted array of bytes with invalid utf8 strings, we get exceptions...

Let's get rid of all this craziness and switch to Uint8Arrays everywhere, and provide base64 utilities as a bonus.

Proposal for nacl.sign API change (next version)

I'd like to change the signature API sometime in the future to this:

nacl.sign(message, secretKey) -> signedMessage
nacl.sign.open(signedMessage, publicKey) -> message | null

(Maybe instead of null, return false when verification fails? null makes more sense to me in this case)

Basically, this is how signatures in NaCl/TweetNaCl work.

But since everyone likes to have signatures separate from messages ("detached signatures"), we will add the following new methods to get the behavior similar, but not identical, to what we currently have:

nacl.sign.detached(message, secretKey) -> signature
nacl.sign.detached.verify(message, signature, publicKey) -> true | false

Note that it's verify and not open, because it returns only true or false, not the "unsigned" message or false like nacl.sign.open.

This is inspired by libsodium.

Compatibility

This would require major version bump (to 1.0.0, argh) according to semver principles.

To deliberately break apps which upgraded to 1.0.0 without changing code, we can throw exception if nacl.sign.open is called with 3 arguments. We can do nothing with nacl.sign, though: instead of just signature it will return signed message. This isn't dangerous. I don't think there's enough users right now anyway to cause headaches :)

Comments?

Provide functions to get public keys from secret keys.

nacl.box.keyPair.fromSecretKey(secretKey) => // returns key pair
nacl.sign.keyPair.fromSecretKey(secretKey) => // -"-

Implementation of the first one is easy:

exports.box.keyPair.fromSecretKey = function(secretKey) {
  checkArrayTypes(secretKey);
  if (secretKey.length !== crypto_box_SECRETKEYBYTES)
    throw new Error('bad secret key size');
  var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  crypto_scalarmult_base(pk, secretKey);
  return {publicKey: pk, secretKey: secretKey};
};

~~Sign will be ~copy of crypto_sign_keypair, which is ugly, but I don't want to refactor tweenacl.c-based code.~~ (Don't file issues when ill! Sign public key is just the second 32-byte part of the secret key).

Multiplication of 32 bit ints is not following mod 2^32 bits, like does in C

In C, when int32 is multiplied with int32, overflowing, operation works as multiplication mod 2^32 bits. I.e. in C a_b === a_b mod 2^32.

Do run https://github.com/3nsoft/ecma-nacl/blob/master/tests/util/int32.js in node. It shows that in JS, for some values a_b === a_b mod 2^32, and a_b !== a_b mod 2^32 for others.
It has to do with JS treating numbers the same way, irrespective of whether they come from Uint32Array, or not, -- all are treated as JS numbers (60 bits + funky stuff?).

I can see that your code simply uses multiplication. It might be not very good.

Also, add tests, which will take huge amount of random inputs and go through your code and https://github.com/tonyg/js-nacl which would be the fastest way to reproduces strict functional comparison with original C code.
I'd love to have a test vector, which will make current code fail, but I only have a theoretical reason that it may fail. Yet, I see no way to prove, that it won't fail.

Bad signatures in JavaScriptCore

Signatures generated in Safari on iOS 7.1.1 (11D201) are non-deterministic: on demo page, clicking "Sign" will give (two?) different results.

Here's an example of incorrect signature that was generated:

Secret key:
hsOCXS8UNr83yghuNxev6jtg+GjAB809TdzWcmrUTZ2zcPN70pBoFekEti9KAg4rvliDTRoGAux3zcC0+gxRZQ==

Public Key:
s3Dze9KQaBXpBLYvSgIOK75Yg00aBgLsd83AtPoMUWU=

Signature:
h1zqNftia044SG02OkQbK8+rCXFTGiFHtcMiW42EhsOyyVXk+Ak/FqL4wt5OWMMGQGFAY+02viJlb2TQzXqmBA==

Message:
Hello world

In Chrome on the same iOS signatures are correct (note that Chrome uses the same JS engine, but without JIT).

This applies to both previous untyped version and the new one with typed arrays.

Question regarding license

Hello,

The CCO-1.0 license in tweetnacl-js makes it difficult to use the module and all of its dependents in an enterprise context. Would it be possible for the license to change to a license approved by Open Source Initiative (ie. MIT, Apache, BSD...)?

Thank you,
Mi Ji

Add nacl.sign.keyPair.fromSeed

This function will return a key pair generated from a seed (which should be random), instead of calling randombytes internally, which is what nacl.sign.keyPair does.

On one hand, there's currently no way to do what this function does without copying half of the library, on the other hand, it complicates code (and makes diff from tweenacl.c not so pretty) for an uncommon use case (which can also be dangerous if you're not careful with producing proper seeds, e.g. from passwords with weak derivation function).

Filed under "maybe".

TweetNaCl used in PassLok 2.2

I though you'd like to know that I'm using your impressive library in the new version of PassLok, which can be found here:
https://github.com/fruiz500/passlok
I'm also using scrypt-async (with the trick you suggested to make it synchronous), and ed2curve.
I'm listing you everywhere that credit is given, but please let me know if this is unsatisfactory.
Great job!

Allow use of nodejs Buffer objects instead of Uint8Array where applicable

Uint8Array is a great choice for browser-based apps like miniLock. In nodejs apps, the standard is to use node's Buffer system, which is used by many other npm libraries and in all IO including networks and local filesystem operations. While it is easy to convert types with new Uint8Array(buffer) and new Buffer(uint8array) these are both unsatisfying because both conversions create copies of data - not references. Copying can be slow for larger pieces of data, but maybe more importantly it means secrets like secretKeys and nonces end up being duplicated whenever a conversion is needed, leaving them floating around for garbage collection unless lots of care (and extra code) is written to zero those resources out. This provides a dangerous incentive for people to write less secure code. Even people with good intentions would have a difficult time keeping track of it all.

Skimming the tweetnacl-js source it seems like Buffer and Uint8Array both provide equivalent functionality for crypto uses. One difference is that node Buffers are not preinitialized with zeros. Buffers contain garbage data from system memory similar to a malloc. This provides a performance boost but might make detecting bugs more difficult when cryptographically random input is expected and sort-of random garbage data is erroneously received.

I'd like tweetnacl-js to offer a way to switch it from Uint8Array to Buffer objects, and I'd prefer it default to Buffer when it's available. Both Uint8Array and Buffer provide [] byte accessors and a 'length' property. I think that's all tweetnacl-js needs?

At a minimum, it would be helpful if functions like nacl.box() would accept Buffer objects as inputs. Converting the output would still be annoying, but not nearly as annoying as having to convert all the inputs and manage their safe erasure.

Avoid leaking secrets in to deallocated system memory

TweetNaCL-js isn't very careful in the way it stores and releases random numbers. The use of Uint8Array is a positive step because these arrays represent real memory and when zeroed out really do erase the data from RAM. Erasing random numbers and other secrets from RAM is worthwhile to prevent mallocs in this process and future processes from reading memory containing deallocated secrets. Malicious apps sometimes do huge mallocs to sample parts of ram and try to find secrets. Network protocols sometimes thoughtlessly allow remote access to uncleared sections of memory when they allow remote peers to request more data than they write in to their outgoing packet buffer. NodeJS apps are particularly susceptible to this in the context of tweetnacl-js because all networking is done using Buffer objects and Buffers are not automatically filled with zeros when created - they contain garbage data from system memory with a reasonable likelihood of occupying the same space as deallocated Uint8Arrays. Tweetnacl-js should take more advantage of the good defensive security practices Uint8Arrays enable. Reading through the code so far I've found these leaky areas:

In the default random number generators:

// browser platforms:
nacl.setPRNG(function(x, n) {
  var i, v = new Uint8Array(n);
  crypto.getRandomValues(v);
  for (i = 0; i < n; i++) x[i] = v[i];
});
// node-compatible platforms:
nacl.setPRNG(function(x, n) {
  var i, v = crypto.randomBytes(n);
  for (i = 0; i < n; i++) x[i] = v[i];
});

In both instances v[] is released by the garbage collector, presumably leaving all the contents in system memory. This could be solved by modifying the for loop:

for (i = 0; i < n; i++) {
  x[i] = v[i];
  v[i] = 0;
}

the various .keyPair() functions and their underlying C ports don't look leaky.

nacl.box.keyPair.fromSecretKey() and nacl.sign.keyPair.fromSecretKey() are less than ideal:

// last line of function pointlessly allocates another copy of the secretKey.
return {publicKey: pk, secretKey: new Uint8Array(secretKey)};

I was surprised by this. I thought Uint8Array and other typed arrays worked via reference to the same buffers, not copying. Turns out that's only true if you pass the buffer property to the constructor:

a = new Uint8Array([1,2,3]);
b = new Uint8Array(a);
c = new Uint8Array(a.buffer);
a[0] = 5;
// now b[0] is still 1
// c[0] is now 5, because they share the same buffer

I'd like tweetnacl-js to avoid creating copies of Uint8Arrays where it isn't strictly necessary to do so. When it is necessary to copy a Uint8Array or Buffer internally, it should fill those arrays with zeros as soon as it's done using them. Nothing that contains random bytes or something derived from them should end up deallocated by the garbage collector without being returned to the user. The README.md should mention this class of vulnerability and indicate how users can proactively defend against them, and the API should make it easy to do so.

New high-level API function names

Utilities

  • nacl.util.decodeBase64
  • nacl.util.encodeBase64
  • nacl.util.decodeUTF8
  • nacl.util.encodeUTF8

PRNG

  • nacl.randomBytes

Secretbox

  • nacl.secretbox
  • nacl.secretbox.open
  • nacl.secretbox.keyLength
  • nacl.secretbox.nonceLength

Box

  • nacl.box
  • nacl.box.open
  • nacl.box.before
  • nacl.box.after
  • nacl.box.open.after
  • nacl.box.keyPair
  • nacl.box.publicKeyLength
  • nacl.box.secretKeyLength
  • nacl.box.nonceLength

Signatures

  • nacl.sign
  • nacl.sign.open
  • nacl.sign.keyPair
  • nacl.sign.publicKeyLength
  • nacl.sign.secretKeyLength
  • nacl.sign.signatureLength

Hash

  • nacl.hash
  • nacl.hash.hashLength // or nacl.hash.length ?

Low-level

  • nacl.lowlevel.* // contains every low-level function

Add urlSafe option to base64

Additional optional boolean argument:

nacl.util.encodeBase64(arr, urlSafe)
nacl.util.decodeBase64(s, urlSafe)

to encode/decode using URL-safe encoding (changing + to -, / to _).

timing attacks

Your answer about whether this library protects against a timing side-channel attack is "Hopefully, as best as it could be done in JavaScript." in #73. Are you talking about https://github.com/dchest/tweetnacl-js#constant-time-comparison?

I wonder if any claim can be made about this library being safe from side-channels since it's an important part of the original NaCl source code and design and something that NaCl is known to protect against. People might not be aware of any differences in security of the C version of NaCl versus any port to a higher-level language.

Just opened up a related question with more references to the problem of JS crypto side-channel resistance in the libsodium.js issue tracker: jedisct1/libsodium.js#21

shorter/longer nonce

I see that a 24-byte length is hardcoded for the nonce value. But looking through the original NaCl paper, it appears that it doesn't need to be this way. I have an application where it would be advantageous to use a shorter nonce because of space limitations, and the 24 bytes eat too much of it.

Is there a way to specify a nonce length different from 24 bytes?

Forward secrecy / Axolotl

Hey guys, I've written a barebones javascript implementation of Axolotl that uses TweetNacl heavily internally. I'm just posting it here because it seems like there might be a lot of overlap between people using TweetNacl and people interested in forward secrecy / axolotl ratcheting.

https://github.com/alax/forward-secrecy

Thanks! 😄

Get signing public key from DH public key, for the same secret Key/seed

This is somewhat related to #46 but not quite. I would like the same secret key to work for DH and for signing. One way to do it is this:

  1. Generate a DH keypair with: nacl.box.keyPair()
  2. Get the signing secret key from the DH secret key as a seed:
    secretKey_sign = nacl.sign.keyPair.fromSeed(secretKey_DH),
    the first 32 bytes will be the same as secretKey_DH
  3. Get the signing public key from the signing secret key with: nacl.sign.keyPair.fromSecretKey(secretKey_sign)

Now, the signer can do this and end up with two different public keys to give out, but it would be cleaner if the rest of the world could get one public key from the other. I guess the main difficulty is that those are points on different curves: a Montgomery curve for DH, and an Edwards curve for signatures, so that the process might require reversing one of the secret key -> public key generation steps.

But since the two curves are intimately related, perhaps the two public keys are related in some way that would allow calculating one from the other directly. Is there a possibility of this?

Thanks!

C version uses i64 & u64 -- integers, but file has Float64Array's all over

nacl.js as well as nacl-fast.js have Float64Array's in places where i64 & u64 types are present in C code.

There are no floating point operations in NaCl. And JS's regular number, which happens to be float64, are OK to do 32 bits operation, with an exception of multiplication (as it has been said in #41 ). Yet, when C code has u64, the intention of C developers, I suppose, is to have/use all 64 bits in mod 64-bits arithmetic.

If you prove that it is OK to have float64 instead of u64, then such code will be provably correct. Otherwise, not-failing tests do not constitute such proof (unless it is run on all possible inputs).

Let's say with line 667 in nacl-fast:

function M(o, a, b) {
 var i, j, t = new Float64Array(31);
 for (i = 0; i < 31; i++) t[i] = 0;
 for (i = 0; i < 16; i++) {
   for (j = 0; j < 16; j++) {
     t[i+j] += a[i] * b[j];
   }
 }
 ...

Even if a's and b's are within 32 bits, where is a gauruntee that t's will not be rounded as a float, instead of overflowing as in integers.

tweetnacl-js incompatible with tweetnacl & nacl

box and secretbox are incompatible with the core nacl and tweetnacl releases as it does not zero padded the boxes although I don't quite understand why the core releases to this and prefect your implementation it make the library unusable as it is not interoperable with the core libraries

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.