简体   繁体   English

如何使用 Firebase Cloud Function 加密字符串

[英]How to encrypt a String with a Firebase Cloud Function

I'm trying to encrypt a string inside my Firebase Cloud Function. I would love to use SHA-256 or AES-256 for this.我正在尝试加密我的 Firebase Cloud Function 中的一个字符串。我很乐意为此使用 SHA-256 或 AES-256。 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.谢谢。

A good choice for this is probably the crypto module.一个不错的选择可能是 crypto 模块。 It provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.它提供加密功能,包括一组用于 OpenSSL 的 hash、HMAC、密码、解密、签名和验证功能的包装器。

You can use crypto.createHash(algorithm\[, options\]) to encrypt a string.您可以使用crypto.createHash(algorithm\[, options\])来加密字符串。 Check the documentation on this function .查看有关此 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.使用此命令安装 crypto-js。 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您可以查看Google Tink 库

A multi-language, cross-platform library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.一种多语言、跨平台的库,提供安全、易于正确使用且难以(呃)滥用的加密 API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM