83

復号化する必要のないパスワードとデータのハッシュにはbcryptを使用しています。復号化する必要がある他のユーザー情報を保護するにはどうすればよいですか?

たとえば、誰かがデータベースへのアクセス権を取得した場合に備えて、ユーザーの本名をプレーン テキストにしたくないとしましょう。これはやや機密性の高いデータですが、時々呼び出してプレーン テキストで表示する必要もあります。これを行う簡単な方法はありますか?

4

7 に答える 7

12

これは正しく答えられていますが、crypto ライブラリを使用するための適切なパターンはクラス ラッパー内にあり、これを長年にわたってさまざまなプロジェクトにコピー/貼り付けてきました。

const crypto = require("crypto");

class Encrypter {
  constructor(encryptionKey) {
    this.algorithm = "aes-192-cbc";
    this.key = crypto.scryptSync(encryptionKey, "salt", 24);
  }

  encrypt(clearText) {
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);
    const encrypted = cipher.update(clearText, "utf8", "hex");
    return [
      encrypted + cipher.final("hex"),
      Buffer.from(iv).toString("hex"),
    ].join("|");
  }

  dencrypt(encryptedText) {
    const [encrypted, iv] = encryptedText.split("|");
    if (!iv) throw new Error("IV not found");
    const decipher = crypto.createDecipheriv(
      this.algorithm,
      this.key,
      Buffer.from(iv, "hex")
    );
    return decipher.update(encrypted, "hex", "utf8") + decipher.final("utf8");
  }
}
// Usage

const encrypter = new Encrypter("secret");

const clearText = "adventure time";
const encrypted = encrypter.encrypt(clearText);
const dencrypted = encrypter.dencrypt(encrypted);

console.log({ worked: clearText === dencrypted });
于 2021-03-04T13:51:51.567 に答える