Socket
Socket
Sign inDemoInstall

libp2p-crypto

Package Overview
Dependencies
Maintainers
2
Versions
67
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

libp2p-crypto - npm Package Compare versions

Comparing version 0.17.9 to 0.18.0

21

CHANGELOG.md

@@ -0,1 +1,22 @@

<a name="0.18.0"></a>
# [0.18.0](https://github.com/libp2p/js-libp2p-crypto/compare/v0.17.9...v0.18.0) (2020-08-07)
### Bug Fixes
* remove rendundant public key ([#181](https://github.com/libp2p/js-libp2p-crypto/issues/181)) ([afcffc8](https://github.com/libp2p/js-libp2p-crypto/commit/afcffc8))
* replace node buffers with uint8arrays ([#180](https://github.com/libp2p/js-libp2p-crypto/issues/180)) ([a0f387a](https://github.com/libp2p/js-libp2p-crypto/commit/a0f387a))
### BREAKING CHANGES
* The private ed25519 key will no longer include the redundant public key
* chore: fix lint
* - Where node Buffers were returned, now Uint8Arrays are
* chore: remove commented code
<a name="0.17.9"></a>

@@ -2,0 +23,0 @@ ## [0.17.9](https://github.com/libp2p/js-libp2p-crypto/compare/v0.17.8...v0.17.9) (2020-08-05)

21

package.json
{
"name": "libp2p-crypto",
"version": "0.17.9",
"version": "0.18.0",
"description": "Crypto primitives for libp2p",

@@ -42,3 +42,2 @@ "main": "src/index.js",

"dependencies": {
"buffer": "^5.5.0",
"err-code": "^2.0.0",

@@ -48,10 +47,10 @@ "is-typedarray": "^1.0.0",

"keypair": "^1.0.1",
"multibase": "^1.0.1",
"multicodec": "^1.0.4",
"multihashing-async": "^0.8.1",
"multibase": "^3.0.0",
"multicodec": "^2.0.0",
"multihashing-async": "^2.0.1",
"node-forge": "^0.9.1",
"pem-jwk": "^2.0.0",
"protons": "^1.2.1",
"protons": "^2.0.0",
"secp256k1": "^4.0.0",
"uint8arrays": "^1.0.0",
"uint8arrays": "^1.1.0",
"ursa-optional": "^0.10.1"

@@ -91,5 +90,6 @@ },

"Hugo Dias <hugomrdias@gmail.com>",
"Cayman <caymannava@gmail.com>",
"Yusef Napora <yusef@napora.org>",
"Cayman <caymannava@gmail.com>",
"Victor Bjelkholm <victorbjelkholm@gmail.com>",
"ᴠɪᴄᴛᴏʀ ʙᴊᴇʟᴋʜᴏʟᴍ <victorbjelkholm@gmail.com>",
"Alex Potsides <alex@achingbrain.net>",
"Arve Knudsen <arve.knudsen@gmail.com>",

@@ -100,10 +100,9 @@ "Vasco Santos <vasco.santos@ua.pt>",

"Richard Schneider <makaretu@gmail.com>",
"Alex Potsides <alex@achingbrain.net>",
"dirkmc <dirkmdev@gmail.com>",
"Alberto Elias <hi@albertoelias.me>",
"nikuda <nikuda@gmail.com>",
"Carson Farmer <carson.farmer@gmail.com>",
"Tom Swindell <t.swindell@rubyx.co.uk>",
"Carson Farmer <carson.farmer@gmail.com>",
"Joao Santos <jrmsantos15@gmail.com>"
]
}

@@ -23,6 +23,8 @@ # js-libp2p-crypto

- [js-libp2p-crypto](#js-libp2p-crypto)
- [Lead Maintainer](#Lead-Maintainer)
- [Table of Contents](#Table-of-Contents)
- [Install](#Install)
- [API](#API)
- [Lead Maintainer](#lead-maintainer)
- [Table of Contents](#table-of-contents)
- [Install](#install)
- [Usage](#usage)
- [Web Crypto API](#web-crypto-api)
- [API](#api)
- [`crypto.aes`](#cryptoaes)

@@ -36,14 +38,15 @@ - [`crypto.aes.create(key, iv)`](#cryptoaescreatekey-iv)

- [`crypto.keys`](#cryptokeys)
- [`crypto.keys.generateKeyPair(type, bits)`](#cryptokeysgenerateKeyPairtype-bits)
- [`crypto.keys.generateEphemeralKeyPair(curve)`](#cryptokeysgenerateEphemeralKeyPaircurve)
- [`crypto.keys.keyStretcher(cipherType, hashType, secret)`](#cryptokeyskeyStretchercipherType-hashType-secret)
- [`crypto.keys.marshalPublicKey(key, [type])`](#cryptokeysmarshalPublicKeykey-type)
- [`crypto.keys.unmarshalPublicKey(buf)`](#cryptokeysunmarshalPublicKeybuf)
- [`crypto.keys.marshalPrivateKey(key, [type])`](#cryptokeysmarshalPrivateKeykey-type)
- [`crypto.keys.unmarshalPrivateKey(buf)`](#cryptokeysunmarshalPrivateKeybuf)
- [`crypto.keys.import(pem, password)`](#cryptokeysimportpem-password)
- [`crypto.randomBytes(number)`](#cryptorandomBytesnumber)
- [`crypto.pbkdf2(password, salt, iterations, keySize, hash)`](#cryptopbkdf2password-salt-iterations-keySize-hash)
- [Contribute](#Contribute)
- [License](#License)
- [`crypto.keys.generateKeyPair(type, bits)`](#cryptokeysgeneratekeypairtype-bits)
- [`crypto.keys.generateEphemeralKeyPair(curve)`](#cryptokeysgenerateephemeralkeypaircurve)
- [`crypto.keys.keyStretcher(cipherType, hashType, secret)`](#cryptokeyskeystretcherciphertype-hashtype-secret)
- [`crypto.keys.marshalPublicKey(key, [type])`](#cryptokeysmarshalpublickeykey-type)
- [`crypto.keys.unmarshalPublicKey(buf)`](#cryptokeysunmarshalpublickeybuf)
- [`crypto.keys.marshalPrivateKey(key, [type])`](#cryptokeysmarshalprivatekeykey-type)
- [`crypto.keys.unmarshalPrivateKey(buf)`](#cryptokeysunmarshalprivatekeybuf)
- [`crypto.keys.import(encryptedKey, password)`](#cryptokeysimportencryptedkey-password)
- [`privateKey.export(password, format)`](#privatekeyexportpassword-format)
- [`crypto.randomBytes(number)`](#cryptorandombytesnumber)
- [`crypto.pbkdf2(password, salt, iterations, keySize, hash)`](#cryptopbkdf2password-salt-iterations-keysize-hash)
- [Contribute](#contribute)
- [License](#license)

@@ -87,4 +90,4 @@ ## Install

- `key: Buffer` The key, if length `16` then `AES 128` is used. For length `32`, `AES 256` is used.
- `iv: Buffer` Must have length `16`.
- `key: Uint8Array` The key, if length `16` then `AES 128` is used. For length `32`, `AES 256` is used.
- `iv: Uint8Array` Must have length `16`.

@@ -95,11 +98,11 @@ Returns `Promise<{decrypt<Function>, encrypt<Function>}>`

- `data: Buffer`
- `data: Uint8Array`
Returns `Promise<Buffer>`
Returns `Promise<Uint8Array>`
##### `encrypt(data)`
- `data: Buffer`
- `data: Uint8Array`
Returns `Promise<Buffer>`
Returns `Promise<Uint8Array>`

@@ -112,6 +115,6 @@ ```js

// A 16 bytes array, 128 Bits, AES-128 is chosen
const key128 = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
const key128 = Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
// A 16 bytes array, 128 Bits,
const IV = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
const IV = Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])

@@ -123,5 +126,5 @@ async function main () {

const cipher = await crypto.aes.create(key128, IV)
const encryptedBuffer = await cipher.encrypt(Buffer.from(decryptedMessage))
const encryptedBuffer = await cipher.encrypt(Uint8Array.from(decryptedMessage))
console.log(encryptedBuffer)
// prints: <Buffer 42 f1 67 d9 2e 42 d0 32 9e b1 f8 3c>
// prints: <Uint8Array 42 f1 67 d9 2e 42 d0 32 9e b1 f8 3c>

@@ -133,3 +136,3 @@ // Decrypting

console.log(decryptedBuffer)
// prints: <Buffer 42 f1 67 d9 2e 42 d0 32 9e b1 f8 3c>
// prints: <Uint8Array 42 f1 67 d9 2e 42 d0 32 9e b1 f8 3c>

@@ -150,3 +153,3 @@ console.log(decryptedBuffer.toString('utf-8'))

- `hash: String`
- `secret: Buffer`
- `secret: Uint8Array`

@@ -157,5 +160,5 @@ Returns `Promise<{digest<Function>}>`

- `data: Buffer`
- `data: Uint8Array`
Returns `Promise<Buffer>`
Returns `Promise<Uint8Array>`

@@ -169,4 +172,4 @@ Example:

const hash = 'SHA1' // 'SHA256' || 'SHA512'
const hmac = await crypto.hmac.create(hash, Buffer.from('secret'))
const sig = await hmac.digest(Buffer.from('hello world'))
const hmac = await crypto.hmac.create(hash, uint8ArrayFromString('secret'))
const sig = await hmac.digest(uint8ArrayFromString('hello world'))
console.log(sig)

@@ -191,3 +194,3 @@ }

Returns `Promise<{privateKey<Buffer>, publicKey<Buffer>}>`
Returns `Promise<{privateKey<Uint8Array>, publicKey<Uint8Array>}>`

@@ -210,3 +213,3 @@ Generates a keypair of the given type and bitsize.

{
key: Buffer,
key: Uint8Array,
genSharedKey: Function

@@ -220,3 +223,3 @@ }

- `hashType: String`, one of `'SHA1'`, `SHA256`, `SHA512`
- `secret: Buffer`
- `secret: Uint8Array`

@@ -232,10 +235,10 @@ Returns `Promise`

k1: {
iv: Buffer,
cipherKey: Buffer,
macKey: Buffer
iv: Uint8Array,
cipherKey: Uint8Array,
macKey: Uint8Array
},
k2: {
iv: Buffer,
cipherKey: Buffer,
macKey: Buffer
iv: Uint8Array,
cipherKey: Uint8Array,
macKey: Uint8Array
}

@@ -250,3 +253,3 @@ }

Returns `Buffer`
Returns `Uint8Array`

@@ -257,3 +260,3 @@ Converts a public key object into a protobuf serialized public key.

- `buf: Buffer`
- `buf: Uint8Array`

@@ -269,3 +272,3 @@ Returns `RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey`

Returns `Buffer`
Returns `Uint8Array`

@@ -276,3 +279,3 @@ Converts a private key object into a protobuf serialized private key.

- `buf: Buffer`
- `buf: Uint8Array`

@@ -305,5 +308,5 @@ Returns `Promise<RsaPrivateKey|Ed25519PrivateKey|Secp256k1PrivateKey>`

Returns `Buffer`
Returns `Uint8Array`
Generates a Buffer with length `number` populated by random bytes.
Generates a Uint8Array with length `number` populated by random bytes.

@@ -310,0 +313,0 @@ ### `crypto.pbkdf2(password, salt, iterations, keySize, hash)`

'use strict'
const { Buffer } = require('buffer')
require('node-forge/lib/aes')
const forge = require('node-forge/lib/forge')
const uint8ArrayToString = require('uint8arrays/to-string')
const uint8ArrayFromString = require('uint8arrays/from-string')
module.exports = {
createCipheriv: (mode, key, iv) => {
const cipher2 = forge.cipher.createCipher('AES-CTR', key.toString('binary'))
cipher2.start({ iv: iv.toString('binary') })
const cipher2 = forge.cipher.createCipher('AES-CTR', uint8ArrayToString(key, 'ascii'))
cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })
return {
update: (data) => {
cipher2.update(forge.util.createBuffer(data.toString('binary')))
return Buffer.from(cipher2.output.getBytes(), 'binary')
cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))
return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')
}

@@ -18,8 +20,8 @@ }

createDecipheriv: (mode, key, iv) => {
const cipher2 = forge.cipher.createDecipher('AES-CTR', key.toString('binary'))
cipher2.start({ iv: iv.toString('binary') })
const cipher2 = forge.cipher.createDecipher('AES-CTR', uint8ArrayToString(key, 'ascii'))
cipher2.start({ iv: uint8ArrayToString(iv, 'ascii') })
return {
update: (data) => {
cipher2.update(forge.util.createBuffer(data.toString('binary')))
return Buffer.from(cipher2.output.getBytes(), 'binary')
cipher2.update(forge.util.createBuffer(uint8ArrayToString(data, 'ascii')))
return uint8ArrayFromString(cipher2.output.getBytes(), 'ascii')
}

@@ -26,0 +28,0 @@ }

'use strict'
const crypto = require('crypto')
const uint8ArrayConcat = require('uint8arrays/concat')
const uint8ArrayFromString = require('uint8arrays/from-string')

@@ -30,5 +32,5 @@ // Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples

* @private
* @param {Buffer} data
* @param {Buffer} key
* @returns {Promise<Buffer>}
* @param {Uint8Array} data
* @param {Uint8Array} key
* @returns {Promise<Uint8Array>}
*/

@@ -42,5 +44,5 @@ async function encryptWithKey (data, key) { // eslint-disable-line require-await

// Encrypt and prepend nonce.
const ciphertext = Buffer.concat([cipher.update(data), cipher.final()])
const ciphertext = uint8ArrayConcat([cipher.update(data), cipher.final()])
return Buffer.concat([nonce, ciphertext, cipher.getAuthTag()])
return uint8ArrayConcat([nonce, ciphertext, cipher.getAuthTag()])
}

@@ -52,5 +54,5 @@

*
* @param {Buffer} data The data to decrypt
* @param {string|Buffer} password A plain password
* @returns {Promise<Buffer>}
* @param {Uint8Array} data The data to decrypt
* @param {string|Uint8Array} password A plain password
* @returns {Promise<Uint8Array>}
*/

@@ -61,7 +63,11 @@ async function encrypt (data, password) { // eslint-disable-line require-await

if (typeof password === 'string' || password instanceof String) {
password = uint8ArrayFromString(password)
}
// Derive a key using PBKDF2.
const key = crypto.pbkdf2Sync(Buffer.from(password), salt, iterations, keyLength, digest)
const key = crypto.pbkdf2Sync(password, salt, iterations, keyLength, digest)
// Encrypt and prepend salt.
return Buffer.concat([salt, await encryptWithKey(Buffer.from(data), key)])
return uint8ArrayConcat([salt, await encryptWithKey(Uint8Array.from(data), key)])
}

@@ -77,8 +83,8 @@

* @private
* @param {Buffer} ciphertextAndNonce The data to decrypt
* @param {Buffer} key
* @returns {Promise<Buffer>}
* @param {Uint8Array} ciphertextAndNonce The data to decrypt
* @param {Uint8Array} key
* @returns {Promise<Uint8Array>}
*/
async function decryptWithKey (ciphertextAndNonce, key) { // eslint-disable-line require-await
// Create buffers of nonce, ciphertext and tag.
// Create Uint8Arrays of nonce, ciphertext and tag.
const nonce = ciphertextAndNonce.slice(0, nonceLength)

@@ -93,3 +99,3 @@ const ciphertext = ciphertextAndNonce.slice(nonceLength, ciphertextAndNonce.length - algorithmTagLength)

cipher.setAuthTag(tag)
return Buffer.concat([cipher.update(ciphertext), cipher.final()])
return uint8ArrayConcat([cipher.update(ciphertext), cipher.final()])
}

@@ -103,12 +109,16 @@

*
* @param {Buffer} data The data to decrypt
* @param {string|Buffer} password A plain password
* @param {Uint8Array} data The data to decrypt
* @param {string|Uint8Array} password A plain password
*/
async function decrypt (data, password) { // eslint-disable-line require-await
// Create buffers of salt and ciphertextAndNonce.
// Create Uint8Arrays of salt and ciphertextAndNonce.
const salt = data.slice(0, saltLength)
const ciphertextAndNonce = data.slice(saltLength)
if (typeof password === 'string' || password instanceof String) {
password = uint8ArrayFromString(password)
}
// Derive the key using PBKDF2.
const key = crypto.pbkdf2Sync(Buffer.from(password), salt, iterations, keyLength, digest)
const key = crypto.pbkdf2Sync(password, salt, iterations, keyLength, digest)

@@ -115,0 +125,0 @@ // Decrypt and return result.

'use strict'
const { Buffer } = require('buffer')
const webcrypto = require('../webcrypto')

@@ -13,3 +13,4 @@ const lengths = require('./lengths')

const sign = async (key, data) => {
return Buffer.from(await webcrypto.get().subtle.sign({ name: 'HMAC' }, key, data))
const buf = await webcrypto.get().subtle.sign({ name: 'HMAC' }, key, data)
return new Uint8Array(buf, buf.byteOffset, buf.byteLength)
}

@@ -16,0 +17,0 @@

@@ -34,4 +34,4 @@ /// <reference types="node" />

interface Cipher {
encrypt(data: Buffer): Promise<Buffer>;
decrypt(data: Buffer): Promise<Buffer>;
encrypt(data: Uint8Array): Promise<Uint8Array>;
decrypt(data: Uint8Array): Promise<Uint8Array>;
}

@@ -43,3 +43,3 @@ /**

*/
function create(key: Buffer, iv: Buffer): Promise<Cipher>;
function create(key: Uint8Array, iv: Uint8Array): Promise<Cipher>;
}

@@ -58,3 +58,3 @@

interface Digest {
digest(data: Buffer): Promise<Buffer>;
digest(data: Uint8Array): Promise<Uint8Array>;
length: 20 | 32 | 64 | number;

@@ -67,3 +67,3 @@ }

hash: "SHA1" | "SHA256" | "SHA512" | string,
secret: Buffer
secret: Uint8Array
): Promise<Digest>;

@@ -76,7 +76,7 @@ }

export interface PublicKey {
readonly bytes: Buffer;
verify(data: Buffer, sig: Buffer): Promise<boolean>;
marshal(): Buffer;
readonly bytes: Uint8Array;
verify(data: Uint8Array, sig: Uint8Array): Promise<boolean>;
marshal(): Uint8Array;
equals(key: PublicKey): boolean;
hash(): Promise<Buffer>;
hash(): Promise<Uint8Array>;
}

@@ -89,7 +89,7 @@

readonly public: PublicKey;
readonly bytes: Buffer;
sign(data: Buffer): Promise<Buffer>;
marshal(): Buffer;
readonly bytes: Uint8Array;
sign(data: Uint8Array): Promise<Uint8Array>;
marshal(): Uint8Array;
equals(key: PrivateKey): boolean;
hash(): Promise<Buffer>;
hash(): Promise<Uint8Array>;
/**

@@ -110,6 +110,6 @@ * Gets the ID of the key.

export interface Keystretcher {
(res: Buffer): Keystretcher;
iv: Buffer;
cipherKey: Buffer;
macKey: Buffer;
(res: Uint8Array): Keystretcher;
iv: Uint8Array;
cipherKey: Uint8Array;
macKey: Uint8Array;
}

@@ -137,28 +137,28 @@

class RsaPublicKey implements PublicKey {
constructor(key: Buffer);
readonly bytes: Buffer;
verify(data: Buffer, sig: Buffer): Promise<boolean>;
marshal(): Buffer;
encrypt(bytes: Buffer): Buffer;
constructor(key: Uint8Array);
readonly bytes: Uint8Array;
verify(data: Uint8Array, sig: Uint8Array): Promise<boolean>;
marshal(): Uint8Array;
encrypt(bytes: Uint8Array): Uint8Array;
equals(key: PublicKey): boolean;
hash(): Promise<Buffer>;
hash(): Promise<Uint8Array>;
}
class RsaPrivateKey implements PrivateKey {
constructor(key: any, publicKey: Buffer);
constructor(key: any, publicKey: Uint8Array);
readonly public: RsaPublicKey;
readonly bytes: Buffer;
genSecret(): Buffer;
sign(data: Buffer): Promise<Buffer>;
decrypt(bytes: Buffer): Buffer;
marshal(): Buffer;
readonly bytes: Uint8Array;
genSecret(): Uint8Array;
sign(data: Uint8Array): Promise<Uint8Array>;
decrypt(bytes: Uint8Array): Uint8Array;
marshal(): Uint8Array;
equals(key: PrivateKey): boolean;
hash(): Promise<Buffer>;
hash(): Promise<Uint8Array>;
id(): Promise<string>;
export(password: string, format?: string): Promise<string>;
}
function unmarshalRsaPublicKey(buf: Buffer): RsaPublicKey;
function unmarshalRsaPrivateKey(buf: Buffer): Promise<RsaPrivateKey>;
function unmarshalRsaPublicKey(buf: Uint8Array): RsaPublicKey;
function unmarshalRsaPrivateKey(buf: Uint8Array): Promise<RsaPrivateKey>;
function generateKeyPair(bits: number): Promise<RsaPrivateKey>;
function fromJwk(jwk: Buffer): Promise<RsaPrivateKey>;
function fromJwk(jwk: Uint8Array): Promise<RsaPrivateKey>;
}

@@ -168,19 +168,19 @@

class Ed25519PublicKey implements PublicKey {
constructor(key: Buffer);
readonly bytes: Buffer;
verify(data: Buffer, sig: Buffer): Promise<boolean>;
marshal(): Buffer;
encrypt(bytes: Buffer): Buffer;
constructor(key: Uint8Array);
readonly bytes: Uint8Array;
verify(data: Uint8Array, sig: Uint8Array): Promise<boolean>;
marshal(): Uint8Array;
encrypt(bytes: Uint8Array): Uint8Array;
equals(key: PublicKey): boolean;
hash(): Promise<Buffer>;
hash(): Promise<Uint8Array>;
}
class Ed25519PrivateKey implements PrivateKey {
constructor(key: Buffer, publicKey: Buffer);
constructor(key: Uint8Array, publicKey: Uint8Array);
readonly public: Ed25519PublicKey;
readonly bytes: Buffer;
sign(data: Buffer): Promise<Buffer>;
marshal(): Buffer;
readonly bytes: Uint8Array;
sign(data: Uint8Array): Promise<Uint8Array>;
marshal(): Uint8Array;
equals(key: PrivateKey): boolean;
hash(): Promise<Buffer>;
hash(): Promise<Uint8Array>;
id(): Promise<string>;

@@ -191,8 +191,8 @@ export(password: string, format?: string): Promise<string>;

function unmarshalEd25519PrivateKey(
buf: Buffer
buf: Uint8Array
): Promise<Ed25519PrivateKey>;
function unmarshalEd25519PublicKey(buf: Buffer): Ed25519PublicKey;
function unmarshalEd25519PublicKey(buf: Uint8Array): Ed25519PublicKey;
function generateKeyPair(): Promise<Ed25519PrivateKey>;
function generateKeyPairFromSeed(
seed: Buffer
seed: Uint8Array
): Promise<Ed25519PrivateKey>;

@@ -203,19 +203,19 @@ }

class Secp256k1PublicKey implements PublicKey {
constructor(key: Buffer);
readonly bytes: Buffer;
verify(data: Buffer, sig: Buffer): Promise<boolean>;
marshal(): Buffer;
encrypt(bytes: Buffer): Buffer;
constructor(key: Uint8Array);
readonly bytes: Uint8Array;
verify(data: Uint8Array, sig: Uint8Array): Promise<boolean>;
marshal(): Uint8Array;
encrypt(bytes: Uint8Array): Uint8Array;
equals(key: PublicKey): boolean;
hash(): Promise<Buffer>;
hash(): Promise<Uint8Array>;
}
class Secp256k1PrivateKey implements PrivateKey {
constructor(key: Uint8Array | Buffer, publicKey: Uint8Array | Buffer);
constructor(key: Uint8Array, publicKey: Uint8Array);
readonly public: Secp256k1PublicKey;
readonly bytes: Buffer;
sign(data: Buffer): Promise<Buffer>;
marshal(): Buffer;
readonly bytes: Uint8Array;
sign(data: Uint8Array): Promise<Uint8Array>;
marshal(): Uint8Array;
equals(key: PrivateKey): boolean;
hash(): Promise<Buffer>;
hash(): Promise<Uint8Array>;
id(): Promise<string>;

@@ -226,5 +226,5 @@ export(password: string, format?: string): Promise<string>;

function unmarshalSecp256k1PrivateKey(
bytes: Buffer
bytes: Uint8Array
): Promise<Secp256k1PrivateKey>;
function unmarshalSecp256k1PublicKey(bytes: Buffer): Secp256k1PublicKey;
function unmarshalSecp256k1PublicKey(bytes: Uint8Array): Secp256k1PublicKey;
function generateKeyPair(): Promise<Secp256k1PrivateKey>;

@@ -281,4 +281,4 @@ }

): Promise<{
key: Buffer;
genSharedKey: (theirPub: Buffer, forcePrivate?: any) => Promise<Buffer>;
key: Uint8Array;
genSharedKey: (theirPub: Uint8Array, forcePrivate?: any) => Promise<Uint8Array>;
}>;

@@ -295,3 +295,3 @@

hashType: HashType | string,
secret: Buffer | string
secret: Uint8Array | string
): Promise<StretchPair>;

@@ -303,3 +303,3 @@

*/
export function unmarshalPublicKey(buf: Buffer): PublicKey;
export function unmarshalPublicKey(buf: Uint8Array): PublicKey;

@@ -311,3 +311,3 @@ /**

*/
export function marshalPublicKey(key: PublicKey, type?: KeyType | string): Buffer;
export function marshalPublicKey(key: PublicKey, type?: KeyType | string): Uint8Array;

@@ -318,3 +318,3 @@ /**

*/
export function unmarshalPrivateKey(buf: Buffer): Promise<PrivateKey>;
export function unmarshalPrivateKey(buf: Uint8Array): Promise<PrivateKey>;

@@ -326,3 +326,3 @@ /**

*/
export function marshalPrivateKey(key: PrivateKey, type?: KeyType | string): Buffer;
export function marshalPrivateKey(key: PrivateKey, type?: KeyType | string): Uint8Array;

@@ -339,6 +339,6 @@ /**

/**
* Generates a Buffer populated by random bytes.
* @param The size of the random bytes Buffer.
* Generates a Uint8Array populated by random bytes.
* @param The size of the random bytes Uint8Array.
*/
export function randomBytes(number: number): Buffer;
export function randomBytes(number: number): Uint8Array;

@@ -354,7 +354,7 @@ /**

export function pbkdf2(
password: string | Buffer,
salt: string | Buffer,
password: string | Uint8Array,
salt: string | Uint8Array,
iterations: number,
keySize: number,
hash: string
): Buffer;
): Uint8Array;
'use strict'
const errcode = require('err-code')
const { Buffer } = require('buffer')
const webcrypto = require('../webcrypto')
const { bufferToBase64url, base64urlToBuffer } = require('../util')
const { base64urlToBuffer } = require('../util')
const validateCurveType = require('./validate-curve-type')
const uint8ArrayToString = require('uint8arrays/to-string')
const uint8ArrayConcat = require('uint8arrays/concat')
const uint8ArrayEquals = require('uint8arrays/equals')

@@ -59,3 +61,3 @@ const bits = {

return Buffer.from(await webcrypto.get().subtle.deriveBits(
const buffer = await webcrypto.get().subtle.deriveBits(
{

@@ -68,3 +70,5 @@ name: 'ECDH',

bits[curve]
))
)
return new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength)
}

@@ -92,4 +96,4 @@

return Buffer.concat([
Buffer.from([4]), // uncompressed point
return uint8ArrayConcat([
Uint8Array.from([4]), // uncompressed point
base64urlToBuffer(jwk.x, byteLen),

@@ -104,3 +108,3 @@ base64urlToBuffer(jwk.y, byteLen)

if (!key.slice(0, 1).equals(Buffer.from([4]))) {
if (uint8ArrayEquals(!key.slice(0, 1), Uint8Array.from([4]))) {
throw errcode(new Error('Cannot unmarshal public key - invalid key format'), 'ERR_INVALID_KEY_FORMAT')

@@ -112,4 +116,4 @@ }

crv: curve,
x: bufferToBase64url(key.slice(1, byteLen + 1), byteLen),
y: bufferToBase64url(key.slice(1 + byteLen), byteLen),
x: uint8ArrayToString(key.slice(1, byteLen + 1), 'base64url'),
y: uint8ArrayToString(key.slice(1 + byteLen), 'base64url'),
ext: true

@@ -121,3 +125,3 @@ }

...unmarshalPublicKey(curve, key.public),
d: bufferToBase64url(key.private)
d: uint8ArrayToString(key.private, 'base64url')
})
'use strict'
const { Buffer } = require('buffer')
const sha = require('multihashing-async/src/sha')

@@ -8,2 +7,3 @@ const protobuf = require('protons')

const errcode = require('err-code')
const uint8ArrayEquals = require('uint8arrays/equals')

@@ -24,3 +24,3 @@ const crypto = require('./ed25519')

marshal () {
return Buffer.from(this._key)
return this._key
}

@@ -36,3 +36,3 @@

equals (key) {
return this.bytes.equals(key.bytes)
return uint8ArrayEquals(this.bytes, key.bytes)
}

@@ -46,4 +46,4 @@

class Ed25519PrivateKey {
// key - 64 byte Uint8Array or Buffer containing private key
// publicKey - 32 byte Uint8Array or Buffer containing public key
// key - 64 byte Uint8Array containing private key
// publicKey - 32 byte Uint8Array containing public key
constructor (key, publicKey) {

@@ -63,3 +63,3 @@ this._key = ensureKey(key, crypto.privateKeyLength)

marshal () {
return Buffer.concat([Buffer.from(this._key), Buffer.from(this._publicKey)])
return this._key
}

@@ -75,3 +75,3 @@

equals (key) {
return this.bytes.equals(key.bytes)
return uint8ArrayEquals(this.bytes, key.bytes)
}

@@ -102,3 +102,3 @@

* @param {string} [format=libp2p-key] - The format in which to export as
* @returns {Promise<Buffer>} The encrypted private key
* @returns {Promise<Uint8Array>} The encrypted private key
*/

@@ -147,3 +147,3 @@ async export (password, format = 'libp2p-key') { // eslint-disable-line require-await

if (key.length !== length) {
throw errcode(new Error(`Key must be a Uint8Array or Buffer of length ${length}, got ${key.length}`), 'ERR_INVALID_KEY_TYPE')
throw errcode(new Error(`Key must be a Uint8Array of length ${length}, got ${key.length}`), 'ERR_INVALID_KEY_TYPE')
}

@@ -150,0 +150,0 @@ return key

@@ -19,3 +19,3 @@ 'use strict'

return forge.pki.ed25519.sign({ message: msg, privateKey: key })
// return Buffer.from(nacl.sign.detached(msg, key))
// return Uint8Array.from(nacl.sign.detached(msg, key))
}

@@ -22,0 +22,0 @@

@@ -12,3 +12,3 @@ 'use strict'

*
* @param {Buffer} privateKey The PrivateKey protobuf buffer
* @param {Uint8Array} privateKey The PrivateKey protobuf
* @param {string} password

@@ -15,0 +15,0 @@ * @returns {Promise<string>} A base64 encoded string

@@ -14,3 +14,3 @@ 'use strict'

* @param {string} password
* @returns {Promise<Buffer>} The private key protobuf buffer
* @returns {Promise<Uint8Array>} The private key protobuf
*/

@@ -17,0 +17,0 @@ import: async function (privateKey, password) {

'use strict'
const { Buffer } = require('buffer')
const protobuf = require('protons')

@@ -10,2 +9,3 @@ const keysPBM = protobuf(require('./keys.proto'))

const errcode = require('err-code')
const uint8ArrayFromString = require('uint8arrays/from-string')

@@ -134,4 +134,4 @@ const importer = require('./importer')

let der = forge.asn1.toDer(forge.pki.privateKeyToAsn1(key))
der = Buffer.from(der.getBytes(), 'binary')
der = uint8ArrayFromString(der.getBytes(), 'ascii')
return supportedKeys.rsa.unmarshalRsaPrivateKey(der)
}
'use strict'
const { Buffer } = require('buffer')
const errcode = require('err-code')
const uint8ArrayConcat = require('uint8arrays/concat')
const uint8ArrayFromString = require('uint8arrays/from-string')
const hmac = require('../hmac')

@@ -38,3 +40,3 @@

const hmacKeySize = 20
const seed = Buffer.from('key expansion')
const seed = uint8ArrayFromString('key expansion')
const resultLength = 2 * (ivSize + cipherKeySize + hmacKeySize)

@@ -49,3 +51,3 @@

while (j < resultLength) {
const b = await m.digest(Buffer.concat([a, seed]))
const b = await m.digest(uint8ArrayConcat([a, seed]))
let todo = b.length

@@ -63,3 +65,3 @@

const half = resultLength / 2
const resultBuffer = Buffer.concat(result)
const resultBuffer = uint8ArrayConcat(result)
const r1 = resultBuffer.slice(0, half)

@@ -66,0 +68,0 @@ const r2 = resultBuffer.slice(half, resultLength)

'use strict'
const { Buffer } = require('buffer')
const webcrypto = require('../webcrypto')
const randomBytes = require('../random-bytes')
const uint8ArrayToString = require('uint8arrays/to-string')
const uint8ArrayFromString = require('uint8arrays/from-string')

@@ -78,3 +79,3 @@ exports.utils = require('./rsa-utils')

return Buffer.from(sig)
return new Uint8Array(sig, sig.byteOffset, sig.byteLength)
}

@@ -133,4 +134,4 @@

- Convert JWK to nodeForge
- Convert msg buffer to nodeForge buffer: ByteBuffer is a "binary-string backed buffer", so let's make our buffer a binary string
- Convert resulting nodeForge buffer to buffer: it returns a binary string, turn that into a uint8array(buffer)
- Convert msg Uint8Array to nodeForge buffer: ByteBuffer is a "binary-string backed buffer", so let's make our Uint8Array a binary string
- Convert resulting nodeForge buffer to Uint8Array: it returns a binary string, turn that into a Uint8Array

@@ -143,5 +144,5 @@ */

const fkey = pub ? jwk2pub(key) : jwk2priv(key)
const fmsg = Buffer.from(msg).toString('binary')
const fmsg = uint8ArrayToString(Uint8Array.from(msg), 'ascii')
const fomsg = handle(fmsg, fkey)
return Buffer.from(fomsg, 'binary')
return uint8ArrayFromString(fomsg, 'ascii')
}

@@ -148,0 +149,0 @@

@@ -5,4 +5,5 @@ 'use strict'

const protobuf = require('protons')
const multibase = require('multibase')
const errcode = require('err-code')
const uint8ArrayEquals = require('uint8arrays/equals')
const uint8ArrayToString = require('uint8arrays/to-string')

@@ -42,3 +43,3 @@ require('node-forge/lib/sha512')

equals (key) {
return this.bytes.equals(key.bytes)
return uint8ArrayEquals(this.bytes, key.bytes)
}

@@ -53,3 +54,3 @@

// key - Object of the jwk format
// publicKey - Buffer of the spki format
// publicKey - Uint8Array of the spki format
constructor (key, publicKey) {

@@ -92,3 +93,3 @@ this._key = key

equals (key) {
return this.bytes.equals(key.bytes)
return uint8ArrayEquals(this.bytes, key.bytes)
}

@@ -111,3 +112,3 @@

const hash = await this.public.hash()
return multibase.encode('base58btc', hash).toString().slice(1)
return uint8ArrayToString(hash, 'base58btc')
}

@@ -114,0 +115,0 @@

'use strict'
const { Buffer } = require('buffer')
require('node-forge/lib/asn1')

@@ -8,7 +7,8 @@ require('node-forge/lib/rsa')

const { bigIntegerToUintBase64url, base64urlToBigInteger } = require('./../util')
const uint8ArrayFromString = require('uint8arrays/from-string')
const uint8ArrayToString = require('uint8arrays/to-string')
// Convert a PKCS#1 in ASN1 DER format to a JWK key
exports.pkcs1ToJwk = function (bytes) {
bytes = Buffer.from(bytes) // convert Uint8Arrays
const asn1 = forge.asn1.fromDer(bytes.toString('binary'))
const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))
const privateKey = forge.pki.privateKeyFromAsn1(asn1)

@@ -45,3 +45,3 @@

return Buffer.from(forge.asn1.toDer(asn1).getBytes(), 'binary')
return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')
}

@@ -51,3 +51,3 @@

exports.pkixToJwk = function (bytes) {
const asn1 = forge.asn1.fromDer(bytes.toString('binary'))
const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'))
const publicKey = forge.pki.publicKeyFromAsn1(asn1)

@@ -71,3 +71,3 @@

return Buffer.from(forge.asn1.toDer(asn1).getBytes(), 'binary')
return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii')
}
'use strict'
const multibase = require('multibase')
const sha = require('multihashing-async/src/sha')
const errcode = require('err-code')
const uint8ArrayEquals = require('uint8arrays/equals')
const uint8ArrayToString = require('uint8arrays/to-string')

@@ -34,3 +35,3 @@ const exporter = require('./exporter')

equals (key) {
return this.bytes.equals(key.bytes)
return uint8ArrayEquals(this.bytes, key.bytes)
}

@@ -71,3 +72,3 @@

equals (key) {
return this.bytes.equals(key.bytes)
return uint8ArrayEquals(this.bytes, key.bytes)
}

@@ -90,3 +91,3 @@

const hash = await this.public.hash()
return multibase.encode('base58btc', hash).toString().slice(1)
return uint8ArrayToString(hash, 'base58btc')
}

@@ -93,0 +94,0 @@

'use strict'
const { Buffer } = require('buffer')
var isTypedArray = require('is-typedarray').strict
const secp256k1 = require('secp256k1')

@@ -9,17 +7,2 @@ const sha = require('multihashing-async/src/sha')

function typedArrayTobuffer (arr) {
if (isTypedArray(arr)) {
// To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer
var buf = Buffer.from(arr.buffer)
if (arr.byteLength !== arr.buffer.byteLength) {
// Respect the "view", i.e. byteOffset and byteLength, without doing a copy
buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)
}
return buf
} else {
// Pass through all other types to `Buffer.from`
return Buffer.from(arr)
}
}
module.exports = (randomBytes) => {

@@ -39,3 +22,3 @@ const privateKeyLength = 32

const sig = secp256k1.ecdsaSign(digest, key)
return typedArrayTobuffer(secp256k1.signatureExport(sig.signature))
return secp256k1.signatureExport(sig.signature)
}

@@ -45,3 +28,3 @@

const digest = await sha.digest(msg, HASH_ALGORITHM)
sig = typedArrayTobuffer(secp256k1.signatureImport(sig))
sig = secp256k1.signatureImport(sig)
return secp256k1.ecdsaVerify(sig, digest, key)

@@ -54,7 +37,7 @@ }

}
return typedArrayTobuffer(secp256k1.publicKeyConvert(key, true))
return secp256k1.publicKeyConvert(key, true)
}
function decompressPublicKey (key) {
return typedArrayTobuffer(secp256k1.publicKeyConvert(key, false))
return secp256k1.publicKeyConvert(key, false)
}

@@ -76,3 +59,3 @@

validatePrivateKey(privateKey)
return typedArrayTobuffer(secp256k1.publicKeyCreate(privateKey))
return secp256k1.publicKeyCreate(privateKey)
}

@@ -79,0 +62,0 @@

'use strict'
const { Buffer } = require('buffer')
require('node-forge/lib/util')
require('node-forge/lib/jsbn')
const forge = require('node-forge/lib/forge')
const uint8ArrayFromString = require('uint8arrays/from-string')
const uint8ArrayToString = require('uint8arrays/to-string')
const uint8ArrayConcat = require('uint8arrays/concat')
exports.bigIntegerToUintBase64url = (num, len) => {
// Call `.abs()` to convert to unsigned
let buf = Buffer.from(num.abs().toByteArray()) // toByteArray converts to big endian
let buf = Uint8Array.from(num.abs().toByteArray()) // toByteArray converts to big endian

@@ -20,34 +22,20 @@ // toByteArray() gives us back a signed array, which will include a leading 0

if (buf.length > len) throw new Error('byte array longer than desired length')
buf = Buffer.concat([Buffer.alloc(len - buf.length), buf])
buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])
}
return exports.bufferToBase64url(buf)
return uint8ArrayToString(buf, 'base64url')
}
// Convert a Buffer to a base64 encoded string without padding
// Adapted from https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#appendix-C
exports.bufferToBase64url = buf => {
return buf
.toString('base64')
.split('=')[0] // Remove any trailing '='s
.replace(/\+/g, '-') // 62nd char of encoding
.replace(/\//g, '_') // 63rd char of encoding
}
// Convert a base64url encoded string to a BigInteger
exports.base64urlToBigInteger = str => {
const buf = exports.base64urlToBuffer(str)
return new forge.jsbn.BigInteger(buf.toString('hex'), 16)
return new forge.jsbn.BigInteger(uint8ArrayToString(buf, 'base16'), 16)
}
exports.base64urlToBuffer = (str, len) => {
str = (str + '==='.slice((str.length + 3) % 4))
.replace(/-/g, '+')
.replace(/_/g, '/')
let buf = uint8ArrayFromString(str, 'base64urlpad')
let buf = Buffer.from(str, 'base64')
if (len != null) {
if (buf.length > len) throw new Error('byte array longer than desired length')
buf = Buffer.concat([Buffer.alloc(len - buf.length), buf])
buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])
}

@@ -54,0 +42,0 @@

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc