Learn how to encode and encrypt simple strings and numbers in Node.js with Typescript

In a project that I worked on a while ago, I was presented with a problem that wasn’t very unique. It involved how we could safely pass identifiable user information such as phone numbers encoded and encrypted by a third party service in Ruby, to be decrypted and decoded into our application for the user.

//Link with encrypted token
https://example.com?token=XXXXX

Ruby provides straightforward handling for signed and unsigned big endians using pack() and unpack() methods for accessing underlying bits and bytes. However, Javascript has the problem of not properly handling large integers, as it can only store signed or unsigned integers of up to 53 bits. See Number.MAX_SAFE_INTEGER.

Image for post

Photo by Austin Distel on Unsplash

In this case, we both shared the same encryption key, a process known as Symmetric Encryption. This means that the same encryption key must be used to decrypt the data.

In that project and some applications, where we want to encode and encrypt sensitive data, we also need to be able to decode and decrypt this information, when we need it, anywhere in our application, as such that the decrypted value is not altered during the process ensuring Data Integrity. Essentially:

const value = 0123456789 // Initial value
const token = encrypt(value) // Encrypted token
const decryptedValue = decrypt(token) // Decrypted value
value === decryptedValue // Must be TRUE

Simply using Base64 encoding, which will obfuscate and create short tokens is not a reliable security solution as Base64 strings can be easily decoded. For this article, I will demonstrate how you can create a simple, secure and fast symmetric encryption solution to encrypt data, and applied across any application even as short, SEO-friendly URL parameters using the following tools:-

  • Typescript — adds static typed definitions to JavaScript
  • Symmetric Encryption — cryptographic encryption technique which uses the same encryption keys for both encryption and decryption of data
  • Crypto — built-in Node.js module which provides cryptographic functionality
  • Buffer — subclass of JavaScript’s Uint8Array class used for character encoding and decoding
  • Testing using Mocha and Chai
  • Automated testing, version management and package publishing using GitHub, CircleCI and Semantic release

#typescript #javascript #node #security #web-development

A Simple Encryption Library in Node.js with Typescript
14.85 GEEK