npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@emartech/easy-crypto

v4.0.1

Published

Provides simple wrappers around Node's crypto implementation.

Downloads

1,170

Maintainers

mfawalmfawalfcolombo-sapfcolombo-sapmrclsumrclsutaylor-sethtaylor-sethdputtadputtamkrikoormkrikoorsamthomas02samthomas02robertoraczemarsysrobertoraczemarsyseggarciaeggarciarollandghrollandghsap-nssap-nsirvansapirvansapdhruv-sapdhruv-sapandras-marton-emarsysandras-marton-emarsyssseidmedsseidmedfhasefhasealanshialanshijisaacsonjisaacsoni850773i850773csjakaboscsjakabosborcsaborcsabcsizmadiabcsizmadiaschroedersteffenschroedersteffensfarielsfarielbotondjavorkabotondjavorkai534456i534456daniel.balazsdaniel.balazstade82tade82probalazsprobalazsluca.fasolino.seluca.fasolino.sermafteiuscairmafteiuscailhammerllhammerlbencsobencsomfel0123mfel0123franziskajungfranziskajungd056437d056437ekkovatsekkovatslaralangnaularalangnauemarsys-stephen-ivesemarsys-stephen-ivestothbence8tothbence8earlpittsearlpittsiabrahamiabrahamzhollerzhollerbalintkemenyemarsysbalintkemenyemarsysccarrollemccarrollemdunaicapadunaicapabobby_russelbobby_russelsovagossovagostothmarci25tothmarci25mariannagmariannagestefanlesnjakovicestefanlesnjakovicmrmeszarosmrmeszarosbence.tothbence.tothjason-nelson-01jason-nelson-01drahos.istvandrahos.istvanpeccpeccbirokhunbirokhunlaszlo.orilaszlo.oridpkemarsysdpkemarsysnathan-matthews-sapnathan-matthews-saptroywiegandtroywiegandnikolett.tarnikolett.tarbronikabronikacenglersapcenglersapmlesh-sapmlesh-sapgillyesgillyesdanielisapdanielisapsridevirsridevirabieler-sapabieler-sapaidanlesh-sapaidanlesh-saptonyhsaptonyhsapkarlabrandlkarlabrandlkonradschewekonradschewemanasbommakantimanasbommakantidudaaslacidudaaslaciemarsys-securityemarsys-securitynorbert-levajsics-emarsysnorbert-levajsics-emarsysronnykrosseronnykrossevszegedivszegedisap-amsap-amnnieman-sapnnieman-sapariceemariceemdwolter_emarsysdwolter_emarsysrcsullagrcsullagttoth2ttoth2tbucsanszkitbucsanszkidszunomardszunomardschuppadschuppaandras.sarroandras.sarrondomkendomkesevket-atasevensevket-atasevenplsapplsapmattfeldhake_emarsysmattfeldhake_emarsysatittelatittelandrasp3aandrasp3amruellmruelladroszleradroszlererikpetroemarerikpetroemarrimo86rimo86tillmannrtillmannrmarkjarvismarkjarvisgeczirobertgecziroberttsiraitnpmtsiraitnpmbborsibborsizbalazszbalazsziyadgziyadgpinterapinteraapoonapoonianhelmrichianhelmrichvarszegikvarszegikrkumari03rkumari03cseby92cseby92bozsadambozsadamjfillmorejfillmoreviktor.szellviktor.szellbencekadaremarbencekadaremarroxanamsroxanamsdkocsis-emarsysdkocsis-emarsysdemajo_emsdemajo_emsmarko.fritzschemarko.fritzscheagruczaagruczadmorvaidmorvainish343nish343koloshkoloshazorahai3904azorahai3904skrivooskrivoomark.adorjanmark.adorjanburciburcidimitrovndimitrovnivanfroehlichivanfroehlichiulianmihaiiulianmihaixueboliangxuebolianggresztergreszterbercziandbercziandcrileycrileydrewhodsonsapdrewhodsonsapjviesersapjviesersapsixstepsixstepsap-jjfsap-jjfsapfssapfsattilamuller01attilamuller01scotthetrickscotthetrickoliverweisenburgeroliverweisenburgermaurogrecomaurogreconicolaeciumacnicolaeciumacasciortino1asciortino1pendicg24pendicg24marton.matusekmarton.matusekadamszabolcsadamszabolcsbtalosbtalosbence.utobence.utodaniels1404daniels1404saphendricksjoergsaphendricksjoergmmartin2mmartin2fenyopetifenyopetimmothersillmmothersillbrandon-sapbrandon-sappjohnson02pjohnson02mhunyadymhunyadymengjiao.zhaomengjiao.zhaoushnpmushnpmdkorposdkorposxin.hexin.heviauviauzsomborhzsomborhmuddammuddamnvkaur2nvkaur2jbleclercjbleclercjamescockerjamescockerarnaud.buchholzarnaud.buchholzjerryrichardsonjerryrichardsonretfalvibenceretfalvibenceakapaakapamklsmklskaajkaajknagyknagyrehrethrehrethmhegedusmhegedusmmartinmmartinbsoosbsoosemarsys-deployeremarsys-deployerdravendravenjudgejudgedaniel.bankydaniel.bankyszeistszeistrgargyargargyamarton.papp.emarsysmarton.papp.emarsysdgyenesdgyeness.viktors.viktorm4w4q7m4w4q7david.barkoczidavid.barkocziqw3rqw3rtamas.tothtamas.tothgergaczdgergaczdgerikegerikealkraalkraepgrubmairepgrubmairmorbanmorbanettancosettancosepmartiniepmartinigabor.balla.emarsysgabor.balla.emarsysmzsombormzsomborejperssonejperssonejwalkerejwalkerllosonczyllosonczyiben12iben12kartonfarkaskartonfarkasadamoaadamoambarnambarnapevapevabforgacsbforgacskozmakozmangabor84ngabor84zerosuxxzerosuxxedosreckiedosreckieadanieleadanielselatorselatorkkimakkkimakgaborbgaborbglendvaiglendvailverasztolverasztordoczirdoczifentosifentosiboristomicboristomicmbazsombazsodmihalekdmihaleklhalaszlhalaszevspasevskievspasevskidsztankodsztankotbugartbugarfqqdkfqqdkmenyhertfatyolmenyhertfatyolzoltanrideg-emarsyszoltanrideg-emarsyssarakollsarakollmmolnar-emarmmolnar-emarattila.galattila.galbenjamingehlbenjamingehltdorkaatdorkaalkonyalkonyagpap_emagpap_emavimtaaivimtaailloki-emarsyslloki-emarsysborziborzipmaksa_emarsyspmaksa_emarsysdfaragodfarago

