How to encrypt a String with a Firebase Cloud Function

Viewed 1162

I'm trying to encrypt a string inside my Firebase Cloud Function. I would love to use SHA-256 or AES-256 for this. However I didn't find the right approach yet.

exports.myfunction = functions.https.onCall((data, context) => {  
  const someString = "Hello World!"
  const encryptedString = // How could I do this here?

  return encryptedString
})

Therefore any help is appreciated! Thanks.

3 Answers

A good choice for this is probably the crypto module. It provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

You can use crypto.createHash(algorithm\[, options\]) to encrypt a string. Check the documentation on this function.

This is the final solution:

// Use `require('crypto')` to access this module.
const crypto = require('crypto');

exports.myfunction = functions.https.onCall((data, context) => {  
  const secret = 'Hello World!';
  const hash = crypto.createHash('sha256')
                   .update(pwd)
                   .digest('base64'); // you can also use 'hex'
  return hash
})

Also take a look at the official documentation.

Install crypto-js with this command. npm install crypto-js

Then import it and encode your string.

const AES = require("crypto-js/aes");
const SHA256 = require("crypto-js/sha256");

exports.myfunction = functions.https.onCall((data, context) => {  
  const someString = "Hello World!";
  const encryptedString = SHA256(someString);
  // or
  const encryptedString = AES(someString);

  return encryptedString;
})

You may have a look at the Google Tink Library

A multi-language, cross-platform library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.

Related