feat: add randomBytes function (#45)

* feat: add randomBytes function

* fix: apply CR
This commit is contained in:
David Dias 2016-12-01 11:42:19 +00:00 committed by GitHub
parent f979fcd3c2
commit 98b37d49c4
3 changed files with 27 additions and 0 deletions

View File

@ -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. 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 ## Contribute

View File

@ -71,3 +71,12 @@ exports.marshalPrivateKey = (key, type) => {
return key.bytes 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
}

View File

@ -97,5 +97,18 @@ describe('libp2p-crypto', () => {
true 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)
})
}) })
}) })