AnthonyzNg
AnthonyzNg

Reputation: 1

Flutter RSA Encryption - cannot use public key to encrypt string

there~ I am new at flutter development, I am trying to use the Node.js server to send a public key to flutter for encrypting the password However, it just not working, I had tried to send the public key by JSON format or by pem file to flutter and use [Flutter]-encrypt and [Flutter]-simple_rsa library to do the encrypted but it still not working. How can I do this? Please help,thanks a lot.

[Node.js] - using [node-rsa] to create the key [Flutter] - using [encrypt] to encrypt the string Code show as below:

Server-Side[Node.js]:

Key generator

function generator() {
         publicDer = key.exportKey('pkcs1-private-pem')
         privateDer = key.exportKey('pkcs1-public-pem')
        fs.writeFile('./pem/public.pem', publicDer, (err) => {
        if (err) throw err
        })
        fs.writeFile('./pem/private.pem', privateDer, (err) => {
        if (err) throw err
        })
    }

Send key.pem file to client

//------------------------send file to client
app.get('/getFile',(req,res)=>{
    var filePath = path.join(__dirname, './pem/public.pem');
    var stat = fs.statSync(filePath);
    res.writeHead(200,{
        'Content-Type': 'application/x-x509-ca-cert',
        'Content-Length': stat.size,
        'Content-Disposition' :'filename="PublicKey.pem'
    });
    var readStream = fs.createReadStream(filePath);
    readStream.pipe(res);
});

Client-Side [Flutter]

  Future<String> encode(pwd) async{
    try{
      Response response = await Dio().post("http://10.0.2.2:8124/login/key");
      print(response.data['pub_key'].toString());
      var tmp_str = 'Hello';
 
      if(await _checkPermission()==true){
       var tmp_path = await  _createPath();
       var result =  _downloadFile("http://10.0.2.2:8124/getFile",tmp_path);
       tmp_path += "PublicKey.pem";
      final publicKey = await parseKeyFromFile<RSAPublicKey>(tmp_path);
       final encrypter = Encrypter(RSA(publicKey: publicKey));
       final encrypted = encrypter.encrypt(tmp_str);
       print(encrypted.base64);
      }
    }catch(e){
          return e.toString();
    }
  }

Download pem file is successful. the result as below: enter image description here

Upvotes: 0

Views: 3570

Answers (1)

Quyen Anh Nguyen
Quyen Anh Nguyen

Reputation: 1720

You can use this package https://pub.dev/packages/encrypt#asymmetric Note that when follow example, I can't parse pem key so I modified a little bit like bellow then it works.

final publicPem = await rootBundle.loadString('assets/public.pem');
final publicKey1 = RSAKeyParser().parse(publicPem) as RSAPublicKey;

Upvotes: 1

Related Questions