Keywords

cryptoaes

Readme

node-easy-crypto Codeship Status for emartech/node-easy-crypto Depedencies Dev depedencies

Provides simple wrappers around Node's crypto implementation. The library provides two interfaces: simple and advanced. Simple mode is designed for ease-of-use and advanced mode provides some performance benefits in certain use-cases. See below for more details.

All the underlying crypto operations are the same.

Simple usage (Recommended)

To get started just require the lib and create an instance right away.

const crypto = require('crypto');
const easyCrypto = require('@emartech/easy-crypto');

const password = crypto.randomBytes(24).toString('hex');
const randomData = crypto.randomBytes(1024).toString('hex');

const ecrypto = easyCrypto(password);

async function exampleAsyncFunction() {
    const encrypted = await ecrypto.encrypt(randomData);
    const decrypted = await ecrypto.decrypt(encrypted);
    randomData === decrypted; //true
}

Advanced usage (Use for performance)

Key derivation is a resource heavy process. The default settings recompute the key before each encryption/decryption process.

These options allow you to cache the result of the key derivation. This is required if you need to encrypt/decrypt multiple times with the same derived key. Caching the keys with node-cache saves you the time to have to recompute it before every encryption/decryption.

To get started just require the lib and create an instance right away.

const crypto = require('crypto');
const easyCrypto = require('@emartech/easy-crypto');

const password = crypto.randomBytes(24).toString('hex');
const randomData = [
    crypto.randomBytes(1024).toString('hex'),
    crypto.randomBytes(1024).toString('hex'),
    crypto.randomBytes(1024).toString('hex')
];

const ecrypto = easyCrypto(password, {
  encryptCacheTtl: 3600,
  decryptCachePoolSize: 100,
});

async function exampleAsyncFunction() {
    const encrypted = await Promise.all(
        randomData.map(item => ecrypto.encrypt(item))
    );

    const decrypted = await Promise.all(
        encrypted.map(item => ecrypto.decrypt(item))
    );
    
    return data.reduce((allValid, item, index) => {
        return allValid && item === decrypted[index];
    }, true);
}

Interface

Initialization

There aren't too many options you can change and that is on purpose. This small wrapper library is secure by default. You can change two configurations: encryptCacheTtl, decryptCachePoolSize by passing them to the initialization function as follows:

let ecrypto = require('@emartech/easy-crypto')('password', {
  encryptCacheTtl: 3600,
  decryptCachePoolSize: 100,
});

password

password should be any normal string. It will be used to generate the encryption key.

encryptCacheTtl

Time in seconds while the same key is reused during encryption. Must be an integer.

decryptCachePoolSize

Maximum number of keys kept in the cache during decryption. Must be an integer.

encrypt(plaintext) -> ciphertext

plaintext must be utf-8 encoded string. It will be "converted" to bytes and those will be used for the cryptographic operations. The output of this operations is base64 encoded buffers. This will be used as the input of the decrypt operation. This return value is a Promise.

decrypt(ciphertext) -> plaintext

ciphertext must be the output of the encrypt method. The library is not compatible with any other encryption library out of the box! The output of this operation is the original utf-8 encoded string. This return value is a Promise.

The crypto parts

The library is only a thin wrapper of node's own crypto module. It uses well known and battle tested encryption techniques. It provides a convenient wrapper around these functions, taking away the details of using encryption correctly. Feel free to explore the source!

Encryption process

  1. It generates random bytes for later operations
  2. passwordSaltSize random bytes are used to create the 256 bit long encryption key from the password using pbkdf2 and the given iteration count
  3. The plaintext is encrypted using aes-256-gcm with the generated key and a 12 bytes long random initialization vector, this operation also yields a 16 bytes long authentication tag, which can be used to verify the encrypted data's integrity
  4. It concatenates the following data to into a buffer: passwordSalt bytes, initialization vector bytes, ciphertext bytes, authentication tag bytes
  5. It encodes the whole buffer using base64 and returns it

Decryption process

  1. It decodes the base64 input to bytes
  2. It slices this data into: passwordSalt bytes, initialization vector bytes, ciphertext bytes, authentication tag bytes
  3. The passwordSalt bytes and the password are used to generate the 256 bit long encryption key using pbkdf2 and the given iteration count
  4. The ciphertext bytes are decrypted using aes-256-gcm with the generated key the initialization vector bytes. During encryption the integrity of the date is also verified using the authentication tag bytes
  5. It encodes the decrypted buffer using utf-8 and returns it

Found a bug? Have a comment?

Please find us, we would love your feedback!