【问题标题】:Is it possible to encrypt a piece of text with a password to produce an encrypted text that is the same length as the original text in Node.js?是否可以用密码对一段文本进行加密,以生成与 Node.js 中的原始文本长度相同的加密文本?
【发布时间】:2021-05-12 23:54:11
【问题描述】:

我有 2 个变量:textpasswordtext 是我想加密的一些信息,password 是我想用来加密文本的密码。我了解如何在 Node.js 中加密文本,但我所需要的与我目前所见的不同。

我的目标是让函数使用密码处理文本,并生成与原始文本在长度上合理接近的内容。

这是我已经想出的:

class Encryptor {
    constructor(encryptionKey) {
        this.algorithm = "aes256";
        this.key = encryptionKey
    }
  
    encrypt(text) {
        var cipher = crypto.createCipher(this.algorithm, this.key);
        var encrypted = cipher.update(text, 'utf8', 'base64') + cipher.final('base64');

        return encrypted;
    }
  
    decrypt(encrypted) {
        var decipher = crypto.createDecipher(this.algorithm, this.key);
        var decrypted = decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8');

        return decrypted;
    }
}

我是这样使用的:

let text = "I am some secret info"
let password = "password"
let encryptor = new Encryptor(password);
let encrypted = encryptor.encrypt(text);

console.log(text.length, encrypted.length)

这给了我一个大约是原始长度 2 倍的加密文本。但是,当与magic... 之类的文本一起使用时,它的作用远不止于此。

这让我想到了我的问题:有没有办法用密码加密文本并生成长度接近原始文本的加密文本?

谢谢!

【问题讨论】:

    标签: node.js encryption cryptography


    【解决方案1】:

    您正在测量 base64 编码密文的长度。

    如果您需要对输出进行 base64 编码,那么对纯文本也进行 base64 编码,您会看到它们的长度大致相同。

    如果您不需要对输出进行 base64 编码,则不要对密文进行 base64 编码,您将再次看到它们的长度大致相同。

    您只是使用不同的编码方案对两条消息进行编码。但它们的信息量大致相同。以相同的方式对它们进行编码,它们的长度大致相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多