Skip to content

Instantly share code, notes, and snippets.

@deian
Created May 25, 2014 01:56
Show Gist options
  • Save deian/f2de2f1c33580ed1b3fd to your computer and use it in GitHub Desktop.
Save deian/f2de2f1c33580ed1b3fd to your computer and use it in GitHub Desktop.
Using OpenPGP.JS to verify signature of a file
"use strict";
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var async = require('async');
var crypto = require('crypto');
var pgp = require('openpgp');
// Get keys from keyring
// The keyring is stored in openpgp.store/openpgp-public-keys
var keyring = new pgp.Keyring(),
keys = keyring.getAllKeys();
if(keys.length <= 0) {
throw "Unexpected keyring size";
}
// Make sure that all the keys in the keyring are valid.
// At a later point we may want to allow invalid keys so long as the
// update is not signed with these.
keys.forEach(function (key) {
if( key.verifyPrimaryKey() !== pgp.enums.keyStatus.valid ) {
throw ("Failed to verify key "+key.primaryKey.fingerprint);
}
console.log("Verified "+key.primaryKey.fingerprint
+" ["+key.users[0].userId.userid+"]");
});
verify_update(**FILETOVERIFY**, keys, function(err, result) {
if (err) throw err;
});
// Each update tarball should have an accompaning cleartext signed
// sha1sum file. This file is created as:
//
// sha1sum $update > $update.sha1sum
// gpg --armor --clearsign $update.sha1sum
//
// Where $update is the filename of the update tarball.
// This function first verifies the signature with the supplied keys
// and then the actual sha1 of the file.
//
// Note: this function assues that the supplied keys are valid.
function verify_update(filename, keys, cb_) {
var sig_name = filename+".sha1sum.asc";
console.log("Reading signature file \'"+sig_name+"\'");
fs.readFile(filename+'.sha1sum.asc', 'utf8', function(err, data) {
if (err) { return cb_(err); }
var sig = pgp.cleartext.readArmored(data);
var verified = sig.verify(keys);
if (!verified || verified.length <= 0 || !verified[0].valid) {
console.log("Verifying signature: FAILED!");
return cb_("Invalid signature.");
}
console.log("Verifying signature: OK!");
return verify_sha1sum(filename, sig.text.split(' ')[0], cb_);
});
}
function verify_sha1sum(filename, sha1sum, cb_) {
var hash = crypto.createHash('sha1');
var inp = fs.createReadStream(filename);
hash.setEncoding('hex');
inp.on('error', cb_)
.on('end', function() {
hash.end();
if(hash.read() !== sha1sum) {
console.log("Verifying SHA1 of \'"+filename+"\': FAILED!");
return cb_("Invalid sha1sum; expected: "+sha1sum+
", got: "+hash.read());
} else {
console.log("Verifying SHA1 of \'"+filename+"\': OK!");
return cb_();
}
});
inp.pipe(hash);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment