Skip to content

Commit

Permalink
Removed unused hex2utf16le function
Browse files Browse the repository at this point in the history
  • Loading branch information
tinybike committed Apr 14, 2017
1 parent 5ff348e commit cdfece3
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 140 deletions.
114 changes: 64 additions & 50 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,37 @@
keythereum
==========
# keythereum

[![Build Status](https://travis-ci.org/ethereumjs/keythereum.svg?branch=master)](https://travis-ci.org/ethereumjs/keythereum)
[![Coverage Status](https://coveralls.io/repos/github/ethereumjs/keythereum/badge.svg?branch=master)](https://coveralls.io/github/ethereumjs/keythereum?branch=master)
[![npm version](https://badge.fury.io/js/keythereum.svg)](http://badge.fury.io/js/keythereum)
[![Build Status](https://travis-ci.org/ethereumjs/keythereum.svg?branch=master)](https://travis-ci.org/ethereumjs/keythereum) [![Coverage Status](https://coveralls.io/repos/github/ethereumjs/keythereum/badge.svg?branch=master)](https://coveralls.io/github/ethereumjs/keythereum?branch=master) [![npm version](https://badge.fury.io/js/keythereum.svg)](http://badge.fury.io/js/keythereum)

Keythereum is a JavaScript tool to generate, import and export Ethereum keys. This provides a simple way to use the same account locally and in web wallets. It can be used for verifiable cold storage wallets.

Keythereum uses the same key derivation functions (PBKDF2-SHA256 or scrypt), symmetric ciphers (AES-128-CTR or AES-128-CBC), and message authentication codes as [geth](https://github.com/ethereum/go-ethereum). You can export your generated key to file, copy it to your data directory's keystore, and immediately start using it in your local Ethereum client.

Note: starting in version 0.5.0, keythereum's `encrypt` and `decrypt` functions both return Buffers instead of strings. This is a breaking change for anyone using these functions directly!
*Note: starting in version 0.5.0, keythereum's `encrypt` and `decrypt` functions both return Buffers instead of strings. This is a breaking change for anyone using these functions directly!*

Installation
------------
## Installation

$ npm install keythereum
```
npm install keythereum
```

Usage
-----
## Usage

To use keythereum in Node.js, just `require` it:

```javascript
var keythereum = require("keythereum");
```

A minified, browserified file `dist/keythereum.min.js` is included for use in the browser. Including this file simply attaches the `keythereum` object to `window`:

```html
<script src="dist/keythereum.min.js" type="text/javascript"></script>
```

### Key creation

Generate a new random private key (256 bit), as well as the salt (256 bit) used by the key derivation function, and the initialization vector (128 bit) used to AES-128-CTR encrypt the key. `create` is asynchronous if it is passed a callback function, and synchronous otherwise.

```javascript
// optional private key and initialization vector sizes in bytes
// (if params is not passed to create, keythereum.constants is used by default)
Expand All @@ -54,58 +55,64 @@ keythereum.create(params, function (dk) {
### Key export

You will need to specify a password and (optionally) a key derivation function. If unspecified, PBKDF2-SHA256 will be used to derive the AES secret key.

```javascript
var password = "wheethereum";
var kdf = "pbkdf2"; // or "scrypt" to use the scrypt kdf
```

The `dump` function is used to export key info to keystore ["secret-storage" format](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition). If a callback function is supplied as the sixth parameter to `dump`, it will run asynchronously:

```javascript
// if options is not passed to dump, it will use the values in
// keythereum.constants by default
// Note: if options is unspecified, the values in keythereum.constants are used.
var options = {
kdf: "pbkdf2",
cipher: "aes-128-ctr",
kdfparams: {
c: 262144,
dklen: 32,
prf: "hmac-sha256"
}
kdf: "pbkdf2",
cipher: "aes-128-ctr",
kdfparams: {
c: 262144,
dklen: 32,
prf: "hmac-sha256"
}
};

// synchronous
var keyObject = keythereum.dump(password, dk.privateKey, dk.salt, dk.iv, options);
// keyObject:
{
address: '008aeeda4d805471df9b2a5b0f38a0c3bcba786b',
Crypto: {
cipher: 'aes-128-ctr',
ciphertext: '5318b4d5bcd28de64ee5559e671353e16f075ecae9f99c7a79a38af5f869aa46',
cipherparams: {
iv: '6087dab2f9fdbbfaddc31a909735c1e6'
},
mac: '517ead924a9d0dc3124507e3393d175ce3ff7c1e96529c6c555ce9e51205e9b2',
kdf: 'pbkdf2',
kdfparams: {
c: 262144,
dklen: 32,
prf: 'hmac-sha256',
salt: 'ae3cd4e7013836a3df6bd7241b12db061dbe2c6785853cce422d148a624ce0bd'
}
address: "008aeeda4d805471df9b2a5b0f38a0c3bcba786b",
Crypto: {
cipher: "aes-128-ctr",
ciphertext: "5318b4d5bcd28de64ee5559e671353e16f075ecae9f99c7a79a38af5f869aa46",
cipherparams: {
iv: "6087dab2f9fdbbfaddc31a909735c1e6"
},
id: 'e13b209c-3b2f-4327-bab0-3bef2e51630d',
version: 3
mac: "517ead924a9d0dc3124507e3393d175ce3ff7c1e96529c6c555ce9e51205e9b2",
kdf: "pbkdf2",
kdfparams: {
c: 262144,
dklen: 32,
prf: "hmac-sha256",
salt: "ae3cd4e7013836a3df6bd7241b12db061dbe2c6785853cce422d148a624ce0bd"
}
},
id: "e13b209c-3b2f-4327-bab0-3bef2e51630d",
version: 3
}

// asynchronous
keythereum.dump(password, dk.privateKey, dk.salt, dk.iv, options, function (keyObject) {
// do stuff!
// do stuff!
});
```

`dump` creates an object and not a JSON string. In Node, the `exportToFile` method provides an easy way to export this formatted key object to file. It creates a JSON file in the `keystore` sub-directory, and uses geth's current file-naming convention (ISO timestamp concatenated with the key's derived Ethereum address).
```

```javascript
keythereum.exportToFile(keyObject);
```

After successful key export, you will see a message like:

```
Saved to file:
keystore/UTC--2015-08-11T06:13:53.359Z--008aeeda4d805471df9b2a5b0f38a0c3bcba786b
Expand All @@ -117,53 +124,60 @@ To use with geth, copy this file to your Ethereum keystore folder
### Key import

Importing a key from geth's keystore can only be done on Node. The JSON file is parsed into an object with the same structure as `keyObject` above.

```javascript
// specify a data directory (optional; defaults to ~/.ethereum)
// Specify a data directory (optional; defaults to ~/.ethereum)
var datadir = "/home/jack/.ethereum-test";

// synchronous
// Synchronous
var keyObject = keythereum.importFromFile(address, datadir);

// asynchronous
// Asynchronous
keythereum.importFromFile(address, datadir, function (keyObject) {
// do stuff
// do stuff
});
```
This has been tested with version 3 and version 1, but not version 2, keys. (Please send me a version 2 keystore file if you have one, so I can test it!)

To recover the plaintext private key from the key object, use `keythereum.recover`. The private key is returned as a Buffer.

```javascript
// synchronous
var privateKey = keythereum.recover(password, keyObject);
// privateKey:
<Buffer ...>

// asynchronous
// Asynchronous
keythereum.recover(password, keyObject, function (privateKey) {
// do stuff
// do stuff
});
```

### Hashing rounds

By default, keythereum uses 65536 hashing rounds in its key derivation functions, compared to the 262144 geth uses by default. (Keythereum's JSON output files are still compatible with geth, however, since they tell geth how many rounds to use.) These values are user-editable: `keythereum.constants.pbkdf2.c` is the number of rounds for PBKDF2, and `keythereum.constants.scrypt.n` is the number of rounds for scrypt.

Tests
-----
## Tests

Unit tests are in the `test` directory, and can be run with mocha:

$ npm test
```
npm test
```

`test/geth.js` is an integration test, which is run (along with `test/keys.js`) using:

$ npm run geth
```
npm run geth
```

`geth.js` generates 1000 random private keys, encrypts each key using a randomly-generated passphrase, dumps the encrypted key info to a JSON file, then spawns a geth instance and attempts to unlock each account using its passphrase and JSON file. The passphrases are between 1 and 100 random bytes. Each passphrase is tested in both hexadecimal and base-64 encodings, and with PBKDF2-SHA256 and scrypt key derivation functions.

By default, the flags passed to geth are:

$ geth --etherbase <account> --unlock <account> --nodiscover --networkid "10101" --port 30304 --rpcport 8547 --datadir test/fixtures --password test/fixtures/.password
```
geth --etherbase <account> --unlock <account> --nodiscover --networkid "10101" --port 30304 --rpcport 8547 --datadir test/fixtures --password test/fixtures/.password
```

`test/fixtures/.password` is a file which contains the passphrase. The `.password` file, as well as the JSON key files generated by `geth.js`, are automatically deleted after the test.

Expand Down
20 changes: 4 additions & 16 deletions dist/keythereum.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (global){
var keythereum = global.keythereum || require('./');
global.keys = keythereum;
global.keythereum = keythereum;

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
Expand Down Expand Up @@ -33,6 +32,8 @@ function keccak256(buffer) {

module.exports = {

version: "0.5.2",

browser: typeof process === "undefined" || !process.nextTick || Boolean(process.browser),

crypto: crypto,
Expand All @@ -53,15 +54,15 @@ module.exports = {

// Key derivation function parameters
pbkdf2: {
c: 65536,
c: 262144,
dklen: 32,
hash: "sha256",
prf: "hmac-sha256"
},
scrypt: {
memory: 280000000,
dklen: 32,
n: 65536,
n: 262144,
r: 1,
p: 8
}
Expand Down Expand Up @@ -105,19 +106,6 @@ module.exports = {
return Buffer.from(str, enc);
},

/**
* Convert a hex-encoded string to UTF-16.
* @param {string|buffer} input Hex-encoded string.
* @return {string} UTF16-LE string.
*/
hex2utf16le: function (input) {
input = this.str2buf(input, "hex");
if (input.length % 2 !== 0) {
throw new Error("Can't convert input to UTF-16: invalid length");
}
return input.toString("utf16le");
},

/**
* Check if the selected cipher is available.
* @param {string} algo Encryption algorithm.
Expand Down
2 changes: 1 addition & 1 deletion dist/keythereum.min.js

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion exports.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
var keythereum = global.keythereum || require('./');
global.keys = keythereum;
global.keythereum = keythereum;
19 changes: 4 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ function keccak256(buffer) {

module.exports = {

version: "0.5.2",

browser: typeof process === "undefined" || !process.nextTick || Boolean(process.browser),

crypto: crypto,
Expand All @@ -44,15 +46,15 @@ module.exports = {

// Key derivation function parameters
pbkdf2: {
c: 65536,
c: 262144,
dklen: 32,
hash: "sha256",
prf: "hmac-sha256"
},
scrypt: {
memory: 280000000,
dklen: 32,
n: 65536,
n: 262144,
r: 1,
p: 8
}
Expand Down Expand Up @@ -96,19 +98,6 @@ module.exports = {
return Buffer.from(str, enc);
},

/**
* Convert a hex-encoded string to UTF-16.
* @param {string|buffer} input Hex-encoded string.
* @return {string} UTF16-LE string.
*/
hex2utf16le: function (input) {
input = this.str2buf(input, "hex");
if (input.length % 2 !== 0) {
throw new Error("Can't convert input to UTF-16: invalid length");
}
return input.toString("utf16le");
},

/**
* Check if the selected cipher is available.
* @param {string} algo Encryption algorithm.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "keythereum",
"version": "0.5.1",
"version": "0.5.2",
"description": "Create, import and export Ethereum keys",
"main": "index.js",
"directories": {
Expand Down
56 changes: 0 additions & 56 deletions test/keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,6 @@ var privateKey = crypto.randomBytes(32);
// suppress logging
keythereum.constants.quiet = !DEBUG;

// change hashing rounds to match geth's default
keythereum.constants.pbkdf2.c = 262144;
keythereum.constants.scrypt.n = 262144;

describe("Check if valid hex-encoded string", function () {
var test = function (t) {
it(t.description, function () {
Expand Down Expand Up @@ -237,58 +233,6 @@ describe("Convert a string to a Buffer", function () {
});
});

describe("Convert a hex-encoded string or buffer to a UTF-16 string", function () {
var test = function (t) {
it("[string] " + t.description, function () {
var output;
try {
output = keythereum.hex2utf16le(t.input);
} catch (exc) {
output = exc;
}
t.assertions(output);
});
it("[buffer] " + t.description, function () {
var output;
try {
output = keythereum.hex2utf16le(Buffer.from(t.input, "hex"));
} catch (exc) {
output = exc;
}
t.assertions(output);
});
};
test({
description: "deadbeef -> 귞",
input: "deadbeef",
assertions: function (output) {
assert.strictEqual(output, "귞");
}
});
test({
description: "0326 -> ☃",
input: "0326",
assertions: function (output) {
assert.strictEqual(output, "☃");
}
});
test({
description: "03260326 -> ☃☃",
input: "03260326",
assertions: function (output) {
assert.strictEqual(output, "☃☃");
}
});
test({
description: "032603 should throw an invalid length error",
input: "032603",
assertions: function (output) {
assert.instanceOf(output, Error);
assert.strictEqual(output.message, "Can't convert input to UTF-16: invalid length");
}
});
});

describe("Check if selected cipher is available", function () {
var test = function (t) {
it(t.description, function () {
Expand Down

0 comments on commit cdfece3

Please sign in to comment.