Jac*_*nak 2 encryption rsa node.js
我正在使用 node-rsa 包通过 RSA 函数进行非对称加密。
目前,我正在生成我的公钥和私钥,如下所示:
generateKeys = function() {
const key = new NodeRSA({ b: 1024 });
return {
public: key.exportKey('public'),
private: key.exportKey('private'),
}
}
Run Code Online (Sandbox Code Playgroud)
有没有可能的方法从给定的字符串生成密钥?我想这样做,以便我的用户可以轻松写下他们的私钥,这对我的项目很重要。毕竟,写下 1024 个字符长的私钥几乎是不可能的。
我希望有这样的事情:
const key = new NodeRSA({ b: 1024 }, "Secret goes here")
Run Code Online (Sandbox Code Playgroud)
我认为这可能是可能的,因为 sha256 函数可以接受任何字符串进行哈希。我知道 RSA 加密并不是真正的哈希函数,所以我不确定是否可以达到相同的效果。
任何帮助表示赞赏!
似乎有一个简单的方法可以做到这一点。有一个名为 的包cryptico
可以做到这一点。
首先安装包:
npm i cryptico
Run Code Online (Sandbox Code Playgroud)
const cryptico = require('cryptico');
const PassPhrase = "The Moon is a Harsh Mistress.";
// The length of the RSA key, in bits.
const Bits = 1024;
const RSAkey = cryptico.generateRSAKey(PassPhrase, Bits);
const PublicKeyString = cryptico.publicKeyString(RSAkey);
Run Code Online (Sandbox Code Playgroud)
可以在这里找到更好、更完整的示例
因此,如果您需要ASYMMETRIC加密(据我所知,这适用于一对称为publickey和 的密钥privatekey),您可以简单地使用纯Node.js实现。
const { generateKeyPairSync, publicEncrypt, privateDecrypt } = require('crypto');
const PassPhrase = "The Moon is a Harsh Mistress.";
const Bits = 1024;
const encryptWithRSA = (input, publickey) => {
const buffer = Buffer.from(input, 'utf-8');
const encrypted = publicEncrypt(publicKey, buffer);
return encrypted.toString("base64");
}
const decryptWithRSA = function (input, privatekey) {
const buffer = Buffer.from(input, 'base64');
const decrypted = privateDecrypt(
{
key: privatekey,
passphrase: PassPhrase,
},
buffer,
)
return decrypted.toString("utf8");
};
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: Bits,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: PassPhrase
}
});
const encrypted = encryptWithRSA('yes i know', publicKey)
console.log(encrypted);
console.log(decryptWithRSA(encrypted, privateKey));
Run Code Online (Sandbox Code Playgroud)
encrypted如你所知,该值是随机的)t3Gw+PlKn84gx2wkj99we345C6ZjIElpgDkzXjio2aWRwI28qTMev14H7o219P6Lw9STGnfK4FgTYO/cvLGlzplqRv6X5AgrstwsGQN88wmKHe5+6cxlpzPFNPWLUqtAvsIOPZe+ghaRGCkOT2ETUp4PiqwOTJ2EtmyVqQHt+f4=
yes i know
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2427 次 |
| 最近记录: |