简体   繁体   中英

Calculate the key id of public key using openpgp.js

Using OpenPGP.js v1.3.0 I can successfully create a public/private key pair and encrypt/decrypt ok.

I am struggling to obtain the key id using this function (found in openpgp.js and public_key.js):

/**
 * Calculates the key id of the key
 * @return {String} A 8 byte key id
 */
PublicKey.prototype.getKeyId = function () {
  if (this.keyid) {
    return this.keyid;
  }
  this.keyid = new type_keyid();
  if (this.version == 4) {
    this.keyid.read(util.hex2bin(this.getFingerprint()).substr(12, 8));
  } else if (this.version == 3) {
    this.keyid.read(this.mpi[0].write().substr(-8));
  }
  return this.keyid;
};

PublicKey() also in openpgp.js:

/**
 * @constructor
 */
function PublicKey() {
  this.tag = enums.packet.publicKey;
  this.version = 4;
  /** Key creation date.
   * @type {Date} */
  this.created = new Date();
  /** A list of multiprecision integers
   * @type {module:type/mpi} */
  this.mpi = [];
  /** Public key algorithm
   * @type {module:enums.publicKey} */
  this.algorithm = 'rsa_sign';
  // time in days (V3 only)
  this.expirationTimeV3 = 0;
  /**
   * Fingerprint in lowercase hex
   * @type {String}
   */
  this.fingerprint = null;
  /**
   * Keyid
   * @type {module:type/keyid}
   */
  this.keyid = null;
}

and trying to get the key id like this:

var publickey = openpgp.key.readArmored(myPublicKey);
//var keyID = openpgp.packet.PublicKey(publickey).getKeyId()[0].toHex();
var keyID = openpgp.PublicKey(publickey).getKeyId()[0].toHex();
console.log(keyID);

which gives me the error: TypeError: openpgp.PublicKey is not a function.

Thanks.

I asked the question here: http://www.mail-archive.com/list@openpgpjs.org/msg00932.html and received a very helpful reply.

var openpgp = window.openpgp;
var testPublicKey = sessionStorage.getItem('testPublicKey');
var foundKeys = openpgp.key.readArmored(testPublicKey).keys;

if (!foundKeys || foundKeys.length !== 1) {
    throw new Error("Key not read, or more than one key found");
}

var pubKey = foundKeys[0]; foundKeys = null;

var getFingerprint = function (key) {
    // openpgp.key <- Class
    // key <- Instance received by params
    return key.primaryKey.fingerprint;
};

var getKeyId = function (key) {
    return key.primaryKey.getKeyId().toHex();
}

console.log(getFingerprint(pubKey));
console.log(getKeyId(pubKey));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM