Skip to content

Commit

Permalink
Initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
queicherius committed Jan 10, 2017
0 parents commit 61b9d1f
Show file tree
Hide file tree
Showing 9 changed files with 323 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .babelrc
@@ -0,0 +1,11 @@
{
"presets": ["latest", "stage-0"],
"env": {
"test": {
"plugins": [
["istanbul", {"include": ["src/**"]}],
"rewire"
]
}
}
}
22 changes: 22 additions & 0 deletions .gitignore
@@ -0,0 +1,22 @@
# Logs
npm-debug.log*

# Coverage directories
coverage/
.nyc_output/

# Compiled code
build/

# Dependencies
node_modules/

# Optional npm cache directory
.npm/

# Webflow
.idea/

# Operating System
.DS_Store
Thumbs.db
22 changes: 22 additions & 0 deletions .npmignore
@@ -0,0 +1,22 @@
# Logs
npm-debug.log*

# Coverage directories
coverage/
.nyc_output/

# Source code
src/

# Dependencies
node_modules/

# Optional npm cache directory
.npm/

# Webflow
.idea/

# Operating System
.DS_Store
Thumbs.db
8 changes: 8 additions & 0 deletions .travis.yml
@@ -0,0 +1,8 @@
language: node_js
node_js:
- "6"
after_script: "$(npm bin)/codecov"
branches:
only:
- master
- /^greenkeeper.*$/
21 changes: 21 additions & 0 deletions LICENCE
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 queicherius (David Reeß)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
77 changes: 77 additions & 0 deletions README.md
@@ -0,0 +1,77 @@
# asymmetric-crypto

