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.
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 #javascript #node #security #web-development