diff --git a/LICENSE b/LICENSE index b249dfc..a58c00e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ The MIT License (MIT) -Copyright (c) 2016 Push.Rocks +Copyright (c) 2014 Maurice Butler +Copyright (c) 2016 Lossless GmbH Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/ts/index.ts b/ts/index.ts index a7bb233..1f57c5e 100644 --- a/ts/index.ts +++ b/ts/index.ts @@ -8,3 +8,5 @@ export { create, docker, normalize, indent }; export { Base64, base64 } from './smartstring.base64'; export { Domain } from './smartstring.domain'; export { GitRepo } from './smartstring.git'; + +export { Cryptr } from './smartstring.encryption'; diff --git a/ts/smartstring.encryption.ts b/ts/smartstring.encryption.ts new file mode 100644 index 0000000..fb6e6df --- /dev/null +++ b/ts/smartstring.encryption.ts @@ -0,0 +1,43 @@ +import * as plugins from './smartstring.plugins'; + +const algorithm = 'aes-256-ctr'; + +export class Cryptr { + private key: Buffer; + + constructor(secret) { + if (!secret || typeof secret !== 'string') { + throw new Error('Cryptr: secret must be a non-0-length string'); + } + + this.key = plugins.crypto + .createHash('sha256') + .update(String(secret)) + .digest(); + } + + encrypt(value: string) { + if (value == null) { + throw new Error('value must not be null or undefined'); + } + + const iv = plugins.crypto.randomBytes(16); + const cipher = plugins.crypto.createCipheriv(algorithm, this.key, iv); + const encrypted = cipher.update(String(value), 'utf8', 'hex') + cipher.final('hex'); + + return iv.toString('hex') + encrypted; + } + + decrypt(value: string) { + if (value == null) { + throw new Error('value must not be null or undefined'); + } + + const stringValue = String(value); + const iv = Buffer.from(stringValue.slice(0, 32), 'hex'); + const encrypted = stringValue.slice(32); + + const decipher = plugins.crypto.createDecipheriv(algorithm, this.key, iv); + return decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8'); + } +} diff --git a/ts/smartstring.plugins.ts b/ts/smartstring.plugins.ts index 9f5f479..4163605 100644 --- a/ts/smartstring.plugins.ts +++ b/ts/smartstring.plugins.ts @@ -1,6 +1,15 @@ +// node native +import * as crypto from 'crypto'; + +export { + crypto +} + +// third party export let jsBase64 = require('js-base64').Base64; export let stripIndent = require('strip-indent'); export let normalizeNewline = require('normalize-newline'); export let randomatic = require('randomatic'); export let cryptoRandomString = require('crypto-random-string'); +