diff --git a/README.md b/README.md index 0bc8239..ed50879 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,11 @@ Converts a private key object into a protobuf serialized private key. Converts a protobuf serialized private key into its representative object. +### `randomBytes(number)` + +- `number: Number` + +Generates a Buffer with length `number` populated by random bytes. ## Contribute diff --git a/src/index.js b/src/index.js index 4bbe6f7..fb7e50e 100644 --- a/src/index.js +++ b/src/index.js @@ -71,3 +71,12 @@ exports.marshalPrivateKey = (key, type) => { return key.bytes } + +exports.randomBytes = (number) => { + if (!number || typeof number !== 'number') { + throw new Error('first argument must be a Number bigger than 0') + } + const buf = new Buffer(number) + c.rsa.getRandomValues(buf) + return buf +} diff --git a/test/index.spec.js b/test/index.spec.js index 0e9fe35..19b18a6 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -97,5 +97,18 @@ describe('libp2p-crypto', () => { true ) }) + + it('randomBytes throws with no number passed', () => { + expect(() => { + crypto.randomBytes() + }).to.throw + }) + + it('randomBytes', () => { + const buf1 = crypto.randomBytes(10) + expect(buf1.length).to.equal(10) + const buf2 = crypto.randomBytes(10) + expect(buf1).to.not.eql(buf2) + }) }) })