Usare OpenPGP in Node.js

Mattepuffo's logo
Usare OpenPGP in Node.js

Usare OpenPGP in Node.js

Piccolo esempio minimale su come usare OpenPGP in Node.js con la libreria OpenPGP.js!

La nostra applicazione si basa su Express, e quindi prevede l'uso di qualche rotta.

Prima di tutto installiamo la libreria:

npm install --save openpgp

Detto ciò questa la nostra rotta principale:

const express = require('express');
const router = express.Router();
const openpgp = require('openpgp');

router.get('/', function (req, res, next) {
    (async () => {
        const encrypted = await openpgp.encrypt({
            message: await openpgp.createMessage({text: 'MESSAGGIO'}),
            passwords: ['PASSWORD']
        });
        console.log(encrypted);

        const message = await openpgp.readMessage({
            armoredMessage: encrypted
        });
        const {data: decrypted} = await openpgp.decrypt({
            message: message,
            passwords: ['PASSWORD']
        });
        console.log(decrypted);
    })();
});

module.exports = router;

Questo il risultato in console:

  test-express:server Listening on port 3000 +0ms
GET / 304 219.857 ms - -
-----BEGIN PGP MESSAGE-----

wy4ECQMIpwv1yWGtiIvghz5lIH1dmSaaSAjwKjVAKdaIiMZkM/Di81Nk0nUl
O0EF0joBvZc8V6dI4Kc1i/qAo6m5qgy5nNZ1zxP8qcEZZSRBMYkQaYGAeD56
HjDJZMC5lEYSf0nzEn7yUzv6
=Ehk8
-----END PGP MESSAGE-----

MESSAGGIO
GET /stylesheets/style.css 304 1.594 ms - -

Per accedere dovete aprire un browser sull'indirizzo localhost:3000 (sempre che non abbiate cambiato qualche parametro).

Il testo da criptare/decriptare e la password li ho impostati fissi nel codice.

Come esercizio potreste vedere di passarli come parametri.

Per completezza vi giro anche il file app.js, che è l'entry point della mia applicazione:

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

app.use(function (req, res, next) {
    next(createError(404));
});

app.use(function (err, req, res, next) {
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

Enjoy!


Condividi

Commentami!