[![Build Status](https://img.shields.io/travis/queicherius/asymmetric-crypto.svg?style=flat-square)](https://travis-ci.org/queicherius/asymmetric-crypto)
[![Coverage Status](https://img.shields.io/codecov/c/github/queicherius/asymmetric-crypto/master.svg?style=flat-square)](https://codecov.io/github/queicherius/asymmetric-crypto)

> Encryption and signing using public-key cryptography (via [`tweetnacl`](https://github.com/dchest/tweetnacl-js))
## Install

```
npm install asymmetric-crypto
```

This module can be used for Node.js as well as browsers using [Browserify](https://github.com/substack/browserify-handbook#how-node_modules-works).

## Usage

```js
import * as crypto from 'asymmetric-crypto'

// Generate a key pair
const keyPair = crypto.keyPair()
// -> {
// secretKey: 'KOy7fMWMkRc+QX8dzpfX9VwJKlc/+Zkyw5C7RGTXT920IjiKUdOSe/3sNnrETw7ej9TBFzsPyRfkWGMsGLAufQ==',
// publicKey: 'tCI4ilHTknv97DZ6xE8O3o/UwRc7D8kX5FhjLBiwLn0='
// }

// Regenerate a key pair from the secret key
const newKeyPair = crypto.fromSecretKey(keyPair.secretKey)
// -> {
// secretKey: 'KOy7fMWMkRc+QX8dzpfX9VwJKlc/+Zkyw5C7RGTXT920IjiKUdOSe/3sNnrETw7ej9TBFzsPyRfkWGMsGLAufQ==',
// publicKey: 'tCI4ilHTknv97DZ6xE8O3o/UwRc7D8kX5FhjLBiwLn0='
// }

const myKeyPair = crypto.keyPair()
const theirKeyPair = crypto.keyPair()

// Encrypt data
const encrypted = crypto.encrypt('some data', theirKeyPair.publicKey, myKeyPair.secretKey)
// -> {
// data: '63tP2r8WQuJ+k+jzsd8pbT6WYPHMTafpeg==',
// nonce: 'BDHALdoeBiGg7wJbVdfJhVQQyvpxrBSo'
// }

// Decrypt data
const decrypted = crypto.decrypt(encrypted.data, encrypted.nonce, myKeyPair.publicKey, theirKeyPair.secretKey)
// -> 'some data'

// Sign a message
const message = 'some message'
const signature = crypto.sign(message, myKeyPair.secretKey)
// -> '8oz1aNkSBG1qvYhc+E2VBkgHSxCORGdsyf7LFQuLDmZvJt6vaEzHMIsofmTykMunhCrChEHT9Fgw3sp/W6+7Bw=='

// Verify the signature on a message
const validSignature = crypto.verify(message, signature, myKeyPair.publicKey)
// -> true
```

## Tests

```
npm test
```

## Internals

- [`tweetnacl`](https://github.com/dchest/tweetnacl-js) for the cryptographic implementation
- [`tweetnacl-util`](https://github.com/dchest/tweetnacl-util-js) for converting into / from strings
- [`ed2curve`](https://github.com/dchest/ed2curve-js) for converting *Ed25519* keys into *curve25519-xsalsa20-poly1305* keys (so you can encrypt and sign with the same key pair)

## Licence

MIT

---

Thanks to @pguth for the inspiration. :smile:
24 changes: 24 additions & 0 deletions package.json
@@ -0,0 +1,24 @@
{
"name": "asymmetric-crypto",
"version": "0.1.0",
"description": "Encryption and signing using public-key cryptography (via tweetnacl)",
"main": "./build/index.js",
"scripts": {
"build": "abc build",
"test": "abc test && abc lint"
},
"author": "queicherius@gmail.com",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/queicherius/asymmetric-crypto"
},
"dependencies": {
"ed2curve": "^0.2.1",
"tweetnacl": "^0.14.5",
"tweetnacl-util": "^0.13.5"
},
"devDependencies": {
"abc-environment": "^1.0.5"
}
}
70 changes: 70 additions & 0 deletions src/index.js
@@ -0,0 +1,70 @@
import nacl from 'tweetnacl'
import naclUtil from 'tweetnacl-util'
import ed2curve from 'ed2curve'

export function keyPair () {
const keyPair = nacl.sign.keyPair()

return {
secretKey: naclUtil.encodeBase64(keyPair.secretKey),
publicKey: naclUtil.encodeBase64(keyPair.publicKey)
}
}

export function fromSecretKey (secretKey) {
secretKey = naclUtil.decodeBase64(secretKey)

const keyPair = nacl.sign.keyPair.fromSecretKey(secretKey)

return {
secretKey: naclUtil.encodeBase64(keyPair.secretKey),
publicKey: naclUtil.encodeBase64(keyPair.publicKey)
}
}

export function encrypt (data, theirPublicKey, mySecretKey) {
data = naclUtil.decodeUTF8(data)
theirPublicKey = ed2curve.convertPublicKey(naclUtil.decodeBase64(theirPublicKey))
mySecretKey = ed2curve.convertSecretKey(naclUtil.decodeBase64(mySecretKey))

const nonce = nacl.randomBytes(nacl.box.nonceLength)

data = nacl.box(data, nonce, theirPublicKey, mySecretKey)

return {
data: naclUtil.encodeBase64(data),
nonce: naclUtil.encodeBase64(nonce)
}
}

export function decrypt (data, nonce, theirPublicKey, mySecretKey) {
data = naclUtil.decodeBase64(data)
nonce = naclUtil.decodeBase64(nonce)
theirPublicKey = ed2curve.convertPublicKey(naclUtil.decodeBase64(theirPublicKey))
mySecretKey = ed2curve.convertSecretKey(naclUtil.decodeBase64(mySecretKey))

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

if (!data) {
throw new Error('failed opening nacl.box')
}

return naclUtil.encodeUTF8(data)
}

export function sign (data, mySecretKey) {
data = naclUtil.decodeUTF8(data)
mySecretKey = naclUtil.decodeBase64(mySecretKey)

data = nacl.sign.detached(data, mySecretKey)

return naclUtil.encodeBase64(data)
}

export function verify (data, signature, theirPublicKey) {
data = naclUtil.decodeUTF8(data)
signature = naclUtil.decodeBase64(signature)
theirPublicKey = naclUtil.decodeBase64(theirPublicKey)

return nacl.sign.detached.verify(data, signature, theirPublicKey)
}
68 changes: 68 additions & 0 deletions tests/index.spec.js
@@ -0,0 +1,68 @@
/* eslint-env node, mocha */
import { expect } from 'chai'
import * as module from '../src/index.js'

describe('key generation', () => {
it('generates a key pair', () => {
const keyPair = module.keyPair()
expect(keyPair.secretKey).to.be.a('string')
expect(keyPair.publicKey).to.be.a('string')
})

it('generates a key pair from the secret key', () => {
const keyPair = module.keyPair()
const keyPairFromSecretKey = module.fromSecretKey(keyPair.secretKey)
expect(keyPair).to.deep.equal(keyPairFromSecretKey)
})
})

describe('encryption', () => {
it('encrypts and decrypts', () => {
const myKeyPair = module.keyPair()
const theirKeyPair = module.keyPair()
const data = 'some data to encrypt'

const encrypted = module.encrypt(data, theirKeyPair.publicKey, myKeyPair.secretKey)
expect(encrypted.data).to.be.a('string')
expect(encrypted.nonce).to.be.a('string')

const decrypted = module.decrypt(encrypted.data, encrypted.nonce, myKeyPair.publicKey, theirKeyPair.secretKey)
expect(decrypted).to.equal(data)
})

it('fails decryption when using the wrong key', () => {
const randomKeyPair = module.keyPair()
const publicKey = 'J2rbR/Be2ukJuf6od+amUufeb4iN3pnF8hOHTprfUgY='
const encrypted = {
data: '1WTd5WyEhy9lX+z1ibF2C4ChghbAKfYmM/DV4LePC2us+cfU',
nonce: 'u8VL7Ekv7GiJcThczjbYgfI/ZN95OdUz'
}

expect(() => {
module.decrypt(encrypted.data, encrypted.nonce, publicKey, randomKeyPair.secretKey)
}).to.throw('failed opening nacl.box')
})
})

describe('signing', () => {
it('signs and verifies', () => {
const myKeyPair = module.keyPair()
const data = 'some data to sign'

const signed = module.sign(data, myKeyPair.secretKey)
expect(signed).to.be.a('string')

const verified = module.verify(data, signed, myKeyPair.publicKey)
expect(verified).to.equal(true)
})

it('fails verification for the wrong key', () => {
const myKeyPair = module.keyPair()
const otherKeyPair = module.keyPair()
const data = 'some data to sign'
const signed = module.sign(data, myKeyPair.secretKey)

const verified = module.verify(data, signed, otherKeyPair.publicKey)
expect(verified).to.equal(false)
})
})

0 comments on commit 61b9d1f

Please sign in to comment.