Encrypt and decrypt from Javascript (nodeJS) to dart (Flutter) and from dart to Javascript

2,059

Solution 1

Keygen (NodeJS)

Docs: 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',      
        format: 'pem',
    },
}, (err, publicKey, privateKey) => {
    // Handle errors and use the generated key pair.
});

NodeJS encryption via JSEncrypt library

node-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 encryption via crypton

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);
  }
}

Solution 2

Check out this package for your crypto needs including RSA keys/ciphers.

Share:
2,059
paniko
Author by

paniko

Updated on December 16, 2022

Comments

  • paniko
    paniko over 1 year

    As the title suggests, I would like to know if there is a way to encrypt and decrypt, using for example the RSA algorithm, data from javascript to dart and the opposite. I saw that there is a library, 'js', which allows you to use javascript code in dart but I was not able to use it for what I need. I tried also to use various libraries provided for both languages ​​to perform these encryption operations but they are not compatible between the two languages.

  • paniko
    paniko about 4 years
    i saw the pointycastle package(dart) and cryptoJS (NodeJS) but i don't know how i can merge pointycastle with cryptoJS
  • Camilo Ortegón
    Camilo Ortegón over 3 years
    Wow, thank you so much, I've been looking for so long for a full response. This works perfectly with NodeJS and Flutter.