|
1 |
| -cipher-base |
2 |
| -=== |
| 1 | +# cipher-base |
3 | 2 |
|
4 |
| -[](https://travis-ci.org/crypto-browserify/cipher-base) |
| 3 | +[](https://www.npmjs.org/package/cipher-base) |
| 4 | +[](https://travis-ci.org/crypto-browserify/cipher-base) |
5 | 5 |
|
6 |
| -Abstract base class to inherit from if you want to create streams implementing |
7 |
| -the same api as node crypto streams. |
| 6 | +[](https://github.com./feross/standard) |
8 | 7 |
|
9 |
| -Requires you to implement 2 methods `_final` and `_update`. `_update` takes a |
10 |
| -buffer and should return a buffer, `_final` takes no arguments and should return |
11 |
| -a buffer. |
| 8 | +Abstract base class to inherit from if you want to create streams implementing the same API as node crypto [Cipher][1] or [Decipher][2] (for [Hash][3] check [crypto-browserify/hash-base][4]). |
12 | 9 |
|
| 10 | +## Example |
13 | 11 |
|
14 |
| -The constructor takes one argument and that is a string which if present switches |
15 |
| -it into hash mode, i.e. the object you get from crypto.createHash or |
16 |
| -crypto.createSign, this switches the name of the final method to be the string |
17 |
| -you passed instead of `final` and returns `this` from update. |
| 12 | +```js |
| 13 | +const CipherBase = require('cipher-base') |
| 14 | +const inherits = require('inherits') |
| 15 | + |
| 16 | +// our cipher will apply XOR 0x42 to every encrypted byte |
| 17 | +function MyCipher () { |
| 18 | + CipherBase.call(this, true) // for Deciper you need pass `false` |
| 19 | +} |
| 20 | + |
| 21 | +inherits(MyCipher, CipherBase) |
| 22 | + |
| 23 | +MyCipher.prototype._isAuthenticatedMode = function () { |
| 24 | + return false |
| 25 | +} |
| 26 | + |
| 27 | +MyCipher.prototype._setAutoPadding = function (ap) {} |
| 28 | +MyCipher.prototype._setAAD = function (aadbuf) {} |
| 29 | + |
| 30 | +MyCipher.prototype._update = function (data) { |
| 31 | + const result = Buffer.allocUnsafe(data.length) |
| 32 | + for (let i = 0; i < data.length; ++i) result[i] = data[i] ^ 0x42 |
| 33 | + return result |
| 34 | +} |
| 35 | + |
| 36 | +MyCipher.prototype._final = function () { |
| 37 | + return Buffer.allocUnsafe(0) |
| 38 | +} |
| 39 | + |
| 40 | +const data = Buffer.from([ 0x00, 0x42 ]) |
| 41 | +const cipher = new MyCipher() |
| 42 | +console.log(Buffer.concat([cipher.update(data), cipher.final()])) |
| 43 | +// => <Buffer 42 00> |
| 44 | +``` |
| 45 | + |
| 46 | +## LICENSE |
| 47 | + |
| 48 | +MIT |
| 49 | + |
| 50 | +[1]: https://nodejs.org/api/crypto.html#crypto_class_cipher |
| 51 | +[2]: https://nodejs.org/api/crypto.html#crypto_class_decipher |
| 52 | +[3]: https://nodejs.org/api/crypto.html#crypto_class_hash |
| 53 | +[4]: https://github.com./crypto-browserify/hash-base |
0 commit comments