gpt4 book ai didi

node.js - 如何在flutter(解密)和Node(加密)中实现RSA?

转载 作者:行者123 更新时间:2023-12-03 03:58:39 34 4
gpt4 key购买 nike

我需要实现RSA。我从nodejs生成公钥和私钥,我将私钥发送给客户端。我能够使用来自nodejs的公钥加密数据,但无法从flutter解密,我曾在flutter中尝试过各种库(simple_rsa,加密等),但这些都不起作用,我收到填充错误,无效的私钥错误。有人可以建议我如何实现吗?

这是我的代码

Nodejs

    crypto.generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: '',
}
}, (err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
if(err)
throw err
//Publickey, PrivateKey
});
encrypt = function(data, publicKey) {
var buffer = Buffer.from(data);
var encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString("base64");
};

我正在向客户端发送加密功能返回值,这是味精
Flutter代码
(尝试过许多库,这是其中一个使用simple_rsa的库)
    final decpKey = "-----BEGIN RSA PRIVATE KEY-----\nProc-Type:.........";
final msg = "fH2EBmBS4fRHG1.............";

final decryptedText = await decryptString(msg, decpKey); //Error: Invalid private key
print(decryptedText);

最佳答案

Keygen(NodeJS)
文件:https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypair_type_options_callback

const { generateKeyPair } = require('crypto');

generateKeyPair('rsa', {
modulusLength: 4096, // key size in bits
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8', // !!! pkcs1 doesn't work for me
format: 'pem',
},
}, (err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
});
NodeJS 通过 JSEncrypt 库进行加密
节点jsencrypt: https://www.npmjs.com/package/node-jsencrypt
JSEncrypt: https://travistidwell.com/jsencrypt/#
const JSEncrypt = require('node-jsencrypt');  

function encrypt(text, key) {
const crypt = new JSEncrypt();
crypt.setKey(key);
return crypt.encrypt(text);
}

function decrypt(encrypted, privateKey) {
const crypt = new JSEncrypt();
crypt.setPrivateKey(privateKey);
return crypt.decrypt(encrypted);
}
Dart 通过 加密加密
GitHub上的 https://github.com/konstantinullrich/crypton
import 'package:crypton/crypton.dart';

import 'encryption.dart';

class AsymmetricCrypt implements Encryption {
final String _key;
RSAPublicKey _publicKey;
RSAPrivateKey _privateKey;

AsymmetricCrypt._(this._key);

@override
String encrypt(String plain) {
_publicKey ??= RSAPublicKey.fromPEM(_key);
return _publicKey.encrypt(plain);
}

@override
String decrypt(String data) {
_privateKey ??= RSAPrivateKey.fromPEM(_key);
return _privateKey.decrypt(data);
}
}

关于node.js - 如何在flutter(解密)和Node(加密)中实现RSA?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58960959/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com