From 8505924f34b623816c99b7833a24db493645f7a5 Mon Sep 17 00:00:00 2001 From: BafS Date: Mon, 12 Feb 2018 17:20:34 +0100 Subject: [PATCH 1/4] Remove 'user strict' 'use strict' is unnecessary inside modules because module code is always strict mode code. Ref: https://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-code --- Gruntfile.js | 2 - src/cleartext.js | 2 - src/config/config.js | 2 - src/config/index.js | 2 - src/config/localStorage.js | 2 - src/crypto/cfb.js | 2 - src/crypto/cipher/aes.js | 2 - src/crypto/cipher/blowfish.js | 2 - src/crypto/cipher/cast5.js | 2 - src/crypto/cipher/des.js | 2 - src/crypto/cipher/index.js | 2 - src/crypto/crypto.js | 2 - src/crypto/gcm.js | 2 - src/crypto/hash/index.js | 2 - src/crypto/hash/md5.js | 2 - src/crypto/hash/sha.js | 2 - src/crypto/index.js | 2 - src/crypto/pkcs1.js | 2 - src/crypto/public_key/dsa.js | 2 - src/crypto/public_key/elgamal.js | 2 - src/crypto/public_key/elliptic/curves.js | 2 - src/crypto/public_key/elliptic/ecdh.js | 2 - src/crypto/public_key/elliptic/ecdsa.js | 2 - src/crypto/public_key/elliptic/eddsa.js | 2 - src/crypto/public_key/elliptic/index.js | 2 - src/crypto/public_key/elliptic/key.js | 2 - src/crypto/public_key/index.js | 2 - src/crypto/public_key/rsa.js | 2 - src/crypto/random.js | 2 - src/crypto/signature.js | 2 - src/encoding/armor.js | 2 - src/encoding/base64.js | 2 - src/enums.js | 2 - src/hkp.js | 2 - src/index.js | 2 - src/key.js | 2 - src/keyring/index.js | 2 - src/keyring/keyring.js | 2 - src/keyring/localstore.js | 2 - src/message.js | 2 - src/openpgp.js | 2 - src/packet/all_packets.js | 2 - src/packet/clone.js | 2 - src/packet/compressed.js | 2 - src/packet/index.js | 2 - src/packet/literal.js | 2 - src/packet/marker.js | 2 - src/packet/one_pass_signature.js | 2 - src/packet/packet.js | 2 - src/packet/packetlist.js | 2 - src/packet/public_key.js | 2 - .../public_key_encrypted_session_key.js | 2 - src/packet/public_subkey.js | 2 - src/packet/secret_key.js | 2 - src/packet/secret_subkey.js | 2 - src/packet/sym_encrypted_aead_protected.js | 2 - .../sym_encrypted_integrity_protected.js | 2 - src/packet/sym_encrypted_session_key.js | 2 - src/packet/symmetrically_encrypted.js | 2 - src/packet/trust.js | 2 - src/packet/user_attribute.js | 2 - src/packet/userid.js | 2 - src/signature.js | 2 - src/type/ecdh_symkey.js | 2 - src/type/kdf_params.js | 2 - src/type/keyid.js | 2 - src/type/mpi.js | 2 - src/type/oid.js | 2 - src/type/s2k.js | 2 - src/util.js | 2 - src/worker/async_proxy.js | 2 - test/crypto/aes_kw.js | 2 - test/crypto/cipher/aes.js | 6 +- test/crypto/cipher/blowfish.js | 2 - test/crypto/cipher/cast5.js | 4 +- test/crypto/cipher/des.js | 286 +++++++++--------- test/crypto/cipher/twofish.js | 2 - test/crypto/crypto.js | 2 - test/crypto/elliptic.js | 2 - test/crypto/hash/md5.js | 2 - test/crypto/hash/ripemd.js | 2 - test/crypto/hash/sha.js | 2 - test/crypto/pkcs5.js | 2 - test/crypto/random.js | 2 - test/general/armor.js | 4 +- test/general/ecc_nist.js | 2 - test/general/hkp.js | 2 - test/general/key.js | 2 - test/general/keyring.js | 2 - test/general/oid.js | 2 - test/general/openpgp.js | 2 - test/general/packet.js | 4 +- test/general/signature.js | 2 - test/general/util.js | 2 - test/general/x25519.js | 2 - test/worker/async_proxy.js | 2 - 96 files changed, 147 insertions(+), 339 deletions(-) diff --git a/Gruntfile.js b/Gruntfile.js index 9cd136bb..2e08483e 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,5 +1,3 @@ -'use strict'; - module.exports = function(grunt) { var lintFiles = [ diff --git a/src/cleartext.js b/src/cleartext.js index 94f49862..dd93f49f 100644 --- a/src/cleartext.js +++ b/src/cleartext.js @@ -24,8 +24,6 @@ * @module cleartext */ -'use strict'; - import config from './config'; import armor from './encoding/armor'; import enums from './enums'; diff --git a/src/config/config.js b/src/config/config.js index b2645463..1a9fccf8 100644 --- a/src/config/config.js +++ b/src/config/config.js @@ -21,8 +21,6 @@ * @module config/config */ -'use strict'; - import enums from '../enums.js'; export default { diff --git a/src/config/index.js b/src/config/index.js index 0de7718f..2beddebb 100644 --- a/src/config/index.js +++ b/src/config/index.js @@ -3,6 +3,4 @@ * @module config */ -'use strict'; - export { default } from './config.js'; \ No newline at end of file diff --git a/src/config/localStorage.js b/src/config/localStorage.js index 5718a036..000c2cec 100644 --- a/src/config/localStorage.js +++ b/src/config/localStorage.js @@ -3,8 +3,6 @@ * @module config/localStorage */ -'use strict'; - /** * @constructor */ diff --git a/src/crypto/cfb.js b/src/crypto/cfb.js index 1e2d8b00..d9ffbe55 100644 --- a/src/crypto/cfb.js +++ b/src/crypto/cfb.js @@ -22,8 +22,6 @@ * @module crypto/cfb */ -'use strict'; - import cipher from './cipher'; export default { diff --git a/src/crypto/cipher/aes.js b/src/crypto/cipher/aes.js index 8fc9c2e6..6197ace0 100644 --- a/src/crypto/cipher/aes.js +++ b/src/crypto/cipher/aes.js @@ -2,8 +2,6 @@ * @module crypto/cipher/aes */ -'use strict'; - import asmCrypto from 'asmcrypto-lite'; // TODO use webCrypto or nodeCrypto when possible. diff --git a/src/crypto/cipher/blowfish.js b/src/crypto/cipher/blowfish.js index 279e4497..f2404a16 100644 --- a/src/crypto/cipher/blowfish.js +++ b/src/crypto/cipher/blowfish.js @@ -7,8 +7,6 @@ * @module crypto/cipher/blowfish */ -'use strict'; - /* * Javascript implementation based on Bruce Schneier's reference implementation. * diff --git a/src/crypto/cipher/cast5.js b/src/crypto/cipher/cast5.js index 3a4a2d0c..19efcc93 100644 --- a/src/crypto/cipher/cast5.js +++ b/src/crypto/cipher/cast5.js @@ -16,8 +16,6 @@ /** @module crypto/cipher/cast5 */ -'use strict'; - function OpenpgpSymencCast5() { this.BlockSize = 8; this.KeySize = 16; diff --git a/src/crypto/cipher/des.js b/src/crypto/cipher/des.js index 321f3bce..300e71ed 100644 --- a/src/crypto/cipher/des.js +++ b/src/crypto/cipher/des.js @@ -25,8 +25,6 @@ * @module crypto/cipher/des */ -'use strict'; - function des(keys, message, encrypt, mode, iv, padding) { //declaring this locally speeds things up a bit var spfunction1 = new Array(0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, diff --git a/src/crypto/cipher/index.js b/src/crypto/cipher/index.js index 3f1274a6..1cf71cff 100644 --- a/src/crypto/cipher/index.js +++ b/src/crypto/cipher/index.js @@ -6,8 +6,6 @@ * @module crypto/cipher */ -'use strict'; - import aes from './aes.js'; import desModule from './des.js'; import cast5 from './cast5.js'; diff --git a/src/crypto/crypto.js b/src/crypto/crypto.js index 9bccc5ec..a8c1348e 100644 --- a/src/crypto/crypto.js +++ b/src/crypto/crypto.js @@ -28,8 +28,6 @@ * @module crypto/crypto */ -'use strict'; - import random from './random.js'; import cipher from './cipher'; import publicKey from './public_key'; diff --git a/src/crypto/gcm.js b/src/crypto/gcm.js index 39786cc8..e577a90f 100644 --- a/src/crypto/gcm.js +++ b/src/crypto/gcm.js @@ -20,8 +20,6 @@ * the WebCrypto api as well as node.js' crypto api. */ -'use strict'; - import asmCrypto from 'asmcrypto-lite'; import util from '../util.js'; import config from '../config'; diff --git a/src/crypto/hash/index.js b/src/crypto/hash/index.js index 1b6173e1..ce1a5918 100644 --- a/src/crypto/hash/index.js +++ b/src/crypto/hash/index.js @@ -5,8 +5,6 @@ * @module crypto/hash */ -'use strict'; - import Rusha from 'rusha'; import RIPEMD160 from 'ripemd160'; import asmCrypto from 'asmcrypto-lite'; diff --git a/src/crypto/hash/md5.js b/src/crypto/hash/md5.js index 3fd6c4e9..eb5a799b 100644 --- a/src/crypto/hash/md5.js +++ b/src/crypto/hash/md5.js @@ -17,8 +17,6 @@ * @module crypto/hash/md5 */ -'use strict'; - import util from '../../util.js'; /** diff --git a/src/crypto/hash/sha.js b/src/crypto/hash/sha.js index eb39c368..864b7924 100644 --- a/src/crypto/hash/sha.js +++ b/src/crypto/hash/sha.js @@ -19,8 +19,6 @@ * 1 = SHA-1, 2 = SHA-224/SHA-256, 4 = SHA-384/SHA-512 */ -"use strict"; - var SUPPORTED_ALGS = 4 | 2 | 1; /** diff --git a/src/crypto/index.js b/src/crypto/index.js index c1530db2..4b2cbe1f 100644 --- a/src/crypto/index.js +++ b/src/crypto/index.js @@ -3,8 +3,6 @@ * @module crypto */ -'use strict'; - import cipher from './cipher'; import hash from './hash'; import cfb from './cfb'; diff --git a/src/crypto/pkcs1.js b/src/crypto/pkcs1.js index a15d62d9..4ba3e1d1 100644 --- a/src/crypto/pkcs1.js +++ b/src/crypto/pkcs1.js @@ -25,8 +25,6 @@ * @module crypto/pkcs1 */ -'use strict'; - import random from './random.js'; import util from '../util.js'; import BigInteger from './public_key/jsbn.js'; diff --git a/src/crypto/public_key/dsa.js b/src/crypto/public_key/dsa.js index d9c20eed..3d6ec237 100644 --- a/src/crypto/public_key/dsa.js +++ b/src/crypto/public_key/dsa.js @@ -25,8 +25,6 @@ * @module crypto/public_key/dsa */ -'use strict'; - import BigInteger from './jsbn.js'; import random from '../random.js'; import hashModule from '../hash'; diff --git a/src/crypto/public_key/elgamal.js b/src/crypto/public_key/elgamal.js index 14b39016..f7a4175f 100644 --- a/src/crypto/public_key/elgamal.js +++ b/src/crypto/public_key/elgamal.js @@ -24,8 +24,6 @@ * @module crypto/public_key/elgamal */ -'use strict'; - import BigInteger from './jsbn.js'; import random from '../random.js'; import util from '../../util.js'; diff --git a/src/crypto/public_key/elliptic/curves.js b/src/crypto/public_key/elliptic/curves.js index 9b7cf974..b26e4de3 100644 --- a/src/crypto/public_key/elliptic/curves.js +++ b/src/crypto/public_key/elliptic/curves.js @@ -25,8 +25,6 @@ * @module crypto/public_key/elliptic/curve */ -'use strict'; - import { ec as EC, eddsa as EdDSA } from 'elliptic'; import { KeyPair } from './key'; import BigInteger from '../jsbn'; diff --git a/src/crypto/public_key/elliptic/ecdh.js b/src/crypto/public_key/elliptic/ecdh.js index ff5d3f4e..fdc97336 100644 --- a/src/crypto/public_key/elliptic/ecdh.js +++ b/src/crypto/public_key/elliptic/ecdh.js @@ -30,8 +30,6 @@ * @module crypto/public_key/elliptic/ecdh */ -'use strict'; - import curves from './curves'; import BigInteger from '../jsbn'; import cipher from '../../cipher'; diff --git a/src/crypto/public_key/elliptic/ecdsa.js b/src/crypto/public_key/elliptic/ecdsa.js index 0e2dd6e3..b64d2c69 100644 --- a/src/crypto/public_key/elliptic/ecdsa.js +++ b/src/crypto/public_key/elliptic/ecdsa.js @@ -24,8 +24,6 @@ * @module crypto/public_key/elliptic/ecdsa */ -'use strict'; - import hash from '../../hash'; import curves from './curves'; import BigInteger from '../jsbn'; diff --git a/src/crypto/public_key/elliptic/eddsa.js b/src/crypto/public_key/elliptic/eddsa.js index 4cf1e85b..485aff27 100644 --- a/src/crypto/public_key/elliptic/eddsa.js +++ b/src/crypto/public_key/elliptic/eddsa.js @@ -24,8 +24,6 @@ * @module crypto/public_key/elliptic/eddsa */ -'use strict'; - import BN from 'bn.js'; import hash from '../../hash'; import curves from './curves'; diff --git a/src/crypto/public_key/elliptic/index.js b/src/crypto/public_key/elliptic/index.js index 39108f0a..c250d594 100644 --- a/src/crypto/public_key/elliptic/index.js +++ b/src/crypto/public_key/elliptic/index.js @@ -25,8 +25,6 @@ * @module crypto/public_key/elliptic */ -'use strict'; - import {get, generate, getPreferredHashAlgo} from './curves'; import ecdsa from './ecdsa'; import eddsa from './eddsa'; diff --git a/src/crypto/public_key/elliptic/key.js b/src/crypto/public_key/elliptic/key.js index cc9d7404..b9fe25e4 100644 --- a/src/crypto/public_key/elliptic/key.js +++ b/src/crypto/public_key/elliptic/key.js @@ -30,8 +30,6 @@ * @module crypto/public_key/elliptic/key */ -'use strict'; - import curves from './curves'; import BigInteger from '../jsbn'; import hash from '../../hash'; diff --git a/src/crypto/public_key/index.js b/src/crypto/public_key/index.js index ed29c250..ae4aac89 100644 --- a/src/crypto/public_key/index.js +++ b/src/crypto/public_key/index.js @@ -6,8 +6,6 @@ * @module crypto/public_key */ -'use strict'; - /** @see module:crypto/public_key/rsa */ import rsa from './rsa.js'; /** @see module:crypto/public_key/elgamal */ diff --git a/src/crypto/public_key/rsa.js b/src/crypto/public_key/rsa.js index e87eb904..477530d9 100644 --- a/src/crypto/public_key/rsa.js +++ b/src/crypto/public_key/rsa.js @@ -24,8 +24,6 @@ * @module crypto/public_key/rsa */ -'use strict'; - import BigInteger from './jsbn.js'; import util from '../../util.js'; import random from '../random.js'; diff --git a/src/crypto/random.js b/src/crypto/random.js index dafa16b7..04166dea 100644 --- a/src/crypto/random.js +++ b/src/crypto/random.js @@ -23,8 +23,6 @@ * @module crypto/random */ -'use strict'; - import type_mpi from '../type/mpi.js'; import util from '../util.js'; diff --git a/src/crypto/signature.js b/src/crypto/signature.js index 07310966..96e86623 100644 --- a/src/crypto/signature.js +++ b/src/crypto/signature.js @@ -5,8 +5,6 @@ * @requires crypto/public_key * @module crypto/signature */ -'use strict'; - import util from '../util'; import publicKey from './public_key'; import pkcs1 from './pkcs1.js'; diff --git a/src/encoding/armor.js b/src/encoding/armor.js index 4c854910..eda28d86 100644 --- a/src/encoding/armor.js +++ b/src/encoding/armor.js @@ -22,8 +22,6 @@ * @module encoding/armor */ -'use strict'; - import base64 from './base64.js'; import enums from '../enums.js'; import config from '../config'; diff --git a/src/encoding/base64.js b/src/encoding/base64.js index e4d22cfe..b1d7bb9b 100644 --- a/src/encoding/base64.js +++ b/src/encoding/base64.js @@ -15,8 +15,6 @@ * @module encoding/base64 */ -'use strict'; - var b64s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Standard radix-64 var b64u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; // URL-safe radix-64 diff --git a/src/enums.js b/src/enums.js index 00040ea9..607b0e53 100644 --- a/src/enums.js +++ b/src/enums.js @@ -1,5 +1,3 @@ -'use strict'; - /** * @module enums */ diff --git a/src/hkp.js b/src/hkp.js index 5c967c8d..c4725c14 100644 --- a/src/hkp.js +++ b/src/hkp.js @@ -20,8 +20,6 @@ * in order to lookup and upload keys on standard public key servers. */ -'use strict'; - import config from './config'; /** diff --git a/src/index.js b/src/index.js index 1b242b87..0b771afe 100644 --- a/src/index.js +++ b/src/index.js @@ -1,7 +1,5 @@ /* eslint-disable import/newline-after-import, import/first */ -'use strict'; - /** * Export high level api as default. * Usage: diff --git a/src/key.js b/src/key.js index a929729c..35e4b0d5 100644 --- a/src/key.js +++ b/src/key.js @@ -25,8 +25,6 @@ * @module key */ -'use strict'; - import config from './config'; import crypto from './crypto'; import armor from './encoding/armor'; diff --git a/src/keyring/index.js b/src/keyring/index.js index 430e4caa..1279a644 100644 --- a/src/keyring/index.js +++ b/src/keyring/index.js @@ -1,5 +1,3 @@ -'use strict'; - /** * @see module:keyring/keyring * @module keyring diff --git a/src/keyring/keyring.js b/src/keyring/keyring.js index 7bb89ba9..8226ebe4 100644 --- a/src/keyring/keyring.js +++ b/src/keyring/keyring.js @@ -23,8 +23,6 @@ * @param {keyring/localstore} [storeHandler] class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods */ -'use strict'; - import { readArmored } from '../key'; import LocalStore from './localstore'; diff --git a/src/keyring/localstore.js b/src/keyring/localstore.js index 4bbc8588..3a6532f8 100644 --- a/src/keyring/localstore.js +++ b/src/keyring/localstore.js @@ -24,8 +24,6 @@ * @param {String} prefix prefix for itemnames in localstore */ -'use strict'; - import config from '../config'; import { readArmored } from '../key'; import util from '../util'; diff --git a/src/message.js b/src/message.js index dfd60da3..1f7002da 100644 --- a/src/message.js +++ b/src/message.js @@ -27,8 +27,6 @@ * @module message */ -'use strict'; - import config from './config'; import crypto from './crypto'; import armor from './encoding/armor'; diff --git a/src/openpgp.js b/src/openpgp.js index 8181351e..a82fc255 100644 --- a/src/openpgp.js +++ b/src/openpgp.js @@ -32,8 +32,6 @@ * for extending and developing on top of the base library. */ -'use strict'; - import * as messageLib from './message'; import { CleartextMessage } from './cleartext'; import { generate, reformat } from './key'; diff --git a/src/packet/all_packets.js b/src/packet/all_packets.js index 093e8770..e16c41c9 100644 --- a/src/packet/all_packets.js +++ b/src/packet/all_packets.js @@ -3,8 +3,6 @@ * @module packet */ -'use strict'; - import enums from '../enums.js'; import * as packets from './all_packets.js'; // re-import module to parse packets from tag diff --git a/src/packet/clone.js b/src/packet/clone.js index 8c7bff7d..8cd3f56e 100644 --- a/src/packet/clone.js +++ b/src/packet/clone.js @@ -21,8 +21,6 @@ * the structured cloning algorithm. */ -'use strict'; - import { Key } from '../key'; import { Message } from '../message'; import { CleartextMessage } from '../cleartext'; diff --git a/src/packet/compressed.js b/src/packet/compressed.js index b63ef6a7..991b7c97 100644 --- a/src/packet/compressed.js +++ b/src/packet/compressed.js @@ -29,8 +29,6 @@ * @module packet/compressed */ -'use strict'; - import enums from '../enums.js'; import util from '../util.js'; import Zlib from '../compression/zlib.min.js'; diff --git a/src/packet/index.js b/src/packet/index.js index 629a4b7f..81fedb82 100644 --- a/src/packet/index.js +++ b/src/packet/index.js @@ -1,5 +1,3 @@ -'use strict'; - import * as packets from './all_packets.js'; import * as clone from './clone.js'; import List from './packetlist.js'; diff --git a/src/packet/literal.js b/src/packet/literal.js index 4205b6df..4d6c29d8 100644 --- a/src/packet/literal.js +++ b/src/packet/literal.js @@ -25,8 +25,6 @@ * @module packet/literal */ -'use strict'; - import util from '../util.js'; import enums from '../enums.js'; diff --git a/src/packet/marker.js b/src/packet/marker.js index c3da0558..1c008a38 100644 --- a/src/packet/marker.js +++ b/src/packet/marker.js @@ -29,8 +29,6 @@ * @module packet/marker */ -'use strict'; - import enums from '../enums.js'; /** diff --git a/src/packet/one_pass_signature.js b/src/packet/one_pass_signature.js index bf80c33f..fa7fd2bd 100644 --- a/src/packet/one_pass_signature.js +++ b/src/packet/one_pass_signature.js @@ -29,8 +29,6 @@ * @module packet/one_pass_signature */ -'use strict'; - import util from '../util.js'; import enums from '../enums.js'; import type_keyid from '../type/keyid.js'; diff --git a/src/packet/packet.js b/src/packet/packet.js index 866e6524..7accc016 100644 --- a/src/packet/packet.js +++ b/src/packet/packet.js @@ -21,8 +21,6 @@ * @module packet/packet */ -'use strict'; - import util from '../util.js'; export default { diff --git a/src/packet/packetlist.js b/src/packet/packetlist.js index d671206a..63aff6e7 100644 --- a/src/packet/packetlist.js +++ b/src/packet/packetlist.js @@ -10,8 +10,6 @@ * @module packet/packetlist */ -'use strict'; - import util from '../util'; import packetParser from './packet.js'; import * as packets from './all_packets.js'; diff --git a/src/packet/public_key.js b/src/packet/public_key.js index 2d754af8..5e15edcf 100644 --- a/src/packet/public_key.js +++ b/src/packet/public_key.js @@ -29,8 +29,6 @@ * @module packet/public_key */ -'use strict'; - import crypto from '../crypto'; import enums from '../enums'; import util from '../util'; diff --git a/src/packet/public_key_encrypted_session_key.js b/src/packet/public_key_encrypted_session_key.js index 9d86e2e0..e6eebc9e 100644 --- a/src/packet/public_key_encrypted_session_key.js +++ b/src/packet/public_key_encrypted_session_key.js @@ -38,8 +38,6 @@ * @module packet/public_key_encrypted_session_key */ -'use strict'; - import type_keyid from '../type/keyid.js'; import util from '../util.js'; import type_ecdh_symkey from '../type/ecdh_symkey.js'; diff --git a/src/packet/public_subkey.js b/src/packet/public_subkey.js index 45b8523c..1c71a77a 100644 --- a/src/packet/public_subkey.js +++ b/src/packet/public_subkey.js @@ -21,8 +21,6 @@ * @module packet/public_subkey */ -'use strict'; - import publicKey from './public_key.js'; import enums from '../enums.js'; diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index 8c54d5db..f21880f4 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -31,8 +31,6 @@ * @module packet/secret_key */ -'use strict'; - import publicKey from './public_key.js'; import enums from '../enums.js'; import util from '../util.js'; diff --git a/src/packet/secret_subkey.js b/src/packet/secret_subkey.js index 45cc2563..2439cf7b 100644 --- a/src/packet/secret_subkey.js +++ b/src/packet/secret_subkey.js @@ -21,8 +21,6 @@ * @module packet/secret_subkey */ -'use strict'; - import secretKey from './secret_key.js'; import enums from '../enums.js'; diff --git a/src/packet/sym_encrypted_aead_protected.js b/src/packet/sym_encrypted_aead_protected.js index 36284b13..631ea56a 100644 --- a/src/packet/sym_encrypted_aead_protected.js +++ b/src/packet/sym_encrypted_aead_protected.js @@ -20,8 +20,6 @@ * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: AEAD Protected Data Packet */ -'use strict'; - import util from '../util.js'; import crypto from '../crypto'; import enums from '../enums.js'; diff --git a/src/packet/sym_encrypted_integrity_protected.js b/src/packet/sym_encrypted_integrity_protected.js index c7f6cfca..c236b44d 100644 --- a/src/packet/sym_encrypted_integrity_protected.js +++ b/src/packet/sym_encrypted_integrity_protected.js @@ -32,8 +32,6 @@ * @module packet/sym_encrypted_integrity_protected */ -'use strict'; - import asmCrypto from 'asmcrypto-lite'; import util from '../util.js'; import crypto from '../crypto'; diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index 63e8f698..f7603af0 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -36,8 +36,6 @@ * @module packet/sym_encrypted_session_key */ -'use strict'; - import util from '../util.js'; import type_s2k from '../type/s2k.js'; import enums from '../enums.js'; diff --git a/src/packet/symmetrically_encrypted.js b/src/packet/symmetrically_encrypted.js index 25a469c8..c1f6a356 100644 --- a/src/packet/symmetrically_encrypted.js +++ b/src/packet/symmetrically_encrypted.js @@ -28,8 +28,6 @@ * @module packet/symmetrically_encrypted */ -'use strict'; - import crypto from '../crypto'; import enums from '../enums.js'; import config from '../config'; diff --git a/src/packet/trust.js b/src/packet/trust.js index c4617da5..8eeed343 100644 --- a/src/packet/trust.js +++ b/src/packet/trust.js @@ -3,8 +3,6 @@ * @module packet/trust */ -'use strict'; - import enums from '../enums.js'; /** diff --git a/src/packet/user_attribute.js b/src/packet/user_attribute.js index 00689898..efd57f99 100644 --- a/src/packet/user_attribute.js +++ b/src/packet/user_attribute.js @@ -36,8 +36,6 @@ * @module packet/user_attribute */ -'use strict'; - import util from '../util.js'; import packet from './packet.js'; import enums from '../enums.js'; diff --git a/src/packet/userid.js b/src/packet/userid.js index 5c5f4580..68ff8958 100644 --- a/src/packet/userid.js +++ b/src/packet/userid.js @@ -28,8 +28,6 @@ * @module packet/userid */ -'use strict'; - import util from '../util.js'; import enums from '../enums.js'; diff --git a/src/signature.js b/src/signature.js index 276201a0..368809b6 100644 --- a/src/signature.js +++ b/src/signature.js @@ -24,8 +24,6 @@ * @module signature */ -'use strict'; - import packet from './packet'; import enums from './enums.js'; import armor from './encoding/armor.js'; diff --git a/src/type/ecdh_symkey.js b/src/type/ecdh_symkey.js index e49cd155..ced69679 100644 --- a/src/type/ecdh_symkey.js +++ b/src/type/ecdh_symkey.js @@ -22,8 +22,6 @@ * @module type/ecdh_symkey */ -'use strict'; - import util from '../util'; module.exports = ECDHSymmetricKey; diff --git a/src/type/kdf_params.js b/src/type/kdf_params.js index 8a33a026..30bcf469 100644 --- a/src/type/kdf_params.js +++ b/src/type/kdf_params.js @@ -22,8 +22,6 @@ * @module type/kdf_params */ -'use strict'; - import enums from '../enums.js'; module.exports = KDFParams; diff --git a/src/type/keyid.js b/src/type/keyid.js index ed2b20a8..9d404324 100644 --- a/src/type/keyid.js +++ b/src/type/keyid.js @@ -26,8 +26,6 @@ * @module type/keyid */ -'use strict'; - import util from '../util.js'; /** diff --git a/src/type/mpi.js b/src/type/mpi.js index 18750b96..d8da6d0f 100644 --- a/src/type/mpi.js +++ b/src/type/mpi.js @@ -34,8 +34,6 @@ * @module type/mpi */ -'use strict'; - import BigInteger from '../crypto/public_key/jsbn'; import util from '../util'; diff --git a/src/type/oid.js b/src/type/oid.js index be633321..d46f306a 100644 --- a/src/type/oid.js +++ b/src/type/oid.js @@ -23,8 +23,6 @@ * @module type/oid */ -'use strict'; - import util from '../util.js'; module.exports = OID; diff --git a/src/type/s2k.js b/src/type/s2k.js index 0a54bf9b..bcb8228f 100644 --- a/src/type/s2k.js +++ b/src/type/s2k.js @@ -29,8 +29,6 @@ * @module type/s2k */ -'use strict'; - import enums from '../enums.js'; import util from '../util.js'; import crypto from '../crypto'; diff --git a/src/util.js b/src/util.js index 4b3f977c..712184a8 100644 --- a/src/util.js +++ b/src/util.js @@ -21,8 +21,6 @@ * @module util */ -'use strict'; - import config from './config'; export default { diff --git a/src/worker/async_proxy.js b/src/worker/async_proxy.js index 99d56554..0453db13 100644 --- a/src/worker/async_proxy.js +++ b/src/worker/async_proxy.js @@ -15,8 +15,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -'use strict'; - import util from '../util.js'; import crypto from '../crypto'; import packet from '../packet'; diff --git a/test/crypto/aes_kw.js b/test/crypto/aes_kw.js index 9500711d..9c6085df 100644 --- a/test/crypto/aes_kw.js +++ b/test/crypto/aes_kw.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var expect = require('chai').expect; diff --git a/test/crypto/cipher/aes.js b/test/crypto/cipher/aes.js index 231c2af5..fbc345f7 100644 --- a/test/crypto/cipher/aes.js +++ b/test/crypto/cipher/aes.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); var util = openpgp.util, @@ -30,7 +28,7 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function [[0xF0,0xF1,0xF2,0xF3,0xF5,0xF6,0xF7,0xF8,0xFA,0xFB,0xFC,0xFD,0xFE,0x01,0x00,0x02],[0x12,0xA8,0xCF,0xA2,0x3E,0xA7,0x64,0xFD,0x87,0x62,0x32,0xB4,0xE8,0x42,0xBC,0x44],[0x31,0x6F,0xB6,0x8E,0xDB,0xA7,0x36,0xC5,0x3E,0x78,0x47,0x7B,0xF9,0x13,0x72,0x5C]], [[0x04,0x05,0x06,0x07,0x09,0x0A,0x0B,0x0C,0x0E,0x0F,0x10,0x11,0x13,0x14,0x15,0x16],[0xBC,0xAF,0x32,0x41,0x5E,0x83,0x08,0xB3,0x72,0x3E,0x5F,0xDD,0x85,0x3C,0xCC,0x80],[0x69,0x36,0xF2,0xB9,0x3A,0xF8,0x39,0x7F,0xD3,0xA7,0x71,0xFC,0x01,0x1C,0x8C,0x37]], [[0x2C,0x2D,0x2E,0x2F,0x31,0x32,0x33,0x34,0x36,0x37,0x38,0x39,0x3B,0x3C,0x3D,0x3E],[0x89,0xAF,0xAE,0x68,0x5D,0x80,0x1A,0xD7,0x47,0xAC,0xE9,0x1F,0xC4,0x9A,0xDD,0xE0],[0xF3,0xF9,0x2F,0x7A,0x9C,0x59,0x17,0x9C,0x1F,0xCC,0x2C,0x2B,0xA0,0xB0,0x82,0xCD]]]; - + var testvectors192 = [[[0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12,0x14,0x15,0x16,0x17,0x19,0x1A,0x1B,0x1C],[0x2D,0x33,0xEE,0xF2,0xC0,0x43,0x0A,0x8A,0x9E,0xBF,0x45,0xE8,0x09,0xC4,0x0B,0xB6],[0xDF,0xF4,0x94,0x5E,0x03,0x36,0xDF,0x4C,0x1C,0x56,0xBC,0x70,0x0E,0xFF,0x83,0x7F]], [[0x1E,0x1F,0x20,0x21,0x23,0x24,0x25,0x26,0x28,0x29,0x2A,0x2B,0x2D,0x2E,0x2F,0x30,0x32,0x33,0x34,0x35,0x37,0x38,0x39,0x3A],[0x6A,0xA3,0x75,0xD1,0xFA,0x15,0x5A,0x61,0xFB,0x72,0x35,0x3E,0x0A,0x5A,0x87,0x56],[0xB6,0xFD,0xDE,0xF4,0x75,0x27,0x65,0xE3,0x47,0xD5,0xD2,0xDC,0x19,0x6D,0x12,0x52]], [[0x3C,0x3D,0x3E,0x3F,0x41,0x42,0x43,0x44,0x46,0x47,0x48,0x49,0x4B,0x4C,0x4D,0x4E,0x50,0x51,0x52,0x53,0x55,0x56,0x57,0x58],[0xBC,0x37,0x36,0x51,0x8B,0x94,0x90,0xDC,0xB8,0xED,0x60,0xEB,0x26,0x75,0x8E,0xD4],[0xD2,0x36,0x84,0xE3,0xD9,0x63,0xB3,0xAF,0xCF,0x1A,0x11,0x4A,0xCA,0x90,0xCB,0xD6]], @@ -46,7 +44,7 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function [[0x68,0x69,0x6A,0x6B,0x6D,0x6E,0x6F,0x70,0x72,0x73,0x74,0x75,0x77,0x78,0x79,0x7A,0x7C,0x7D,0x7E,0x7F,0x81,0x82,0x83,0x84],[0x32,0xDF,0x99,0xB4,0x31,0xED,0x5D,0xC5,0xAC,0xF8,0xCA,0xF6,0xDC,0x6C,0xE4,0x75],[0x07,0x80,0x5A,0xA0,0x43,0x98,0x6E,0xB2,0x36,0x93,0xE2,0x3B,0xEF,0x8F,0x34,0x38]], [[0x86,0x87,0x88,0x89,0x8B,0x8C,0x8D,0x8E,0x90,0x91,0x92,0x93,0x95,0x96,0x97,0x98,0x9A,0x9B,0x9C,0x9D,0x9F,0xA0,0xA1,0xA2],[0x7F,0xDC,0x2B,0x74,0x6F,0x3F,0x66,0x52,0x96,0x94,0x3B,0x83,0x71,0x0D,0x1F,0x82],[0xDF,0x0B,0x49,0x31,0x03,0x8B,0xAD,0xE8,0x48,0xDE,0xE3,0xB4,0xB8,0x5A,0xA4,0x4B]], [[0xA4,0xA5,0xA6,0xA7,0xA9,0xAA,0xAB,0xAC,0xAE,0xAF,0xB0,0xB1,0xB3,0xB4,0xB5,0xB6,0xB8,0xB9,0xBA,0xBB,0xBD,0xBE,0xBF,0xC0],[0x8F,0xBA,0x15,0x10,0xA3,0xC5,0xB8,0x7E,0x2E,0xAA,0x3F,0x7A,0x91,0x45,0x5C,0xA2],[0x59,0x2D,0x5F,0xDE,0xD7,0x65,0x82,0xE4,0x14,0x3C,0x65,0x09,0x93,0x09,0x47,0x7C]]]; - + var testvectors256 = [[[0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12,0x14,0x15,0x16,0x17,0x19,0x1A,0x1B,0x1C,0x1E,0x1F,0x20,0x21,0x23,0x24,0x25,0x26],[0x83,0x4E,0xAD,0xFC,0xCA,0xC7,0xE1,0xB3,0x06,0x64,0xB1,0xAB,0xA4,0x48,0x15,0xAB],[0x19,0x46,0xDA,0xBF,0x6A,0x03,0xA2,0xA2,0xC3,0xD0,0xB0,0x50,0x80,0xAE,0xD6,0xFC]], [[0x28,0x29,0x2A,0x2B,0x2D,0x2E,0x2F,0x30,0x32,0x33,0x34,0x35,0x37,0x38,0x39,0x3A,0x3C,0x3D,0x3E,0x3F,0x41,0x42,0x43,0x44,0x46,0x47,0x48,0x49,0x4B,0x4C,0x4D,0x4E],[0xD9,0xDC,0x4D,0xBA,0x30,0x21,0xB0,0x5D,0x67,0xC0,0x51,0x8F,0x72,0xB6,0x2B,0xF1],[0x5E,0xD3,0x01,0xD7,0x47,0xD3,0xCC,0x71,0x54,0x45,0xEB,0xDE,0xC6,0x2F,0x2F,0xB4]], [[0x50,0x51,0x52,0x53,0x55,0x56,0x57,0x58,0x5A,0x5B,0x5C,0x5D,0x5F,0x60,0x61,0x62,0x64,0x65,0x66,0x67,0x69,0x6A,0x6B,0x6C,0x6E,0x6F,0x70,0x71,0x73,0x74,0x75,0x76],[0xA2,0x91,0xD8,0x63,0x01,0xA4,0xA7,0x39,0xF7,0x39,0x21,0x73,0xAA,0x3C,0x60,0x4C],[0x65,0x85,0xC8,0xF4,0x3D,0x13,0xA6,0xBE,0xAB,0x64,0x19,0xFC,0x59,0x35,0xB9,0xD0]], diff --git a/test/crypto/cipher/blowfish.js b/test/crypto/cipher/blowfish.js index fa02e280..b35c0b72 100644 --- a/test/crypto/cipher/blowfish.js +++ b/test/crypto/cipher/blowfish.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); var util = openpgp.util, diff --git a/test/crypto/cipher/cast5.js b/test/crypto/cipher/cast5.js index 5a59de84..1f8e61c9 100644 --- a/test/crypto/cipher/cast5.js +++ b/test/crypto/cipher/cast5.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); var util = openpgp.util, @@ -13,7 +11,7 @@ it('CAST-128 cipher test with test vectors from RFC2144', function (done) { return util.hexstrdump(result) == util.hexstrdump(util.bin2str(output)); } - + var testvectors = [[[0x01,0x23,0x45,0x67,0x12,0x34,0x56,0x78,0x23,0x45,0x67,0x89,0x34,0x56,0x78,0x9A],[0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF],[0x23,0x8B,0x4F,0xE5,0x84,0x7E,0x44,0xB2]]]; for (var i = 0; i < testvectors.length; i++) { diff --git a/test/crypto/cipher/des.js b/test/crypto/cipher/des.js index ea5b2509..0c80366d 100644 --- a/test/crypto/cipher/des.js +++ b/test/crypto/cipher/des.js @@ -1,144 +1,142 @@ -'use strict'; - -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); - -var util = openpgp.util, - chai = require('chai'), - expect = chai.expect; - -describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', function() { - // see https://csrc.nist.gov/publications/nistpubs/800-20/800-20.pdf - var key = new Uint8Array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]); - var testvectors = [[[0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x95,0xF8,0xA5,0xE5,0xDD,0x31,0xD9,0x00]], - [[0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0xDD,0x7F,0x12,0x1C,0xA5,0x01,0x56,0x19]], - [[0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x2E,0x86,0x53,0x10,0x4F,0x38,0x34,0xEA]], - [[0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x4B,0xD3,0x88,0xFF,0x6C,0xD8,0x1D,0x4F]], - [[0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x20,0xB9,0xE7,0x67,0xB2,0xFB,0x14,0x56]], - [[0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x55,0x57,0x93,0x80,0xD7,0x71,0x38,0xEF]], - [[0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x6C,0xC5,0xDE,0xFA,0xAF,0x04,0x51,0x2F]], - [[0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x0D,0x9F,0x27,0x9B,0xA5,0xD8,0x72,0x60]], - [[0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00],[0xD9,0x03,0x1B,0x02,0x71,0xBD,0x5A,0x0A]], - [[0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00],[0x42,0x42,0x50,0xB3,0x7C,0x3D,0xD9,0x51]], - [[0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00],[0xB8,0x06,0x1B,0x7E,0xCD,0x9A,0x21,0xE5]], - [[0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00],[0xF1,0x5D,0x0F,0x28,0x6B,0x65,0xBD,0x28]], - [[0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00],[0xAD,0xD0,0xCC,0x8D,0x6E,0x5D,0xEB,0xA1]], - [[0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00],[0xE6,0xD5,0xF8,0x27,0x52,0xAD,0x63,0xD1]], - [[0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00],[0xEC,0xBF,0xE3,0xBD,0x3F,0x59,0x1A,0x5E]], - [[0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00],[0xF3,0x56,0x83,0x43,0x79,0xD1,0x65,0xCD]], - [[0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00],[0x2B,0x9F,0x98,0x2F,0x20,0x03,0x7F,0xA9]], - [[0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00],[0x88,0x9D,0xE0,0x68,0xA1,0x6F,0x0B,0xE6]], - [[0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00],[0xE1,0x9E,0x27,0x5D,0x84,0x6A,0x12,0x98]], - [[0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00],[0x32,0x9A,0x8E,0xD5,0x23,0xD7,0x1A,0xEC]], - [[0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00],[0xE7,0xFC,0xE2,0x25,0x57,0xD2,0x3C,0x97]], - [[0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00],[0x12,0xA9,0xF5,0x81,0x7F,0xF2,0xD6,0x5D]], - [[0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00],[0xA4,0x84,0xC3,0xAD,0x38,0xDC,0x9C,0x19]], - [[0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00],[0xFB,0xE0,0x0A,0x8A,0x1E,0xF8,0xAD,0x72]], - [[0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00],[0x75,0x0D,0x07,0x94,0x07,0x52,0x13,0x63]], - [[0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00],[0x64,0xFE,0xED,0x9C,0x72,0x4C,0x2F,0xAF]], - [[0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00],[0xF0,0x2B,0x26,0x3B,0x32,0x8E,0x2B,0x60]], - [[0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00],[0x9D,0x64,0x55,0x5A,0x9A,0x10,0xB8,0x52]], - [[0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00],[0xD1,0x06,0xFF,0x0B,0xED,0x52,0x55,0xD7]], - [[0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00],[0xE1,0x65,0x2C,0x6B,0x13,0x8C,0x64,0xA5]], - [[0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00],[0xE4,0x28,0x58,0x11,0x86,0xEC,0x8F,0x46]], - [[0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00],[0xAE,0xB5,0xF5,0xED,0xE2,0x2D,0x1A,0x36]], - [[0x00,0x00,0x00,0x00,0x80,0x00,0x00,0x00],[0xE9,0x43,0xD7,0x56,0x8A,0xEC,0x0C,0x5C]], - [[0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00],[0xDF,0x98,0xC8,0x27,0x6F,0x54,0xB0,0x4B]], - [[0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00],[0xB1,0x60,0xE4,0x68,0x0F,0x6C,0x69,0x6F]], - [[0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00],[0xFA,0x07,0x52,0xB0,0x7D,0x9C,0x4A,0xB8]], - [[0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00],[0xCA,0x3A,0x2B,0x03,0x6D,0xBC,0x85,0x02]], - [[0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00],[0x5E,0x09,0x05,0x51,0x7B,0xB5,0x9B,0xCF]], - [[0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00],[0x81,0x4E,0xEB,0x3B,0x91,0xD9,0x07,0x26]], - [[0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00],[0x4D,0x49,0xDB,0x15,0x32,0x91,0x9C,0x9F]], - [[0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x00],[0x25,0xEB,0x5F,0xC3,0xF8,0xCF,0x06,0x21]], - [[0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00],[0xAB,0x6A,0x20,0xC0,0x62,0x0D,0x1C,0x6F]], - [[0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00],[0x79,0xE9,0x0D,0xBC,0x98,0xF9,0x2C,0xCA]], - [[0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00],[0x86,0x6E,0xCE,0xDD,0x80,0x72,0xBB,0x0E]], - [[0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00],[0x8B,0x54,0x53,0x6F,0x2F,0x3E,0x64,0xA8]], - [[0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00],[0xEA,0x51,0xD3,0x97,0x55,0x95,0xB8,0x6B]], - [[0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00],[0xCA,0xFF,0xC6,0xAC,0x45,0x42,0xDE,0x31]], - [[0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00],[0x8D,0xD4,0x5A,0x2D,0xDF,0x90,0x79,0x6C]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00],[0x10,0x29,0xD5,0x5E,0x88,0x0E,0xC2,0xD0]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00],[0x5D,0x86,0xCB,0x23,0x63,0x9D,0xBE,0xA9]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00],[0x1D,0x1C,0xA8,0x53,0xAE,0x7C,0x0C,0x5F]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00],[0xCE,0x33,0x23,0x29,0x24,0x8F,0x32,0x28]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00],[0x84,0x05,0xD1,0xAB,0xE2,0x4F,0xB9,0x42]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00],[0xE6,0x43,0xD7,0x80,0x90,0xCA,0x42,0x07]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00],[0x48,0x22,0x1B,0x99,0x37,0x74,0x8A,0x23]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00],[0xDD,0x7C,0x0B,0xBD,0x61,0xFA,0xFD,0x54]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80],[0x2F,0xBC,0x29,0x1A,0x57,0x0D,0xB5,0xC4]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40],[0xE0,0x7C,0x30,0xD7,0xE4,0xE2,0x6E,0x12]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20],[0x09,0x53,0xE2,0x25,0x8E,0x8E,0x90,0xA1]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10],[0x5B,0x71,0x1B,0xC4,0xCE,0xEB,0xF2,0xEE]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08],[0xCC,0x08,0x3F,0x1E,0x6D,0x9E,0x85,0xF6]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04],[0xD2,0xFD,0x88,0x67,0xD5,0x0D,0x2D,0xFE]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02],[0x06,0xE7,0xEA,0x22,0xCE,0x92,0x70,0x8F]], - [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01],[0x16,0x6B,0x40,0xB4,0x4A,0xBA,0x4B,0xD6]]]; - - it('3DES EDE test vectors', function (done) { - for (var i = 0; i < testvectors.length; i++) { - var des = new openpgp.crypto.cipher.tripledes(key); - - var encr = util.bin2str(des.encrypt(testvectors[i][0], key)); - - expect(encr, 'vector with block ' + util.hexidump(testvectors[i][0]) + - ' and key ' + util.hexstrdump(util.Uint8Array2str(key)) + - ' should be ' + util.hexidump(testvectors[i][1]) + - ' != ' + util.hexidump(encr)).to.be.equal(util.bin2str(testvectors[i][1])); - } - done(); - }); - - it('DES encrypt/decrypt padding tests', function (done) { - var key = new Uint8Array([0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF]); - var testvectors = new Array(); - testvectors[0] = [[[0x01], [0x24, 0xC7, 0x4A, 0x9A, 0x79, 0x75, 0x4B, 0xC7]], - [[0x02, 0x03], [0xA7, 0x7A, 0x9A, 0x59, 0x8A, 0x86, 0x85, 0xC5]], - [[0x03, 0x04, 0x05], [0x01, 0xCF, 0xEB, 0x6A, 0x74, 0x60, 0xF5, 0x02]], - [[0x04, 0x05, 0x06, 0x07], [0xA8, 0xF0, 0x3D, 0x59, 0xBA, 0x6B, 0x0E, 0x76]], - [[0x05, 0x06, 0x07, 0x08, 0x09], [0x86, 0x40, 0x33, 0x61, 0x3F, 0x55, 0x73, 0x49]], - [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0x13, 0x21, 0x3E, 0x0E, 0xCE, 0x2C, 0x94, 0x01]], - [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0x30, 0x49, 0x97, 0xC1, 0xDA, 0xD5, 0x59, 0xA5]], - [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9]]]; - testvectors[1] = [[[0x01], [0xF2, 0xAB, 0x1C, 0x9E, 0x70, 0x7D, 0xCC, 0x92]], - [[0x02, 0x03], [0x6B, 0x4C, 0x67, 0x24, 0x9F, 0xB7, 0x4D, 0xAC]], - [[0x03, 0x04, 0x05], [0x68, 0x95, 0xAB, 0xA8, 0xEA, 0x53, 0x13, 0x23]], - [[0x04, 0x05, 0x06, 0x07], [0xC8, 0xDE, 0x60, 0x8F, 0xF6, 0x09, 0x90, 0xB5]], - [[0x05, 0x06, 0x07, 0x08, 0x09], [0x19, 0x13, 0x50, 0x20, 0x70, 0x40, 0x2E, 0x09]], - [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0xA8, 0x23, 0x40, 0xC6, 0x17, 0xA6, 0x31, 0x4A]], - [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0x36, 0x62, 0xF2, 0x99, 0x68, 0xD4, 0xBF, 0x7C]], - [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9, 0x08, 0x6F, 0x9A, 0x1D, 0x74, 0xC9, 0x4D, 0x4E]]]; - testvectors[2] = [[[0x01], [0x83, 0x68, 0xE4, 0x9C, 0x84, 0xCC, 0xCB, 0xF0]], - [[0x02, 0x03], [0xBB, 0xA8, 0x0B, 0x66, 0x1B, 0x62, 0xC4, 0xC8]], - [[0x03, 0x04, 0x05], [0x9A, 0xD7, 0x5A, 0x24, 0xFD, 0x3F, 0xBF, 0x22]], - [[0x04, 0x05, 0x06, 0x07], [0x14, 0x4E, 0x68, 0x6D, 0x2E, 0xC1, 0xB7, 0x52]], - [[0x05, 0x06, 0x07, 0x08, 0x09], [0x12, 0x0A, 0x51, 0x08, 0xF9, 0xA3, 0x03, 0x74]], - [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0xB2, 0x07, 0xD1, 0x05, 0xF6, 0x67, 0xAF, 0xBA]], - [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0xCA, 0x59, 0x61, 0x3A, 0x83, 0x23, 0x26, 0xDD]], - [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9]]]; - - var des = new openpgp.crypto.cipher.des(key); - - for (var padding = 0; padding < 3; padding++) { - var thisVectorSet = testvectors[padding]; - - for (var i = 0; i < thisVectorSet.length; i++) { - var encrypted = des.encrypt(thisVectorSet[i][0], padding); - var decrypted = des.decrypt(encrypted, padding); - - expect(util.bin2str(encrypted), 'vector with block [' + util.hexidump(thisVectorSet[i][0]) + - '] and key [' + util.hexstrdump(util.Uint8Array2str(key)) + - '] and padding [' + padding + - '] should be ' + util.hexidump(thisVectorSet[i][1]) + - ' - Actually [' + util.hexidump(encrypted) + - ']').to.equal(util.bin2str(thisVectorSet[i][1])); - expect(util.bin2str(decrypted), 'vector with block [' + util.hexidump(thisVectorSet[i][0]) + - '] and key [' + util.hexstrdump(util.Uint8Array2str(key)) + - '] and padding [' + padding + - '] should be ' + util.hexidump(thisVectorSet[i][0]) + - ' - Actually [' + util.hexidump(decrypted) + - ']').to.equal(util.bin2str(thisVectorSet[i][0])); - } - } - done(); - }); -}); +var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); + +var util = openpgp.util, + chai = require('chai'), + expect = chai.expect; + +describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', function() { + // see https://csrc.nist.gov/publications/nistpubs/800-20/800-20.pdf + var key = new Uint8Array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]); + var testvectors = [[[0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x95,0xF8,0xA5,0xE5,0xDD,0x31,0xD9,0x00]], + [[0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0xDD,0x7F,0x12,0x1C,0xA5,0x01,0x56,0x19]], + [[0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x2E,0x86,0x53,0x10,0x4F,0x38,0x34,0xEA]], + [[0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x4B,0xD3,0x88,0xFF,0x6C,0xD8,0x1D,0x4F]], + [[0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x20,0xB9,0xE7,0x67,0xB2,0xFB,0x14,0x56]], + [[0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x55,0x57,0x93,0x80,0xD7,0x71,0x38,0xEF]], + [[0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x6C,0xC5,0xDE,0xFA,0xAF,0x04,0x51,0x2F]], + [[0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x0D,0x9F,0x27,0x9B,0xA5,0xD8,0x72,0x60]], + [[0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00],[0xD9,0x03,0x1B,0x02,0x71,0xBD,0x5A,0x0A]], + [[0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00],[0x42,0x42,0x50,0xB3,0x7C,0x3D,0xD9,0x51]], + [[0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00],[0xB8,0x06,0x1B,0x7E,0xCD,0x9A,0x21,0xE5]], + [[0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00],[0xF1,0x5D,0x0F,0x28,0x6B,0x65,0xBD,0x28]], + [[0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00],[0xAD,0xD0,0xCC,0x8D,0x6E,0x5D,0xEB,0xA1]], + [[0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00],[0xE6,0xD5,0xF8,0x27,0x52,0xAD,0x63,0xD1]], + [[0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00],[0xEC,0xBF,0xE3,0xBD,0x3F,0x59,0x1A,0x5E]], + [[0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00],[0xF3,0x56,0x83,0x43,0x79,0xD1,0x65,0xCD]], + [[0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00],[0x2B,0x9F,0x98,0x2F,0x20,0x03,0x7F,0xA9]], + [[0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00],[0x88,0x9D,0xE0,0x68,0xA1,0x6F,0x0B,0xE6]], + [[0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00],[0xE1,0x9E,0x27,0x5D,0x84,0x6A,0x12,0x98]], + [[0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00],[0x32,0x9A,0x8E,0xD5,0x23,0xD7,0x1A,0xEC]], + [[0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00],[0xE7,0xFC,0xE2,0x25,0x57,0xD2,0x3C,0x97]], + [[0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00],[0x12,0xA9,0xF5,0x81,0x7F,0xF2,0xD6,0x5D]], + [[0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00],[0xA4,0x84,0xC3,0xAD,0x38,0xDC,0x9C,0x19]], + [[0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00],[0xFB,0xE0,0x0A,0x8A,0x1E,0xF8,0xAD,0x72]], + [[0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00],[0x75,0x0D,0x07,0x94,0x07,0x52,0x13,0x63]], + [[0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00],[0x64,0xFE,0xED,0x9C,0x72,0x4C,0x2F,0xAF]], + [[0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00],[0xF0,0x2B,0x26,0x3B,0x32,0x8E,0x2B,0x60]], + [[0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00],[0x9D,0x64,0x55,0x5A,0x9A,0x10,0xB8,0x52]], + [[0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00],[0xD1,0x06,0xFF,0x0B,0xED,0x52,0x55,0xD7]], + [[0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00],[0xE1,0x65,0x2C,0x6B,0x13,0x8C,0x64,0xA5]], + [[0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00],[0xE4,0x28,0x58,0x11,0x86,0xEC,0x8F,0x46]], + [[0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00],[0xAE,0xB5,0xF5,0xED,0xE2,0x2D,0x1A,0x36]], + [[0x00,0x00,0x00,0x00,0x80,0x00,0x00,0x00],[0xE9,0x43,0xD7,0x56,0x8A,0xEC,0x0C,0x5C]], + [[0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00],[0xDF,0x98,0xC8,0x27,0x6F,0x54,0xB0,0x4B]], + [[0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00],[0xB1,0x60,0xE4,0x68,0x0F,0x6C,0x69,0x6F]], + [[0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00],[0xFA,0x07,0x52,0xB0,0x7D,0x9C,0x4A,0xB8]], + [[0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00],[0xCA,0x3A,0x2B,0x03,0x6D,0xBC,0x85,0x02]], + [[0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00],[0x5E,0x09,0x05,0x51,0x7B,0xB5,0x9B,0xCF]], + [[0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00],[0x81,0x4E,0xEB,0x3B,0x91,0xD9,0x07,0x26]], + [[0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00],[0x4D,0x49,0xDB,0x15,0x32,0x91,0x9C,0x9F]], + [[0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x00],[0x25,0xEB,0x5F,0xC3,0xF8,0xCF,0x06,0x21]], + [[0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00],[0xAB,0x6A,0x20,0xC0,0x62,0x0D,0x1C,0x6F]], + [[0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00],[0x79,0xE9,0x0D,0xBC,0x98,0xF9,0x2C,0xCA]], + [[0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00],[0x86,0x6E,0xCE,0xDD,0x80,0x72,0xBB,0x0E]], + [[0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00],[0x8B,0x54,0x53,0x6F,0x2F,0x3E,0x64,0xA8]], + [[0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00],[0xEA,0x51,0xD3,0x97,0x55,0x95,0xB8,0x6B]], + [[0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00],[0xCA,0xFF,0xC6,0xAC,0x45,0x42,0xDE,0x31]], + [[0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00],[0x8D,0xD4,0x5A,0x2D,0xDF,0x90,0x79,0x6C]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00],[0x10,0x29,0xD5,0x5E,0x88,0x0E,0xC2,0xD0]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00],[0x5D,0x86,0xCB,0x23,0x63,0x9D,0xBE,0xA9]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00],[0x1D,0x1C,0xA8,0x53,0xAE,0x7C,0x0C,0x5F]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00],[0xCE,0x33,0x23,0x29,0x24,0x8F,0x32,0x28]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00],[0x84,0x05,0xD1,0xAB,0xE2,0x4F,0xB9,0x42]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00],[0xE6,0x43,0xD7,0x80,0x90,0xCA,0x42,0x07]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00],[0x48,0x22,0x1B,0x99,0x37,0x74,0x8A,0x23]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00],[0xDD,0x7C,0x0B,0xBD,0x61,0xFA,0xFD,0x54]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80],[0x2F,0xBC,0x29,0x1A,0x57,0x0D,0xB5,0xC4]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40],[0xE0,0x7C,0x30,0xD7,0xE4,0xE2,0x6E,0x12]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20],[0x09,0x53,0xE2,0x25,0x8E,0x8E,0x90,0xA1]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10],[0x5B,0x71,0x1B,0xC4,0xCE,0xEB,0xF2,0xEE]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08],[0xCC,0x08,0x3F,0x1E,0x6D,0x9E,0x85,0xF6]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04],[0xD2,0xFD,0x88,0x67,0xD5,0x0D,0x2D,0xFE]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02],[0x06,0xE7,0xEA,0x22,0xCE,0x92,0x70,0x8F]], + [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01],[0x16,0x6B,0x40,0xB4,0x4A,0xBA,0x4B,0xD6]]]; + + it('3DES EDE test vectors', function (done) { + for (var i = 0; i < testvectors.length; i++) { + var des = new openpgp.crypto.cipher.tripledes(key); + + var encr = util.bin2str(des.encrypt(testvectors[i][0], key)); + + expect(encr, 'vector with block ' + util.hexidump(testvectors[i][0]) + + ' and key ' + util.hexstrdump(util.Uint8Array2str(key)) + + ' should be ' + util.hexidump(testvectors[i][1]) + + ' != ' + util.hexidump(encr)).to.be.equal(util.bin2str(testvectors[i][1])); + } + done(); + }); + + it('DES encrypt/decrypt padding tests', function (done) { + var key = new Uint8Array([0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF]); + var testvectors = new Array(); + testvectors[0] = [[[0x01], [0x24, 0xC7, 0x4A, 0x9A, 0x79, 0x75, 0x4B, 0xC7]], + [[0x02, 0x03], [0xA7, 0x7A, 0x9A, 0x59, 0x8A, 0x86, 0x85, 0xC5]], + [[0x03, 0x04, 0x05], [0x01, 0xCF, 0xEB, 0x6A, 0x74, 0x60, 0xF5, 0x02]], + [[0x04, 0x05, 0x06, 0x07], [0xA8, 0xF0, 0x3D, 0x59, 0xBA, 0x6B, 0x0E, 0x76]], + [[0x05, 0x06, 0x07, 0x08, 0x09], [0x86, 0x40, 0x33, 0x61, 0x3F, 0x55, 0x73, 0x49]], + [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0x13, 0x21, 0x3E, 0x0E, 0xCE, 0x2C, 0x94, 0x01]], + [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0x30, 0x49, 0x97, 0xC1, 0xDA, 0xD5, 0x59, 0xA5]], + [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9]]]; + testvectors[1] = [[[0x01], [0xF2, 0xAB, 0x1C, 0x9E, 0x70, 0x7D, 0xCC, 0x92]], + [[0x02, 0x03], [0x6B, 0x4C, 0x67, 0x24, 0x9F, 0xB7, 0x4D, 0xAC]], + [[0x03, 0x04, 0x05], [0x68, 0x95, 0xAB, 0xA8, 0xEA, 0x53, 0x13, 0x23]], + [[0x04, 0x05, 0x06, 0x07], [0xC8, 0xDE, 0x60, 0x8F, 0xF6, 0x09, 0x90, 0xB5]], + [[0x05, 0x06, 0x07, 0x08, 0x09], [0x19, 0x13, 0x50, 0x20, 0x70, 0x40, 0x2E, 0x09]], + [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0xA8, 0x23, 0x40, 0xC6, 0x17, 0xA6, 0x31, 0x4A]], + [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0x36, 0x62, 0xF2, 0x99, 0x68, 0xD4, 0xBF, 0x7C]], + [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9, 0x08, 0x6F, 0x9A, 0x1D, 0x74, 0xC9, 0x4D, 0x4E]]]; + testvectors[2] = [[[0x01], [0x83, 0x68, 0xE4, 0x9C, 0x84, 0xCC, 0xCB, 0xF0]], + [[0x02, 0x03], [0xBB, 0xA8, 0x0B, 0x66, 0x1B, 0x62, 0xC4, 0xC8]], + [[0x03, 0x04, 0x05], [0x9A, 0xD7, 0x5A, 0x24, 0xFD, 0x3F, 0xBF, 0x22]], + [[0x04, 0x05, 0x06, 0x07], [0x14, 0x4E, 0x68, 0x6D, 0x2E, 0xC1, 0xB7, 0x52]], + [[0x05, 0x06, 0x07, 0x08, 0x09], [0x12, 0x0A, 0x51, 0x08, 0xF9, 0xA3, 0x03, 0x74]], + [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0xB2, 0x07, 0xD1, 0x05, 0xF6, 0x67, 0xAF, 0xBA]], + [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0xCA, 0x59, 0x61, 0x3A, 0x83, 0x23, 0x26, 0xDD]], + [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9]]]; + + var des = new openpgp.crypto.cipher.des(key); + + for (var padding = 0; padding < 3; padding++) { + var thisVectorSet = testvectors[padding]; + + for (var i = 0; i < thisVectorSet.length; i++) { + var encrypted = des.encrypt(thisVectorSet[i][0], padding); + var decrypted = des.decrypt(encrypted, padding); + + expect(util.bin2str(encrypted), 'vector with block [' + util.hexidump(thisVectorSet[i][0]) + + '] and key [' + util.hexstrdump(util.Uint8Array2str(key)) + + '] and padding [' + padding + + '] should be ' + util.hexidump(thisVectorSet[i][1]) + + ' - Actually [' + util.hexidump(encrypted) + + ']').to.equal(util.bin2str(thisVectorSet[i][1])); + expect(util.bin2str(decrypted), 'vector with block [' + util.hexidump(thisVectorSet[i][0]) + + '] and key [' + util.hexstrdump(util.Uint8Array2str(key)) + + '] and padding [' + padding + + '] should be ' + util.hexidump(thisVectorSet[i][0]) + + ' - Actually [' + util.hexidump(decrypted) + + ']').to.equal(util.bin2str(thisVectorSet[i][0])); + } + } + done(); + }); +}); diff --git a/test/crypto/cipher/twofish.js b/test/crypto/cipher/twofish.js index 15bb95ee..723d4aa4 100644 --- a/test/crypto/cipher/twofish.js +++ b/test/crypto/cipher/twofish.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); var util = openpgp.util, diff --git a/test/crypto/crypto.js b/test/crypto/crypto.js index ee1e852f..e9ad19d9 100644 --- a/test/crypto/crypto.js +++ b/test/crypto/crypto.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'); diff --git a/test/crypto/elliptic.js b/test/crypto/elliptic.js index 2c9ed482..70f8465f 100644 --- a/test/crypto/elliptic.js +++ b/test/crypto/elliptic.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'); diff --git a/test/crypto/hash/md5.js b/test/crypto/hash/md5.js index e5cace62..54e9dc42 100644 --- a/test/crypto/hash/md5.js +++ b/test/crypto/hash/md5.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); var util = openpgp.util, diff --git a/test/crypto/hash/ripemd.js b/test/crypto/hash/ripemd.js index eca1afbb..8db2ba63 100644 --- a/test/crypto/hash/ripemd.js +++ b/test/crypto/hash/ripemd.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); var util = openpgp.util, diff --git a/test/crypto/hash/sha.js b/test/crypto/hash/sha.js index e8647818..3d1cba29 100644 --- a/test/crypto/hash/sha.js +++ b/test/crypto/hash/sha.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); var util = openpgp.util, diff --git a/test/crypto/pkcs5.js b/test/crypto/pkcs5.js index 2e078ffa..b2562c5f 100644 --- a/test/crypto/pkcs5.js +++ b/test/crypto/pkcs5.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var expect = require('chai').expect; diff --git a/test/crypto/random.js b/test/crypto/random.js index 4de1a9a9..e10bc3df 100644 --- a/test/crypto/random.js +++ b/test/crypto/random.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'), diff --git a/test/general/armor.js b/test/general/armor.js index 6aef929d..9f56b684 100644 --- a/test/general/armor.js +++ b/test/general/armor.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'), @@ -338,4 +336,4 @@ describe("ASCII armor", function() { }); - + diff --git a/test/general/ecc_nist.js b/test/general/ecc_nist.js index 59cc26e4..fa4adbbc 100644 --- a/test/general/ecc_nist.js +++ b/test/general/ecc_nist.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'); diff --git a/test/general/hkp.js b/test/general/hkp.js index 4d0df07f..2e2ce2f5 100644 --- a/test/general/hkp.js +++ b/test/general/hkp.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'), diff --git a/test/general/key.js b/test/general/key.js index 22a7afd8..38ccfd98 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'); diff --git a/test/general/keyring.js b/test/general/keyring.js index 67394380..e135ce83 100644 --- a/test/general/keyring.js +++ b/test/general/keyring.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var keyring = new openpgp.Keyring(), diff --git a/test/general/oid.js b/test/general/oid.js index b4f4e68a..fe0fe85b 100644 --- a/test/general/oid.js +++ b/test/general/oid.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var expect = require('chai').expect; diff --git a/test/general/openpgp.js b/test/general/openpgp.js index 0990f3b3..b9943d9b 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -1,7 +1,5 @@ /* globals tryTests: true */ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var sinon = require('sinon'), diff --git a/test/general/packet.js b/test/general/packet.js index e5637348..37c692f4 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'); @@ -307,7 +305,7 @@ describe("Packet", function() { var msg = new openpgp.packet.List(); msg.read(openpgp.armor.decode(armored_msg).data); - msg[0].decrypt(key).then(() => { + msg[0].decrypt(key).then(() => { msg[1].decrypt(msg[0].sessionKeyAlgorithm, msg[0].sessionKey); var text = stringify(msg[1].packets[0].packets[0].data); diff --git a/test/general/signature.js b/test/general/signature.js index b8126c99..0c399121 100644 --- a/test/general/signature.js +++ b/test/general/signature.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'); diff --git a/test/general/util.js b/test/general/util.js index b3b6a72d..3db13100 100644 --- a/test/general/util.js +++ b/test/general/util.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'), diff --git a/test/general/x25519.js b/test/general/x25519.js index da89aa2e..1419d69b 100644 --- a/test/general/x25519.js +++ b/test/general/x25519.js @@ -1,5 +1,3 @@ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var elliptic = openpgp.crypto.publicKey.elliptic; diff --git a/test/worker/async_proxy.js b/test/worker/async_proxy.js index 8968658d..5e781bcf 100644 --- a/test/worker/async_proxy.js +++ b/test/worker/async_proxy.js @@ -1,7 +1,5 @@ /* globals tryTests: true */ -'use strict'; - var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); var chai = require('chai'), From 08949b03263a6a336d72854f0ce7408207421863 Mon Sep 17 00:00:00 2001 From: BafS Date: Mon, 12 Feb 2018 21:57:30 +0100 Subject: [PATCH 2/4] Radix should be specified Part of the best practices https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt and https://eslint.org/docs/rules/radix --- .eslintrc.js | 8 ++------ src/enums.js | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index baccf3a6..a13ac8ed 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -277,10 +277,6 @@ module.exports = { "prefer-template": "off", "quote-props": "off", "quotes": "off", - "radix": [ - "error", - "as-needed" - ], "require-await": "error", "require-jsdoc": "off", "rest-spread-spacing": "error", @@ -327,12 +323,12 @@ module.exports = { "never" ], - // Custom silencers: + // Custom silencers: "camelcase": 0, "no-debugger": 0, "require-await": 0, "no-multi-assign": 0, - "no-underscore-dangle": 0, + "no-underscore-dangle": 0, "no-restricted-syntax": 0, "one-var-declaration-per-line": 0, diff --git a/src/enums.js b/src/enums.js index 607b0e53..4ea90c0b 100644 --- a/src/enums.js +++ b/src/enums.js @@ -381,7 +381,7 @@ export default { /** Converts from an integer to string. */ read: function(type, e) { for (var i in type) { - if (type[i] === parseInt(e)) { + if (type[i] === parseInt(e, 10)) { return i; } } From fa177141ebe270e4e26ee836758e0a7265be98cc Mon Sep 17 00:00:00 2001 From: BafS Date: Tue, 13 Feb 2018 22:38:10 +0100 Subject: [PATCH 3/4] Use let and const ES6 features. Remove var, for let or const if possible, clean some syntax, enforce one var per declaration and semicolons --- .eslintrc.js | 8 - src/cleartext.js | 57 +- src/config/index.js | 2 +- src/config/localStorage.js | 4 +- src/crypto/aes_kw.js | 82 +- src/crypto/cfb.js | 78 +- src/crypto/cipher/aes.js | 3 +- src/crypto/cipher/blowfish.js | 417 ++++--- src/crypto/cipher/cast5.js | 89 +- src/crypto/cipher/des.js | 223 ++-- src/crypto/cipher/twofish.js | 106 +- src/crypto/crypto.js | 100 +- src/crypto/gcm.js | 14 +- src/crypto/hash/index.js | 15 +- src/crypto/hash/md5.js | 33 +- src/crypto/hash/sha.js | 1044 ++++++++--------- src/crypto/index.js | 2 +- src/crypto/pkcs1.js | 47 +- src/crypto/public_key/dsa.js | 22 +- src/crypto/public_key/elgamal.js | 7 +- src/crypto/public_key/elliptic/curves.js | 39 +- src/crypto/public_key/elliptic/eddsa.js | 12 +- src/crypto/public_key/elliptic/index.js | 2 +- src/crypto/public_key/elliptic/key.js | 25 +- src/crypto/public_key/jsbn.js | 327 +++--- src/crypto/public_key/rsa.js | 47 +- src/crypto/random.js | 38 +- src/crypto/signature.js | 120 +- src/encoding/armor.js | 125 +- src/encoding/base64.js | 31 +- src/enums.js | 6 +- src/hkp.js | 13 +- src/key.js | 342 +++--- src/keyring/keyring.js | 35 +- src/keyring/localstore.js | 12 +- src/message.js | 167 ++- src/openpgp.js | 49 +- src/packet/all_packets.js | 6 +- src/packet/clone.js | 20 +- src/packet/compressed.js | 8 +- src/packet/index.js | 2 +- src/packet/literal.js | 18 +- src/packet/one_pass_signature.js | 7 +- src/packet/packet.js | 42 +- src/packet/packetlist.js | 89 +- src/packet/public_key.js | 32 +- .../public_key_encrypted_session_key.js | 37 +- src/packet/secret_key.js | 98 +- src/packet/signature.js | 131 ++- .../sym_encrypted_integrity_protected.js | 17 +- src/packet/sym_encrypted_session_key.js | 37 +- src/packet/symmetrically_encrypted.js | 4 +- src/packet/user_attribute.js | 8 +- src/signature.js | 4 +- src/type/ecdh_symkey.js | 8 +- src/type/keyid.js | 6 +- src/type/mpi.js | 17 +- src/type/oid.js | 7 +- src/type/s2k.js | 45 +- src/util.js | 120 +- src/worker/async_proxy.js | 4 +- src/worker/worker.js | 8 +- test/crypto/aes_kw.js | 16 +- test/crypto/cipher/aes.js | 33 +- test/crypto/cipher/blowfish.js | 23 +- test/crypto/cipher/cast5.js | 29 +- test/crypto/cipher/des.js | 77 +- test/crypto/cipher/twofish.js | 30 +- test/crypto/crypto.js | 105 +- test/crypto/elliptic.js | 137 ++- test/crypto/hash/md5.js | 23 +- test/crypto/hash/ripemd.js | 11 +- test/crypto/hash/sha.js | 15 +- test/crypto/pkcs5.js | 30 +- test/crypto/random.js | 15 +- test/general/armor.js | 63 +- test/general/ecc_nist.js | 61 +- test/general/hkp.js | 11 +- test/general/key.js | 259 ++-- test/general/keyring.js | 119 +- test/general/oid.js | 22 +- test/general/openpgp.js | 273 ++--- test/general/packet.js | 175 +-- test/general/signature.js | 280 +++-- test/general/util.js | 81 +- test/general/x25519.js | 149 +-- test/worker/async_proxy.js | 15 +- 87 files changed, 3250 insertions(+), 3320 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index a13ac8ed..8c53889f 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -51,7 +51,6 @@ module.exports = { "before": true } ], - "block-scoped-var": "off", "block-spacing": [ "error", "always" @@ -239,7 +238,6 @@ module.exports = { "no-useless-constructor": "error", "no-useless-rename": "error", "no-useless-return": "error", - "no-var": "off", "no-void": "error", "no-warning-comments": "off", "no-whitespace-before-property": "error", @@ -254,7 +252,6 @@ module.exports = { } ], "object-shorthand": "off", - "one-var": "off", "one-var-declaration-per-line": [ "error", "initializations" @@ -267,7 +264,6 @@ module.exports = { "padded-blocks": "off", "padding-line-between-statements": "error", "prefer-arrow-callback": "off", - "prefer-const": "off", "prefer-destructuring": "off", "prefer-numeric-literals": "error", "prefer-promise-reject-errors": "error", @@ -279,8 +275,6 @@ module.exports = { "quotes": "off", "require-await": "error", "require-jsdoc": "off", - "rest-spread-spacing": "error", - "semi": "off", "semi-spacing": [ "error", { @@ -314,7 +308,6 @@ module.exports = { "never" ], "valid-jsdoc": "off", - "vars-on-top": "off", "wrap-iife": "error", "wrap-regex": "off", "yield-star-spacing": "error", @@ -354,6 +347,5 @@ module.exports = { "no-array-constructor": 0, "no-constant-condition": 0, "no-buffer-constructor": 0, // deprecated - "no-restricted-properties": 0 // Math.pow } }; diff --git a/src/cleartext.js b/src/cleartext.js index dd93f49f..9d827e0a 100644 --- a/src/cleartext.js +++ b/src/cleartext.js @@ -43,7 +43,7 @@ export function CleartextMessage(text, signature) { return new CleartextMessage(text, signature); } // normalize EOL to canonical form - this.text = text.replace(/\r/g, '').replace(/[\t ]+\n/g, "\n").replace(/\n/g,"\r\n"); + this.text = text.replace(/\r/g, '').replace(/[\t ]+\n/g, "\n").replace(/\n/g, "\r\n"); if (signature && !(signature instanceof Signature)) { throw new Error('Invalid signature input'); } @@ -55,8 +55,8 @@ export function CleartextMessage(text, signature) { * @return {Array} array of keyid objects */ CleartextMessage.prototype.getSigningKeyIds = function() { - var keyIds = []; - var signatureList = this.signature.packets; + const keyIds = []; + const signatureList = this.signature.packets; signatureList.forEach(function(packet) { keyIds.push(packet.issuerKeyId); }); @@ -78,20 +78,20 @@ CleartextMessage.prototype.sign = async function(privateKeys) { * @return {module:signature~Signature} new detached signature of message content */ CleartextMessage.prototype.signDetached = async function(privateKeys) { - var packetlist = new packet.List(); - var literalDataPacket = new packet.Literal(); + const packetlist = new packet.List(); + const literalDataPacket = new packet.Literal(); literalDataPacket.setText(this.text); await Promise.all(privateKeys.map(async function(privateKey) { if (privateKey.isPublic()) { throw new Error('Need private key for signing'); } await privateKey.verifyPrimaryUser(); - var signingKeyPacket = privateKey.getSigningKeyPacket(); + const signingKeyPacket = privateKey.getSigningKeyPacket(); if (!signingKeyPacket) { throw new Error('Could not find valid key packet for signing in key ' + privateKey.primaryKey.getKeyId().toHex()); } - var signaturePacket = new packet.Signature(); + const signaturePacket = new packet.Signature(); signaturePacket.signatureType = enums.signature.text; signaturePacket.hashAlgorithm = config.prefer_hash_algorithm; signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; @@ -122,27 +122,27 @@ CleartextMessage.prototype.verify = function(keys) { * @return {Array<{keyid: module:type/keyid, valid: Boolean}>} list of signer's keyid and validity of signature */ CleartextMessage.prototype.verifyDetached = function(signature, keys) { - var signatureList = signature.packets; - var literalDataPacket = new packet.Literal(); + const signatureList = signature.packets; + const literalDataPacket = new packet.Literal(); // we assume that cleartext signature is generated based on UTF8 cleartext literalDataPacket.setText(this.text); return Promise.all(signatureList.map(async function(signature) { - var keyPacket = null; + let keyPacket = null; await Promise.all(keys.map(async function(key) { await key.verifyPrimaryUser(); // Look for the unique key packet that matches issuerKeyId of signature - var result = key.getSigningKeyPacket(signature.issuerKeyId, config.verify_expired_keys); + const result = key.getSigningKeyPacket(signature.issuerKeyId, config.verify_expired_keys); if (result) { keyPacket = result; } })); - var verifiedSig = { + const verifiedSig = { keyid: signature.issuerKeyId, valid: keyPacket ? await signature.verify(keyPacket, literalDataPacket) : null }; - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.push(signature); verifiedSig.signature = new Signature(packetlist); @@ -156,7 +156,7 @@ CleartextMessage.prototype.verifyDetached = function(signature, keys) { */ CleartextMessage.prototype.getText = function() { // normalize end of line to \n - return this.text.replace(/\r\n/g,"\n"); + return this.text.replace(/\r\n/g, "\n"); }; /** @@ -164,7 +164,7 @@ CleartextMessage.prototype.getText = function() { * @return {String} ASCII armor */ CleartextMessage.prototype.armor = function() { - var body = { + const body = { hash: enums.read(enums.hash, config.prefer_hash_algorithm).toUpperCase(), text: this.text, data: this.signature.packets.write() @@ -180,15 +180,15 @@ CleartextMessage.prototype.armor = function() { * @static */ export function readArmored(armoredText) { - var input = armor.decode(armoredText); + const input = armor.decode(armoredText); if (input.type !== enums.armor.signed) { throw new Error('No cleartext signed message.'); } - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.read(input.data); verifyHeaders(input.headers, packetlist); - var signature = new Signature(packetlist); - var newMessage = new CleartextMessage(input.text, signature); + const signature = new Signature(packetlist); + const newMessage = new CleartextMessage(input.text, signature); return newMessage; } @@ -199,23 +199,23 @@ export function readArmored(armoredText) { * @param {module:packet/packetlist} packetlist The packetlist with signature packets */ function verifyHeaders(headers, packetlist) { - var checkHashAlgos = function(hashAlgos) { - function check(algo) { - return packetlist[i].hashAlgorithm === algo; - } - for (var i = 0; i < packetlist.length; i++) { - if (packetlist[i].tag === enums.packet.signature && !hashAlgos.some(check)) { + const checkHashAlgos = function(hashAlgos) { + const check = packet => algo => packet.hashAlgorithm === algo; + + for (let i = 0; i < packetlist.length; i++) { + if (packetlist[i].tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { return false; } } return true; }; - var oneHeader = null; - var hashAlgos = []; + + let oneHeader = null; + let hashAlgos = []; headers.forEach(function(header) { oneHeader = header.match(/Hash: (.+)/); // get header value if (oneHeader) { - oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace + oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace oneHeader = oneHeader.split(','); oneHeader = oneHeader.map(function(hash) { hash = hash.toLowerCase(); @@ -230,6 +230,7 @@ function verifyHeaders(headers, packetlist) { throw new Error('Only "Hash" header allowed in cleartext signed message'); } }); + if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) { throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed'); } else if (!checkHashAlgos(hashAlgos)) { diff --git a/src/config/index.js b/src/config/index.js index 2beddebb..b5c0d2c5 100644 --- a/src/config/index.js +++ b/src/config/index.js @@ -3,4 +3,4 @@ * @module config */ -export { default } from './config.js'; \ No newline at end of file +export { default } from './config.js'; diff --git a/src/config/localStorage.js b/src/config/localStorage.js index 000c2cec..af3823d5 100644 --- a/src/config/localStorage.js +++ b/src/config/localStorage.js @@ -14,8 +14,8 @@ export default function LocalStorage() {} * if config is null the default config will be used */ LocalStorage.prototype.read = function () { - var raw = window.localStorage.getItem("config"); - var cf = (raw === null ? null : JSON.parse(raw)); + const raw = window.localStorage.getItem("config"); + const cf = (raw === null ? null : JSON.parse(raw)); if (cf === null) { this.config = this.default_config; this.write(); diff --git a/src/crypto/aes_kw.js b/src/crypto/aes_kw.js index e96172c5..edf72994 100644 --- a/src/crypto/aes_kw.js +++ b/src/crypto/aes_kw.js @@ -21,16 +21,16 @@ import cipher from './cipher'; import util from '../util'; function wrap(key, data) { - var aes = new cipher["aes" + (key.length*8)](key); - var IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - var P = unpack(data); - var A = IV; - var R = P; - var n = P.length/2; - var t = new Uint32Array([0, 0]); - var B = new Uint32Array(4); - for (var j = 0; j <= 5; ++j) { - for (var i = 0; i < n; ++i) { + const aes = new cipher["aes" + (key.length*8)](key); + const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); + const P = unpack(data); + let A = IV; + const R = P; + const n = P.length/2; + const t = new Uint32Array([0, 0]); + let B = new Uint32Array(4); + for (let j = 0; j <= 5; ++j) { + for (let i = 0; i < n; ++i) { t[1] = n * j + (1 + i); // B = A B[0] = A[0]; @@ -42,8 +42,8 @@ function wrap(key, data) { B = unpack(aes.encrypt(pack(B))); // A = MSB(64, B) ^ t A = B.subarray(0, 2); - A[0] = A[0] ^ t[0]; - A[1] = A[1] ^ t[1]; + A[0] ^= t[0]; + A[1] ^= t[1]; // R[i] = LSB(64, B) R[2*i] = B[2]; R[2*i+1] = B[3]; @@ -53,16 +53,16 @@ function wrap(key, data) { } function unwrap(key, data) { - var aes = new cipher["aes" + (key.length*8)](key); - var IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - var C = unpack(data); - var A = C.subarray(0, 2); - var R = C.subarray(2); - var n = C.length/2-1; - var t = new Uint32Array([0, 0]); - var B = new Uint32Array(4); - for (var j = 5; j >= 0; --j) { - for (var i = n - 1; i >= 0; --i) { + const aes = new cipher["aes" + (key.length*8)](key); + const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); + const C = unpack(data); + let A = C.subarray(0, 2); + const R = C.subarray(2); + const n = C.length/2-1; + const t = new Uint32Array([0, 0]); + let B = new Uint32Array(4); + for (let j = 5; j >= 0; --j) { + for (let i = n - 1; i >= 0; --i) { t[1] = n * j + (i + 1); // B = A ^ t B[0] = A[0] ^ t[0]; @@ -87,10 +87,10 @@ function unwrap(key, data) { function createArrayBuffer(data) { if (util.isString(data)) { - var length = data.length; - var buffer = new ArrayBuffer(length); - var view = new Uint8Array(buffer); - for (var j = 0; j < length; ++j) { + const { length } = data; + const buffer = new ArrayBuffer(length); + const view = new Uint8Array(buffer); + for (let j = 0; j < length; ++j) { view[j] = data.charCodeAt(j); } return buffer; @@ -99,29 +99,29 @@ function createArrayBuffer(data) { } function unpack(data) { - var length = data.length; - var buffer = createArrayBuffer(data); - var view = new DataView(buffer); - var arr = new Uint32Array(length/4); - for (var i=0; i block_size * pos) { - var encblock = cipherfn.encrypt(blockc); + const encblock = cipherfn.encrypt(blockc); blocki = plaintext.subarray((pos * block_size), (pos * block_size) + block_size); for (i = 0; i < blocki.length; i++) { blockc[i] = blocki[i] ^ encblock[i]; @@ -285,25 +289,25 @@ export default { normalDecrypt: function(cipherfn, key, ciphertext, iv) { cipherfn = new cipher[cipherfn](key); - var block_size = cipherfn.blockSize; + const block_size = cipherfn.blockSize; - var blockp; - var pos = 0; - var plaintext = new Uint8Array(ciphertext.length); - var offset = 0; - var i, j = 0; + let blockp; + let pos = 0; + const plaintext = new Uint8Array(ciphertext.length); + const offset = 0; + let i; + let j = 0; if (iv === null) { blockp = new Uint8Array(block_size); for (i = 0; i < block_size; i++) { blockp[i] = 0; } - } - else { + } else { blockp = iv.subarray(0, block_size); } while (ciphertext.length > (block_size * pos)) { - var decblock = cipherfn.encrypt(blockp); + const decblock = cipherfn.encrypt(blockp); blockp = ciphertext.subarray((pos * (block_size)) + offset, (pos * (block_size)) + (block_size) + offset); for (i = 0; i < blockp.length; i++) { plaintext[j++] = blockp[i] ^ decblock[i]; diff --git a/src/crypto/cipher/aes.js b/src/crypto/cipher/aes.js index 6197ace0..f99cabf6 100644 --- a/src/crypto/cipher/aes.js +++ b/src/crypto/cipher/aes.js @@ -6,8 +6,7 @@ import asmCrypto from 'asmcrypto-lite'; // TODO use webCrypto or nodeCrypto when possible. export default function aes(length) { - - var c = function(key) { + const c = function(key) { this.key = Uint8Array.from(key); this.encrypt = function(block) { diff --git a/src/crypto/cipher/blowfish.js b/src/crypto/cipher/blowfish.js index f2404a16..aa5ec826 100644 --- a/src/crypto/cipher/blowfish.js +++ b/src/crypto/cipher/blowfish.js @@ -27,184 +27,184 @@ Blowfish.prototype.BLOCKSIZE = 8; */ Blowfish.prototype.SBOXES = [ [ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, - 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, - 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, - 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, - 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, - 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, - 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, - 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, - 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, - 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, - 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, - 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, - 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, - 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, - 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, - 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, - 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, - 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, - 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, - 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, - 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, - 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, + 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, + 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, + 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, + 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, + 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, + 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, + 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, + 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, + 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, + 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, + 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, + 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, + 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, + 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, + 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, + 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a ], [ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, - 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, - 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, - 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, - 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, - 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, - 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, - 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, - 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, - 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, - 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, - 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, - 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, - 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, - 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, - 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, - 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, - 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, - 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, - 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, - 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, - 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, + 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, + 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, + 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, + 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, + 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, + 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, + 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, + 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, + 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, + 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, + 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, + 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, + 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, + 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, + 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, + 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, + 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 ], [ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, - 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, - 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, - 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, - 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, - 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, - 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, - 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, - 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, - 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, - 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, - 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, - 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, - 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, - 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, - 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, - 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, - 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, - 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, - 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, - 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, - 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, + 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, + 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, + 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, + 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, + 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, + 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, + 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, + 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, + 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, + 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, + 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, + 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, + 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, + 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, + 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, + 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, + 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 ], [ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, - 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, - 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, - 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, - 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, - 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, - 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, - 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, - 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, - 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, - 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, - 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, - 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, - 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, - 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, - 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, - 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, - 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, - 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, - 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, - 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, - 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, + 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, + 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, + 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, + 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, + 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, + 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, + 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, + 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, + 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, + 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, + 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, + 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, + 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, + 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, + 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, + 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, + 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 ] ]; @@ -212,9 +212,9 @@ Blowfish.prototype.SBOXES = [ //* This is the default PARRAY //* Blowfish.prototype.PARRAY = [ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, - 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, + 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b ]; //* @@ -231,7 +231,7 @@ Blowfish.prototype.NN = 16; //* Blowfish.prototype._clean = function(xx) { if (xx < 0) { - var yy = xx & 0x7FFFFFFF; + const yy = xx & 0x7FFFFFFF; xx = yy + 0x80000000; } return xx; @@ -241,23 +241,19 @@ Blowfish.prototype._clean = function(xx) { //* This is the mixing function that uses the sboxes //* Blowfish.prototype._F = function(xx) { - var aa; - var bb; - var cc; - var dd; - var yy; + let yy; - dd = xx & 0x00FF; + const dd = xx & 0x00FF; xx >>>= 8; - cc = xx & 0x00FF; + const cc = xx & 0x00FF; xx >>>= 8; - bb = xx & 0x00FF; + const bb = xx & 0x00FF; xx >>>= 8; - aa = xx & 0x00FF; + const aa = xx & 0x00FF; yy = this.sboxes[0][aa] + this.sboxes[1][bb]; - yy = yy ^ this.sboxes[2][cc]; - yy = yy + this.sboxes[3][dd]; + yy ^= this.sboxes[2][cc]; + yy += this.sboxes[3][dd]; return yy; }; @@ -267,22 +263,22 @@ Blowfish.prototype._F = function(xx) { //* and does NN rounds of Blowfish on them. //* Blowfish.prototype._encrypt_block = function(vals) { - var dataL = vals[0]; - var dataR = vals[1]; + let dataL = vals[0]; + let dataR = vals[1]; - var ii; + let ii; for (ii = 0; ii < this.NN; ++ii) { - dataL = dataL ^ this.parray[ii]; + dataL ^= this.parray[ii]; dataR = this._F(dataL) ^ dataR; - var tmp = dataL; + const tmp = dataL; dataL = dataR; dataR = tmp; } - dataL = dataL ^ this.parray[this.NN + 0]; - dataR = dataR ^ this.parray[this.NN + 1]; + dataL ^= this.parray[this.NN + 0]; + dataR ^= this.parray[this.NN + 1]; vals[0] = this._clean(dataR); vals[1] = this._clean(dataL); @@ -298,9 +294,9 @@ Blowfish.prototype._encrypt_block = function(vals) { //* the F() method to deconstruct the vector. //* Blowfish.prototype.encrypt_block = function(vector) { - var ii; - var vals = [0, 0]; - var off = this.BLOCKSIZE / 2; + let ii; + const vals = [0, 0]; + const off = this.BLOCKSIZE / 2; for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); @@ -308,7 +304,7 @@ Blowfish.prototype.encrypt_block = function(vector) { this._encrypt_block(vals); - var ret = []; + const ret = []; for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); @@ -324,22 +320,22 @@ Blowfish.prototype.encrypt_block = function(vector) { //* and undoes NN rounds of Blowfish on them. //* Blowfish.prototype._decrypt_block = function(vals) { - var dataL = vals[0]; - var dataR = vals[1]; + let dataL = vals[0]; + let dataR = vals[1]; - var ii; + let ii; for (ii = this.NN + 1; ii > 1; --ii) { - dataL = dataL ^ this.parray[ii]; + dataL ^= this.parray[ii]; dataR = this._F(dataL) ^ dataR; - var tmp = dataL; + const tmp = dataL; dataL = dataR; dataR = tmp; } - dataL = dataL ^ this.parray[1]; - dataR = dataR ^ this.parray[0]; + dataL ^= this.parray[1]; + dataR ^= this.parray[0]; vals[0] = this._clean(dataR); vals[1] = this._clean(dataL); @@ -350,14 +346,13 @@ Blowfish.prototype._decrypt_block = function(vals) { //* sboxes and parray for this encryption. //* Blowfish.prototype.init = function(key) { - var ii; - var jj = 0; + let ii; + let jj = 0; this.parray = []; for (ii = 0; ii < this.NN + 2; ++ii) { - var data = 0x00000000; - var kk; - for (kk = 0; kk < 4; ++kk) { + let data = 0x00000000; + for (let kk = 0; kk < 4; ++kk) { data = (data << 8) | (key[jj] & 0x00FF); if (++jj >= key.length) { jj = 0; @@ -374,7 +369,7 @@ Blowfish.prototype.init = function(key) { } } - var vals = [0x00000000, 0x00000000]; + const vals = [0x00000000, 0x00000000]; for (ii = 0; ii < this.NN + 2; ii += 2) { this._encrypt_block(vals); diff --git a/src/crypto/cipher/cast5.js b/src/crypto/cipher/cast5.js index 19efcc93..fd423f83 100644 --- a/src/crypto/cipher/cast5.js +++ b/src/crypto/cipher/cast5.js @@ -35,7 +35,7 @@ function OpenpgpSymencCast5() { }; this.reset = function() { - for (var i = 0; i < 16; i++) { + for (let i = 0; i < 16; i++) { this.masking[i] = 0; this.rotate[i] = 0; } @@ -46,12 +46,12 @@ function OpenpgpSymencCast5() { }; this.encrypt = function(src) { - var dst = new Array(src.length); + const dst = new Array(src.length); - for (var i = 0; i < src.length; i += 8) { - var l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - var r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - var t; + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; t = r; r = l ^ f1(r, this.masking[0], this.rotate[0]); @@ -119,12 +119,12 @@ function OpenpgpSymencCast5() { }; this.decrypt = function(src) { - var dst = new Array(src.length); + const dst = new Array(src.length); - for (var i = 0; i < src.length; i += 8) { - var l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - var r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - var t; + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; t = r; r = l ^ f1(r, this.masking[15], this.rotate[15]); @@ -190,7 +190,7 @@ function OpenpgpSymencCast5() { return dst; }; - var scheduleA = new Array(4); + const scheduleA = new Array(4); scheduleA[0] = new Array(4); scheduleA[0][0] = new Array(4, 0, 0xd, 0xf, 0xc, 0xe, 0x8); @@ -217,7 +217,7 @@ function OpenpgpSymencCast5() { scheduleA[3][2] = new Array(2, 5, 7, 6, 5, 4, 16 + 1); scheduleA[3][3] = new Array(3, 7, 0xa, 9, 0xb, 8, 16 + 3); - var scheduleB = new Array(4); + const scheduleB = new Array(4); scheduleB[0] = new Array(4); scheduleB[0][0] = new Array(16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2); @@ -247,24 +247,24 @@ function OpenpgpSymencCast5() { // changed 'in' to 'inn' (in javascript 'in' is a reserved word) this.keySchedule = function(inn) { - var t = new Array(8); - var k = new Array(32); + const t = new Array(8); + const k = new Array(32); - var i, j; + let j; - for (i = 0; i < 4; i++) { + for (let i = 0; i < 4; i++) { j = i * 4; t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; } - var x = [6, 7, 4, 5]; - var ki = 0; - var w; + const x = [6, 7, 4, 5]; + let ki = 0; + let w; - for (var half = 0; half < 2; half++) { - for (var round = 0; round < 4; round++) { + for (let half = 0; half < 2; half++) { + for (let round = 0; round < 4; round++) { for (j = 0; j < 4; j++) { - var a = scheduleA[round][j]; + const a = scheduleA[round][j]; w = t[a[1]]; w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; @@ -276,7 +276,7 @@ function OpenpgpSymencCast5() { } for (j = 0; j < 4; j++) { - var b = scheduleB[round][j]; + const b = scheduleB[round][j]; w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; @@ -289,7 +289,7 @@ function OpenpgpSymencCast5() { } } - for (i = 0; i < 16; i++) { + for (let i = 0; i < 16; i++) { this.masking[i] = k[i]; this.rotate[i] = k[16 + i] & 0x1f; } @@ -298,24 +298,24 @@ function OpenpgpSymencCast5() { // These are the three 'f' functions. See RFC 2144, section 2.2. function f1(d, m, r) { - var t = m + d; - var I = (t << r) | (t >>> (32 - r)); + const t = m + d; + const I = (t << r) | (t >>> (32 - r)); return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; } function f2(d, m, r) { - var t = m ^ d; - var I = (t << r) | (t >>> (32 - r)); + const t = m ^ d; + const I = (t << r) | (t >>> (32 - r)); return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; } function f3(d, m, r) { - var t = m - d; - var I = (t << r) | (t >>> (32 - r)); + const t = m - d; + const I = (t << r) | (t >>> (32 - r)); return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; } - var sBox = new Array(8); + const sBox = new Array(8); sBox[0] = new Array( 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, @@ -348,7 +348,8 @@ function OpenpgpSymencCast5() { 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, - 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf); + 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf + ); sBox[1] = new Array( 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, @@ -382,7 +383,8 @@ function OpenpgpSymencCast5() { 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, - 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1); + 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 + ); sBox[2] = new Array( 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, @@ -416,7 +418,8 @@ function OpenpgpSymencCast5() { 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, - 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783); + 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 + ); sBox[3] = new Array( 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, @@ -450,7 +453,8 @@ function OpenpgpSymencCast5() { 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, - 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2); + 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 + ); sBox[4] = new Array( 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, @@ -484,7 +488,8 @@ function OpenpgpSymencCast5() { 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, - 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4); + 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 + ); sBox[5] = new Array( 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, @@ -518,7 +523,8 @@ function OpenpgpSymencCast5() { 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, - 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f); + 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f + ); sBox[6] = new Array( 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, @@ -552,7 +558,8 @@ function OpenpgpSymencCast5() { 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, - 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3); + 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 + ); sBox[7] = new Array( 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, @@ -586,8 +593,8 @@ function OpenpgpSymencCast5() { 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, - 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e); - + 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e + ); } export default function Cast5(key) { diff --git a/src/crypto/cipher/des.js b/src/crypto/cipher/des.js index 300e71ed..b346a7bf 100644 --- a/src/crypto/cipher/des.js +++ b/src/crypto/cipher/des.js @@ -27,65 +27,92 @@ function des(keys, message, encrypt, mode, iv, padding) { //declaring this locally speeds things up a bit - var spfunction1 = new Array(0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, + const spfunction1 = new Array( + 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, - 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004); - var spfunction2 = new Array(-0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, + 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 + ); + const spfunction2 = new Array( + -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, - -0x7fef7fe0, 0x108000); - var spfunction3 = new Array(0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, + -0x7fef7fe0, 0x108000 + ); + const spfunction3 = new Array( + 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, - 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200); - var spfunction4 = new Array(0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, + 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 + ); + const spfunction4 = new Array( + 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, - 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080); - var spfunction5 = new Array(0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, + 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 + ); + const spfunction5 = new Array( + 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, - 0x40080000, 0x2080100, 0x40000100); - var spfunction6 = new Array(0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, + 0x40080000, 0x2080100, 0x40000100 + ); + const spfunction6 = new Array( + 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, - 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010); - var spfunction7 = new Array(0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, + 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 + ); + const spfunction7 = new Array( + 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, - 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002); - var spfunction8 = new Array(0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, + 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 + ); + const spfunction8 = new Array( + 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, - 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000); + 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 + ); //create the 16 or 48 subkeys we will need - var m = 0, - i, j, temp, right1, right2, left, right, looping; - var cbcleft, cbcleft2, cbcright, cbcright2; - var endloop, loopinc; - var len = message.length; + let m = 0; + let i; + let j; + let temp; + let right1; + let right2; + let left; + let right; + let looping; + let cbcleft; + let cbcleft2; + let cbcright; + let cbcright2; + let endloop; + let loopinc; + let len = message.length; //set up the loops for single and triple des - var iterations = keys.length === 32 ? 3 : 9; //single or triple des + const iterations = keys.length === 32 ? 3 : 9; //single or triple des if (iterations === 3) { looping = encrypt ? new Array(0, 32, 2) : new Array(30, -2, -2); } else { @@ -100,8 +127,8 @@ function des(keys, message, encrypt, mode, iv, padding) { } //store the result here - var result = new Uint8Array(len); - var k = 0; + let result = new Uint8Array(len); + let k = 0; if (mode === 1) { //CBC mode cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; @@ -224,48 +251,76 @@ function des(keys, message, encrypt, mode, iv, padding) { function des_createKeys(key) { //declaring this locally speeds things up a bit - var pc2bytes0 = new Array(0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, - 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204); - var pc2bytes1 = new Array(0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, - 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101); - var pc2bytes2 = new Array(0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, - 0x1000000, 0x1000008, 0x1000800, 0x1000808); - var pc2bytes3 = new Array(0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, - 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000); - var pc2bytes4 = new Array(0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, - 0x41000, 0x1010, 0x41010); - var pc2bytes5 = new Array(0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, - 0x2000000, 0x2000400, 0x2000020, 0x2000420); - var pc2bytes6 = new Array(0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, - 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002); - var pc2bytes7 = new Array(0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, - 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800); - var pc2bytes8 = new Array(0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, - 0x2000002, 0x2040002, 0x2000002, 0x2040002); - var pc2bytes9 = new Array(0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, - 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408); - var pc2bytes10 = new Array(0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, - 0x102000, 0x102020, 0x102000, 0x102020); - var pc2bytes11 = new Array(0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, - 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200); - var pc2bytes12 = new Array(0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, - 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010); - var pc2bytes13 = new Array(0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105); + const pc2bytes0 = new Array( + 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, + 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 + ); + const pc2bytes1 = new Array( + 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, + 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 + ); + const pc2bytes2 = new Array( + 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, + 0x1000000, 0x1000008, 0x1000800, 0x1000808 + ); + const pc2bytes3 = new Array( + 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, + 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 + ); + const pc2bytes4 = new Array( + 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, + 0x41000, 0x1010, 0x41010 + ); + const pc2bytes5 = new Array( + 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, + 0x2000000, 0x2000400, 0x2000020, 0x2000420 + ); + const pc2bytes6 = new Array( + 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, + 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 + ); + const pc2bytes7 = new Array( + 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, + 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 + ); + const pc2bytes8 = new Array( + 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, + 0x2000002, 0x2040002, 0x2000002, 0x2040002 + ); + const pc2bytes9 = new Array( + 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, + 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 + ); + const pc2bytes10 = new Array( + 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, + 0x102000, 0x102020, 0x102000, 0x102020 + ); + const pc2bytes11 = new Array( + 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, + 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 + ); + const pc2bytes12 = new Array( + 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, + 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 + ); + const pc2bytes13 = new Array(0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105); //how many iterations (1 for des, 3 for triple des) - var iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys //stores the return keys - var keys = new Array(32 * iterations); + const keys = new Array(32 * iterations); //now define the left shifts which need to be done - var shifts = new Array(0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0); + const shifts = new Array(0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0); //other variables - var lefttemp, righttemp, m = 0, - n = 0, - temp; + let lefttemp; + let righttemp; + let m = 0; + let n = 0; + let temp; - for (var j = 0; j < iterations; j++) { //either 1 or 3 iterations - var left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - var right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations + let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; @@ -296,7 +351,7 @@ function des_createKeys(key) { right = temp; //now go through and perform these shifts on the left and right keys - for (var i = 0; i < shifts.length; i++) { + for (let i = 0; i < shifts.length; i++) { //shift the keys either one or two bits to the left if (shifts[i]) { left = (left << 2) | (left >>> 26); @@ -329,9 +384,9 @@ function des_createKeys(key) { function des_addPadding(message, padding) { - var padLength = 8 - (message.length % 8); + const padLength = 8 - (message.length % 8); - var pad; + let pad; if (padding === 2 && (padLength < 8)) { //pad the message with spaces pad = " ".charCodeAt(0); } else if (padding === 1) { //PKCS7 padding @@ -340,16 +395,15 @@ function des_addPadding(message, padding) { pad = 0; } else if (padLength === 8) { return message; - } - else { + } else { throw new Error('des: invalid padding'); } - var paddedMessage = new Uint8Array(message.length + padLength); - for(var i = 0; i < message.length; i++) { + const paddedMessage = new Uint8Array(message.length + padLength); + for (let i = 0; i < message.length; i++) { paddedMessage[i] = message[i]; } - for(var j = 0; j < padLength; j++) { + for (let j = 0; j < padLength; j++) { paddedMessage[message.length + j] = pad; } @@ -357,22 +411,21 @@ function des_addPadding(message, padding) { } function des_removePadding(message, padding) { - var padLength = null; - var pad; + let padLength = null; + let pad; if (padding === 2) { // space padded pad = " ".charCodeAt(0); } else if (padding === 1) { // PKCS7 padLength = message[message.length - 1]; } else if (!padding) { // null padding pad = 0; - } - else { + } else { throw new Error('des: invalid padding'); } - if(!padLength) { + if (!padLength) { padLength = 1; - while(message[message.length - padLength] === pad) { + while (message[message.length - padLength] === pad) { padLength++; } padLength--; @@ -386,16 +439,22 @@ function des_removePadding(message, padding) { function Des(key) { this.key = []; - for (var i = 0; i < 3; i++) { + for (let i = 0; i < 3; i++) { this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); } this.encrypt = function(block) { - return des(des_createKeys(this.key[2]), - des(des_createKeys(this.key[1]), - des(des_createKeys(this.key[0]), - block, true, 0, null, null), - false, 0, null, null), true, 0, null, null); + return des( + des_createKeys(this.key[2]), + des( + des_createKeys(this.key[1]), + des( + des_createKeys(this.key[0]), + block, true, 0, null, null + ), + false, 0, null, null + ), true, 0, null, null + ); }; } @@ -409,12 +468,12 @@ function OriginalDes(key) { this.key = key; this.encrypt = function(block, padding) { - var keys = des_createKeys(this.key); + const keys = des_createKeys(this.key); return des(keys, block, true, 0, null, padding); }; this.decrypt = function(block, padding) { - var keys = des_createKeys(this.key); + const keys = des_createKeys(this.key); return des(keys, block, false, 0, null, padding); }; } diff --git a/src/crypto/cipher/twofish.js b/src/crypto/cipher/twofish.js index 95b54614..9692ab0d 100644 --- a/src/crypto/cipher/twofish.js +++ b/src/crypto/cipher/twofish.js @@ -26,7 +26,7 @@ //Math //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -var MAXINT = 0xFFFFFFFF; +const MAXINT = 0xFFFFFFFF; function rotw(w, n) { return (w << n | w >>> (32 - n)) & MAXINT; @@ -50,18 +50,18 @@ function getB(x, n) { function createTwofish() { // - var keyBytes = null; - var dataBytes = null; - var dataOffset = -1; + let keyBytes = null; + let dataBytes = null; + let dataOffset = -1; // var dataLength = -1; - var algorithmName = null; + let algorithmName = null; // var idx2 = -1; // algorithmName = "twofish"; - var tfsKey = []; - var tfsM = [ + let tfsKey = []; + let tfsM = [ [], [], [], @@ -70,36 +70,43 @@ function createTwofish() { function tfsInit(key) { keyBytes = key; - var i, a, b, c, d, meKey = [], - moKey = [], - inKey = []; - var kLen; - var sKey = []; - var f01, f5b, fef; + let i; + let a; + let b; + let c; + let d; + const meKey = []; + const moKey = []; + const inKey = []; + let kLen; + const sKey = []; + let f01; + let f5b; + let fef; - var q0 = [ + const q0 = [ [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] ]; - var q1 = [ + const q1 = [ [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] ]; - var q2 = [ + const q2 = [ [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] ]; - var q3 = [ + const q3 = [ [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] ]; - var ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; - var ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; - var q = [ + const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; + const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; + const q = [ [], [] ]; - var m = [ + const m = [ [], [], [], @@ -115,7 +122,9 @@ function createTwofish() { } function mdsRem(p, q) { - var i, t, u; + let i; + let t; + let u; for (i = 0; i < 8; i++) { t = q >>> 24; q = ((q << 8) & MAXINT) | p >>> 24; @@ -135,19 +144,18 @@ function createTwofish() { } function qp(n, x) { - var a, b, c, d; - a = x >> 4; - b = x & 15; - c = q0[n][a ^ b]; - d = q1[n][ror4[b] ^ ashx[a]]; + const a = x >> 4; + const b = x & 15; + const c = q0[n][a ^ b]; + const d = q1[n][ror4[b] ^ ashx[a]]; return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; } function hFun(x, key) { - var a = getB(x, 0), - b = getB(x, 1), - c = getB(x, 2), - d = getB(x, 3); + let a = getB(x, 0); + let b = getB(x, 1); + let c = getB(x, 2); + let d = getB(x, 3); switch (kLen) { case 4: a = q[1][a] ^ getB(key[3], 0); @@ -241,8 +249,8 @@ function createTwofish() { } function tfsFrnd(r, blk) { - var a = tfsG0(blk[0]); - var b = tfsG1(blk[1]); + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; a = tfsG0(blk[2]); @@ -252,8 +260,8 @@ function createTwofish() { } function tfsIrnd(i, blk) { - var a = tfsG0(blk[0]); - var b = tfsG1(blk[1]); + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); a = tfsG0(blk[2]); @@ -275,12 +283,11 @@ function createTwofish() { function tfsEncrypt(data, offset) { dataBytes = data; dataOffset = offset; - var blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], - getW(dataBytes, dataOffset + 4) ^ tfsKey[1], - getW(dataBytes, dataOffset + 8) ^ tfsKey[2], - getW(dataBytes, dataOffset + 12) ^ tfsKey[3] - ]; - for (var j = 0; j < 8; j++) { + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], + getW(dataBytes, dataOffset + 4) ^ tfsKey[1], + getW(dataBytes, dataOffset + 8) ^ tfsKey[2], + getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; + for (let j = 0; j < 8; j++) { tfsFrnd(j, blk); } setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); @@ -294,12 +301,11 @@ function createTwofish() { function tfsDecrypt(data, offset) { dataBytes = data; dataOffset = offset; - var blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], - getW(dataBytes, dataOffset + 4) ^ tfsKey[5], - getW(dataBytes, dataOffset + 8) ^ tfsKey[6], - getW(dataBytes, dataOffset + 12) ^ tfsKey[7] - ]; - for (var j = 7; j >= 0; j--) { + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], + getW(dataBytes, dataOffset + 4) ^ tfsKey[5], + getW(dataBytes, dataOffset + 8) ^ tfsKey[6], + getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; + for (let j = 7; j >= 0; j--) { tfsIrnd(j, blk); } setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); @@ -340,12 +346,12 @@ export default function TF(key) { function toArray(typedArray) { // Array.apply([], typedArray) does not work in PhantomJS 1.9 - var result = []; - for (var i = 0; i < typedArray.length; i++) { + const result = []; + for (let i = 0; i < typedArray.length; i++) { result[i] = typedArray[i]; } return result; } TF.keySize = TF.prototype.keySize = 32; -TF.blockSize = TF.prototype.blockSize = 16; \ No newline at end of file +TF.blockSize = TF.prototype.blockSize = 16; diff --git a/src/crypto/crypto.js b/src/crypto/crypto.js index a8c1348e..4cee1f7e 100644 --- a/src/crypto/crypto.js +++ b/src/crypto/crypto.js @@ -41,9 +41,8 @@ function constructParams(types, data) { return types.map(function(type, i) { if (data && data[i]) { return new type(data[i]); - } else { - return new type(); } + return new type(); }); } @@ -58,36 +57,34 @@ export default { * @return {Array} encrypted session key parameters */ publicKeyEncrypt: async function(algo, publicParams, data, fingerprint) { - var types = this.getEncSessionKeyParamTypes(algo); + const types = this.getEncSessionKeyParamTypes(algo); return (async function() { - var m; + let m; switch (algo) { case 'rsa_encrypt': - case 'rsa_encrypt_sign': - var rsa = new publicKey.rsa(); - var n = publicParams[0].toBigInteger(); - var e = publicParams[1].toBigInteger(); + case 'rsa_encrypt_sign': { + const rsa = new publicKey.rsa(); + const n = publicParams[0].toBigInteger(); + const e = publicParams[1].toBigInteger(); m = data.toBigInteger(); return constructParams(types, [rsa.encrypt(m, e, n)]); - - case 'elgamal': - var elgamal = new publicKey.elgamal(); - var p = publicParams[0].toBigInteger(); - var g = publicParams[1].toBigInteger(); - var y = publicParams[2].toBigInteger(); + } + case 'elgamal': { + const elgamal = new publicKey.elgamal(); + const p = publicParams[0].toBigInteger(); + const g = publicParams[1].toBigInteger(); + const y = publicParams[2].toBigInteger(); m = data.toBigInteger(); return constructParams(types, elgamal.encrypt(m, g, p, y)); - - case 'ecdh': - var ecdh = publicKey.elliptic.ecdh; - var curve = publicParams[0]; - var kdf_params = publicParams[2]; - var R = publicParams[1].toBigInteger(); - var res = await ecdh.encrypt( - curve.oid, kdf_params.cipher, kdf_params.hash, data, R, fingerprint - ); + } + case 'ecdh': { + const { ecdh } = publicKey.elliptic; + const curve = publicParams[0]; + const kdf_params = publicParams[2]; + const R = publicParams[1].toBigInteger(); + const res = await ecdh.encrypt(curve.oid, kdf_params.cipher, kdf_params.hash, data, R, fingerprint); return constructParams(types, [res.V, res.C]); - + } default: return []; } @@ -105,39 +102,40 @@ export default { */ publicKeyDecrypt: async function(algo, keyIntegers, dataIntegers, fingerprint) { - var p; + let p; return new type_mpi(await (async function() { switch (algo) { case 'rsa_encrypt_sign': - case 'rsa_encrypt': - var rsa = new publicKey.rsa(); + case 'rsa_encrypt': { + const rsa = new publicKey.rsa(); // 0 and 1 are the public key. - var n = keyIntegers[0].toBigInteger(); - var e = keyIntegers[1].toBigInteger(); + const n = keyIntegers[0].toBigInteger(); + const e = keyIntegers[1].toBigInteger(); // 2 to 5 are the private key. - var d = keyIntegers[2].toBigInteger(); + const d = keyIntegers[2].toBigInteger(); p = keyIntegers[3].toBigInteger(); - var q = keyIntegers[4].toBigInteger(); - var u = keyIntegers[5].toBigInteger(); - var m = dataIntegers[0].toBigInteger(); + const q = keyIntegers[4].toBigInteger(); + const u = keyIntegers[5].toBigInteger(); + const m = dataIntegers[0].toBigInteger(); return rsa.decrypt(m, n, e, d, p, q, u); - case 'elgamal': - var elgamal = new publicKey.elgamal(); - var x = keyIntegers[3].toBigInteger(); - var c1 = dataIntegers[0].toBigInteger(); - var c2 = dataIntegers[1].toBigInteger(); + } + case 'elgamal': { + const elgamal = new publicKey.elgamal(); + const x = keyIntegers[3].toBigInteger(); + const c1 = dataIntegers[0].toBigInteger(); + const c2 = dataIntegers[1].toBigInteger(); p = keyIntegers[0].toBigInteger(); return elgamal.decrypt(c1, c2, p, x); - - case 'ecdh': - var ecdh = publicKey.elliptic.ecdh; - var curve = keyIntegers[0]; - var kdf_params = keyIntegers[2]; - var V = dataIntegers[0].toBigInteger(); - var C = dataIntegers[1].data; - var r = keyIntegers[3].toBigInteger(); + } + case 'ecdh': { + const { ecdh } = publicKey.elliptic; + const curve = keyIntegers[0]; + const kdf_params = keyIntegers[2]; + const V = dataIntegers[0].toBigInteger(); + const C = dataIntegers[1].data; + const r = keyIntegers[3].toBigInteger(); return ecdh.decrypt(curve.oid, kdf_params.cipher, kdf_params.hash, V, C, r, fingerprint); - + } default: return null; } @@ -255,17 +253,17 @@ export default { * @return {Array} The array of parameters */ generateParams: function(algo, bits, curve) { - var types = this.getPubKeyParamTypes(algo).concat(this.getPrivKeyParamTypes(algo)); + const types = this.getPubKeyParamTypes(algo).concat(this.getPrivKeyParamTypes(algo)); switch (algo) { case 'rsa_encrypt': case 'rsa_encrypt_sign': - case 'rsa_sign': + case 'rsa_sign': { //remember "publicKey" refers to the crypto/public_key dir - var rsa = new publicKey.rsa(); + const rsa = new publicKey.rsa(); return rsa.generate(bits, "10001").then(function(keyObject) { return constructParams(types, [keyObject.n, keyObject.ee, keyObject.d, keyObject.p, keyObject.q, keyObject.u]); }); - + } case 'ecdsa': case 'eddsa': return publicKey.elliptic.generate(curve).then(function (keyObject) { diff --git a/src/crypto/gcm.js b/src/crypto/gcm.js index e577a90f..9d505150 100644 --- a/src/crypto/gcm.js +++ b/src/crypto/gcm.js @@ -41,7 +41,7 @@ const ALGO = 'AES-GCM'; * @return {Promise} The ciphertext output */ function encrypt(cipher, plaintext, key, iv) { - if (cipher.substr(0,3) !== 'aes') { + if (cipher.substr(0, 3) !== 'aes') { return Promise.reject(new Error('GCM mode supports only AES cipher')); } @@ -49,9 +49,8 @@ function encrypt(cipher, plaintext, key, iv) { return webEncrypt(plaintext, key, iv); } else if (nodeCrypto && config.use_native) { // Node crypto library return nodeEncrypt(plaintext, key, iv); - } else { // asm.js fallback - return Promise.resolve(asmCrypto.AES_GCM.encrypt(plaintext, key, iv)); - } + } // asm.js fallback + return Promise.resolve(asmCrypto.AES_GCM.encrypt(plaintext, key, iv)); } /** @@ -63,7 +62,7 @@ function encrypt(cipher, plaintext, key, iv) { * @return {Promise} The plaintext output */ function decrypt(cipher, ciphertext, key, iv) { - if (cipher.substr(0,3) !== 'aes') { + if (cipher.substr(0, 3) !== 'aes') { return Promise.reject(new Error('GCM mode supports only AES cipher')); } @@ -71,9 +70,8 @@ function decrypt(cipher, ciphertext, key, iv) { return webDecrypt(ciphertext, key, iv); } else if (nodeCrypto && config.use_native) { // Node crypto library return nodeDecrypt(ciphertext, key, iv); - } else { // asm.js fallback - return Promise.resolve(asmCrypto.AES_GCM.decrypt(ciphertext, key, iv)); - } + } // asm.js fallback + return Promise.resolve(asmCrypto.AES_GCM.decrypt(ciphertext, key, iv)); } export default { diff --git a/src/crypto/hash/index.js b/src/crypto/hash/index.js index ce1a5918..39729d5a 100644 --- a/src/crypto/hash/index.js +++ b/src/crypto/hash/index.js @@ -12,21 +12,20 @@ import sha from './sha.js'; import md5 from './md5.js'; import util from '../../util.js'; -const rusha = new Rusha(), - nodeCrypto = util.getNodeCrypto(), - Buffer = util.getNodeBuffer(); +const rusha = new Rusha(); +const nodeCrypto = util.getNodeCrypto(); +const Buffer = util.getNodeBuffer(); function node_hash(type) { return function (data) { - var shasum = nodeCrypto.createHash(type); + const shasum = nodeCrypto.createHash(type); shasum.update(new Buffer(data)); return new Uint8Array(shasum.digest()); }; } -var hash_fns; -if(nodeCrypto) { // Use Node native crypto for all hash functions - +let hash_fns; +if (nodeCrypto) { // Use Node native crypto for all hash functions hash_fns = { md5: node_hash('md5'), sha1: node_hash('sha1'), @@ -36,9 +35,7 @@ if(nodeCrypto) { // Use Node native crypto for all hash functions sha512: node_hash('sha512'), ripemd: node_hash('ripemd160') }; - } else { // Use JS fallbacks - hash_fns = { /** @see module:crypto/hash/md5 */ md5: md5, diff --git a/src/crypto/hash/md5.js b/src/crypto/hash/md5.js index eb5a799b..6750d41b 100644 --- a/src/crypto/hash/md5.js +++ b/src/crypto/hash/md5.js @@ -24,16 +24,16 @@ import util from '../../util.js'; * @param {String} entree string to hash */ export default function(entree) { - var hex = md5(util.Uint8Array2str(entree)); - var bin = util.str2Uint8Array(util.hex2bin(hex)); + const hex = md5(util.Uint8Array2str(entree)); + const bin = util.str2Uint8Array(util.hex2bin(hex)); return bin; } function md5cycle(x, k) { - var a = x[0], - b = x[1], - c = x[2], - d = x[3]; + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; a = ff(a, b, c, d, k[0], 7, -680876936); d = ff(d, a, b, c, k[1], 12, -389564586); @@ -107,7 +107,6 @@ function md5cycle(x, k) { x[1] = add32(b, x[1]); x[2] = add32(c, x[2]); x[3] = add32(d, x[3]); - } function cmn(q, a, b, x, s, t) { @@ -132,14 +131,14 @@ function ii(a, b, c, d, x, s, t) { } function md51(s) { - var n = s.length, - state = [1732584193, -271733879, -1732584194, 271733878], - i; + const n = s.length; + const state = [1732584193, -271733879, -1732584194, 271733878]; + let i; for (i = 64; i <= s.length; i += 64) { md5cycle(state, md5blk(s.substring(i - 64, i))); } s = s.substring(i - 64); - var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (i = 0; i < s.length; i++) { tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); } @@ -171,8 +170,8 @@ function md51(s) { * 8-bit unsigned value arrays. */ function md5blk(s) { /* I figured global was faster. */ - var md5blks = [], - i; /* Andy King said do it this way. */ + const md5blks = []; + let i; /* Andy King said do it this way. */ for (i = 0; i < 64; i += 4) { md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24); @@ -180,11 +179,11 @@ function md5blk(s) { /* I figured global was faster. */ return md5blks; } -var hex_chr = '0123456789abcdef'.split(''); +const hex_chr = '0123456789abcdef'.split(''); function rhex(n) { - var s = '', - j = 0; + let s = ''; + let j = 0; for (; j < 4; j++) { s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; } @@ -192,7 +191,7 @@ function rhex(n) { } function hex(x) { - for (var i = 0; i < x.length; i++) { + for (let i = 0; i < x.length; i++) { x[i] = rhex(x[i]); } return x.join(''); diff --git a/src/crypto/hash/sha.js b/src/crypto/hash/sha.js index 864b7924..023863d4 100644 --- a/src/crypto/hash/sha.js +++ b/src/crypto/hash/sha.js @@ -10,7 +10,7 @@ * Several functions taken from Paul Johnston */ - /** +/** * SUPPORTED_ALGS is the stub for a compile flag that will cause pruning of * functions that are not needed when a limited number of SHA families are * selected @@ -19,7 +19,7 @@ * 1 = SHA-1, 2 = SHA-224/SHA-256, 4 = SHA-384/SHA-512 */ -var SUPPORTED_ALGS = 4 | 2 | 1; +const SUPPORTED_ALGS = 4 | 2 | 1; /** * Int_64 is a object for 2 32-bit numbers emulating a 64-bit number @@ -30,8 +30,7 @@ var SUPPORTED_ALGS = 4 | 2 | 1; * @param {number} msint_32 The most significant 32-bits of a 64-bit number * @param {number} lsint_32 The least significant 32-bits of a 64-bit number */ -function Int_64(msint_32, lsint_32) -{ +function Int_64(msint_32, lsint_32) { this.highOrder = msint_32; this.lowOrder = lsint_32; } @@ -47,35 +46,32 @@ function Int_64(msint_32, lsint_32) * "value" contains the output number array and "binLen" is the binary * length of "value" */ -function str2binb(str, utfType) -{ - var bin = [], codePnt, binArr = [], byteCnt = 0, i, j, offset; +function str2binb(str, utfType) { + const bin = []; + let codePnt; + let binArr = []; + let byteCnt = 0; + let i; + let j; + let offset; - if ("UTF8" === utfType) - { - for (i = 0; i < str.length; i += 1) - { + if (utfType === "UTF8") { + for (i = 0; i < str.length; i += 1) { codePnt = str.charCodeAt(i); binArr = []; - if (0x80 > codePnt) - { + if (codePnt < 0x80) { binArr.push(codePnt); - } - else if (0x800 > codePnt) - { + } else if (codePnt < 0x800) { binArr.push(0xC0 | (codePnt >>> 6)); binArr.push(0x80 | (codePnt & 0x3F)); - } - else if ((0xd800 > codePnt) || (0xe000 <= codePnt)) { + } else if ((codePnt < 0xd800) || (codePnt >= 0xe000)) { binArr.push( 0xe0 | (codePnt >>> 12), 0x80 | ((codePnt >>> 6) & 0x3f), 0x80 | (codePnt & 0x3f) ); - } - else - { + } else { i += 1; codePnt = 0x10000 + (((codePnt & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff)); binArr.push( @@ -86,40 +82,33 @@ function str2binb(str, utfType) ); } - for (j = 0; j < binArr.length; j += 1) - { + for (j = 0; j < binArr.length; j += 1) { offset = byteCnt >>> 2; - while (bin.length <= offset) - { + while (bin.length <= offset) { bin.push(0); } bin[offset] |= binArr[j] << (24 - (8 * (byteCnt % 4))); byteCnt += 1; } } - } - else if (("UTF16BE" === utfType) || "UTF16LE" === utfType) - { - for (i = 0; i < str.length; i += 1) - { + } else if ((utfType === "UTF16BE") || utfType === "UTF16LE") { + for (i = 0; i < str.length; i += 1) { codePnt = str.charCodeAt(i); /* Internally strings are UTF-16BE so only change if UTF-16LE */ - if ("UTF16LE" === utfType) - { + if (utfType === "UTF16LE") { j = codePnt & 0xFF; codePnt = (j << 8) | (codePnt >> 8); } offset = byteCnt >>> 2; - while (bin.length <= offset) - { + while (bin.length <= offset) { bin.push(0); } bin[offset] |= codePnt << (16 - (8 * (byteCnt % 4))); byteCnt += 2; } } - return {"value" : bin, "binLen" : byteCnt * 8}; + return { "value" : bin, "binLen" : byteCnt * 8 }; } /** @@ -131,34 +120,30 @@ function str2binb(str, utfType) * "value" contains the output number array and "binLen" is the binary * length of "value" */ -function hex2binb(str) -{ - var bin = [], length = str.length, i, num, offset; +function hex2binb(str) { + const bin = []; + const { length } = str; + let num; + let offset; - if (0 !== (length % 2)) - { - throw "String of HEX type must be in byte increments"; + if ((length % 2) !== 0) { + throw new Error('String of HEX type must be in byte increments'); } - for (i = 0; i < length; i += 2) - { + for (let i = 0; i < length; i += 2) { num = parseInt(str.substr(i, 2), 16); - if (!isNaN(num)) - { + if (!isNaN(num)) { offset = i >>> 3; - while (bin.length <= offset) - { + while (bin.length <= offset) { bin.push(0); } bin[i >>> 3] |= num << (24 - (4 * (i % 8))); - } - else - { - throw "String of HEX type contains invalid characters"; + } else { + throw new Error('String of HEX type contains invalid characters'); } } - return {"value" : bin, "binLen" : length * 4}; + return { "value" : bin, "binLen" : length * 4 }; } /** @@ -170,23 +155,22 @@ function hex2binb(str) * "value" contains the output number array and "binLen" is the binary * length of "value" */ -function bytes2binb(str) -{ - var bin = [], codePnt, i, offset; +function bytes2binb(str) { + const bin = []; + let codePnt; + let offset; - for (i = 0; i < str.length; i += 1) - { + for (let i = 0; i < str.length; i += 1) { codePnt = str.charCodeAt(i); offset = i >>> 2; - if (bin.length <= offset) - { + if (bin.length <= offset) { bin.push(0); } bin[offset] |= codePnt << (24 - (8 * (i % 4))); } - return {"value" : bin, "binLen" : str.length * 8}; + return { "value" : bin, "binLen" : str.length * 8 }; } /** @@ -198,24 +182,22 @@ function bytes2binb(str) * "value" contains the output array and "binLen" is the binary * length of "value" */ -function typed2binb(array) -{ +function typed2binb(array) { + const bin = []; + let octet; + let offset; - var bin = [], octet, i, offset; - - for (i = 0; i < array.length; i += 1) - { + for (let i = 0; i < array.length; i += 1) { octet = array[i]; offset = i >>> 2; - if (bin.length <= offset) - { + if (bin.length <= offset) { bin.push(0); } bin[offset] |= octet << (24 - (8 * (i % 4))); } - return {"value" : bin, "binLen" : array.length * 8}; + return { "value" : bin, "binLen" : array.length * 8 }; } /** @@ -227,38 +209,38 @@ function typed2binb(array) * "value" contains the output number array and "binLen" is the binary * length of "value" */ -function b642binb(str) -{ - var retVal = [], byteCnt = 0, index, i, j, tmpInt, strPart, firstEqual, offset, - b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +function b642binb(str) { + const retVal = []; + let byteCnt = 0; + let index; + let j; + let tmpInt; + let strPart; + let firstEqual; + let offset; + const b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - if (-1 === str.search(/^[a-zA-Z0-9=+\/]+$/)) - { - throw "Invalid character in base-64 string"; + if (str.search(/^[a-zA-Z0-9=+\/]+$/) === -1) { + throw new Error('Invalid character in base-64 string'); } firstEqual = str.indexOf('='); str = str.replace(/\=/g, ''); - if ((-1 !== firstEqual) && (firstEqual < str.length)) - { - throw "Invalid '=' found in base-64 string"; + if ((firstEqual !== -1) && (firstEqual < str.length)) { + throw new Error('Invalid \'=\' found in base-64 string'); } - for (i = 0; i < str.length; i += 4) - { + for (let i = 0; i < str.length; i += 4) { strPart = str.substr(i, 4); tmpInt = 0; - for (j = 0; j < strPart.length; j += 1) - { + for (j = 0; j < strPart.length; j += 1) { index = b64Tab.indexOf(strPart[j]); tmpInt |= index << (18 - (6 * j)); } - for (j = 0; j < strPart.length - 1; j += 1) - { + for (j = 0; j < strPart.length - 1; j += 1) { offset = byteCnt >>> 2; - while (retVal.length <= offset) - { + while (retVal.length <= offset) { retVal.push(0); } retVal[offset] |= ((tmpInt >>> (16 - (j * 8))) & 0xFF) << @@ -267,7 +249,7 @@ function b642binb(str) } } - return {"value" : retVal, "binLen" : byteCnt * 8}; + return { "value" : retVal, "binLen" : byteCnt * 8 }; } /** @@ -281,20 +263,20 @@ function b642binb(str) * @return {string} Hexidecimal representation of the parameter in string * form */ -function binb2hex(binarray, formatOpts) -{ - var hex_tab = "0123456789abcdef", str = "", - length = binarray.length * 4, i, srcByte; +function binb2hex(binarray, formatOpts) { + const hex_tab = "0123456789abcdef"; + let str = ""; + const length = binarray.length * 4; + let srcByte; - for (i = 0; i < length; i += 1) - { + for (let i = 0; i < length; i += 1) { /* The below is more than a byte but it gets taken care of later */ srcByte = binarray[i >>> 2] >>> ((3 - (i % 4)) * 8); str += hex_tab.charAt((srcByte >>> 4) & 0xF) + hex_tab.charAt(srcByte & 0xF); } - return (formatOpts["outputUpper"]) ? str.toUpperCase() : str; + return (formatOpts.outputUpper) ? str.toUpperCase() : str; } /** @@ -308,13 +290,16 @@ function binb2hex(binarray, formatOpts) * @return {string} Base-64 encoded representation of the parameter in * string form */ -function binb2b64(binarray, formatOpts) -{ - var str = "", length = binarray.length * 4, i, j, triplet, offset, int1, int2, - b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +function binb2b64(binarray, formatOpts) { + let str = ""; + const length = binarray.length * 4; + let triplet; + let offset; + let int1; + let int2; + const b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - for (i = 0; i < length; i += 3) - { + for (let i = 0; i < length; i += 3) { offset = (i + 1) >>> 2; int1 = (binarray.length <= offset) ? 0 : binarray[offset]; offset = (i + 2) >>> 2; @@ -322,15 +307,11 @@ function binb2b64(binarray, formatOpts) triplet = (((binarray[i >>> 2] >>> 8 * (3 - i % 4)) & 0xFF) << 16) | (((int1 >>> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((int2 >>> 8 * (3 - (i + 2) % 4)) & 0xFF); - for (j = 0; j < 4; j += 1) - { - if (i * 8 + j * 6 <= binarray.length * 32) - { + for (let j = 0; j < 4; j += 1) { + if (i * 8 + j * 6 <= binarray.length * 32) { str += b64Tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F); - } - else - { - str += formatOpts["b64Pad"]; + } else { + str += formatOpts.b64Pad; } } } @@ -347,12 +328,12 @@ function binb2b64(binarray, formatOpts) * @return {string} Raw bytes representation of the parameter in string * form */ -function binb2bytes(binarray, formatOpts) -{ - var str = "", length = binarray.length * 4, i, srcByte; +function binb2bytes(binarray, formatOpts) { + let str = ""; + const length = binarray.length * 4; + let srcByte; - for (i = 0; i < length; i += 1) - { + for (let i = 0; i < length; i += 1) { srcByte = (binarray[i >>> 2] >>> ((3 - (i % 4)) * 8)) & 0xFF; str += String.fromCharCode(srcByte); } @@ -369,13 +350,11 @@ function binb2bytes(binarray, formatOpts) * @param {!Object} formatOpts Unused Hash list * @return {Uint8Array} Raw bytes representation of the parameter */ -function binb2typed(binarray, formatOpts) -{ - var length = binarray.length * 4; - var arr = new Uint8Array(length), i; +function binb2typed(binarray, formatOpts) { + const length = binarray.length * 4; + const arr = new Uint8Array(length); - for (i = 0; i < length; i += 1) - { + for (let i = 0; i < length; i += 1) { arr[i] = (binarray[i >>> 2] >>> ((3 - (i % 4)) * 8)) & 0xFF; } @@ -392,33 +371,25 @@ function binb2typed(binarray, formatOpts) * @return {{outputUpper : boolean, b64Pad : string}} Validated hash list * containing output formatting options */ -function getOutputOpts(outputOpts) -{ - var retVal = {"outputUpper" : false, "b64Pad" : "="}; +function getOutputOpts(outputOpts) { + const retVal = { "outputUpper" : false, "b64Pad" : "=" }; - try - { - if (outputOpts.hasOwnProperty("outputUpper")) - { - retVal["outputUpper"] = outputOpts["outputUpper"]; + try { + if (outputOpts.hasOwnProperty("outputUpper")) { + retVal.outputUpper = outputOpts.outputUpper; } - if (outputOpts.hasOwnProperty("b64Pad")) - { - retVal["b64Pad"] = outputOpts["b64Pad"]; + if (outputOpts.hasOwnProperty("b64Pad")) { + retVal.b64Pad = outputOpts.b64Pad; } - } - catch(ignore) - {} + } catch (ignore) {} - if ("boolean" !== typeof(retVal["outputUpper"])) - { - throw "Invalid outputUpper formatting option"; + if (typeof (retVal.outputUpper) !== "boolean") { + throw new Error('Invalid outputUpper formatting option'); } - if ("string" !== typeof(retVal["b64Pad"])) - { - throw "Invalid b64Pad formatting option"; + if (typeof (retVal.b64Pad) !== "string") { + throw new Error('Invalid b64Pad formatting option'); } return retVal; @@ -432,8 +403,7 @@ function getOutputOpts(outputOpts) * @param {number} n The number of bits to shift * @return {number} The x shifted circularly by n bits */ -function rotl_32(x, n) -{ +function rotl_32(x, n) { return (x << n) | (x >>> (32 - n)); } @@ -445,8 +415,7 @@ function rotl_32(x, n) * @param {number} n The number of bits to shift * @return {number} The x shifted circularly by n bits */ -function rotr_32(x, n) -{ +function rotr_32(x, n) { return (x >>> n) | (x << (32 - n)); } @@ -458,23 +427,20 @@ function rotr_32(x, n) * @param {number} n The number of bits to shift * @return {Int_64} The x shifted circularly by n bits */ -function rotr_64(x, n) -{ - var retVal = null, tmp = new Int_64(x.highOrder, x.lowOrder); +function rotr_64(x, n) { + let retVal = null; + const tmp = new Int_64(x.highOrder, x.lowOrder); - if (32 >= n) - { + if (n <= 32) { retVal = new Int_64( - (tmp.highOrder >>> n) | ((tmp.lowOrder << (32 - n)) & 0xFFFFFFFF), - (tmp.lowOrder >>> n) | ((tmp.highOrder << (32 - n)) & 0xFFFFFFFF) - ); - } - else - { + (tmp.highOrder >>> n) | ((tmp.lowOrder << (32 - n)) & 0xFFFFFFFF), + (tmp.lowOrder >>> n) | ((tmp.highOrder << (32 - n)) & 0xFFFFFFFF) + ); + } else { retVal = new Int_64( - (tmp.lowOrder >>> (n - 32)) | ((tmp.highOrder << (64 - n)) & 0xFFFFFFFF), - (tmp.highOrder >>> (n - 32)) | ((tmp.lowOrder << (64 - n)) & 0xFFFFFFFF) - ); + (tmp.lowOrder >>> (n - 32)) | ((tmp.highOrder << (64 - n)) & 0xFFFFFFFF), + (tmp.highOrder >>> (n - 32)) | ((tmp.lowOrder << (64 - n)) & 0xFFFFFFFF) + ); } return retVal; @@ -488,8 +454,7 @@ function rotr_64(x, n) * @param {number} n The number of bits to shift * @return {number} The x shifted by n bits */ -function shr_32(x, n) -{ +function shr_32(x, n) { return x >>> n; } @@ -501,23 +466,19 @@ function shr_32(x, n) * @param {number} n The number of bits to shift * @return {Int_64} The x shifted by n bits */ -function shr_64(x, n) -{ - var retVal = null; +function shr_64(x, n) { + let retVal = null; - if (32 >= n) - { + if (n <= 32) { retVal = new Int_64( - x.highOrder >>> n, - x.lowOrder >>> n | ((x.highOrder << (32 - n)) & 0xFFFFFFFF) - ); - } - else - { + x.highOrder >>> n, + x.lowOrder >>> n | ((x.highOrder << (32 - n)) & 0xFFFFFFFF) + ); + } else { retVal = new Int_64( - 0, - x.highOrder >>> (n - 32) - ); + 0, + x.highOrder >>> (n - 32) + ); } return retVal; @@ -532,8 +493,7 @@ function shr_64(x, n) * @param {number} z The third 32-bit integer argument * @return {number} The NIST specified output of the function */ -function parity_32(x, y, z) -{ +function parity_32(x, y, z) { return x ^ y ^ z; } @@ -546,8 +506,7 @@ function parity_32(x, y, z) * @param {number} z The third 32-bit integer argument * @return {number} The NIST specified output of the function */ -function ch_32(x, y, z) -{ +function ch_32(x, y, z) { return (x & y) ^ (~x & z); } @@ -560,12 +519,11 @@ function ch_32(x, y, z) * @param {Int_64} z The third 64-bit integer argument * @return {Int_64} The NIST specified output of the function */ -function ch_64(x, y, z) -{ +function ch_64(x, y, z) { return new Int_64( - (x.highOrder & y.highOrder) ^ (~x.highOrder & z.highOrder), - (x.lowOrder & y.lowOrder) ^ (~x.lowOrder & z.lowOrder) - ); + (x.highOrder & y.highOrder) ^ (~x.highOrder & z.highOrder), + (x.lowOrder & y.lowOrder) ^ (~x.lowOrder & z.lowOrder) + ); } /** @@ -577,8 +535,7 @@ function ch_64(x, y, z) * @param {number} z The third 32-bit integer argument * @return {number} The NIST specified output of the function */ -function maj_32(x, y, z) -{ +function maj_32(x, y, z) { return (x & y) ^ (x & z) ^ (y & z); } @@ -591,16 +548,15 @@ function maj_32(x, y, z) * @param {Int_64} z The third 64-bit integer argument * @return {Int_64} The NIST specified output of the function */ -function maj_64(x, y, z) -{ +function maj_64(x, y, z) { return new Int_64( - (x.highOrder & y.highOrder) ^ + (x.highOrder & y.highOrder) ^ (x.highOrder & z.highOrder) ^ (y.highOrder & z.highOrder), - (x.lowOrder & y.lowOrder) ^ + (x.lowOrder & y.lowOrder) ^ (x.lowOrder & z.lowOrder) ^ (y.lowOrder & z.lowOrder) - ); + ); } /** @@ -610,8 +566,7 @@ function maj_64(x, y, z) * @param {number} x The 32-bit integer argument * @return {number} The NIST specified output of the function */ -function sigma0_32(x) -{ +function sigma0_32(x) { return rotr_32(x, 2) ^ rotr_32(x, 13) ^ rotr_32(x, 22); } @@ -622,14 +577,15 @@ function sigma0_32(x) * @param {Int_64} x The 64-bit integer argument * @return {Int_64} The NIST specified output of the function */ -function sigma0_64(x) -{ - var rotr28 = rotr_64(x, 28), rotr34 = rotr_64(x, 34), - rotr39 = rotr_64(x, 39); +function sigma0_64(x) { + const rotr28 = rotr_64(x, 28); + const rotr34 = rotr_64(x, 34); + const rotr39 = rotr_64(x, 39); return new Int_64( - rotr28.highOrder ^ rotr34.highOrder ^ rotr39.highOrder, - rotr28.lowOrder ^ rotr34.lowOrder ^ rotr39.lowOrder); + rotr28.highOrder ^ rotr34.highOrder ^ rotr39.highOrder, + rotr28.lowOrder ^ rotr34.lowOrder ^ rotr39.lowOrder + ); } /** @@ -639,8 +595,7 @@ function sigma0_64(x) * @param {number} x The 32-bit integer argument * @return {number} The NIST specified output of the function */ -function sigma1_32(x) -{ +function sigma1_32(x) { return rotr_32(x, 6) ^ rotr_32(x, 11) ^ rotr_32(x, 25); } @@ -651,14 +606,15 @@ function sigma1_32(x) * @param {Int_64} x The 64-bit integer argument * @return {Int_64} The NIST specified output of the function */ -function sigma1_64(x) -{ - var rotr14 = rotr_64(x, 14), rotr18 = rotr_64(x, 18), - rotr41 = rotr_64(x, 41); +function sigma1_64(x) { + const rotr14 = rotr_64(x, 14); + const rotr18 = rotr_64(x, 18); + const rotr41 = rotr_64(x, 41); return new Int_64( - rotr14.highOrder ^ rotr18.highOrder ^ rotr41.highOrder, - rotr14.lowOrder ^ rotr18.lowOrder ^ rotr41.lowOrder); + rotr14.highOrder ^ rotr18.highOrder ^ rotr41.highOrder, + rotr14.lowOrder ^ rotr18.lowOrder ^ rotr41.lowOrder + ); } /** @@ -668,8 +624,7 @@ function sigma1_64(x) * @param {number} x The 32-bit integer argument * @return {number} The NIST specified output of the function */ -function gamma0_32(x) -{ +function gamma0_32(x) { return rotr_32(x, 7) ^ rotr_32(x, 18) ^ shr_32(x, 3); } @@ -680,14 +635,15 @@ function gamma0_32(x) * @param {Int_64} x The 64-bit integer argument * @return {Int_64} The NIST specified output of the function */ -function gamma0_64(x) -{ - var rotr1 = rotr_64(x, 1), rotr8 = rotr_64(x, 8), shr7 = shr_64(x, 7); +function gamma0_64(x) { + const rotr1 = rotr_64(x, 1); + const rotr8 = rotr_64(x, 8); + const shr7 = shr_64(x, 7); return new Int_64( - rotr1.highOrder ^ rotr8.highOrder ^ shr7.highOrder, - rotr1.lowOrder ^ rotr8.lowOrder ^ shr7.lowOrder - ); + rotr1.highOrder ^ rotr8.highOrder ^ shr7.highOrder, + rotr1.lowOrder ^ rotr8.lowOrder ^ shr7.lowOrder + ); } /** @@ -697,8 +653,7 @@ function gamma0_64(x) * @param {number} x The 32-bit integer argument * @return {number} The NIST specified output of the function */ -function gamma1_32(x) -{ +function gamma1_32(x) { return rotr_32(x, 17) ^ rotr_32(x, 19) ^ shr_32(x, 10); } @@ -709,15 +664,15 @@ function gamma1_32(x) * @param {Int_64} x The 64-bit integer argument * @return {Int_64} The NIST specified output of the function */ -function gamma1_64(x) -{ - var rotr19 = rotr_64(x, 19), rotr61 = rotr_64(x, 61), - shr6 = shr_64(x, 6); +function gamma1_64(x) { + const rotr19 = rotr_64(x, 19); + const rotr61 = rotr_64(x, 61); + const shr6 = shr_64(x, 6); return new Int_64( - rotr19.highOrder ^ rotr61.highOrder ^ shr6.highOrder, - rotr19.lowOrder ^ rotr61.lowOrder ^ shr6.lowOrder - ); + rotr19.highOrder ^ rotr61.highOrder ^ shr6.highOrder, + rotr19.lowOrder ^ rotr61.lowOrder ^ shr6.lowOrder + ); } /** @@ -729,10 +684,9 @@ function gamma1_64(x) * @param {number} b The second 32-bit integer argument to be added * @return {number} The sum of a + b */ -function safeAdd_32_2(a, b) -{ - var lsw = (a & 0xFFFF) + (b & 0xFFFF), - msw = (a >>> 16) + (b >>> 16) + (lsw >>> 16); +function safeAdd_32_2(a, b) { + const lsw = (a & 0xFFFF) + (b & 0xFFFF); + const msw = (a >>> 16) + (b >>> 16) + (lsw >>> 16); return ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); } @@ -748,10 +702,9 @@ function safeAdd_32_2(a, b) * @param {number} d The fourth 32-bit integer argument to be added * @return {number} The sum of a + b + c + d */ -function safeAdd_32_4(a, b, c, d) -{ - var lsw = (a & 0xFFFF) + (b & 0xFFFF) + (c & 0xFFFF) + (d & 0xFFFF), - msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + +function safeAdd_32_4(a, b, c, d) { + const lsw = (a & 0xFFFF) + (b & 0xFFFF) + (c & 0xFFFF) + (d & 0xFFFF); + const msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + (lsw >>> 16); return ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); @@ -769,11 +722,10 @@ function safeAdd_32_4(a, b, c, d) * @param {number} e The fifth 32-bit integer argument to be added * @return {number} The sum of a + b + c + d + e */ -function safeAdd_32_5(a, b, c, d, e) -{ - var lsw = (a & 0xFFFF) + (b & 0xFFFF) + (c & 0xFFFF) + (d & 0xFFFF) + - (e & 0xFFFF), - msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + +function safeAdd_32_5(a, b, c, d, e) { + const lsw = (a & 0xFFFF) + (b & 0xFFFF) + (c & 0xFFFF) + (d & 0xFFFF) + + (e & 0xFFFF); + const msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + (e >>> 16) + (lsw >>> 16); return ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); @@ -788,17 +740,17 @@ function safeAdd_32_5(a, b, c, d, e) * @param {Int_64} y The second 64-bit integer argument to be added * @return {Int_64} The sum of x + y */ -function safeAdd_64_2(x, y) -{ - var lsw, msw, lowOrder, highOrder; +function safeAdd_64_2(x, y) { + let lsw; + let msw; lsw = (x.lowOrder & 0xFFFF) + (y.lowOrder & 0xFFFF); msw = (x.lowOrder >>> 16) + (y.lowOrder >>> 16) + (lsw >>> 16); - lowOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); + const lowOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); lsw = (x.highOrder & 0xFFFF) + (y.highOrder & 0xFFFF) + (msw >>> 16); msw = (x.highOrder >>> 16) + (y.highOrder >>> 16) + (lsw >>> 16); - highOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); + const highOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); return new Int_64(highOrder, lowOrder); } @@ -814,21 +766,21 @@ function safeAdd_64_2(x, y) * @param {Int_64} d The fourth 64-bit integer argument to be added * @return {Int_64} The sum of a + b + c + d */ -function safeAdd_64_4(a, b, c, d) -{ - var lsw, msw, lowOrder, highOrder; +function safeAdd_64_4(a, b, c, d) { + let lsw; + let msw; lsw = (a.lowOrder & 0xFFFF) + (b.lowOrder & 0xFFFF) + (c.lowOrder & 0xFFFF) + (d.lowOrder & 0xFFFF); msw = (a.lowOrder >>> 16) + (b.lowOrder >>> 16) + (c.lowOrder >>> 16) + (d.lowOrder >>> 16) + (lsw >>> 16); - lowOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); + const lowOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); lsw = (a.highOrder & 0xFFFF) + (b.highOrder & 0xFFFF) + (c.highOrder & 0xFFFF) + (d.highOrder & 0xFFFF) + (msw >>> 16); msw = (a.highOrder >>> 16) + (b.highOrder >>> 16) + (c.highOrder >>> 16) + (d.highOrder >>> 16) + (lsw >>> 16); - highOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); + const highOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); return new Int_64(highOrder, lowOrder); } @@ -845,9 +797,9 @@ function safeAdd_64_4(a, b, c, d) * @param {Int_64} e The fourth 64-bit integer argument to be added * @return {Int_64} The sum of a + b + c + d + e */ -function safeAdd_64_5(a, b, c, d, e) -{ - var lsw, msw, lowOrder, highOrder; +function safeAdd_64_5(a, b, c, d, e) { + let lsw; + let msw; lsw = (a.lowOrder & 0xFFFF) + (b.lowOrder & 0xFFFF) + (c.lowOrder & 0xFFFF) + (d.lowOrder & 0xFFFF) + @@ -855,7 +807,7 @@ function safeAdd_64_5(a, b, c, d, e) msw = (a.lowOrder >>> 16) + (b.lowOrder >>> 16) + (c.lowOrder >>> 16) + (d.lowOrder >>> 16) + (e.lowOrder >>> 16) + (lsw >>> 16); - lowOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); + const lowOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); lsw = (a.highOrder & 0xFFFF) + (b.highOrder & 0xFFFF) + (c.highOrder & 0xFFFF) + (d.highOrder & 0xFFFF) + @@ -863,7 +815,7 @@ function safeAdd_64_5(a, b, c, d, e) msw = (a.highOrder >>> 16) + (b.highOrder >>> 16) + (c.highOrder >>> 16) + (d.highOrder >>> 16) + (e.highOrder >>> 16) + (lsw >>> 16); - highOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); + const highOrder = ((msw & 0xFFFF) << 16) | (lsw & 0xFFFF); return new Int_64(highOrder, lowOrder); } @@ -878,18 +830,22 @@ function safeAdd_64_5(a, b, c, d, e) * @return {Array.} The array of integers representing the SHA-1 * hash of message */ -function coreSHA1(message, messageLen) -{ - var W = [], a, b, c, d, e, T, ch = ch_32, parity = parity_32, - maj = maj_32, rotl = rotl_32, safeAdd_2 = safeAdd_32_2, i, t, - safeAdd_5 = safeAdd_32_5, appendedMessageLength, offset, - H = [ - 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 - ]; +function coreSHA1(message, messageLen) { + const W = []; + let T; + const ch = ch_32; + const parity = parity_32; + const maj = maj_32; + const rotl = rotl_32; + const safeAdd_2 = safeAdd_32_2; + const safeAdd_5 = safeAdd_32_5; - offset = (((messageLen + 65) >>> 9) << 4) + 15; - while (message.length <= offset) - { + const H = [ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 + ]; + + const offset = (((messageLen + 65) >>> 9) << 4) + 15; + while (message.length <= offset) { message.push(0); } /* Append '1' at the end of the binary string */ @@ -899,37 +855,23 @@ function coreSHA1(message, messageLen) of 512 but there can never be even multiples of 512 */ message[offset] = messageLen; - appendedMessageLength = message.length; + const appendedMessageLength = message.length; - for (i = 0; i < appendedMessageLength; i += 16) - { - a = H[0]; - b = H[1]; - c = H[2]; - d = H[3]; - e = H[4]; + for (let i = 0; i < appendedMessageLength; i += 16) { + let [a, b, c, d, e] = H; - for (t = 0; t < 80; t += 1) - { - if (t < 16) - { + for (let t = 0; t < 80; t += 1) { + if (t < 16) { W[t] = message[t + i]; - } - else - { + } else { W[t] = rotl(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); } - if (t < 20) - { + if (t < 20) { T = safeAdd_5(rotl(a, 5), ch(b, c, d), e, 0x5a827999, W[t]); - } - else if (t < 40) - { + } else if (t < 40) { T = safeAdd_5(rotl(a, 5), parity(b, c, d), e, 0x6ed9eba1, W[t]); - } - else if (t < 60) - { + } else if (t < 60) { T = safeAdd_5(rotl(a, 5), maj(b, c, d), e, 0x8f1bbcdc, W[t]); } else { T = safeAdd_5(rotl(a, 5), parity(b, c, d), e, 0xca62c1d6, W[t]); @@ -963,44 +905,70 @@ function coreSHA1(message, messageLen) * @return {Array.} The array of integers representing the SHA-2 * hash of message */ -function coreSHA2(message, messageLen, variant) -{ - var a, b, c, d, e, f, g, h, T1, T2, H, numRounds, lengthPosition, i, t, - binaryStringInc, binaryStringMult, safeAdd_2, safeAdd_4, safeAdd_5, - gamma0, gamma1, sigma0, sigma1, ch, maj, Int, W = [], int1, int2, offset, - appendedMessageLength, retVal, - K = [ - 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, - 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, - 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, - 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, - 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, - 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, - 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, - 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, - 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, - 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, - 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, - 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, - 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, - 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, - 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, - 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 - ], - H_trunc = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 - ], - H_full = [ - 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, - 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19 - ]; +function coreSHA2(message, messageLen, variant) { + let a; + let b; + let c; + let d; + let e; + let f; + let g; + let h; + let T1; + let T2; + let H; + let numRounds; + let lengthPosition; + let i; + let t; + let binaryStringInc; + let binaryStringMult; + let safeAdd_2; + let safeAdd_4; + let safeAdd_5; + let gamma0; + let gamma1; + let sigma0; + let sigma1; + let ch; + let maj; + let Int; + const W = []; + let int1; + let int2; + let offset; + let retVal; + let K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 + ]; + const H_trunc = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 + ]; + const H_full = [ + 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, + 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19 + ]; /* Set up the various function handles and variable for the specific * variant */ if ((variant === "SHA-224" || variant === "SHA-256") && - (2 & SUPPORTED_ALGS)) - { + (2 & SUPPORTED_ALGS)) { /* 32-bit variant */ numRounds = 64; lengthPosition = (((messageLen + 65) >>> 9) << 4) + 15; @@ -1017,18 +985,13 @@ function coreSHA2(message, messageLen, variant) maj = maj_32; ch = ch_32; - if ("SHA-224" === variant) - { + if (variant === "SHA-224") { H = H_trunc; - } - else /* "SHA-256" === variant */ - { + } else { /* "SHA-256" === variant */ H = H_full; } - } - else if ((variant === "SHA-384" || variant === "SHA-512") && - (4 & SUPPORTED_ALGS)) - { + } else if ((variant === "SHA-384" || variant === "SHA-512") && + (4 & SUPPORTED_ALGS)) { /* 64-bit variant */ numRounds = 80; lengthPosition = (((messageLen + 128) >>> 10) << 5) + 31; @@ -1046,11 +1009,11 @@ function coreSHA2(message, messageLen, variant) ch = ch_64; K = [ - new Int(K[ 0], 0xd728ae22), new Int(K[ 1], 0x23ef65cd), - new Int(K[ 2], 0xec4d3b2f), new Int(K[ 3], 0x8189dbbc), - new Int(K[ 4], 0xf348b538), new Int(K[ 5], 0xb605d019), - new Int(K[ 6], 0xaf194f9b), new Int(K[ 7], 0xda6d8118), - new Int(K[ 8], 0xa3030242), new Int(K[ 9], 0x45706fbe), + new Int(K[0], 0xd728ae22), new Int(K[1], 0x23ef65cd), + new Int(K[2], 0xec4d3b2f), new Int(K[3], 0x8189dbbc), + new Int(K[4], 0xf348b538), new Int(K[5], 0xb605d019), + new Int(K[6], 0xaf194f9b), new Int(K[7], 0xda6d8118), + new Int(K[8], 0xa3030242), new Int(K[9], 0x45706fbe), new Int(K[10], 0x4ee4b28c), new Int(K[11], 0xd5ffb4e2), new Int(K[12], 0xf27b896f), new Int(K[13], 0x3b1696b1), new Int(K[14], 0x25c71235), new Int(K[15], 0xcf692694), @@ -1088,17 +1051,14 @@ function coreSHA2(message, messageLen, variant) new Int(0x5fcb6fab, 0x3ad6faec), new Int(0x6c44198c, 0x4a475817) ]; - if ("SHA-384" === variant) - { + if (variant === "SHA-384") { H = [ new Int(0xcbbb9d5d, H_trunc[0]), new Int(0x0629a292a, H_trunc[1]), new Int(0x9159015a, H_trunc[2]), new Int(0x0152fecd8, H_trunc[3]), new Int(0x67332667, H_trunc[4]), new Int(0x98eb44a87, H_trunc[5]), new Int(0xdb0c2e0d, H_trunc[6]), new Int(0x047b5481d, H_trunc[7]) ]; - } - else /* "SHA-512" === variant */ - { + } else { /* "SHA-512" === variant */ H = [ new Int(H_full[0], 0xf3bcc908), new Int(H_full[1], 0x84caa73b), new Int(H_full[2], 0xfe94f82b), new Int(H_full[3], 0x5f1d36f1), @@ -1106,14 +1066,11 @@ function coreSHA2(message, messageLen, variant) new Int(H_full[6], 0xfb41bd6b), new Int(H_full[7], 0x137e2179) ]; } - } - else - { + } else { throw "Unexpected error in SHA-2 implementation"; } - while (message.length <= lengthPosition) - { + while (message.length <= lengthPosition) { message.push(0); } /* Append '1' at the end of the binary string */ @@ -1122,35 +1079,23 @@ function coreSHA2(message, messageLen, variant) * length is correct */ message[lengthPosition] = messageLen; - appendedMessageLength = message.length; + const appendedMessageLength = message.length; - for (i = 0; i < appendedMessageLength; i += binaryStringInc) - { - a = H[0]; - b = H[1]; - c = H[2]; - d = H[3]; - e = H[4]; - f = H[5]; - g = H[6]; - h = H[7]; + for (i = 0; i < appendedMessageLength; i += binaryStringInc) { + [a, b, c, d, e, f, g, h] = H; - for (t = 0; t < numRounds; t += 1) - { - if (t < 16) - { + for (t = 0; t < numRounds; t += 1) { + if (t < 16) { offset = t * binaryStringMult + i; int1 = (message.length <= offset) ? 0 : message[offset]; int2 = (message.length <= offset + 1) ? 0 : message[offset + 1]; /* Bit of a hack - for 32-bit, the second term is ignored */ W[t] = new Int(int1, int2); - } - else - { + } else { W[t] = safeAdd_4( - gamma1(W[t - 2]), W[t - 7], - gamma0(W[t - 15]), W[t - 16] - ); + gamma1(W[t - 2]), W[t - 7], + gamma0(W[t - 15]), W[t - 16] + ); } T1 = safeAdd_5(h, sigma1(e), ch(e, f, g), K[t], W[t]); @@ -1163,7 +1108,6 @@ function coreSHA2(message, messageLen, variant) c = b; b = a; a = safeAdd_2(T1, T2); - } H[0] = safeAdd_2(a, H[0]); @@ -1176,19 +1120,14 @@ function coreSHA2(message, messageLen, variant) H[7] = safeAdd_2(h, H[7]); } - if (("SHA-224" === variant) && (2 & SUPPORTED_ALGS)) - { + if ((variant === "SHA-224") && (2 & SUPPORTED_ALGS)) { retVal = [ H[0], H[1], H[2], H[3], H[4], H[5], H[6] ]; - } - else if (("SHA-256" === variant) && (2 & SUPPORTED_ALGS)) - { + } else if ((variant === "SHA-256") && (2 & SUPPORTED_ALGS)) { retVal = H; - } - else if (("SHA-384" === variant) && (4 & SUPPORTED_ALGS)) - { + } else if ((variant === "SHA-384") && (4 & SUPPORTED_ALGS)) { retVal = [ H[0].highOrder, H[0].lowOrder, H[1].highOrder, H[1].lowOrder, @@ -1197,9 +1136,7 @@ function coreSHA2(message, messageLen, variant) H[4].highOrder, H[4].lowOrder, H[5].highOrder, H[5].lowOrder ]; - } - else if (("SHA-512" === variant) && (4 & SUPPORTED_ALGS)) - { + } else if ((variant === "SHA-512") && (4 & SUPPORTED_ALGS)) { retVal = [ H[0].highOrder, H[0].lowOrder, H[1].highOrder, H[1].lowOrder, @@ -1210,9 +1147,7 @@ function coreSHA2(message, messageLen, variant) H[6].highOrder, H[6].lowOrder, H[7].highOrder, H[7].lowOrder ]; - } - else /* This should never be reached */ - { + } else { /* This should never be reached */ throw "Unexpected error in SHA-2 implementation"; } @@ -1227,59 +1162,48 @@ function coreSHA2(message, messageLen, variant) * @this {jsSHA} * @param {string} srcString The string to be hashed * @param {string} inputFormat The format of srcString, HEX, ASCII, TEXT, - * B64, or BYTES + * B64, or BYTES * @param {string=} encoding The text encoding to use to encode the source * string */ -var jsSHA = function(srcString, inputFormat, encoding) -{ - var strBinLen = 0, strToHash = [0], utfType = '', srcConvertRet = null; +const jsSHA = function(srcString, inputFormat, encoding) { + let strBinLen = 0; + let strToHash = [0]; + let utfType = ''; + let srcConvertRet = null; utfType = encoding || "UTF8"; - if (!(("UTF8" === utfType) || ("UTF16BE" === utfType) || ("UTF16LE" === utfType))) - { - throw "encoding must be UTF8, UTF16BE, or UTF16LE"; + if (!((utfType === "UTF8") || (utfType === "UTF16BE") || (utfType === "UTF16LE"))) { + throw new Error('encoding must be UTF8, UTF16BE, or UTF16LE'); } /* Convert the input string into the correct type */ - if ("HEX" === inputFormat) - { - if (0 !== (srcString.length % 2)) - { - throw "srcString of HEX type must be in byte increments"; + if (inputFormat === "HEX") { + if ((srcString.length % 2) !== 0) { + throw new Error('srcString of HEX type must be in byte increments'); } srcConvertRet = hex2binb(srcString); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } - else if (("TEXT" === inputFormat) || ("ASCII" === inputFormat)) - { + strBinLen = srcConvertRet.binLen; + strToHash = srcConvertRet.value; + } else if ((inputFormat === "TEXT") || (inputFormat === "ASCII")) { srcConvertRet = str2binb(srcString, utfType); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } - else if ("B64" === inputFormat) - { + strBinLen = srcConvertRet.binLen; + strToHash = srcConvertRet.value; + } else if (inputFormat === "B64") { srcConvertRet = b642binb(srcString); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } - else if ("BYTES" === inputFormat) - { + strBinLen = srcConvertRet.binLen; + strToHash = srcConvertRet.value; + } else if (inputFormat === "BYTES") { srcConvertRet = bytes2binb(srcString); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } - else if ("TYPED" === inputFormat) - { + strBinLen = srcConvertRet.binLen; + strToHash = srcConvertRet.value; + } else if (inputFormat === "TYPED") { srcConvertRet = typed2binb(srcString); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } - else - { - throw "inputFormat must be HEX, TEXT, ASCII, B64, BYTES, or TYPED"; + strBinLen = srcConvertRet.binLen; + strToHash = srcConvertRet.value; + } else { + throw new Error('inputFormat must be HEX, TEXT, ASCII, B64, BYTES, or TYPED'); } /** @@ -1297,94 +1221,73 @@ var jsSHA = function(srcString, inputFormat, encoding) * @return {string} The string representation of the hash in the format * specified */ - this.getHash = function(variant, format, numRounds, outputFormatOpts) - { - var formatFunc = null, message = strToHash.slice(), - messageBinLen = strBinLen, i; + this.getHash = function(variant, format, numRounds, outputFormatOpts) { + let formatFunc = null; + let message = strToHash.slice(); + let messageBinLen = strBinLen; + let i; /* Need to do argument patching since both numRounds and outputFormatOpts are optional */ - if (3 === arguments.length) - { - if ("number" !== typeof numRounds) - { + if (arguments.length === 3) { + if (typeof numRounds !== "number") { outputFormatOpts = numRounds; numRounds = 1; } - } - else if (2 === arguments.length) - { + } else if (arguments.length === 2) { numRounds = 1; } /* Validate the numRounds argument */ - if ((numRounds !== parseInt(numRounds)) || (1 > numRounds)) - { - throw "numRounds must a integer >= 1"; + if ((numRounds !== parseInt(numRounds)) || (numRounds < 1)) { + throw new Error('numRounds must a integer >= 1'); } /* Validate the output format selection */ - switch (format) - { - case "HEX": - formatFunc = binb2hex; - break; - case "B64": - formatFunc = binb2b64; - break; - case "BYTES": - formatFunc = binb2bytes; - break; - case "TYPED": - formatFunc = binb2typed; - break; - default: - throw "format must be HEX, B64, or BYTES"; + switch (format) { + case "HEX": + formatFunc = binb2hex; + break; + case "B64": + formatFunc = binb2b64; + break; + case "BYTES": + formatFunc = binb2bytes; + break; + case "TYPED": + formatFunc = binb2typed; + break; + default: + throw new Error('format must be HEX, B64, or BYTES'); } - if (("SHA-1" === variant) && (1 & SUPPORTED_ALGS)) - { - for (i = 0; i < numRounds; i += 1) - { + if ((variant === "SHA-1") && (1 & SUPPORTED_ALGS)) { + for (i = 0; i < numRounds; i += 1) { message = coreSHA1(message, messageBinLen); messageBinLen = 160; } - } - else if (("SHA-224" === variant) && (2 & SUPPORTED_ALGS)) - { - for (i = 0; i < numRounds; i += 1) - { + } else if ((variant === "SHA-224") && (2 & SUPPORTED_ALGS)) { + for (i = 0; i < numRounds; i += 1) { message = coreSHA2(message, messageBinLen, variant); messageBinLen = 224; } - } - else if (("SHA-256" === variant) && (2 & SUPPORTED_ALGS)) - { - for (i = 0; i < numRounds; i += 1) - { + } else if ((variant === "SHA-256") && (2 & SUPPORTED_ALGS)) { + for (i = 0; i < numRounds; i += 1) { message = coreSHA2(message, messageBinLen, variant); messageBinLen = 256; } - } - else if (("SHA-384" === variant) && (4 & SUPPORTED_ALGS)) - { - for (i = 0; i < numRounds; i += 1) - { + } else if ((variant === "SHA-384") && (4 & SUPPORTED_ALGS)) { + for (i = 0; i < numRounds; i += 1) { message = coreSHA2(message, messageBinLen, variant); messageBinLen = 384; } - } - else if (("SHA-512" === variant) && (4 & SUPPORTED_ALGS)) - { - for (i = 0; i < numRounds; i += 1) - { + } else if ((variant === "SHA-512") && (4 & SUPPORTED_ALGS)) { + for (i = 0; i < numRounds; i += 1) { message = coreSHA2(message, messageBinLen, variant); messageBinLen = 512; } - } - else - { - throw "Chosen SHA variant is not supported"; + } else { + throw new Error('Chosen SHA variant is not supported'); } return formatFunc(message, getOutputOpts(outputFormatOpts)); @@ -1407,165 +1310,134 @@ var jsSHA = function(srcString, inputFormat, encoding) * @return {string} The string representation of the hash in the format * specified */ - this.getHMAC = function(key, inputFormat, variant, outputFormat, - outputFormatOpts) - { - var formatFunc, keyToUse, blockByteSize, blockBitSize, i, - retVal, lastArrayIndex, keyBinLen, hashBitSize, - keyWithIPad = [], keyWithOPad = [], keyConvertRet = null; + this.getHMAC = function( + key, inputFormat, variant, outputFormat, + outputFormatOpts + ) { + let formatFunc; + let keyToUse; + let blockByteSize; + let i; + let retVal; + let keyBinLen; + let hashBitSize; + const keyWithIPad = []; + const keyWithOPad = []; + let keyConvertRet = null; /* Validate the output format selection */ - switch (outputFormat) - { - case "HEX": - formatFunc = binb2hex; - break; - case "B64": - formatFunc = binb2b64; - break; - case "BYTES": - formatFunc = binb2bytes; - break; - default: - throw "outputFormat must be HEX, B64, or BYTES"; + switch (outputFormat) { + case "HEX": + formatFunc = binb2hex; + break; + case "B64": + formatFunc = binb2b64; + break; + case "BYTES": + formatFunc = binb2bytes; + break; + default: + throw new Error('outputFormat must be HEX, B64, or BYTES'); } /* Validate the hash variant selection and set needed variables */ - if (("SHA-1" === variant) && (1 & SUPPORTED_ALGS)) - { + if ((variant === "SHA-1") && (1 & SUPPORTED_ALGS)) { blockByteSize = 64; hashBitSize = 160; - } - else if (("SHA-224" === variant) && (2 & SUPPORTED_ALGS)) - { + } else if ((variant === "SHA-224") && (2 & SUPPORTED_ALGS)) { blockByteSize = 64; hashBitSize = 224; - } - else if (("SHA-256" === variant) && (2 & SUPPORTED_ALGS)) - { + } else if ((variant === "SHA-256") && (2 & SUPPORTED_ALGS)) { blockByteSize = 64; hashBitSize = 256; - } - else if (("SHA-384" === variant) && (4 & SUPPORTED_ALGS)) - { + } else if ((variant === "SHA-384") && (4 & SUPPORTED_ALGS)) { blockByteSize = 128; hashBitSize = 384; - } - else if (("SHA-512" === variant) && (4 & SUPPORTED_ALGS)) - { + } else if ((variant === "SHA-512") && (4 & SUPPORTED_ALGS)) { blockByteSize = 128; hashBitSize = 512; - } - else - { - throw "Chosen SHA variant is not supported"; + } else { + throw new Error('Chosen SHA variant is not supported'); } /* Validate input format selection */ - if ("HEX" === inputFormat) - { + if (inputFormat === "HEX") { keyConvertRet = hex2binb(key); - keyBinLen = keyConvertRet["binLen"]; - keyToUse = keyConvertRet["value"]; - } - else if (("TEXT" === inputFormat) || ("ASCII" === inputFormat)) - { + keyBinLen = keyConvertRet.binLen; + keyToUse = keyConvertRet.value; + } else if ((inputFormat === "TEXT") || (inputFormat === "ASCII")) { keyConvertRet = str2binb(key, utfType); - keyBinLen = keyConvertRet["binLen"]; - keyToUse = keyConvertRet["value"]; - } - else if ("B64" === inputFormat) - { + keyBinLen = keyConvertRet.binLen; + keyToUse = keyConvertRet.value; + } else if (inputFormat === "B64") { keyConvertRet = b642binb(key); - keyBinLen = keyConvertRet["binLen"]; - keyToUse = keyConvertRet["value"]; - } - else if ("BYTES" === inputFormat) - { + keyBinLen = keyConvertRet.binLen; + keyToUse = keyConvertRet.value; + } else if (inputFormat === "BYTES") { keyConvertRet = bytes2binb(key); - keyBinLen = keyConvertRet["binLen"]; - keyToUse = keyConvertRet["value"]; - } - else - { - throw "inputFormat must be HEX, TEXT, ASCII, B64, or BYTES"; + keyBinLen = keyConvertRet.binLen; + keyToUse = keyConvertRet.value; + } else { + throw new Error('inputFormat must be HEX, TEXT, ASCII, B64, or BYTES'); } /* These are used multiple times, calculate and store them */ - blockBitSize = blockByteSize * 8; - lastArrayIndex = (blockByteSize / 4) - 1; + const blockBitSize = blockByteSize * 8; + const lastArrayIndex = (blockByteSize / 4) - 1; /* Figure out what to do with the key based on its size relative to * the hash's block size */ - if (blockByteSize < (keyBinLen / 8)) - { - if (("SHA-1" === variant) && (1 & SUPPORTED_ALGS)) - { + if (blockByteSize < (keyBinLen / 8)) { + if ((variant === "SHA-1") && (1 & SUPPORTED_ALGS)) { keyToUse = coreSHA1(keyToUse, keyBinLen); - } - else if (6 & SUPPORTED_ALGS) - { + } else if (6 & SUPPORTED_ALGS) { keyToUse = coreSHA2(keyToUse, keyBinLen, variant); - } - else - { - throw "Unexpected error in HMAC implementation"; + } else { + throw new Error('Unexpected error in HMAC implementation'); } /* For all variants, the block size is bigger than the output * size so there will never be a useful byte at the end of the * string */ - while (keyToUse.length <= lastArrayIndex) - { + while (keyToUse.length <= lastArrayIndex) { keyToUse.push(0); } keyToUse[lastArrayIndex] &= 0xFFFFFF00; - } - else if (blockByteSize > (keyBinLen / 8)) - { + } else if (blockByteSize > (keyBinLen / 8)) { /* If the blockByteSize is greater than the key length, there * will always be at LEAST one "useless" byte at the end of the * string */ - while (keyToUse.length <= lastArrayIndex) - { + while (keyToUse.length <= lastArrayIndex) { keyToUse.push(0); } keyToUse[lastArrayIndex] &= 0xFFFFFF00; } /* Create ipad and opad */ - for (i = 0; i <= lastArrayIndex; i += 1) - { + for (i = 0; i <= lastArrayIndex; i += 1) { keyWithIPad[i] = keyToUse[i] ^ 0x36363636; keyWithOPad[i] = keyToUse[i] ^ 0x5C5C5C5C; } /* Calculate the HMAC */ - if (("SHA-1" === variant) && (1 & SUPPORTED_ALGS)) - { + if ((variant === "SHA-1") && (1 & SUPPORTED_ALGS)) { retVal = coreSHA1( - keyWithOPad.concat( - coreSHA1( - keyWithIPad.concat(strToHash), - blockBitSize + strBinLen - ) - ), - blockBitSize + hashBitSize); - } - else if (6 & SUPPORTED_ALGS) - { + keyWithOPad.concat(coreSHA1( + keyWithIPad.concat(strToHash), + blockBitSize + strBinLen + )), + blockBitSize + hashBitSize + ); + } else if (6 & SUPPORTED_ALGS) { retVal = coreSHA2( - keyWithOPad.concat( - coreSHA2( - keyWithIPad.concat(strToHash), - blockBitSize + strBinLen, - variant - ) - ), - blockBitSize + hashBitSize, variant); - } - else - { - throw "Unexpected error in HMAC implementation"; + keyWithOPad.concat(coreSHA2( + keyWithIPad.concat(strToHash), + blockBitSize + strBinLen, + variant + )), + blockBitSize + hashBitSize, variant + ); + } else { + throw new Error('Unexpected error in HMAC implementation'); } return formatFunc(retVal, getOutputOpts(outputFormatOpts)); @@ -1575,27 +1447,27 @@ var jsSHA = function(srcString, inputFormat, encoding) export default { /** SHA1 hash */ sha1: function(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); + const shaObj = new jsSHA(str, "TYPED", "UTF8"); return shaObj.getHash("SHA-1", "TYPED"); }, /** SHA224 hash */ sha224: function(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); + const shaObj = new jsSHA(str, "TYPED", "UTF8"); return shaObj.getHash("SHA-224", "TYPED"); }, /** SHA256 hash */ sha256: function(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); + const shaObj = new jsSHA(str, "TYPED", "UTF8"); return shaObj.getHash("SHA-256", "TYPED"); }, /** SHA384 hash */ sha384: function(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); + const shaObj = new jsSHA(str, "TYPED", "UTF8"); return shaObj.getHash("SHA-384", "TYPED"); }, /** SHA512 hash */ sha512: function(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); + const shaObj = new jsSHA(str, "TYPED", "UTF8"); return shaObj.getHash("SHA-512", "TYPED"); } }; diff --git a/src/crypto/index.js b/src/crypto/index.js index 4b2cbe1f..a5ced4ed 100644 --- a/src/crypto/index.js +++ b/src/crypto/index.js @@ -38,7 +38,7 @@ const mod = { aes_kw: aes_kw }; -for (var i in crypto) { +for (const i in crypto) { mod[i] = crypto[i]; } diff --git a/src/crypto/pkcs1.js b/src/crypto/pkcs1.js index 4ba3e1d1..1acb15d4 100644 --- a/src/crypto/pkcs1.js +++ b/src/crypto/pkcs1.js @@ -33,19 +33,19 @@ import hash from './hash'; /** * ASN1 object identifiers for hashes (See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}) */ -var hash_headers = []; +const hash_headers = []; hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, - 0x10]; + 0x10]; hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, - 0x04, 0x20]; + 0x04, 0x20]; hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, - 0x04, 0x30]; + 0x04, 0x30]; hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, - 0x00, 0x04, 0x40]; + 0x00, 0x04, 0x40]; hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, - 0x00, 0x04, 0x1C]; + 0x00, 0x04, 0x1C]; /** * Create padding with secure random data @@ -54,8 +54,8 @@ hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, * @return {String} Padding as string */ function getPkcs1Padding(length) { - var result = ''; - var randomByte; + let result = ''; + let randomByte; while (result.length < length) { randomByte = random.getSecureRandomOctet(); if (randomByte !== 0) { @@ -75,17 +75,17 @@ export default { * @return {String} EME-PKCS1 padded message */ encode: function(M, k) { - var mLen = M.length; + const mLen = M.length; // length checking if (mLen > k - 11) { throw new Error('Message too long'); } // Generate an octet string PS of length k - mLen - 3 consisting of // pseudo-randomly generated nonzero octets - var PS = getPkcs1Padding(k - mLen - 3); + const PS = getPkcs1Padding(k - mLen - 3); // Concatenate PS, the message M, and other padding to form an // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. - var EM = String.fromCharCode(0) + + const EM = String.fromCharCode(0) + String.fromCharCode(2) + PS + String.fromCharCode(0) + @@ -102,19 +102,18 @@ export default { if (EM.charCodeAt(0) !== 0) { EM = String.fromCharCode(0) + EM; } - var firstOct = EM.charCodeAt(0); - var secondOct = EM.charCodeAt(1); - var i = 2; + const firstOct = EM.charCodeAt(0); + const secondOct = EM.charCodeAt(1); + let i = 2; while (EM.charCodeAt(i) !== 0 && i < EM.length) { i++; } - var psLen = i - 2; - var separator = EM.charCodeAt(i++); + const psLen = i - 2; + const separator = EM.charCodeAt(i++); if (firstOct === 0 && secondOct === 2 && psLen >= 8 && separator === 0) { return EM.substr(i); - } else { - throw new Error('Decryption error'); } + throw new Error('Decryption error'); } }, @@ -127,34 +126,34 @@ export default { * @returns {String} encoded message */ encode: function(algo, M, emLen) { - var i; + let i; // Apply the hash function to the message M to produce a hash value H - var H = util.Uint8Array2str(hash.digest(algo, util.str2Uint8Array(M))); + const H = util.Uint8Array2str(hash.digest(algo, util.str2Uint8Array(M))); if (H.length !== hash.getHashByteLength(algo)) { throw new Error('Invalid hash length'); } // produce an ASN.1 DER value for the hash function used. // Let T be the full hash prefix - var T = ''; + let T = ''; for (i = 0; i < hash_headers[algo].length; i++) { T += String.fromCharCode(hash_headers[algo][i]); } // add hash value to prefix T += H; // and let tLen be the length in octets of T - var tLen = T.length; + const tLen = T.length; if (emLen < tLen + 11) { throw new Error('Intended encoded message length too short'); } // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF // The length of PS will be at least 8 octets - var PS = ''; + let PS = ''; for (i = 0; i < (emLen - tLen - 3); i++) { PS += String.fromCharCode(0xff); } // Concatenate PS, the hash prefix T, and other padding to form the // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || T. - var EM = String.fromCharCode(0x00) + + const EM = String.fromCharCode(0x00) + String.fromCharCode(0x01) + PS + String.fromCharCode(0x00) + diff --git a/src/crypto/public_key/dsa.js b/src/crypto/public_key/dsa.js index 3d6ec237..1fb64979 100644 --- a/src/crypto/public_key/dsa.js +++ b/src/crypto/public_key/dsa.js @@ -40,14 +40,16 @@ export default function DSA() { // of leftmost bits equal to the number of bits of q. This (possibly // truncated) hash function result is treated as a number and used // directly in the DSA signature algorithm. - var hashed_data = util.getLeftNBits(util.Uint8Array2str(hashModule.digest(hashalgo, util.str2Uint8Array(m))), q.bitLength()); - var hash = new BigInteger(util.hexstrdump(hashed_data), 16); + const hashed_data = util.getLeftNBits(util.Uint8Array2str(hashModule.digest(hashalgo, util.str2Uint8Array(m))), q.bitLength()); + const hash = new BigInteger(util.hexstrdump(hashed_data), 16); // FIPS-186-4, section 4.6: // The values of r and s shall be checked to determine if r = 0 or s = 0. // If either r = 0 or s = 0, a new value of k shall be generated, and the // signature shall be recalculated. It is extremely unlikely that r = 0 // or s = 0 if signatures are generated properly. - var k, s1, s2; + let k; + let s1; + let s2; while (true) { k = random.getRandomBigIntegerInRange(BigInteger.ONE, q.subtract(BigInteger.ONE)); s1 = (g.modPow(k, p)).mod(q); @@ -56,14 +58,14 @@ export default function DSA() { break; } } - var result = []; + const result = []; result[0] = s1.toMPI(); result[1] = s2.toMPI(); return result; } function select_hash_algorithm(q) { - var usersetting = config.prefer_hash_algorithm; + const usersetting = config.prefer_hash_algorithm; /* * 1024-bit key, 160-bit q, SHA-1, SHA-224, SHA-256, SHA-384, or SHA-512 hash * 2048-bit key, 224-bit q, SHA-224, SHA-256, SHA-384, or SHA-512 hash @@ -102,8 +104,8 @@ export default function DSA() { this.select_hash_algorithm = select_hash_algorithm; function verify(hashalgo, s1, s2, m, p, q, g, y) { - var hashed_data = util.getLeftNBits(util.Uint8Array2str(hashModule.digest(hashalgo, util.str2Uint8Array(m))), q.bitLength()); - var hash = new BigInteger(util.hexstrdump(hashed_data), 16); + const hashed_data = util.getLeftNBits(util.Uint8Array2str(hashModule.digest(hashalgo, util.str2Uint8Array(m))), q.bitLength()); + const hash = new BigInteger(util.hexstrdump(hashed_data), 16); if (BigInteger.ZERO.compareTo(s1) >= 0 || s1.compareTo(q) >= 0 || BigInteger.ZERO.compareTo(s2) >= 0 || @@ -111,13 +113,13 @@ export default function DSA() { util.print_debug("invalid DSA Signature"); return null; } - var w = s2.modInverse(q); + const w = s2.modInverse(q); if (BigInteger.ZERO.compareTo(w) === 0) { util.print_debug("invalid DSA Signature"); return null; } - var u1 = hash.multiply(w).mod(q); - var u2 = s1.multiply(w).mod(q); + const u1 = hash.multiply(w).mod(q); + const u2 = s1.multiply(w).mod(q); return g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q); } diff --git a/src/crypto/public_key/elgamal.js b/src/crypto/public_key/elgamal.js index f7a4175f..465dc16a 100644 --- a/src/crypto/public_key/elgamal.js +++ b/src/crypto/public_key/elgamal.js @@ -29,13 +29,12 @@ import random from '../random.js'; import util from '../../util.js'; export default function Elgamal() { - function encrypt(m, g, p, y) { // choose k in {2,...,p-2} - var pMinus2 = p.subtract(BigInteger.TWO); - var k = random.getRandomBigIntegerInRange(BigInteger.ONE, pMinus2); + const pMinus2 = p.subtract(BigInteger.TWO); + let k = random.getRandomBigIntegerInRange(BigInteger.ONE, pMinus2); k = k.mod(pMinus2).add(BigInteger.ONE); - var c = []; + const c = []; c[0] = g.modPow(k, p); c[1] = y.modPow(k, p).multiply(m).mod(p); return c; diff --git a/src/crypto/public_key/elliptic/curves.js b/src/crypto/public_key/elliptic/curves.js index b26e4de3..9c8c1b4c 100644 --- a/src/crypto/public_key/elliptic/curves.js +++ b/src/crypto/public_key/elliptic/curves.js @@ -38,14 +38,15 @@ import base64 from '../../../encoding/base64'; const webCrypto = util.getWebCrypto(); const nodeCrypto = util.getNodeCrypto(); -var webCurves = {}, nodeCurves = {}; +let webCurves = {}; +let nodeCurves = {}; webCurves = { 'p256': 'P-256', 'p384': 'P-384', 'p521': 'P-521' }; if (nodeCrypto && config.use_native) { - var knownCurves = nodeCrypto.getCurves(); + const knownCurves = nodeCrypto.getCurves(); nodeCurves = { 'secp256k1': knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, 'p256': knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, @@ -147,7 +148,7 @@ Curve.prototype.keyFromPublic = function (pub) { }; Curve.prototype.genKeyPair = async function () { - var keyPair; + let keyPair; if (webCrypto && config.use_native && this.web) { // If browser doesn't support a curve, we'll catch it try { @@ -160,8 +161,8 @@ Curve.prototype.genKeyPair = async function () { keyPair = await nodeGenKeyPair(this.name); return new KeyPair(this.curve, keyPair); } - var compact = this.curve.curve.type === 'edwards' || this.curve.curve.type === 'mont'; - var r = await this.curve.genKeyPair(); + const compact = this.curve.curve.type === 'edwards' || this.curve.curve.type === 'mont'; + const r = await this.curve.genKeyPair(); if (this.keyType === enums.publicKey.eddsa) { keyPair = { secret: r.getSecret() }; } else { @@ -171,7 +172,7 @@ Curve.prototype.genKeyPair = async function () { }; function get(oid_or_name) { - var name; + let name; if (OID.prototype.isPrototypeOf(oid_or_name) && enums.curve[oid_or_name.toHex()]) { name = enums.write(enums.curve, oid_or_name.toHex()); // by curve OID @@ -188,7 +189,7 @@ function get(oid_or_name) { async function generate(curve) { curve = get(curve); - var keyPair = await curve.genKeyPair(); + const keyPair = await curve.genKeyPair(); return { oid: curve.oid, Q: new BigInteger(keyPair.getPublic()), @@ -203,13 +204,13 @@ function getPreferredHashAlgo(oid) { } module.exports = { - Curve: Curve, - curves: curves, - webCurves: webCurves, - nodeCurves: nodeCurves, - getPreferredHashAlgo: getPreferredHashAlgo, - generate: generate, - get: get + Curve, + curves, + webCurves, + nodeCurves, + getPreferredHashAlgo, + generate, + get }; @@ -222,12 +223,10 @@ module.exports = { async function webGenKeyPair(name) { // Note: keys generated with ECDSA and ECDH are structurally equivalent - var webCryptoKey = await webCrypto.generateKey( - { name: "ECDSA", namedCurve: webCurves[name] }, true, ["sign", "verify"] - ); + const webCryptoKey = await webCrypto.generateKey({ name: "ECDSA", namedCurve: webCurves[name] }, true, ["sign", "verify"]); - var privateKey = await webCrypto.exportKey("jwk", webCryptoKey.privateKey); - var publicKey = await webCrypto.exportKey("jwk", webCryptoKey.publicKey); + const privateKey = await webCrypto.exportKey("jwk", webCryptoKey.privateKey); + const publicKey = await webCrypto.exportKey("jwk", webCryptoKey.publicKey); return { pub: { @@ -239,7 +238,7 @@ async function webGenKeyPair(name) { } async function nodeGenKeyPair(name) { - var ecdh = nodeCrypto.createECDH(nodeCurves[name]); + const ecdh = nodeCrypto.createECDH(nodeCurves[name]); await ecdh.generateKeys(); return { diff --git a/src/crypto/public_key/elliptic/eddsa.js b/src/crypto/public_key/elliptic/eddsa.js index 485aff27..6145b7cd 100644 --- a/src/crypto/public_key/elliptic/eddsa.js +++ b/src/crypto/public_key/elliptic/eddsa.js @@ -60,12 +60,12 @@ async function verify(oid, hash_algo, signature, m, Q) { const curve = curves.get(oid); const key = curve.keyFromPublic(Q.toByteArray()); // EdDSA signature params are expected in little-endian format - const R = Array.from(signature.R.toByteArray()).reverse(), - S = Array.from(signature.S.toByteArray()).reverse(); - return key.verify( - m, { R: [].concat(R, Array(curve.payloadSize - R.length).fill(0)), - S: [].concat(S, Array(curve.payloadSize - S.length).fill(0)) }, hash_algo - ); + const R = Array.from(signature.R.toByteArray()).reverse(); + const S = Array.from(signature.S.toByteArray()).reverse(); + return key.verify(m, { + R: [].concat(R, Array(curve.payloadSize - R.length).fill(0)), + S: [].concat(S, Array(curve.payloadSize - S.length).fill(0)) + }, hash_algo); } module.exports = { diff --git a/src/crypto/public_key/elliptic/index.js b/src/crypto/public_key/elliptic/index.js index c250d594..35bfdb83 100644 --- a/src/crypto/public_key/elliptic/index.js +++ b/src/crypto/public_key/elliptic/index.js @@ -25,7 +25,7 @@ * @module crypto/public_key/elliptic */ -import {get, generate, getPreferredHashAlgo} from './curves'; +import { get, generate, getPreferredHashAlgo } from './curves'; import ecdsa from './ecdsa'; import eddsa from './eddsa'; import ecdh from './ecdh'; diff --git a/src/crypto/public_key/elliptic/key.js b/src/crypto/public_key/elliptic/key.js index b9fe25e4..7e3861fa 100644 --- a/src/crypto/public_key/elliptic/key.js +++ b/src/crypto/public_key/elliptic/key.js @@ -39,9 +39,13 @@ import config from '../../../config'; import base64 from '../../../encoding/base64'; const webCrypto = util.getWebCrypto(); -const webCurves = curves.webCurves; +const { webCurves } = curves; const nodeCrypto = util.getNodeCrypto(); -const nodeCurves = curves.nodeCurves; +const { nodeCurves } = curves; + +// const webCrypto = util.getWebCrypto(); +// const nodeCrypto = util.getNodeCrypto(); +// const { webCurves, nodeCurves } = curves; const jwkToPem = nodeCrypto ? require('jwk-to-pem') : undefined; const ECDSASignature = nodeCrypto ? @@ -102,16 +106,15 @@ KeyPair.prototype.derive = function (pub) { }; KeyPair.prototype.getPublic = function () { - var compact = (this.curve.curve.type === 'edwards' || this.curve.curve.type === 'mont'); + const compact = (this.curve.curve.type === 'edwards' || this.curve.curve.type === 'mont'); return this.keyPair.getPublic('array', compact); }; KeyPair.prototype.getPrivate = function () { if (this.keyType === enums.publicKey.eddsa) { return this.keyPair.getSecret(); - } else { - return this.keyPair.getPrivate().toArray(); } + return this.keyPair.getPrivate().toArray(); }; module.exports = { @@ -127,7 +130,7 @@ module.exports = { async function webSign(curve, hash_algo, message, keyPair) { - var l = curve.payloadSize; + const l = curve.payloadSize; const key = await webCrypto.importKey( "jwk", { @@ -163,11 +166,11 @@ async function webSign(curve, hash_algo, message, keyPair) { }; } -async function webVerify(curve, hash_algo, {r, s}, message, publicKey) { - var l = curve.payloadSize; +async function webVerify(curve, hash_algo, { r, s }, message, publicKey) { + const l = curve.payloadSize; r = Array(l - r.length).fill(0).concat(r); s = Array(l - s.length).fill(0).concat(s); - var signature = new Uint8Array(r.concat(s)).buffer; + const signature = new Uint8Array(r.concat(s)).buffer; const key = await webCrypto.importKey( "jwk", { @@ -224,8 +227,8 @@ async function nodeSign(curve, hash_algo, message, keyPair) { }; } -async function nodeVerify(curve, hash_algo, {r, s}, message, publicKey) { - var signature = ECDSASignature.encode({ r: new BigInteger(r), s: new BigInteger(s) }, 'der'); +async function nodeVerify(curve, hash_algo, { r, s }, message, publicKey) { + const signature = ECDSASignature.encode({ r: new BigInteger(r), s: new BigInteger(s) }, 'der'); const key = jwkToPem( { "kty": "EC", diff --git a/src/crypto/public_key/jsbn.js b/src/crypto/public_key/jsbn.js index bcfe7705..43cb588c 100644 --- a/src/crypto/public_key/jsbn.js +++ b/src/crypto/public_key/jsbn.js @@ -42,19 +42,18 @@ import util from '../../util'; // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit -var dbits; +let dbits; // JavaScript engine analysis -var canary = 0xdeadbeefcafe; -var j_lm = ((canary & 0xffffff) == 0xefcafe); +const canary = 0xdeadbeefcafe; +const j_lm = ((canary & 0xffffff) == 0xefcafe); // (public) Constructor export default function BigInteger(a, b, c) { - if (a != null) - if ("number" == typeof a) this.fromNumber(a, b, c); + if (a != null) { if (typeof a === "number") this.fromNumber(a, b, c); else if (b == null && !util.isString(a)) this.fromString(a, 256); - else this.fromString(a, b); + else this.fromString(a, b); } } // return new, unset BigInteger @@ -74,7 +73,7 @@ function nbi() { function am1(i, x, w, j, c, n) { while (--n >= 0) { - var v = x * this[i++] + w[j] + c; + const v = x * this[i++] + w[j] + c; c = Math.floor(v / 0x4000000); w[j++] = v & 0x3ffffff; } @@ -85,12 +84,12 @@ function am1(i, x, w, j, c, n) { // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, + let xl = x & 0x7fff, xh = x >> 15; while (--n >= 0) { - var l = this[i] & 0x7fff; - var h = this[i++] >> 15; - var m = xh * l + h * xl; + let l = this[i] & 0x7fff; + const h = this[i++] >> 15; + const m = xh * l + h * xl; l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); w[j++] = l & 0x3fffffff; @@ -101,12 +100,12 @@ function am2(i, x, w, j, c, n) { // browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, + let xl = x & 0x3fff, xh = x >> 14; while (--n >= 0) { - var l = this[i] & 0x3fff; - var h = this[i++] >> 14; - var m = xh * l + h * xl; + let l = this[i] & 0x3fff; + const h = this[i++] >> 14; + const m = xh * l + h * xl; l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; c = (l >> 28) + (m >> 14) + xh * h; w[j++] = l & 0xfffffff; @@ -131,15 +130,15 @@ BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1 << dbits) - 1); BigInteger.prototype.DV = (1 << dbits); -var BI_FP = 52; +const BI_FP = 52; BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions -var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; -var BI_RC = new Array(); -var rr, vv; +const BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; +const BI_RC = new Array(); +let rr, vv; rr = "0".charCodeAt(0); for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); @@ -152,14 +151,14 @@ function int2char(n) { } function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; + const c = BI_RC[s.charCodeAt(i)]; return (c == null) ? -1 : c; } // (protected) copy this to r function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; + for (let i = this.t - 1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } @@ -177,7 +176,7 @@ function bnpFromInt(x) { // return bigint initialized to value function nbv(i) { - var r = nbi(); + const r = nbi(); r.fromInt(i); return r; } @@ -185,7 +184,7 @@ function nbv(i) { // (protected) set from string and radix function bnpFromString(s, b) { - var k; + let k; if (b == 16) k = 4; else if (b == 8) k = 3; else if (b == 256) k = 8; // byte array @@ -198,23 +197,21 @@ function bnpFromString(s, b) { } this.t = 0; this.s = 0; - var i = s.length, + let i = s.length, mi = false, sh = 0; while (--i >= 0) { - var x = (k == 8) ? s[i] & 0xff : intAt(s, i); + const x = (k == 8) ? s[i] & 0xff : intAt(s, i); if (x < 0) { if (s.charAt(i) == "-") mi = true; continue; } mi = false; - if (sh == 0) - this[this.t++] = x; + if (sh == 0) this[this.t++] = x; else if (sh + k > this.DB) { this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; this[this.t++] = (x >> (this.DB - sh)); - } else - this[this.t - 1] |= x << sh; + } else this[this.t - 1] |= x << sh; sh += k; if (sh >= this.DB) sh -= this.DB; } @@ -229,7 +226,7 @@ function bnpFromString(s, b) { // (protected) clamp off excess high words function bnpClamp() { - var c = this.s & this.DM; + const c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c)--this.t; } @@ -237,18 +234,18 @@ function bnpClamp() { function bnToString(b) { if (this.s < 0) return "-" + this.negate().toString(b); - var k; + let k; if (b == 16) k = 4; else if (b == 8) k = 3; else if (b == 2) k = 1; else if (b == 32) k = 5; else if (b == 4) k = 2; else return this.toRadix(b); - var km = (1 << k) - 1, + let km = (1 << k) - 1, d, m = false, r = "", i = this.t; - var p = this.DB - (i * this.DB) % k; + let p = this.DB - (i * this.DB) % k; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { m = true; @@ -275,7 +272,7 @@ function bnToString(b) { // (public) -this function bnNegate() { - var r = nbi(); + const r = nbi(); BigInteger.ZERO.subTo(this, r); return r; } @@ -289,9 +286,9 @@ function bnAbs() { // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { - var r = this.s - a.s; + let r = this.s - a.s; if (r != 0) return r; - var i = this.t; + let i = this.t; r = i - a.t; if (r != 0) return (this.s < 0) ? -r : r; while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; @@ -301,7 +298,7 @@ function bnCompareTo(a) { // returns bit length of the integer x function nbits(x) { - var r = 1, + let r = 1, t; if ((t = x >>> 16) != 0) { x = t; @@ -336,7 +333,7 @@ function bnBitLength() { // (protected) r = this << n*DB function bnpDLShiftTo(n, r) { - var i; + let i; for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; for (i = n - 1; i >= 0; --i) r[i] = 0; r.t = this.t + n; @@ -346,7 +343,7 @@ function bnpDLShiftTo(n, r) { // (protected) r = this >> n*DB function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r[i - n] = this[i]; + for (let i = n; i < this.t; ++i) r[i - n] = this[i]; r.t = Math.max(this.t - n, 0); r.s = this.s; } @@ -354,10 +351,10 @@ function bnpDRShiftTo(n, r) { // (protected) r = this << n function bnpLShiftTo(n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), + const bs = n % this.DB; + const cbs = this.DB - bs; + const bm = (1 << cbs) - 1; + let ds = Math.floor(n / this.DB), c = (this.s << bs) & this.DM, i; for (i = this.t - 1; i >= 0; --i) { @@ -375,16 +372,16 @@ function bnpLShiftTo(n, r) { function bnpRShiftTo(n, r) { r.s = this.s; - var ds = Math.floor(n / this.DB); + const ds = Math.floor(n / this.DB); if (ds >= this.t) { r.t = 0; return; } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; + const bs = n % this.DB; + const cbs = this.DB - bs; + const bm = (1 << bs) - 1; r[0] = this[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { + for (let i = ds + 1; i < this.t; ++i) { r[i - ds - 1] |= (this[i] & bm) << cbs; r[i - ds] = this[i] >> bs; } @@ -396,7 +393,7 @@ function bnpRShiftTo(n, r) { // (protected) r = this - a function bnpSubTo(a, r) { - var i = 0, + let i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { @@ -432,9 +429,9 @@ function bnpSubTo(a, r) { // "this" should be the larger one if appropriate. function bnpMultiplyTo(a, r) { - var x = this.abs(), + let x = this.abs(), y = a.abs(); - var i = x.t; + let i = x.t; r.t = i + y.t; while (--i >= 0) r[i] = 0; for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); @@ -446,11 +443,11 @@ function bnpMultiplyTo(a, r) { // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2 * x.t; + const x = this.abs(); + let i = r.t = 2 * x.t; while (--i >= 0) r[i] = 0; for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1); + const c = x.am(i, x[i], r, 2 * i, 0, 1); if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { r[i + x.t] -= x.DV; r[i + x.t + 1] = 1; @@ -465,19 +462,19 @@ function bnpSquareTo(r) { // r != q, this != m. q or r may be null. function bnpDivRemTo(m, q, r) { - var pm = m.abs(); + const pm = m.abs(); if (pm.t <= 0) return; - var pt = this.abs(); + const pt = this.abs(); if (pt.t < pm.t) { if (q != null) q.fromInt(0); if (r != null) this.copyTo(r); return; } if (r == null) r = nbi(); - var y = nbi(), + let y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus + const nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); @@ -485,14 +482,14 @@ function bnpDivRemTo(m, q, r) { pm.copyTo(y); pt.copyTo(r); } - var ys = y.t; - var y0 = y[ys - 1]; + const ys = y.t; + const y0 = y[ys - 1]; if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, + const yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); + let d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; - var i = r.t, + let i = r.t, j = i - ys, t = (q == null) ? nbi() : q; y.dlShiftTo(j, t); @@ -505,7 +502,7 @@ function bnpDivRemTo(m, q, r) { while (y.t < ys) y[y.t++] = 0; while (--j >= 0) { // Estimate quotient digit - var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + let qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out y.dlShiftTo(j, t); r.subTo(t, r); @@ -525,7 +522,7 @@ function bnpDivRemTo(m, q, r) { // (public) this mod a function bnMod(a) { - var r = nbi(); + const r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); return r; @@ -579,9 +576,9 @@ Classic.prototype.sqrTo = cSqrTo; function bnpInvDigit() { if (this.t < 1) return 0; - var x = this[0]; + const x = this[0]; if ((x & 1) == 0) return 0; - var y = x & 3; // y == 1/x mod 2^2 + let y = x & 3; // y == 1/x mod 2^2 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 @@ -606,7 +603,7 @@ function Montgomery(m) { // xR mod m function montConvert(x) { - var r = nbi(); + const r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); @@ -616,7 +613,7 @@ function montConvert(x) { // x/R mod m function montRevert(x) { - var r = nbi(); + const r = nbi(); x.copyTo(r); this.reduce(r); return r; @@ -626,11 +623,11 @@ function montRevert(x) { function montReduce(x) { while (x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { + { x[x.t++] = 0; } + for (let i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff; - var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; + let j = x[i] & 0x7fff; + const u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; // use am to combine the multiply-shift-add into one call j = i + this.m.t; x[j] += this.m.am(0, u0, x, i, 0, this.m.t); @@ -675,7 +672,7 @@ function bnpIsEven() { function bnpExp(e, z) { if (e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), + let r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1; @@ -684,7 +681,7 @@ function bnpExp(e, z) { z.sqrTo(r, r2); if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); else { - var t = r; + const t = r; r = r2; r2 = t; } @@ -695,7 +692,7 @@ function bnpExp(e, z) { // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e, m) { - var z; + let z; if (e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e, z); @@ -733,23 +730,6 @@ BigInteger.ONE = nbv(1); BigInteger.TWO = nbv(2); - - - - - - - - - - - - - - - - - /* * Copyright (c) 2003-2005 Tom Wu (tjw@cs.Stanford.EDU) * All Rights Reserved. @@ -791,7 +771,7 @@ BigInteger.TWO = nbv(2); // (public) function bnClone() { - var r = nbi(); + const r = nbi(); this.copyTo(r); return r; } @@ -839,9 +819,9 @@ function bnSigNum() { function bnpToRadix(b) { if (b == null) b = 10; if (this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), + const cs = this.chunkSize(b); + const a = Math.pow(b, cs); + let d = nbv(a), y = nbi(), z = nbi(), r = ""; @@ -858,13 +838,13 @@ function bnpToRadix(b) { function bnpFromRadix(s, b) { this.fromInt(0); if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), + const cs = this.chunkSize(b); + let d = Math.pow(b, cs), mi = false, j = 0, w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); + for (let i = 0; i < s.length; ++i) { + const x = intAt(s, i); if (x < 0) { if (s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; @@ -887,13 +867,13 @@ function bnpFromRadix(s, b) { // (protected) alternate constructor function bnpFromNumber(a, b, c) { - if ("number" == typeof b) { + if (typeof b === "number") { // new BigInteger(int,int,RNG) if (a < 2) this.fromInt(1); else { this.fromNumber(a, c); if (!this.testBit(a - 1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + { this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); } if (this.isEven()) this.dAddOffset(1, 0); // force odd while (!this.isProbablePrime(b)) { this.dAddOffset(2, 0); @@ -902,7 +882,7 @@ function bnpFromNumber(a, b, c) { } } else { // new BigInteger(int,RNG) - var x = new Array(), + let x = new Array(), t = a & 7; x.length = (a >> 3) + 1; b.nextBytes(x); @@ -915,14 +895,13 @@ function bnpFromNumber(a, b, c) { // (public) convert to bigendian byte array function bnToByteArray() { - var i = this.t, + let i = this.t, r = new Array(); r[0] = this.s; - var p = this.DB - (i * this.DB) % 8, + let p = this.DB - (i * this.DB) % 8, d, k = 0; if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) - r[k++] = d | (this.s << (this.DB - p)); + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) r[k++] = d | (this.s << (this.DB - p)); while (i >= 0) { if (p < 8) { d = (this[i] & ((1 << p) - 1)) << (8 - p); @@ -957,7 +936,7 @@ function bnMax(a) { // (protected) r = this op a (bitwise) function bnpBitwiseTo(a, op, r) { - var i, f, m = Math.min(a.t, this.t); + let i, f, m = Math.min(a.t, this.t); for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); if (a.t < this.t) { f = a.s & this.DM; @@ -979,7 +958,7 @@ function op_and(x, y) { } function bnAnd(a) { - var r = nbi(); + const r = nbi(); this.bitwiseTo(a, op_and, r); return r; } @@ -991,7 +970,7 @@ function op_or(x, y) { } function bnOr(a) { - var r = nbi(); + const r = nbi(); this.bitwiseTo(a, op_or, r); return r; } @@ -1003,7 +982,7 @@ function op_xor(x, y) { } function bnXor(a) { - var r = nbi(); + const r = nbi(); this.bitwiseTo(a, op_xor, r); return r; } @@ -1015,7 +994,7 @@ function op_andnot(x, y) { } function bnAndNot(a) { - var r = nbi(); + const r = nbi(); this.bitwiseTo(a, op_andnot, r); return r; } @@ -1023,8 +1002,8 @@ function bnAndNot(a) { // (public) ~this function bnNot() { - var r = nbi(); - for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; + const r = nbi(); + for (let i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; r.t = this.t; r.s = ~this.s; return r; @@ -1033,7 +1012,7 @@ function bnNot() { // (public) this << n function bnShiftLeft(n) { - var r = nbi(); + const r = nbi(); if (n < 0) this.rShiftTo(-n, r); else this.lShiftTo(n, r); return r; @@ -1042,7 +1021,7 @@ function bnShiftLeft(n) { // (public) this >> n function bnShiftRight(n) { - var r = nbi(); + const r = nbi(); if (n < 0) this.lShiftTo(-n, r); else this.rShiftTo(n, r); return r; @@ -1052,7 +1031,7 @@ function bnShiftRight(n) { function lbit(x) { if (x == 0) return -1; - var r = 0; + let r = 0; if ((x & 0xffff) == 0) { x >>= 16; r += 16; @@ -1076,8 +1055,7 @@ function lbit(x) { // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this[i] != 0) return i * this.DB + lbit(this[i]); + for (let i = 0; i < this.t; ++i) if (this[i] != 0) return i * this.DB + lbit(this[i]); if (this.s < 0) return this.t * this.DB; return -1; } @@ -1085,7 +1063,7 @@ function bnGetLowestSetBit() { // return number of 1 bits in x function cbit(x) { - var r = 0; + let r = 0; while (x != 0) { x &= x - 1; ++r; @@ -1096,16 +1074,16 @@ function cbit(x) { // (public) return number of set bits function bnBitCount() { - var r = 0, + let r = 0, x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); + for (let i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { - var j = Math.floor(n / this.DB); + const j = Math.floor(n / this.DB); if (j >= this.t) return (this.s != 0); return ((this[j] & (1 << (n % this.DB))) != 0); } @@ -1113,7 +1091,7 @@ function bnTestBit(n) { // (protected) this op (1<= 0 r.t = i; while (i > 0) r[--i] = 0; - var j; + let j; for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); r.clamp(); @@ -1295,11 +1273,10 @@ function bnpMultiplyLowerTo(a, n, r) { function bnpMultiplyUpperTo(a, n, r) { --n; - var i = r.t = this.t + a.t - n; + let i = r.t = this.t + a.t - n; r.s = 0; // assumes a,this >= 0 while (--i >= 0) r[i] = 0; - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + for (i = Math.max(n - this.t, 0); i < a.t; ++i) r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); r.clamp(); r.drShiftTo(1, r); } @@ -1319,7 +1296,7 @@ function barrettConvert(x) { if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); else if (x.compareTo(this.m) < 0) return x; else { - var r = nbi(); + const r = nbi(); x.copyTo(r); this.reduce(r); return r; @@ -1368,7 +1345,7 @@ Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e, m) { - var i = e.bitLength(), + let i = e.bitLength(), k, r = nbv(1), z; if (i <= 0) return r; @@ -1377,21 +1354,18 @@ function bnModPow(e, m) { else if (i < 144) k = 4; else if (i < 768) k = 5; else k = 6; - if (i < 8) - z = new Classic(m); - else if (m.isEven()) - z = new Barrett(m); - else - z = new Montgomery(m); + if (i < 8) z = new Classic(m); + else if (m.isEven()) z = new Barrett(m); + else z = new Montgomery(m); // precomputation - var g = new Array(), + let g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { - var g2 = nbi(); + const g2 = nbi(); z.sqrTo(g[1], g2); while (n <= km) { g[n] = nbi(); @@ -1400,7 +1374,7 @@ function bnModPow(e, m) { } } - var j = e.t - 1, + let j = e.t - 1, w, is1 = true, r2 = nbi(), t; @@ -1456,14 +1430,14 @@ function bnModPow(e, m) { // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { - var x = (this.s < 0) ? this.negate() : this.clone(); - var y = (a.s < 0) ? a.negate() : a.clone(); + let x = (this.s < 0) ? this.negate() : this.clone(); + let y = (a.s < 0) ? a.negate() : a.clone(); if (x.compareTo(y) < 0) { - var t = x; + const t = x; x = y; y = t; } - var i = x.getLowestSetBit(), + let i = x.getLowestSetBit(), g = y.getLowestSetBit(); if (g < 0) return x; if (i < g) g = i; @@ -1490,22 +1464,21 @@ function bnGCD(a) { function bnpModInt(n) { if (n <= 0) return 0; - var d = this.DV % n, + let d = this.DV % n, r = (this.s < 0) ? n - 1 : 0; - if (this.t > 0) - if (d == 0) r = this[0] % n; - else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; + if (this.t > 0) { if (d == 0) r = this[0] % n; + else for (let i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; } return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { - var ac = m.isEven(); + const ac = m.isEven(); if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), + let u = m.clone(), v = this.clone(); - var a = nbv(1), + let a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); @@ -1550,30 +1523,28 @@ function bnModInverse(m) { else return d; } -var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, +const lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, - 977, 983, 991, 997 -]; -var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + 977, 983, 991, 997]; +const lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { - var i, x = this.abs(); + let i, x = this.abs(); if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x[0] == lowprimes[i]) return true; + for (i = 0; i < lowprimes.length; ++i) if (x[0] == lowprimes[i]) return true; return false; } if (x.isEven()) return false; i = 1; while (i < lowprimes.length) { - var m = lowprimes[i], + let m = lowprimes[i], j = i + 1; while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); @@ -1585,7 +1556,7 @@ function bnIsProbablePrime(t) { /* added by Recurity Labs */ function nbits(x) { - var n = 1, + let n = 1, t; if ((t = x >>> 16) != 0) { x = t; @@ -1611,9 +1582,9 @@ function nbits(x) { } function bnToMPI() { - var ba = this.toByteArray(); - var size = (ba.length - 1) * 8 + nbits(ba[0]); - var result = ""; + const ba = this.toByteArray(); + const size = (ba.length - 1) * 8 + nbits(ba[0]); + let result = ""; result += String.fromCharCode((size & 0xFF00) >> 8); result += String.fromCharCode(size & 0xFF); result += util.bin2str(ba); @@ -1623,15 +1594,15 @@ function bnToMPI() { // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); + const n1 = this.subtract(BigInteger.ONE); + const k = n1.getLowestSetBit(); if (k <= 0) return false; - var r = n1.shiftRight(k); + const r = n1.shiftRight(k); t = (t + 1) >> 1; if (t > lowprimes.length) t = lowprimes.length; - var a = nbi(); + const a = nbi(); var j, bases = []; - for (var i = 0; i < t; ++i) { + for (let i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 for (;;) { j = lowprimes[Math.floor(Math.random() * lowprimes.length)]; @@ -1639,7 +1610,7 @@ function bnpMillerRabin(t) { } bases.push(j); a.fromInt(j); - var y = a.modPow(r, this); + let y = a.modPow(r, this); if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while (j++ < k && y.compareTo(n1) != 0) { diff --git a/src/crypto/public_key/rsa.js b/src/crypto/public_key/rsa.js index 477530d9..f479ee3a 100644 --- a/src/crypto/public_key/rsa.js +++ b/src/crypto/public_key/rsa.js @@ -31,15 +31,15 @@ import config from '../../config'; function SecureRandom() { function nextBytes(byteArray) { - for (var n = 0; n < byteArray.length; n++) { + for (let n = 0; n < byteArray.length; n++) { byteArray[n] = random.getSecureRandomOctet(); } } this.nextBytes = nextBytes; } -var blinder = BigInteger.ZERO; -var unblinder = BigInteger.ZERO; +let blinder = BigInteger.ZERO; +let unblinder = BigInteger.ZERO; function blind(m, n, e) { if (unblinder.bitLength() === n.bitLength()) { @@ -78,11 +78,11 @@ export default function RSA() { if (config.rsa_blinding) { m = blind(m, n, e); } - var xp = m.mod(p).modPow(d.mod(p.subtract(BigInteger.ONE)), p); - var xq = m.mod(q).modPow(d.mod(q.subtract(BigInteger.ONE)), q); + const xp = m.mod(p).modPow(d.mod(p.subtract(BigInteger.ONE)), p); + const xq = m.mod(q).modPow(d.mod(q.subtract(BigInteger.ONE)), q); util.print_debug("rsa.js decrypt\nxpn:" + util.hexstrdump(xp.toMPI()) + "\nxqn:" + util.hexstrdump(xq.toMPI())); - var t = xq.subtract(xp); + let t = xq.subtract(xp); if (t[0] === 0) { t = xp.subtract(xq); t = t.multiply(u).mod(q); @@ -134,18 +134,18 @@ export default function RSA() { // Generate a new random private key B bits long, using public expt E function generate(B, E) { - var webCrypto = util.getWebCryptoAll(); + const webCrypto = util.getWebCryptoAll(); // // Native RSA keygen using Web Crypto // if (webCrypto) { - var Euint32 = new Uint32Array([parseInt(E, 16)]); // get integer of exponent - var Euint8 = new Uint8Array(Euint32.buffer); // get bytes of exponent - var keyGenOpt; + const Euint32 = new Uint32Array([parseInt(E, 16)]); // get integer of exponent + const Euint8 = new Uint8Array(Euint32.buffer); // get bytes of exponent + let keyGenOpt; - var keys; + let keys; if (window.crypto && window.crypto.webkitSubtle) { // outdated spec implemented by Webkit keyGenOpt = { @@ -157,8 +157,7 @@ export default function RSA() { } }; keys = webCrypto.generateKey(keyGenOpt, true, ['encrypt', 'decrypt']); - } - else { + } else { // current standard spec keyGenOpt = { name: 'RSASSA-PKCS1-v1_5', @@ -187,7 +186,7 @@ export default function RSA() { function exportKey(keypair) { // export the generated keys as JsonWebKey (JWK) // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 - var key = webCrypto.exportKey('jwk', keypair.privateKey); + let key = webCrypto.exportKey('jwk', keypair.privateKey); if (typeof key.then !== 'function') { // IE11 KeyOperation key = util.promisifyIE11Op(key, 'Error exporting RSA key pair.'); } @@ -196,7 +195,7 @@ export default function RSA() { function decodeKey(jwk) { // map JWK parameters to local BigInteger type system - var key = new KeyObject(); + const key = new KeyObject(); key.n = toBigInteger(jwk.n); key.ee = new BigInteger(E, 16); key.d = toBigInteger(jwk.d); @@ -205,8 +204,8 @@ export default function RSA() { key.u = key.p.modInverse(key.q); function toBigInteger(base64url) { - var base64 = base64url.replace(/\-/g, '+').replace(/_/g, '/'); - var hex = util.hexstrdump(atob(base64)); + const base64 = base64url.replace(/\-/g, '+').replace(/_/g, '/'); + const hex = util.hexstrdump(atob(base64)); return new BigInteger(hex, 16); } @@ -218,9 +217,9 @@ export default function RSA() { // return new Promise(function(resolve) { - var key = new KeyObject(); - var rng = new SecureRandom(); - var qs = B >> 1; + const key = new KeyObject(); + const rng = new SecureRandom(); + const qs = B >> 1; key.e = parseInt(E, 16); key.ee = new BigInteger(E, 16); @@ -238,13 +237,13 @@ export default function RSA() { } } if (key.p.compareTo(key.q) <= 0) { - var t = key.p; + const t = key.p; key.p = key.q; key.q = t; } - var p1 = key.p.subtract(BigInteger.ONE); - var q1 = key.q.subtract(BigInteger.ONE); - var phi = p1.multiply(q1); + const p1 = key.p.subtract(BigInteger.ONE); + const q1 = key.q.subtract(BigInteger.ONE); + const phi = p1.multiply(q1); if (phi.gcd(key.ee).compareTo(BigInteger.ONE) === 0) { key.n = key.p.multiply(key.q); key.d = key.ee.modInverse(phi); diff --git a/src/crypto/random.js b/src/crypto/random.js index 04166dea..55a4c8a3 100644 --- a/src/crypto/random.js +++ b/src/crypto/random.js @@ -35,8 +35,8 @@ export default { * @return {Uint8Array} Random byte array */ getRandomBytes: function(length) { - var result = new Uint8Array(length); - for (var i = 0; i < length; i++) { + const result = new Uint8Array(length); + for (let i = 0; i < length; i++) { result[i] = this.getSecureRandomOctet(); } return result; @@ -49,23 +49,23 @@ export default { * @return {Integer} A secure random number */ getSecureRandom: function(from, to) { - var randUint = this.getSecureRandomUint(); - var bits = ((to - from)).toString(2).length; - while ((randUint & (Math.pow(2, bits) - 1)) > (to - from)) { + let randUint = this.getSecureRandomUint(); + const bits = ((to - from)).toString(2).length; + while ((randUint & ((2 ** bits) - 1)) > (to - from)) { randUint = this.getSecureRandomUint(); } - return from + (Math.abs(randUint & (Math.pow(2, bits) - 1))); + return from + (Math.abs(randUint & ((2 ** bits) - 1))); }, getSecureRandomOctet: function() { - var buf = new Uint8Array(1); + const buf = new Uint8Array(1); this.getRandomValues(buf); return buf[0]; }, getSecureRandomUint: function() { - var buf = new Uint8Array(4); - var dv = new DataView(buf.buffer); + const buf = new Uint8Array(4); + const dv = new DataView(buf.buffer); this.getRandomValues(buf); return dv.getUint32(0); }, @@ -83,7 +83,7 @@ export default { } else if (typeof window !== 'undefined' && typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') { window.msCrypto.getRandomValues(buf); } else if (nodeCrypto) { - var bytes = nodeCrypto.randomBytes(buf.length); + const bytes = nodeCrypto.randomBytes(buf.length); buf.set(bytes); } else if (this.randomBuffer.buffer) { this.randomBuffer.get(buf); @@ -102,17 +102,15 @@ export default { if (bits < 1) { throw new Error('Illegal parameter value: bits < 1'); } - var numBytes = Math.floor((bits + 7) / 8); + const numBytes = Math.floor((bits + 7) / 8); - var randomBits = util.Uint8Array2str(this.getRandomBytes(numBytes)); + let randomBits = util.Uint8Array2str(this.getRandomBytes(numBytes)); if (bits % 8 > 0) { - - randomBits = String.fromCharCode( - (Math.pow(2, bits % 8) - 1) & + randomBits = String.fromCharCode(((2 ** (bits % 8)) - 1) & randomBits.charCodeAt(0)) + randomBits.substring(1); } - var mpi = new type_mpi(randomBits); + const mpi = new type_mpi(randomBits); return mpi.toBigInteger(); }, @@ -121,8 +119,8 @@ export default { throw new Error('Illegal parameter value: max <= min'); } - var range = max.subtract(min); - var r = this.getRandomBigInteger(range.bitLength()); + const range = max.subtract(min); + let r = this.getRandomBigInteger(range.bitLength()); while (r.compareTo(range) > 0) { r = this.getRandomBigInteger(range.bitLength()); } @@ -161,7 +159,7 @@ RandomBuffer.prototype.set = function(buf) { if (!(buf instanceof Uint8Array)) { throw new Error('Invalid type: buf not an Uint8Array'); } - var freeSpace = this.buffer.length - this.size; + const freeSpace = this.buffer.length - this.size; if (buf.length > freeSpace) { buf = buf.subarray(0, freeSpace); } @@ -184,7 +182,7 @@ RandomBuffer.prototype.get = function(buf) { if (this.size < buf.length) { throw new Error('Random number buffer depleted'); } - for (var i = 0; i < buf.length; i++) { + for (let i = 0; i < buf.length; i++) { buf[i] = this.buffer[--this.size]; // clear buffer value this.buffer[this.size] = 0; diff --git a/src/crypto/signature.js b/src/crypto/signature.js index 96e86623..be045470 100644 --- a/src/crypto/signature.js +++ b/src/crypto/signature.js @@ -20,11 +20,11 @@ export default { * @return {Boolean} true if signature (sig_data was equal to data over hash) */ verify: async function(algo, hash_algo, msg_MPIs, publickey_MPIs, data) { - var m; - var r; - var s; - var Q; - var curve; + let m; + let r; + let s; + let Q; + let curve; data = util.Uint8Array2str(data); @@ -33,49 +33,54 @@ export default { // RSA (Encrypt or Sign) [HAC] case 2: // RSA Encrypt-Only [HAC] - case 3: + case 3: { // RSA Sign-Only [HAC] - var rsa = new publicKey.rsa(); - var n = publickey_MPIs[0].toBigInteger(); - var k = publickey_MPIs[0].byteLength(); - var e = publickey_MPIs[1].toBigInteger(); + const rsa = new publicKey.rsa(); + const n = publickey_MPIs[0].toBigInteger(); + const k = publickey_MPIs[0].byteLength(); + const e = publickey_MPIs[1].toBigInteger(); m = msg_MPIs[0].toBigInteger(); - var EM = rsa.verify(m, e, n); - var EM2 = pkcs1.emsa.encode(hash_algo, data, k); + const EM = rsa.verify(m, e, n); + const EM2 = pkcs1.emsa.encode(hash_algo, data, k); return EM.compareTo(EM2) === 0; - case 16: + } + case 16: { // Elgamal (Encrypt-Only) [ELGAMAL] [HAC] throw new Error("signing with Elgamal is not defined in the OpenPGP standard."); - case 17: + } + case 17: { // DSA (Digital Signature Algorithm) [FIPS186] [HAC] - var dsa = new publicKey.dsa(); - var s1 = msg_MPIs[0].toBigInteger(); - var s2 = msg_MPIs[1].toBigInteger(); - var p = publickey_MPIs[0].toBigInteger(); - var q = publickey_MPIs[1].toBigInteger(); - var g = publickey_MPIs[2].toBigInteger(); - var y = publickey_MPIs[3].toBigInteger(); + const dsa = new publicKey.dsa(); + const s1 = msg_MPIs[0].toBigInteger(); + const s2 = msg_MPIs[1].toBigInteger(); + const p = publickey_MPIs[0].toBigInteger(); + const q = publickey_MPIs[1].toBigInteger(); + const g = publickey_MPIs[2].toBigInteger(); + const y = publickey_MPIs[3].toBigInteger(); m = data; - var dopublic = dsa.verify(hash_algo, s1, s2, m, p, q, g, y); + const dopublic = dsa.verify(hash_algo, s1, s2, m, p, q, g, y); return dopublic.compareTo(s1) === 0; - case 19: + } + case 19: { // ECDSA - var ecdsa = publicKey.elliptic.ecdsa; - curve = publickey_MPIs[0]; + const { ecdsa } = publicKey.elliptic; + [curve] = publickey_MPIs; r = msg_MPIs[0].toBigInteger(); s = msg_MPIs[1].toBigInteger(); m = data; Q = publickey_MPIs[1].toBigInteger(); - return ecdsa.verify(curve.oid, hash_algo, {r: r, s: s}, m, Q); - case 22: + return ecdsa.verify(curve.oid, hash_algo, { r: r, s: s }, m, Q); + } + case 22: { // EdDSA - var eddsa = publicKey.elliptic.eddsa; - curve = publickey_MPIs[0]; + const { eddsa } = publicKey.elliptic; + [curve] = publickey_MPIs; r = msg_MPIs[0].toBigInteger(); s = msg_MPIs[1].toBigInteger(); m = data; Q = publickey_MPIs[1].toBigInteger(); return eddsa.verify(curve.oid, hash_algo, { R: r, S: s }, m, Q); + } default: throw new Error('Invalid signature algorithm.'); } @@ -90,55 +95,58 @@ export default { * @return {Array} */ sign: async function(hash_algo, algo, keyIntegers, data) { - data = util.Uint8Array2str(data); - var m; - var d; - var curve; - var signature; + let m; + let d; + let curve; + let signature; switch (algo) { case 1: // RSA (Encrypt or Sign) [HAC] case 2: // RSA Encrypt-Only [HAC] - case 3: + case 3: { // RSA Sign-Only [HAC] - var rsa = new publicKey.rsa(); + const rsa = new publicKey.rsa(); d = keyIntegers[2].toBigInteger(); - var n = keyIntegers[0].toBigInteger(); - m = pkcs1.emsa.encode(hash_algo, - data, keyIntegers[0].byteLength()); + const n = keyIntegers[0].toBigInteger(); + m = pkcs1.emsa.encode( + hash_algo, + data, keyIntegers[0].byteLength() + ); return util.str2Uint8Array(rsa.sign(m, d, n).toMPI()); - - case 17: + } + case 17: { // DSA (Digital Signature Algorithm) [FIPS186] [HAC] - var dsa = new publicKey.dsa(); + const dsa = new publicKey.dsa(); - var p = keyIntegers[0].toBigInteger(); - var q = keyIntegers[1].toBigInteger(); - var g = keyIntegers[2].toBigInteger(); - var x = keyIntegers[4].toBigInteger(); + const p = keyIntegers[0].toBigInteger(); + const q = keyIntegers[1].toBigInteger(); + const g = keyIntegers[2].toBigInteger(); + const x = keyIntegers[4].toBigInteger(); m = data; - var result = dsa.sign(hash_algo, m, g, p, q, x); + const result = dsa.sign(hash_algo, m, g, p, q, x); return util.str2Uint8Array(result[0].toString() + result[1].toString()); - case 16: + } + case 16: { // Elgamal (Encrypt-Only) [ELGAMAL] [HAC] throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); - - case 19: + } + case 19: { // ECDSA - var ecdsa = publicKey.elliptic.ecdsa; - curve = keyIntegers[0]; + const { ecdsa } = publicKey.elliptic; + [curve] = keyIntegers; d = keyIntegers[2].toBigInteger(); m = data; signature = await ecdsa.sign(curve.oid, hash_algo, m, d); return util.str2Uint8Array(signature.r.toMPI() + signature.s.toMPI()); - case 22: + } + case 22: { // EdDSA - var eddsa = publicKey.elliptic.eddsa; - curve = keyIntegers[0]; + const { eddsa } = publicKey.elliptic; + [curve] = keyIntegers; d = keyIntegers[2].toBigInteger(); m = data; signature = await eddsa.sign(curve.oid, hash_algo, m, d); @@ -146,7 +154,7 @@ export default { util.Uint8Array2MPI(signature.R.toArrayLike(Uint8Array, 'le', 32)), util.Uint8Array2MPI(signature.S.toArrayLike(Uint8Array, 'le', 32)) )); - + } default: throw new Error('Invalid signature algorithm.'); } diff --git a/src/encoding/armor.js b/src/encoding/armor.js index eda28d86..5abdb096 100644 --- a/src/encoding/armor.js +++ b/src/encoding/armor.js @@ -39,9 +39,9 @@ import config from '../config'; * 6 = SIGNATURE */ function getType(text) { - var reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$\n/m; + const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$\n/m; - var header = text.match(reHeader); + const header = text.match(reHeader); if (!header) { throw new Error('Unknown ASCII armor type'); @@ -59,30 +59,25 @@ function getType(text) { // Header to be used. if (/MESSAGE, PART \d+/.test(header[1])) { return enums.armor.multipart_last; - } else // BEGIN PGP SIGNED MESSAGE if (/SIGNED MESSAGE/.test(header[1])) { return enums.armor.signed; - } else // BEGIN PGP MESSAGE // Used for signed, encrypted, or compressed files. if (/MESSAGE/.test(header[1])) { return enums.armor.message; - } else // BEGIN PGP PUBLIC KEY BLOCK // Used for armoring public keys. if (/PUBLIC KEY BLOCK/.test(header[1])) { return enums.armor.public_key; - } else // BEGIN PGP PRIVATE KEY BLOCK // Used for armoring private keys. if (/PRIVATE KEY BLOCK/.test(header[1])) { return enums.armor.private_key; - } else // BEGIN PGP SIGNATURE // Used for detached signatures, OpenPGP/MIME signatures, and @@ -101,7 +96,7 @@ function getType(text) { * @returns {String} The header information */ function addheader() { - var result = ""; + let result = ""; if (config.show_version) { result += "Version: " + config.versionstring + '\r\n'; } @@ -119,8 +114,8 @@ function addheader() { * @return {String} Base64 encoded checksum */ function getCheckSum(data) { - var c = createcrc24(data); - var bytes = new Uint8Array([c >> 16, (c >> 8) & 0xFF, c & 0xFF]); + const c = createcrc24(data); + const bytes = new Uint8Array([c >> 16, (c >> 8) & 0xFF, c & 0xFF]); return base64.encode(bytes); } @@ -132,8 +127,8 @@ function getCheckSum(data) { * @return {Boolean} True if the given checksum is correct; otherwise false */ function verifyCheckSum(data, checksum) { - var c = getCheckSum(data); - var d = checksum; + const c = getCheckSum(data); + const d = checksum; return c[0] === d[0] && c[1] === d[1] && c[2] === d[2] && c[3] === d[3]; } /** @@ -141,45 +136,45 @@ function verifyCheckSum(data, checksum) { * @param {String} data Data to create a CRC-24 checksum for * @return {Integer} The CRC-24 checksum as number */ -var crc_table = [ - 0x00000000, 0x00864cfb, 0x018ad50d, 0x010c99f6, 0x0393e6e1, 0x0315aa1a, 0x021933ec, 0x029f7f17, 0x07a18139, - 0x0727cdc2, 0x062b5434, 0x06ad18cf, 0x043267d8, 0x04b42b23, 0x05b8b2d5, 0x053efe2e, 0x0fc54e89, 0x0f430272, - 0x0e4f9b84, 0x0ec9d77f, 0x0c56a868, 0x0cd0e493, 0x0ddc7d65, 0x0d5a319e, 0x0864cfb0, 0x08e2834b, 0x09ee1abd, - 0x09685646, 0x0bf72951, 0x0b7165aa, 0x0a7dfc5c, 0x0afbb0a7, 0x1f0cd1e9, 0x1f8a9d12, 0x1e8604e4, 0x1e00481f, - 0x1c9f3708, 0x1c197bf3, 0x1d15e205, 0x1d93aefe, 0x18ad50d0, 0x182b1c2b, 0x192785dd, 0x19a1c926, 0x1b3eb631, - 0x1bb8faca, 0x1ab4633c, 0x1a322fc7, 0x10c99f60, 0x104fd39b, 0x11434a6d, 0x11c50696, 0x135a7981, 0x13dc357a, - 0x12d0ac8c, 0x1256e077, 0x17681e59, 0x17ee52a2, 0x16e2cb54, 0x166487af, 0x14fbf8b8, 0x147db443, 0x15712db5, - 0x15f7614e, 0x3e19a3d2, 0x3e9fef29, 0x3f9376df, 0x3f153a24, 0x3d8a4533, 0x3d0c09c8, 0x3c00903e, 0x3c86dcc5, - 0x39b822eb, 0x393e6e10, 0x3832f7e6, 0x38b4bb1d, 0x3a2bc40a, 0x3aad88f1, 0x3ba11107, 0x3b275dfc, 0x31dced5b, - 0x315aa1a0, - 0x30563856, 0x30d074ad, 0x324f0bba, 0x32c94741, 0x33c5deb7, 0x3343924c, 0x367d6c62, 0x36fb2099, 0x37f7b96f, - 0x3771f594, 0x35ee8a83, 0x3568c678, 0x34645f8e, 0x34e21375, 0x2115723b, 0x21933ec0, 0x209fa736, 0x2019ebcd, - 0x228694da, 0x2200d821, 0x230c41d7, 0x238a0d2c, 0x26b4f302, 0x2632bff9, 0x273e260f, 0x27b86af4, 0x252715e3, - 0x25a15918, 0x24adc0ee, 0x242b8c15, 0x2ed03cb2, 0x2e567049, 0x2f5ae9bf, 0x2fdca544, 0x2d43da53, 0x2dc596a8, - 0x2cc90f5e, 0x2c4f43a5, 0x2971bd8b, 0x29f7f170, 0x28fb6886, 0x287d247d, 0x2ae25b6a, 0x2a641791, 0x2b688e67, - 0x2beec29c, 0x7c3347a4, 0x7cb50b5f, 0x7db992a9, 0x7d3fde52, 0x7fa0a145, 0x7f26edbe, 0x7e2a7448, 0x7eac38b3, - 0x7b92c69d, 0x7b148a66, 0x7a181390, 0x7a9e5f6b, 0x7801207c, 0x78876c87, 0x798bf571, 0x790db98a, 0x73f6092d, - 0x737045d6, 0x727cdc20, 0x72fa90db, 0x7065efcc, 0x70e3a337, 0x71ef3ac1, 0x7169763a, 0x74578814, 0x74d1c4ef, - 0x75dd5d19, 0x755b11e2, 0x77c46ef5, 0x7742220e, 0x764ebbf8, 0x76c8f703, 0x633f964d, 0x63b9dab6, 0x62b54340, - 0x62330fbb, - 0x60ac70ac, 0x602a3c57, 0x6126a5a1, 0x61a0e95a, 0x649e1774, 0x64185b8f, 0x6514c279, 0x65928e82, 0x670df195, - 0x678bbd6e, 0x66872498, 0x66016863, 0x6cfad8c4, 0x6c7c943f, 0x6d700dc9, 0x6df64132, 0x6f693e25, 0x6fef72de, - 0x6ee3eb28, 0x6e65a7d3, 0x6b5b59fd, 0x6bdd1506, 0x6ad18cf0, 0x6a57c00b, 0x68c8bf1c, 0x684ef3e7, 0x69426a11, - 0x69c426ea, 0x422ae476, 0x42aca88d, 0x43a0317b, 0x43267d80, 0x41b90297, 0x413f4e6c, 0x4033d79a, 0x40b59b61, - 0x458b654f, 0x450d29b4, 0x4401b042, 0x4487fcb9, 0x461883ae, 0x469ecf55, 0x479256a3, 0x47141a58, 0x4defaaff, - 0x4d69e604, 0x4c657ff2, 0x4ce33309, 0x4e7c4c1e, 0x4efa00e5, 0x4ff69913, 0x4f70d5e8, 0x4a4e2bc6, 0x4ac8673d, - 0x4bc4fecb, 0x4b42b230, 0x49ddcd27, 0x495b81dc, 0x4857182a, 0x48d154d1, 0x5d26359f, 0x5da07964, 0x5cace092, - 0x5c2aac69, 0x5eb5d37e, 0x5e339f85, 0x5f3f0673, 0x5fb94a88, 0x5a87b4a6, 0x5a01f85d, 0x5b0d61ab, 0x5b8b2d50, - 0x59145247, 0x59921ebc, 0x589e874a, 0x5818cbb1, 0x52e37b16, 0x526537ed, 0x5369ae1b, 0x53efe2e0, 0x51709df7, - 0x51f6d10c, - 0x50fa48fa, 0x507c0401, 0x5542fa2f, 0x55c4b6d4, 0x54c82f22, 0x544e63d9, 0x56d11cce, 0x56575035, 0x575bc9c3, - 0x57dd8538 +const crc_table = [ + 0x00000000, 0x00864cfb, 0x018ad50d, 0x010c99f6, 0x0393e6e1, 0x0315aa1a, 0x021933ec, 0x029f7f17, 0x07a18139, + 0x0727cdc2, 0x062b5434, 0x06ad18cf, 0x043267d8, 0x04b42b23, 0x05b8b2d5, 0x053efe2e, 0x0fc54e89, 0x0f430272, + 0x0e4f9b84, 0x0ec9d77f, 0x0c56a868, 0x0cd0e493, 0x0ddc7d65, 0x0d5a319e, 0x0864cfb0, 0x08e2834b, 0x09ee1abd, + 0x09685646, 0x0bf72951, 0x0b7165aa, 0x0a7dfc5c, 0x0afbb0a7, 0x1f0cd1e9, 0x1f8a9d12, 0x1e8604e4, 0x1e00481f, + 0x1c9f3708, 0x1c197bf3, 0x1d15e205, 0x1d93aefe, 0x18ad50d0, 0x182b1c2b, 0x192785dd, 0x19a1c926, 0x1b3eb631, + 0x1bb8faca, 0x1ab4633c, 0x1a322fc7, 0x10c99f60, 0x104fd39b, 0x11434a6d, 0x11c50696, 0x135a7981, 0x13dc357a, + 0x12d0ac8c, 0x1256e077, 0x17681e59, 0x17ee52a2, 0x16e2cb54, 0x166487af, 0x14fbf8b8, 0x147db443, 0x15712db5, + 0x15f7614e, 0x3e19a3d2, 0x3e9fef29, 0x3f9376df, 0x3f153a24, 0x3d8a4533, 0x3d0c09c8, 0x3c00903e, 0x3c86dcc5, + 0x39b822eb, 0x393e6e10, 0x3832f7e6, 0x38b4bb1d, 0x3a2bc40a, 0x3aad88f1, 0x3ba11107, 0x3b275dfc, 0x31dced5b, + 0x315aa1a0, + 0x30563856, 0x30d074ad, 0x324f0bba, 0x32c94741, 0x33c5deb7, 0x3343924c, 0x367d6c62, 0x36fb2099, 0x37f7b96f, + 0x3771f594, 0x35ee8a83, 0x3568c678, 0x34645f8e, 0x34e21375, 0x2115723b, 0x21933ec0, 0x209fa736, 0x2019ebcd, + 0x228694da, 0x2200d821, 0x230c41d7, 0x238a0d2c, 0x26b4f302, 0x2632bff9, 0x273e260f, 0x27b86af4, 0x252715e3, + 0x25a15918, 0x24adc0ee, 0x242b8c15, 0x2ed03cb2, 0x2e567049, 0x2f5ae9bf, 0x2fdca544, 0x2d43da53, 0x2dc596a8, + 0x2cc90f5e, 0x2c4f43a5, 0x2971bd8b, 0x29f7f170, 0x28fb6886, 0x287d247d, 0x2ae25b6a, 0x2a641791, 0x2b688e67, + 0x2beec29c, 0x7c3347a4, 0x7cb50b5f, 0x7db992a9, 0x7d3fde52, 0x7fa0a145, 0x7f26edbe, 0x7e2a7448, 0x7eac38b3, + 0x7b92c69d, 0x7b148a66, 0x7a181390, 0x7a9e5f6b, 0x7801207c, 0x78876c87, 0x798bf571, 0x790db98a, 0x73f6092d, + 0x737045d6, 0x727cdc20, 0x72fa90db, 0x7065efcc, 0x70e3a337, 0x71ef3ac1, 0x7169763a, 0x74578814, 0x74d1c4ef, + 0x75dd5d19, 0x755b11e2, 0x77c46ef5, 0x7742220e, 0x764ebbf8, 0x76c8f703, 0x633f964d, 0x63b9dab6, 0x62b54340, + 0x62330fbb, + 0x60ac70ac, 0x602a3c57, 0x6126a5a1, 0x61a0e95a, 0x649e1774, 0x64185b8f, 0x6514c279, 0x65928e82, 0x670df195, + 0x678bbd6e, 0x66872498, 0x66016863, 0x6cfad8c4, 0x6c7c943f, 0x6d700dc9, 0x6df64132, 0x6f693e25, 0x6fef72de, + 0x6ee3eb28, 0x6e65a7d3, 0x6b5b59fd, 0x6bdd1506, 0x6ad18cf0, 0x6a57c00b, 0x68c8bf1c, 0x684ef3e7, 0x69426a11, + 0x69c426ea, 0x422ae476, 0x42aca88d, 0x43a0317b, 0x43267d80, 0x41b90297, 0x413f4e6c, 0x4033d79a, 0x40b59b61, + 0x458b654f, 0x450d29b4, 0x4401b042, 0x4487fcb9, 0x461883ae, 0x469ecf55, 0x479256a3, 0x47141a58, 0x4defaaff, + 0x4d69e604, 0x4c657ff2, 0x4ce33309, 0x4e7c4c1e, 0x4efa00e5, 0x4ff69913, 0x4f70d5e8, 0x4a4e2bc6, 0x4ac8673d, + 0x4bc4fecb, 0x4b42b230, 0x49ddcd27, 0x495b81dc, 0x4857182a, 0x48d154d1, 0x5d26359f, 0x5da07964, 0x5cace092, + 0x5c2aac69, 0x5eb5d37e, 0x5e339f85, 0x5f3f0673, 0x5fb94a88, 0x5a87b4a6, 0x5a01f85d, 0x5b0d61ab, 0x5b8b2d50, + 0x59145247, 0x59921ebc, 0x589e874a, 0x5818cbb1, 0x52e37b16, 0x526537ed, 0x5369ae1b, 0x53efe2e0, 0x51709df7, + 0x51f6d10c, + 0x50fa48fa, 0x507c0401, 0x5542fa2f, 0x55c4b6d4, 0x54c82f22, 0x544e63d9, 0x56d11cce, 0x56575035, 0x575bc9c3, + 0x57dd8538 ]; function createcrc24(input) { - var crc = 0xB704CE; + let crc = 0xB704CE; - for (var index = 0; index < input.length; index++) { + for (let index = 0; index < input.length; index++) { crc = (crc << 8) ^ crc_table[((crc >> 16) ^ input[index]) & 0xff]; } return crc & 0xffffff; @@ -193,11 +188,11 @@ function createcrc24(input) { */ function splitHeaders(text) { // empty line with whitespace characters - var reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*\n/m; - var headers = ''; - var body = text; + const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*\n/m; + let headers = ''; + let body = text; - var matchResult = reEmptyLine.exec(text); + const matchResult = reEmptyLine.exec(text); if (matchResult !== null) { headers = text.slice(0, matchResult.index); @@ -220,7 +215,7 @@ function splitHeaders(text) { * @param {Array} headers Armor headers */ function verifyHeaders(headers) { - for (var i = 0; i < headers.length; i++) { + for (let i = 0; i < headers.length; i++) { if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) { throw new Error('Improperly formatted armor header: ' + headers[i]); } @@ -238,10 +233,10 @@ function verifyHeaders(headers) { */ function splitChecksum(text) { text = text.trim(); - var body = text; - var checksum = ""; + let body = text; + let checksum = ""; - var lastEquals = text.lastIndexOf("="); + const lastEquals = text.lastIndexOf("="); if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum body = text.slice(0, lastEquals); @@ -260,22 +255,24 @@ function splitChecksum(text) { * @static */ function dearmor(text) { - var reSplit = /^-----[^-]+-----$\n/m; + const reSplit = /^-----[^-]+-----$\n/m; // remove trailing whitespace at end of line text = text.replace(/[\t\r ]+\n/g, '\n'); - var type = getType(text); + const type = getType(text); text = text.trim() + "\n"; - var splittext = text.split(reSplit); + const splittext = text.split(reSplit); // IE has a bug in split with a re. If the pattern matches the beginning of the // string it doesn't create an empty array element 0. So we need to detect this // so we know the index of the data we are interested in. - var indexBase = 1; + let indexBase = 1; - var result, checksum, msg; + let result; + let checksum; + let msg; if (text.search(reSplit) !== splittext[0].length) { indexBase = 0; @@ -283,7 +280,7 @@ function dearmor(text) { if (type !== 2) { msg = splitHeaders(splittext[indexBase]); - var msg_sum = splitChecksum(msg.body); + const msg_sum = splitChecksum(msg.body); result = { data: base64.decode(msg_sum.body), @@ -295,9 +292,9 @@ function dearmor(text) { } else { // Reverse dash-escaping for msg msg = splitHeaders(splittext[indexBase].replace(/^- /mg, '')); - var sig = splitHeaders(splittext[indexBase + 1].replace(/^- /mg, '')); + const sig = splitHeaders(splittext[indexBase + 1].replace(/^- /mg, '')); verifyHeaders(sig.headers); - var sig_sum = splitChecksum(sig.body); + const sig_sum = splitChecksum(sig.body); result = { text: msg.body.replace(/\n$/, '').replace(/\n/g, "\r\n"), @@ -331,7 +328,7 @@ function dearmor(text) { * @static */ function armor(messagetype, body, partindex, parttotal) { - var result = []; + const result = []; switch (messagetype) { case enums.armor.multipart_section: result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n"); diff --git a/src/encoding/base64.js b/src/encoding/base64.js index b1d7bb9b..b02c6085 100644 --- a/src/encoding/base64.js +++ b/src/encoding/base64.js @@ -15,8 +15,8 @@ * @module encoding/base64 */ -var b64s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Standard radix-64 -var b64u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; // URL-safe radix-64 +const b64s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Standard radix-64 +const b64u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; // URL-safe radix-64 /** * Convert binary array to radix-64 @@ -27,12 +27,14 @@ var b64u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; / */ function s2r(t, u = false) { // TODO check btoa alternative - var b64 = u ? b64u : b64s; - var a, c, n; - var r = [], - l = 0, - s = 0; - var tl = t.length; + const b64 = u ? b64u : b64s; + let a; + let c; + let n; + const r = []; + let l = 0; + let s = 0; + const tl = t.length; for (n = 0; n < tl; n++) { c = t[n]; @@ -89,12 +91,13 @@ function s2r(t, u = false) { */ function r2s(t, u) { // TODO check atob alternative - var b64 = u ? b64u : b64s; - var c, n; - var r = [], - s = 0, - a = 0; - var tl = t.length; + const b64 = u ? b64u : b64s; + let c; + let n; + const r = []; + let s = 0; + let a = 0; + const tl = t.length; for (n = 0; n < tl; n++) { c = b64.indexOf(t.charAt(n)); diff --git a/src/enums.js b/src/enums.js index 4ea90c0b..d384ad4e 100644 --- a/src/enums.js +++ b/src/enums.js @@ -373,14 +373,14 @@ export default { if (type[e] !== undefined) { return type[e]; - } else { - throw new Error('Invalid enum value.'); } + + throw new Error('Invalid enum value.'); }, /** Converts from an integer to string. */ read: function(type, e) { - for (var i in type) { + for (const i in type) { if (type[i] === parseInt(e, 10)) { return i; } diff --git a/src/hkp.js b/src/hkp.js index c4725c14..2c248113 100644 --- a/src/hkp.js +++ b/src/hkp.js @@ -29,7 +29,7 @@ import config from './config'; * the protocol to use e.g. https://pgp.mit.edu */ export default function HKP(keyServerBaseUrl) { - this._baseUrl = keyServerBaseUrl ? keyServerBaseUrl : config.keyserver; + this._baseUrl = keyServerBaseUrl || config.keyserver; this._fetch = typeof window !== 'undefined' ? window.fetch : require('node-fetch'); } @@ -41,8 +41,8 @@ export default function HKP(keyServerBaseUrl) { * @return {Promise} The ascii armored public key. */ HKP.prototype.lookup = function(options) { - var uri = this._baseUrl + '/pks/lookup?op=get&options=mr&search=', - fetch = this._fetch; + let uri = this._baseUrl + '/pks/lookup?op=get&options=mr&search='; + const fetch = this._fetch; if (options.keyId) { uri += '0x' + encodeURIComponent(options.keyId); @@ -56,7 +56,6 @@ HKP.prototype.lookup = function(options) { if (response.status === 200) { return response.text(); } - }).then(function(publicKeyArmored) { if (!publicKeyArmored || publicKeyArmored.indexOf('-----END PGP PUBLIC KEY BLOCK-----') < 0) { return; @@ -71,8 +70,8 @@ HKP.prototype.lookup = function(options) { * @return {Promise} */ HKP.prototype.upload = function(publicKeyArmored) { - var uri = this._baseUrl + '/pks/add', - fetch = this._fetch; + const uri = this._baseUrl + '/pks/add'; + const fetch = this._fetch; return fetch(uri, { method: 'post', @@ -81,4 +80,4 @@ HKP.prototype.upload = function(publicKeyArmored) { }, body: 'keytext=' + encodeURIComponent(publicKeyArmored) }); -}; \ No newline at end of file +}; diff --git a/src/key.js b/src/key.js index 35e4b0d5..ff2185fe 100644 --- a/src/key.js +++ b/src/key.js @@ -60,8 +60,10 @@ export function Key(packetlist) { * @param {module:packet/packetlist} packetlist The packets that form a key */ Key.prototype.packetlist2structure = function(packetlist) { - var user, primaryKeyId, subKey; - for (var i = 0; i < packetlist.length; i++) { + let user; + let primaryKeyId; + let subKey; + for (let i = 0; i < packetlist.length; i++) { switch (packetlist[i].tag) { case enums.packet.publicKey: case enums.packet.secretKey: @@ -154,11 +156,11 @@ Key.prototype.packetlist2structure = function(packetlist) { * @return {module:packet/packetlist} The packets that form a key */ Key.prototype.toPacketlist = function() { - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.push(this.primaryKey); packetlist.push(this.revocationSignature); packetlist.concat(this.directSignatures); - var i; + let i; for (i = 0; i < this.users.length; i++) { packetlist.concat(this.users[i].toPacketlist()); } @@ -175,9 +177,9 @@ Key.prototype.toPacketlist = function() { * @returns {Array<(module:packet/public_subkey|module:packet/secret_subkey)>} */ Key.prototype.getSubkeyPackets = function() { - var subKeys = []; + const subKeys = []; if (this.subKeys) { - for (var i = 0; i < this.subKeys.length; i++) { + for (let i = 0; i < this.subKeys.length; i++) { subKeys.push(this.subKeys[i].subKey); } } @@ -197,9 +199,9 @@ Key.prototype.getAllKeyPackets = function() { * @returns {Array} */ Key.prototype.getKeyIds = function() { - var keyIds = []; - var keys = this.getAllKeyPackets(); - for (var i = 0; i < keys.length; i++) { + const keyIds = []; + const keys = this.getAllKeyPackets(); + for (let i = 0; i < keys.length; i++) { keyIds.push(keys[i].getKeyId()); } return keyIds; @@ -212,12 +214,12 @@ Key.prototype.getKeyIds = function() { * module:packet/secret_subkey|module:packet/secret_key|null)} */ Key.prototype.getKeyPackets = function(packetKeyId) { - var keys = this.getAllKeyPackets(); + const keys = this.getAllKeyPackets(); if (packetKeyId.isWildcard()) { return keys; } - for (var i = 0; i < keys.length; i++) { - var keyId = keys[i].getKeyId(); + for (let i = 0; i < keys.length; i++) { + const keyId = keys[i].getKeyId(); if (keyId.equals(packetKeyId)) { return [keys[i]]; } @@ -230,8 +232,8 @@ Key.prototype.getKeyPackets = function(packetKeyId) { * @return {Array} array of userids */ Key.prototype.getUserIds = function() { - var userids = []; - for (var i = 0; i < this.users.length; i++) { + const userids = []; + for (let i = 0; i < this.users.length; i++) { if (this.users[i].userId) { userids.push(util.Uint8Array2str(this.users[i].userId.write())); } @@ -260,20 +262,22 @@ Key.prototype.isPrivate = function() { * @return {module:key~Key} new public Key */ Key.prototype.toPublic = function() { - var packetlist = new packet.List(); - var keyPackets = this.toPacketlist(); - var bytes; - for (var i = 0; i < keyPackets.length; i++) { + const packetlist = new packet.List(); + const keyPackets = this.toPacketlist(); + let bytes; + let pubKeyPacket; + let pubSubkeyPacket; + for (let i = 0; i < keyPackets.length; i++) { switch (keyPackets[i].tag) { case enums.packet.secretKey: bytes = keyPackets[i].writePublicKey(); - var pubKeyPacket = new packet.PublicKey(); + pubKeyPacket = new packet.PublicKey(); pubKeyPacket.read(bytes); packetlist.push(pubKeyPacket); break; case enums.packet.secretSubkey: bytes = keyPackets[i].writePublicKey(); - var pubSubkeyPacket = new packet.PublicSubkey(); + pubSubkeyPacket = new packet.PublicSubkey(); pubSubkeyPacket.read(bytes); packetlist.push(pubSubkeyPacket); break; @@ -289,7 +293,7 @@ Key.prototype.toPublic = function() { * @return {String} ASCII armor */ Key.prototype.armor = function() { - var type = this.isPublic() ? enums.armor.public_key : enums.armor.private_key; + const type = this.isPublic() ? enums.armor.public_key : enums.armor.private_key; return armor.encode(type, this.toPacketlist().write()); }; @@ -300,17 +304,16 @@ Key.prototype.armor = function() { * @return {(module:packet/secret_subkey|module:packet/secret_key|null)} key packet or null if no signing key has been found */ Key.prototype.getSigningKeyPacket = function(keyId, allowExpired=false) { - var primaryUser = this.getPrimaryUser(allowExpired); + const primaryUser = this.getPrimaryUser(allowExpired); if (primaryUser && (!keyId || this.primaryKey.getKeyId().equals(keyId)) && isValidSigningKeyPacket(this.primaryKey, primaryUser.selfCertificate, allowExpired)) { return this.primaryKey; } if (this.subKeys) { - for (var i = 0; i < this.subKeys.length; i++) { + for (let i = 0; i < this.subKeys.length; i++) { if (!keyId || this.subKeys[i].subKey.getKeyId().equals(keyId)) { - for (var j = 0; j < this.subKeys[i].bindingSignatures.length; j++) { - if (isValidSigningKeyPacket( - this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j], allowExpired)) { + for (let j = 0; j < this.subKeys[i].bindingSignatures.length; j++) { + if (isValidSigningKeyPacket(this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j], allowExpired)) { return this.subKeys[i].subKey; } } @@ -350,7 +353,6 @@ function isValidSigningKeyPacket(keyPacket, signature, allowExpired=false) { // check expiration time of V4 key packet !(keyPacket.version === 4 && signature.keyNeverExpires === false && Date.now() > (keyPacket.created.getTime() + signature.keyExpirationTime*1000)))); - } /** @@ -362,11 +364,10 @@ Key.prototype.getEncryptionKeyPacket = function(keyId) { // V4: by convention subkeys are preferred for encryption service // V3: keys MUST NOT have subkeys if (this.subKeys) { - for (var i = 0; i < this.subKeys.length; i++) { + for (let i = 0; i < this.subKeys.length; i++) { if (!keyId || this.subKeys[i].subKey.getKeyId().equals(keyId)) { - for (var j = 0; j < this.subKeys[i].bindingSignatures.length; j++) { - if (isValidEncryptionKeyPacket( - this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j])) { + for (let j = 0; j < this.subKeys[i].bindingSignatures.length; j++) { + if (isValidEncryptionKeyPacket(this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j])) { return this.subKeys[i].subKey; } } @@ -374,7 +375,7 @@ Key.prototype.getEncryptionKeyPacket = function(keyId) { } } // if no valid subkey for encryption, evaluate primary key - var primaryUser = this.getPrimaryUser(); + const primaryUser = this.getPrimaryUser(); if (primaryUser && (!keyId || this.primaryKey.getKeyId().equals(keyId)) && isValidEncryptionKeyPacket(this.primaryKey, primaryUser.selfCertificate)) { return this.primaryKey; @@ -391,8 +392,8 @@ Key.prototype.encrypt = function(passphrase) { throw new Error("Nothing to encrypt in a public key"); } - var keys = this.getAllKeyPackets(); - for (var i = 0; i < keys.length; i++) { + const keys = this.getAllKeyPackets(); + for (let i = 0; i < keys.length; i++) { keys[i].encrypt(passphrase); keys[i].clearPrivateParams(); } @@ -405,9 +406,9 @@ Key.prototype.encrypt = function(passphrase) { */ Key.prototype.decrypt = function(passphrase) { if (this.isPrivate()) { - var keys = this.getAllKeyPackets(); - for (var i = 0; i < keys.length; i++) { - var success = keys[i].decrypt(passphrase); + const keys = this.getAllKeyPackets(); + for (let i = 0; i < keys.length; i++) { + const success = keys[i].decrypt(passphrase); if (!success) { return false; } @@ -426,12 +427,12 @@ Key.prototype.decrypt = function(passphrase) { */ Key.prototype.decryptKeyPacket = function(keyIds, passphrase) { if (this.isPrivate()) { - var keys = this.getAllKeyPackets(); - for (var i = 0; i < keys.length; i++) { - var keyId = keys[i].getKeyId(); - for (var j = 0; j < keyIds.length; j++) { + const keys = this.getAllKeyPackets(); + for (let i = 0; i < keys.length; i++) { + const keyId = keys[i].getKeyId(); + for (let j = 0; j < keyIds.length; j++) { if (keyId.equals(keyIds[j])) { - var success = keys[i].decrypt(passphrase); + const success = keys[i].decrypt(passphrase); if (!success) { return false; } @@ -455,7 +456,7 @@ Key.prototype.verifyPrimaryKey = async function(allowExpired=false) { // check revocation signature if (this.revocationSignature && !this.revocationSignature.isExpired() && (this.revocationSignature.verified || - await this.revocationSignature.verify(this.primaryKey, {key: this.primaryKey}))) { + await this.revocationSignature.verify(this.primaryKey, { key: this.primaryKey }))) { return enums.keyStatus.revoked; } // check V3 expiration time @@ -470,7 +471,7 @@ Key.prototype.verifyPrimaryKey = async function(allowExpired=false) { } // check for valid self signature await this.verifyPrimaryUser(); - var primaryUser = this.getPrimaryUser(allowExpired); + const primaryUser = this.getPrimaryUser(allowExpired); if (!primaryUser) { return enums.keyStatus.invalid; } @@ -491,7 +492,7 @@ Key.prototype.getExpirationTime = function() { return getExpirationTime(this.primaryKey); } if (this.primaryKey.version === 4) { - var primaryUser = this.getPrimaryUser(); + const primaryUser = this.getPrimaryUser(); if (!primaryUser) { return null; } @@ -520,27 +521,26 @@ function getExpirationTime(keyPacket, selfCertificate) { * @return {{user: Array, selfCertificate: Array}|null} The primary user and the self signature */ Key.prototype.getPrimaryUser = function(allowExpired=false) { - var primaryUsers = []; - for (var i = 0; i < this.users.length; i++) { + let primaryUsers = []; + for (let i = 0; i < this.users.length; i++) { // here we only check the primary user ID, ignoring the primary user attribute if (!this.users[i].userId || !this.users[i].selfCertifications) { continue; } - for (var j = 0; j < this.users[i].selfCertifications.length; j++) { + for (let j = 0; j < this.users[i].selfCertifications.length; j++) { // only consider already validated certificates if (!this.users[i].selfCertifications[j].verified || this.users[i].selfCertifications[j].revoked || (this.users[i].selfCertifications[j].isExpired() && !allowExpired)) { continue; } - primaryUsers.push( - { index: i, user: this.users[i], selfCertificate: this.users[i].selfCertifications[j] } - ); + primaryUsers.push({ index: i, user: this.users[i], selfCertificate: this.users[i].selfCertifications[j] }); } } // sort by primary user flag and signature creation time primaryUsers = primaryUsers.sort(function(a, b) { - var A = a.selfCertificate, B = b.selfCertificate; + const A = a.selfCertificate; + const B = b.selfCertificate; return (B.isPrimaryUserID - A.isPrimaryUserID) || (B.created - A.created); }); return primaryUsers.pop(); @@ -555,7 +555,7 @@ Key.prototype.getPrimaryUser = function(allowExpired=false) { * @param {module:key~Key} key source key to merge */ Key.prototype.update = async function(key) { - var that = this; + const that = this; if (await key.verifyPrimaryKey() === enums.keyStatus.invalid) { return; } @@ -564,7 +564,7 @@ Key.prototype.update = async function(key) { } if (this.isPublic() && key.isPrivate()) { // check for equal subkey packets - var equal = ((this.subKeys && this.subKeys.length) === (key.subKeys && key.subKeys.length)) && + const equal = ((this.subKeys && this.subKeys.length) === (key.subKeys && key.subKeys.length)) && (!this.subKeys || this.subKeys.every(function(destSubKey) { return key.subKeys.some(function(srcSubKey) { return destSubKey.subKey.getFingerprint() === srcSubKey.subKey.getFingerprint(); @@ -579,7 +579,7 @@ Key.prototype.update = async function(key) { // revocation signature if (!this.revocationSignature && key.revocationSignature && !key.revocationSignature.isExpired() && (key.revocationSignature.verified || - await key.revocationSignature.verify(key.primaryKey, {key: key.primaryKey}))) { + await key.revocationSignature.verify(key.primaryKey, { key: key.primaryKey }))) { this.revocationSignature = key.revocationSignature; } // direct signatures @@ -587,7 +587,7 @@ Key.prototype.update = async function(key) { // TODO replace when Promise.some or Promise.any are implemented // users await Promise.all(key.users.map(async function(srcUser) { - var found = false; + let found = false; await Promise.all(that.users.map(async function(dstUser) { if ((srcUser.userId && (srcUser.userId.userid === dstUser.userId.userid)) || (srcUser.userAttribute && (srcUser.userAttribute.equals(dstUser.userAttribute)))) { @@ -603,7 +603,7 @@ Key.prototype.update = async function(key) { // subkeys if (key.subKeys) { await Promise.all(key.subKeys.map(async function(srcSubKey) { - var found = false; + let found = false; await Promise.all(that.subKeys.map(async function(dstSubKey) { if (srcSubKey.subKey.getFingerprint() === dstSubKey.subKey.getFingerprint()) { await dstSubKey.update(srcSubKey, that.primaryKey); @@ -634,7 +634,7 @@ async function mergeSignatures(source, dest, attr, checkFn) { await Promise.all(source.map(async function(sourceSig) { if (!sourceSig.isExpired() && (!checkFn || await checkFn(sourceSig)) && !dest[attr].some(function(destSig) { - return util.equalsUint8Array(destSig.signature,sourceSig.signature); + return util.equalsUint8Array(destSig.signature, sourceSig.signature); })) { dest[attr].push(sourceSig); } @@ -655,13 +655,13 @@ Key.prototype.revoke = function() { */ Key.prototype.signPrimaryUser = async function(privateKeys) { await this.verifyPrimaryUser(); - var {index, user} = this.getPrimaryUser() || {}; + const { index, user } = this.getPrimaryUser() || {}; if (!user) { throw new Error('Could not find primary user'); } - user = await user.sign(this.primaryKey, privateKeys); - var key = new Key(this.toPacketlist()); - key.users[index] = user; + const userSign = await user.sign(this.primaryKey, privateKeys); + const key = new Key(this.toPacketlist()); + key.users[index] = userSign; return key; }; @@ -671,8 +671,8 @@ Key.prototype.signPrimaryUser = async function(privateKeys) { * @return {module:key~Key} new public key with new certificate signature */ Key.prototype.signAllUsers = async function(privateKeys) { - var that = this; - var key = new Key(this.toPacketlist()); + const that = this; + const key = new Key(this.toPacketlist()); key.users = await Promise.all(this.users.map(function(user) { return user.sign(that.primaryKey, privateKeys); })); @@ -687,14 +687,16 @@ Key.prototype.signAllUsers = async function(privateKeys) { * @return {Array<({keyid: module:type/keyid, valid: Boolean})>} list of signer's keyid and validity of signature */ Key.prototype.verifyPrimaryUser = async function(keys) { - var primaryKey = this.primaryKey, primaryUsers = []; - var lastCreated = null, lastPrimaryUserID = null; + const { primaryKey } = this; + const primaryUsers = []; + let lastCreated = null; + let lastPrimaryUserID = null; await Promise.all(this.users.map(async function(user) { // here we verify both the primary user ID or the primary user attribute if (!(user.userId || user.userAttribute) || !user.selfCertifications) { return; } - var dataToVerify = { userid: user.userId || user.userAttribute, key: primaryKey }; + const dataToVerify = { userid: user.userId || user.userAttribute, key: primaryKey }; await Promise.all(user.selfCertifications.map(async function(selfCertification) { // skip if certificate is not the most recent if ((selfCertification.isPrimaryUserID && @@ -713,9 +715,9 @@ Key.prototype.verifyPrimaryUser = async function(keys) { primaryUsers.push(user); })); })); - var user = primaryUsers.pop(); - var results = !user ? [] : keys ? await user.verifyAllCertifications(primaryKey, keys) : - [{ keyid: primaryKey.keyid, valid: await user.verify(primaryKey) === enums.keyStatus.valid }]; + const user = primaryUsers.pop(); + const results = !user ? [] : keys ? await user.verifyAllCertifications(primaryKey, keys) : + [{ keyid: primaryKey.keyid, valid: await user.verify(primaryKey) === enums.keyStatus.valid }]; return results; }; @@ -727,11 +729,11 @@ Key.prototype.verifyPrimaryUser = async function(keys) { * @return {Array<({userid: String, keyid: module:type/keyid, valid: Boolean})>} list of userid, signer's keyid and validity of signature */ Key.prototype.verifyAllUsers = async function(keys) { - var results = []; - var primaryKey = this.primaryKey; + const results = []; + const { primaryKey } = this; await Promise.all(this.users.map(async function(user) { - var signatures = keys ? await user.verifyAllCertifications(primaryKey, keys) : - [{ keyid: primaryKey.keyid, valid: await user.verify(primaryKey) === enums.keyStatus.valid }]; + const signatures = keys ? await user.verifyAllCertifications(primaryKey, keys) : + [{ keyid: primaryKey.keyid, valid: await user.verify(primaryKey) === enums.keyStatus.valid }]; signatures.forEach(signature => { results.push({ userid: user.userId.userid, @@ -763,7 +765,7 @@ function User(userPacket) { * @return {module:packet/packetlist} */ User.prototype.toPacketlist = function() { - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.push(this.userId || this.userAttribute); packetlist.concat(this.revocationCertifications); packetlist.concat(this.selfCertifications); @@ -781,18 +783,17 @@ User.prototype.toPacketlist = function() { */ User.prototype.isRevoked = async function(primaryKey, certificate, key) { if (this.revocationCertifications) { - var dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; + const dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; // TODO clarify OpenPGP's behavior given an expired revocation signature - var results = await Promise.all(this.revocationCertifications.map(async function(revCert) { + const results = await Promise.all(this.revocationCertifications.map(async function(revCert) { return revCert.issuerKeyId.equals(certificate.issuerKeyId) && !revCert.isExpired() && - (revCert.verified || revCert.verify(key ? key : primaryKey, dataToVerify)); + (revCert.verified || revCert.verify(key || primaryKey, dataToVerify)); })); certificate.revoked = results.some(result => result === true); return certificate.revoked; - } else { - return false; } + return false; }; /** @@ -814,8 +815,8 @@ User.prototype.sign = async function(primaryKey, privateKeys) { await privateKey.verifyPrimaryUser(); const signingKeyPacket = privateKey.getSigningKeyPacket(); if (!signingKeyPacket) { - throw new Error('Could not find valid signing key packet in key ' + - privateKey.primaryKey.getKeyId().toHex()); + throw new Error(`Could not find valid signing key packet in key ${ + privateKey.primaryKey.getKeyId().toHex()}`); } if (!signingKeyPacket.isDecrypted) { throw new Error('Private key is not decrypted.'); @@ -843,13 +844,13 @@ User.prototype.sign = async function(primaryKey, privateKeys) { * @return {module:enums.keyStatus} status of the certificate */ User.prototype.verifyCertificate = async function(primaryKey, certificate, keys, allowExpired=false) { - var that = this; - var keyid = certificate.issuerKeyId; - var dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; - var results = await Promise.all(keys.map(async function(key) { + const that = this; + const keyid = certificate.issuerKeyId; + const dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; + const results = await Promise.all(keys.map(async function(key) { if (!key.getKeyIds().some(id => id.equals(keyid))) { return; } await key.verifyPrimaryUser(); - var keyPacket = key.getSigningKeyPacket(keyid, allowExpired); + const keyPacket = key.getSigningKeyPacket(keyid, allowExpired); if (certificate.revoked || await that.isRevoked(primaryKey, certificate, keyPacket)) { return enums.keyStatus.revoked; } @@ -871,12 +872,14 @@ User.prototype.verifyCertificate = async function(primaryKey, certificate, keys, * @return {Array<({keyid: module:type/keyid, valid: Boolean})>} list of signer's keyid and validity of signature */ User.prototype.verifyAllCertifications = async function(primaryKey, keys) { - var that = this; - var certifications = this.selfCertifications.concat(this.otherCertifications || []); + const that = this; + const certifications = this.selfCertifications.concat(this.otherCertifications || []); return Promise.all(certifications.map(async function(certification) { - var status = await that.verifyCertificate(primaryKey, certification, keys); - return { keyid: certification.issuerKeyId, - valid: status === undefined ? null : status === enums.keyStatus.valid }; + const status = await that.verifyCertificate(primaryKey, certification, keys); + return { + keyid: certification.issuerKeyId, + valid: status === undefined ? null : status === enums.keyStatus.valid + }; })); }; @@ -890,22 +893,21 @@ User.prototype.verify = async function(primaryKey) { if (!this.selfCertifications) { return enums.keyStatus.no_self_cert; } - var that = this; - var dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; + const that = this; + const dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; // TODO replace when Promise.some or Promise.any are implemented - var results = [enums.keyStatus.invalid].concat( - await Promise.all(this.selfCertifications.map(async function(selfCertification, i) { - if (selfCertification.revoked || await that.isRevoked(primaryKey, selfCertification)) { - return enums.keyStatus.revoked; - } - if (!(selfCertification.verified || await selfCertification.verify(primaryKey, dataToVerify))) { - return enums.keyStatus.invalid; - } - if (selfCertification.isExpired()) { - return enums.keyStatus.expired; - } - return enums.keyStatus.valid; - }))); + const results = [enums.keyStatus.invalid].concat(await Promise.all(this.selfCertifications.map(async function(selfCertification) { + if (selfCertification.revoked || await that.isRevoked(primaryKey, selfCertification)) { + return enums.keyStatus.revoked; + } + if (!(selfCertification.verified || await selfCertification.verify(primaryKey, dataToVerify))) { + return enums.keyStatus.invalid; + } + if (selfCertification.isExpired()) { + return enums.keyStatus.expired; + } + return enums.keyStatus.valid; + }))); return results.some(status => status === enums.keyStatus.valid) ? enums.keyStatus.valid : results.pop(); }; @@ -916,7 +918,7 @@ User.prototype.verify = async function(primaryKey) { * @param {module:packet/signature} primaryKey primary key used for validation */ User.prototype.update = async function(user, primaryKey) { - var dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; + const dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; // self signatures await mergeSignatures(user, this, 'selfCertifications', async function(srcSelfSig) { return srcSelfSig.verified || srcSelfSig.verify(primaryKey, dataToVerify); @@ -945,10 +947,10 @@ function SubKey(subKeyPacket) { * @return {module:packet/packetlist} */ SubKey.prototype.toPacketlist = function() { - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.push(this.subKey); packetlist.push(this.revocationSignature); - for(var i = 0; i < this.bindingSignatures.length; i++) { + for (let i = 0; i < this.bindingSignatures.length; i++) { packetlist.push(this.bindingSignatures[i]); } return packetlist; @@ -960,11 +962,11 @@ SubKey.prototype.toPacketlist = function() { * @return {Boolean} */ SubKey.prototype.isValidEncryptionKey = async function(primaryKey) { - if(await this.verify(primaryKey) !== enums.keyStatus.valid) { + if (await this.verify(primaryKey) !== enums.keyStatus.valid) { return false; } - for(var i = 0; i < this.bindingSignatures.length; i++) { - if(isValidEncryptionKeyPacket(this.subKey, this.bindingSignatures[i])) { + for (let i = 0; i < this.bindingSignatures.length; i++) { + if (isValidEncryptionKeyPacket(this.subKey, this.bindingSignatures[i])) { return true; } } @@ -978,11 +980,11 @@ SubKey.prototype.isValidEncryptionKey = async function(primaryKey) { * @return {Boolean} */ SubKey.prototype.isValidSigningKey = async function(primaryKey, allowExpired=false) { - if(await this.verify(primaryKey, allowExpired) !== enums.keyStatus.valid) { + if (await this.verify(primaryKey, allowExpired) !== enums.keyStatus.valid) { return false; } - for(var i = 0; i < this.bindingSignatures.length; i++) { - if(isValidSigningKeyPacket(this.subKey, this.bindingSignatures[i], allowExpired)) { + for (let i = 0; i < this.bindingSignatures.length; i++) { + if (isValidSigningKeyPacket(this.subKey, this.bindingSignatures[i], allowExpired)) { return true; } } @@ -997,12 +999,12 @@ SubKey.prototype.isValidSigningKey = async function(primaryKey, allowExpired=fal * @return {module:enums.keyStatus} The status of the subkey */ SubKey.prototype.verify = async function(primaryKey, allowExpired=false) { - var that = this; + const that = this; // TODO clarify OpenPGP's behavior given an expired revocation signature // check subkey revocation signature if (this.revocationSignature && !this.revocationSignature.isExpired() && (this.revocationSignature.verified || - await this.revocationSignature.verify(primaryKey, {key:primaryKey, bind: this.subKey}))) { + await this.revocationSignature.verify(primaryKey, { key: primaryKey, bind: this.subKey }))) { return enums.keyStatus.revoked; } // check V3 expiration time @@ -1012,26 +1014,25 @@ SubKey.prototype.verify = async function(primaryKey, allowExpired=false) { } // check subkey binding signatures (at least one valid binding sig needed) // TODO replace when Promise.some or Promise.any are implemented - var results = [enums.keyStatus.invalid].concat( - await Promise.all(this.bindingSignatures.map(async function(bindingSignature) { + const results = [enums.keyStatus.invalid].concat(await Promise.all(this.bindingSignatures.map(async function(bindingSignature) { // check binding signature is not expired - if(!allowExpired && bindingSignature.isExpired()) { + if (!allowExpired && bindingSignature.isExpired()) { return enums.keyStatus.expired; // last expired binding signature } // check binding signature can verify if (!(bindingSignature.verified || - await bindingSignature.verify(primaryKey, {key: primaryKey, bind: that.subKey}))) { + await bindingSignature.verify(primaryKey, { key: primaryKey, bind: that.subKey }))) { return enums.keyStatus.invalid; // last invalid binding signature } // check V4 expiration time if (that.subKey.version === 4) { - if(!allowExpired && bindingSignature.keyNeverExpires === false && + if (!allowExpired && bindingSignature.keyNeverExpires === false && Date.now() > (that.subKey.created.getTime() + bindingSignature.keyExpirationTime*1000)) { return enums.keyStatus.expired; // last V4 expired binding signature } } return enums.keyStatus.valid; // found a binding signature that passed all checks - }))); + }))); return results.some(status => status === enums.keyStatus.valid) ? enums.keyStatus.valid : results.pop(); }; @@ -1041,13 +1042,13 @@ SubKey.prototype.verify = async function(primaryKey, allowExpired=false) { * @return {Date|null} */ SubKey.prototype.getExpirationTime = function() { - var highest; - for(var i = 0; i < this.bindingSignatures.length; i++) { - var current = getExpirationTime(this.subKey, this.bindingSignatures[i]); - if(current === null) { + let highest; + for (let i = 0; i < this.bindingSignatures.length; i++) { + const current = getExpirationTime(this.subKey, this.bindingSignatures[i]); + if (current === null) { return null; } - if(!highest || current > highest) { + if (!highest || current > highest) { highest = current; } } @@ -1072,11 +1073,11 @@ SubKey.prototype.update = async function(subKey, primaryKey) { this.subKey = subKey.subKey; } // update missing binding signatures - var that = this; + const that = this; await Promise.all(subKey.bindingSignatures.map(async function(newBindingSignature) { if (newBindingSignature.verified || - await newBindingSignature.verify(primaryKey, {key: primaryKey, bind: that.subKey })) { - for (var i = 0; i < that.bindingSignatures.length; i++) { + await newBindingSignature.verify(primaryKey, { key: primaryKey, bind: that.subKey })) { + for (let i = 0; i < that.bindingSignatures.length; i++) { if (that.bindingSignatures[i].issuerKeyId.equals(newBindingSignature.issuerKeyId)) { that.bindingSignatures[i] = newBindingSignature; return; @@ -1091,9 +1092,7 @@ SubKey.prototype.update = async function(subKey, primaryKey) { subKey.revocationSignature && !subKey.revocationSignature.isExpired() && (subKey.revocationSignature.verified || - await subKey.revocationSignature.verify( - primaryKey, {key: primaryKey, bind: this.subKey} - ))) { + await subKey.revocationSignature.verify(primaryKey, { key: primaryKey, bind: this.subKey }))) { this.revocationSignature = subKey.revocationSignature; } }; @@ -1105,19 +1104,19 @@ SubKey.prototype.update = async function(subKey, primaryKey) { * @static */ export function read(data) { - var result = {}; + const result = {}; result.keys = []; try { - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.read(data); - var keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); if (keyIndex.length === 0) { throw new Error('No key packet found'); } - for (var i = 0; i < keyIndex.length; i++) { - var oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + for (let i = 0; i < keyIndex.length; i++) { + const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); try { - var newKey = new Key(oneKeyList); + const newKey = new Key(oneKeyList); result.keys.push(newKey); } catch (e) { result.err = result.err || []; @@ -1139,13 +1138,13 @@ export function read(data) { */ export function readArmored(armoredText) { try { - var input = armor.decode(armoredText); + const input = armor.decode(armoredText); if (!(input.type === enums.armor.public_key || input.type === enums.armor.private_key)) { throw new Error('Armored text not of type key'); } return read(input.data); } catch (e) { - var result = {keys: [], err: []}; + const result = { keys: [], err: [] }; result.err.push(e); return result; } @@ -1166,14 +1165,14 @@ export function readArmored(armoredText) { * @static */ export function generate(options) { - var secretKeyPacket, secretSubkeyPacket; + let secretKeyPacket; + let secretSubkeyPacket; return Promise.resolve().then(() => { - if (options.curve) { try { options.curve = enums.write(enums.curve, options.curve); } catch (e) { - throw new Error('Not valid curve.') + throw new Error('Not valid curve.'); } if (options.curve === enums.curve.ed25519 || options.curve === enums.curve.curve25519) { options.keyType = options.keyType || enums.publicKey.eddsa; @@ -1208,9 +1207,7 @@ export function generate(options) { options.userIds = [options.userIds]; } - return Promise.all([generateSecretKey(), generateSecretSubkey()]).then(() => { - return wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options); - }); + return Promise.all([generateSecretKey(), generateSecretSubkey()]).then(() => wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options)); }); function generateSecretKey() { @@ -1243,9 +1240,9 @@ export function generate(options) { * @static */ export function reformat(options) { - var secretKeyPacket, secretSubkeyPacket; + let secretKeyPacket; + let secretSubkeyPacket; return Promise.resolve().then(() => { - options.keyType = options.keyType || enums.publicKey.rsa_encrypt_sign; if (options.keyType !== enums.publicKey.rsa_encrypt_sign) { // RSA Encrypt-Only and RSA Sign-Only are deprecated and SHOULD NOT be generated throw new Error('Only RSA Encrypt or Sign supported'); @@ -1261,8 +1258,8 @@ export function reformat(options) { if (util.isString(options.userIds)) { options.userIds = [options.userIds]; } - var packetlist = options.privateKey.toPacketlist(); - for (var i = 0; i < packetlist.length; i++) { + const packetlist = options.privateKey.toPacketlist(); + for (let i = 0; i < packetlist.length; i++) { if (packetlist[i].tag === enums.packet.secretKey) { secretKeyPacket = packetlist[i]; options.keyType = secretKeyPacket.algorithm; @@ -1287,19 +1284,18 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options) { } } - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.push(secretKeyPacket); await Promise.all(options.userIds.map(async function(userId, index) { - - var userIdPacket = new packet.Userid(); + const userIdPacket = new packet.Userid(); userIdPacket.read(util.str2Uint8Array(userId)); - var dataToSign = {}; + const dataToSign = {}; dataToSign.userid = userIdPacket; dataToSign.key = secretKeyPacket; - var signaturePacket = new packet.Signature(); + const signaturePacket = new packet.Signature(); signaturePacket.signatureType = enums.signature.cert_generic; signaturePacket.publicKeyAlgorithm = options.keyType; signaturePacket.hashAlgorithm = getPreferredHashAlgo(secretKeyPacket); @@ -1332,19 +1328,19 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options) { } await signaturePacket.sign(secretKeyPacket, dataToSign); - return {userIdPacket, signaturePacket}; + return { userIdPacket, signaturePacket }; })).then(list => { - list.forEach(({userIdPacket, signaturePacket}) => { + list.forEach(({ userIdPacket, signaturePacket }) => { packetlist.push(userIdPacket); packetlist.push(signaturePacket); }); }); if (secretSubkeyPacket) { - var dataToSign = {}; + const dataToSign = {}; dataToSign.key = secretKeyPacket; dataToSign.bind = secretSubkeyPacket; - var subkeySignaturePacket = new packet.Signature(); + const subkeySignaturePacket = new packet.Signature(); subkeySignaturePacket.signatureType = enums.signature.subkey_binding; subkeySignaturePacket.publicKeyAlgorithm = options.keyType; subkeySignaturePacket.hashAlgorithm = getPreferredHashAlgo(secretSubkeyPacket); @@ -1375,23 +1371,23 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options) { * @return {String} */ export function getPreferredHashAlgo(key) { - var hash_algo = config.prefer_hash_algorithm, - pref_algo = hash_algo; + let hash_algo = config.prefer_hash_algorithm; + let pref_algo = hash_algo; if (Key.prototype.isPrototypeOf(key)) { - var primaryUser = key.getPrimaryUser(); + const primaryUser = key.getPrimaryUser(); if (primaryUser && primaryUser.selfCertificate.preferredHashAlgorithms) { - pref_algo = primaryUser.selfCertificate.preferredHashAlgorithms[0]; + [pref_algo] = primaryUser.selfCertificate.preferredHashAlgorithms; hash_algo = crypto.hash.getHashByteLength(hash_algo) <= crypto.hash.getHashByteLength(pref_algo) ? pref_algo : hash_algo; } key = key.getSigningKeyPacket(); } - switch(Object.getPrototypeOf(key)) { + switch (Object.getPrototypeOf(key)) { case packet.SecretKey.prototype: case packet.PublicKey.prototype: case packet.SecretSubkey.prototype: case packet.PublicSubkey.prototype: - switch(key.algorithm) { + switch (key.algorithm) { case 'ecdh': case 'ecdsa': case 'eddsa': @@ -1408,20 +1404,20 @@ export function getPreferredHashAlgo(key) { * @return {enums.symmetric} Preferred symmetric algorithm */ export function getPreferredSymAlgo(keys) { - var prioMap = {}; + const prioMap = {}; keys.forEach(function(key) { - var primaryUser = key.getPrimaryUser(); + const primaryUser = key.getPrimaryUser(); if (!primaryUser || !primaryUser.selfCertificate.preferredSymmetricAlgorithms) { return config.encryption_cipher; } primaryUser.selfCertificate.preferredSymmetricAlgorithms.forEach(function(algo, index) { - var entry = prioMap[algo] || (prioMap[algo] = {prio: 0, count: 0, algo: algo}); + const entry = prioMap[algo] || (prioMap[algo] = { prio: 0, count: 0, algo: algo }); entry.prio += 64 >> index; entry.count++; }); }); - var prefAlgo = {prio: 0, algo: config.encryption_cipher}; - for (var algo in prioMap) { + let prefAlgo = { prio: 0, algo: config.encryption_cipher }; + for (const algo in prioMap) { try { if (algo !== enums.symmetric.plaintext && algo !== enums.symmetric.idea && // not implemented diff --git a/src/keyring/keyring.js b/src/keyring/keyring.js index 8226ebe4..32d09738 100644 --- a/src/keyring/keyring.js +++ b/src/keyring/keyring.js @@ -62,7 +62,7 @@ Keyring.prototype.clear = function() { * @return {Array|null} keys found or null */ Keyring.prototype.getKeysForId = function (keyId, deep) { - var result = []; + let result = []; result = result.concat(this.publicKeys.getForId(keyId, deep) || []); result = result.concat(this.privateKeys.getForId(keyId, deep) || []); return result.length ? result : null; @@ -75,7 +75,7 @@ Keyring.prototype.getKeysForId = function (keyId, deep) { * @return {Array|null} keys found or null */ Keyring.prototype.removeKeysForId = function (keyId) { - var result = []; + let result = []; result = result.concat(this.publicKeys.removeForId(keyId) || []); result = result.concat(this.privateKeys.removeForId(keyId) || []); return result.length ? result : null; @@ -103,8 +103,8 @@ function KeyArray(keys) { * @return {Array} The public keys associated with provided email address. */ KeyArray.prototype.getForAddress = function(email) { - var results = []; - for (var i = 0; i < this.keys.length; i++) { + const results = []; + for (let i = 0; i < this.keys.length; i++) { if (emailCheck(email, this.keys[i])) { results.push(this.keys[i]); } @@ -122,11 +122,11 @@ KeyArray.prototype.getForAddress = function(email) { function emailCheck(email, key) { email = email.toLowerCase(); // escape email before using in regular expression - var emailEsc = email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - var emailRegex = new RegExp('<' + emailEsc + '>'); - var userIds = key.getUserIds(); - for (var i = 0; i < userIds.length; i++) { - var userId = userIds[i].toLowerCase(); + const emailEsc = email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const emailRegex = new RegExp('<' + emailEsc + '>'); + const userIds = key.getUserIds(); + for (let i = 0; i < userIds.length; i++) { + const userId = userIds[i].toLowerCase(); if (email === userId || emailRegex.test(userId)) { return true; } @@ -145,9 +145,8 @@ function emailCheck(email, key) { function keyIdCheck(keyId, keypacket) { if (keyId.length === 16) { return keyId === keypacket.getKeyId().toHex(); - } else { - return keyId === keypacket.getFingerprint(); } + return keyId === keypacket.getFingerprint(); } /** @@ -158,12 +157,12 @@ function keyIdCheck(keyId, keypacket) { * @return {module:key~Key|null} key found or null */ KeyArray.prototype.getForId = function (keyId, deep) { - for (var i = 0; i < this.keys.length; i++) { + for (let i = 0; i < this.keys.length; i++) { if (keyIdCheck(keyId, this.keys[i].primaryKey)) { return this.keys[i]; } if (deep && this.keys[i].subKeys) { - for (var j = 0; j < this.keys[i].subKeys.length; j++) { + for (let j = 0; j < this.keys[i].subKeys.length; j++) { if (keyIdCheck(keyId, this.keys[i].subKeys[j].subKey)) { return this.keys[i]; } @@ -179,12 +178,12 @@ KeyArray.prototype.getForId = function (keyId, deep) { * @return {Array|null} array of error objects or null */ KeyArray.prototype.importKey = function (armored) { - var imported = readArmored(armored); - var that = this; + const imported = readArmored(armored); + const that = this; imported.keys.forEach(async function(key) { // check if key already in key array - var keyidHex = key.primaryKey.getKeyId().toHex(); - var keyFound = that.getForId(keyidHex); + const keyidHex = key.primaryKey.getKeyId().toHex(); + const keyFound = that.getForId(keyidHex); if (keyFound) { await keyFound.update(key); } else { @@ -210,7 +209,7 @@ KeyArray.prototype.push = function (key) { * @return {module:key~Key|null} The key object which has been removed or null */ KeyArray.prototype.removeForId = function (keyId) { - for (var i = 0; i < this.keys.length; i++) { + for (let i = 0; i < this.keys.length; i++) { if (keyIdCheck(keyId, this.keys[i].primaryKey)) { return this.keys.splice(i, 1)[0]; } diff --git a/src/keyring/localstore.js b/src/keyring/localstore.js index 3a6532f8..800d9a7d 100644 --- a/src/keyring/localstore.js +++ b/src/keyring/localstore.js @@ -62,11 +62,11 @@ LocalStore.prototype.loadPrivate = function () { }; function loadKeys(storage, itemname) { - var armoredKeys = JSON.parse(storage.getItem(itemname)); - var keys = []; + const armoredKeys = JSON.parse(storage.getItem(itemname)); + const keys = []; if (armoredKeys !== null && armoredKeys.length !== 0) { - var key; - for (var i = 0; i < armoredKeys.length; i++) { + let key; + for (let i = 0; i < armoredKeys.length; i++) { key = readArmored(armoredKeys[i]); if (!key.err) { keys.push(key.keys[0]); @@ -97,9 +97,9 @@ LocalStore.prototype.storePrivate = function (keys) { }; function storeKeys(storage, itemname, keys) { - var armoredKeys = []; + const armoredKeys = []; if (keys.length) { - for (var i = 0; i < keys.length; i++) { + for (let i = 0; i < keys.length; i++) { armoredKeys.push(keys[i].armor()); } storage.setItem(itemname, JSON.stringify(armoredKeys)); diff --git a/src/message.js b/src/message.js index 1f7002da..e127cd22 100644 --- a/src/message.js +++ b/src/message.js @@ -58,8 +58,8 @@ export function Message(packetlist) { * @return {Array} array of keyid objects */ Message.prototype.getEncryptionKeyIds = function() { - var keyIds = []; - var pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + const keyIds = []; + const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); pkESKeyPacketlist.forEach(function(packet) { keyIds.push(packet.publicKeyId); }); @@ -71,16 +71,16 @@ Message.prototype.getEncryptionKeyIds = function() { * @return {Array} array of keyid objects */ Message.prototype.getSigningKeyIds = function() { - var keyIds = []; - var msg = this.unwrapCompressed(); + const keyIds = []; + const msg = this.unwrapCompressed(); // search for one pass signatures - var onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); + const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); onePassSigList.forEach(function(packet) { keyIds.push(packet.signingKeyId); }); // if nothing found look for signature packets if (!keyIds.length) { - var signatureList = msg.packets.filterByTag(enums.packet.signature); + const signatureList = msg.packets.filterByTag(enums.packet.signature); signatureList.forEach(function(packet) { keyIds.push(packet.issuerKeyId); }); @@ -119,14 +119,13 @@ Message.prototype.decrypt = async function(privateKeys, passwords, sessionKeys) // eslint-disable-next-line no-await-in-loop await symEncryptedPacket.decrypt(keyObjs[i].algorithm, keyObjs[i].data); break; - } - catch(e) { + } catch (e) { exception = e; } } if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) { - throw exception ? exception : new Error('Decryption failed.'); + throw exception || new Error('Decryption failed.'); } const resultMsg = new Message(symEncryptedPacket.packets); @@ -142,10 +141,10 @@ Message.prototype.decrypt = async function(privateKeys, passwords, sessionKeys) * @return {Array<{ data:Uint8Array, algorithm:String }>} array of object with potential sessionKey, algorithm pairs */ Message.prototype.decryptSessionKeys = function(privateKeys, passwords) { - var keyPackets = []; + let keyPackets = []; return Promise.resolve().then(async () => { if (passwords) { - var symESKeyPacketlist = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); + const symESKeyPacketlist = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); if (!symESKeyPacketlist) { throw new Error('No symmetrically encrypted session key packet found.'); } @@ -159,12 +158,12 @@ Message.prototype.decryptSessionKeys = function(privateKeys, passwords) { })); } else if (privateKeys) { - var pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); if (!pkESKeyPacketlist) { throw new Error('No public key encrypted session key packet found.'); } await Promise.all(pkESKeyPacketlist.map(async function(packet) { - var privateKeyPackets = privateKeys.reduce(function(acc, privateKey) { + const privateKeyPackets = privateKeys.reduce(function(acc, privateKey) { return acc.concat(privateKey.getKeyPackets(packet.publicKeyId)); }, []); await Promise.all(privateKeyPackets.map(async function(privateKeyPacket) { @@ -184,26 +183,23 @@ Message.prototype.decryptSessionKeys = function(privateKeys, passwords) { throw new Error('No key or password specified.'); } }).then(() => { - if (keyPackets.length) { - // Return only unique session keys if (keyPackets.length > 1) { - var seen = {}; + const seen = {}; keyPackets = keyPackets.filter(function(item) { - var k = item.sessionKeyAlgorithm + util.Uint8Array2str(item.sessionKey); - if (seen.hasOwnProperty(k)) { - return false; - } - seen[k] = true; - return true; + const k = item.sessionKeyAlgorithm + util.Uint8Array2str(item.sessionKey); + if (seen.hasOwnProperty(k)) { + return false; + } + seen[k] = true; + return true; }); } return keyPackets.map(packet => ({ data: packet.sessionKey, algorithm: packet.sessionKeyAlgorithm })); - } else { - throw new Error('Session key decryption failed.'); } + throw new Error('Session key decryption failed.'); }); }; @@ -212,7 +208,7 @@ Message.prototype.decryptSessionKeys = function(privateKeys, passwords) { * @return {(Uint8Array|null)} literal body of the message as Uint8Array */ Message.prototype.getLiteralData = function() { - var literal = this.packets.findPacket(enums.packet.literal); + const literal = this.packets.findPacket(enums.packet.literal); return (literal && literal.data) || null; }; @@ -221,7 +217,7 @@ Message.prototype.getLiteralData = function() { * @return {(String|null)} filename of literal data packet as string */ Message.prototype.getFilename = function() { - var literal = this.packets.findPacket(enums.packet.literal); + const literal = this.packets.findPacket(enums.packet.literal); return (literal && literal.getFilename()) || null; }; @@ -230,12 +226,11 @@ Message.prototype.getFilename = function() { * @return {(String|null)} literal body of the message interpreted as text */ Message.prototype.getText = function() { - var literal = this.packets.findPacket(enums.packet.literal); + const literal = this.packets.findPacket(enums.packet.literal); if (literal) { return literal.getText(); - } else { - return null; } + return null; }; /** @@ -246,8 +241,10 @@ Message.prototype.getText = function() { * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs * @return {Message} new message with encrypted content */ -Message.prototype.encrypt = function(keys, passwords, sessionKey, wildcard=false) { - let symAlgo, msg, symEncryptedPacket; +Message.prototype.encrypt = function(keys, passwords, sessionKey, wildcard = false) { + let symAlgo; + let msg; + let symEncryptedPacket; return Promise.resolve().then(async () => { if (sessionKey) { if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { @@ -279,7 +276,6 @@ Message.prototype.encrypt = function(keys, passwords, sessionKey, wildcard=false symEncryptedPacket.packets = this.packets; return symEncryptedPacket.encrypt(symAlgo, sessionKey); - }).then(() => { msg.packets.push(symEncryptedPacket); symEncryptedPacket.packets = new packet.List(); // remove packets after encryption @@ -303,17 +299,17 @@ Message.prototype.encrypt = function(keys, passwords, sessionKey, wildcard=false * @return {Message} new message with encrypted content */ export function encryptSessionKey(sessionKey, symAlgo, publicKeys, passwords, wildcard=false) { - var results, packetlist = new packet.List(); + const packetlist = new packet.List(); return Promise.resolve().then(async () => { if (publicKeys) { - results = await Promise.all(publicKeys.map(async function(key) { + const results = await Promise.all(publicKeys.map(async function(key) { await key.verifyPrimaryUser(); - var encryptionKeyPacket = key.getEncryptionKeyPacket(); + const encryptionKeyPacket = key.getEncryptionKeyPacket(); if (!encryptionKeyPacket) { throw new Error('Could not find valid key packet for encryption in key ' + key.primaryKey.getKeyId().toHex()); } - var pkESKeyPacket = new packet.PublicKeyEncryptedSessionKey(); + const pkESKeyPacket = new packet.PublicKeyEncryptedSessionKey(); pkESKeyPacket.publicKeyId = wildcard ? type_keyid.wildcard() : encryptionKeyPacket.getKeyId(); pkESKeyPacket.publicKeyAlgorithm = encryptionKeyPacket.algorithm; pkESKeyPacket.sessionKey = sessionKey; @@ -326,13 +322,11 @@ export function encryptSessionKey(sessionKey, symAlgo, publicKeys, passwords, wi } if (passwords) { - const testDecrypt = async function(keyPacket, password) { try { await keyPacket.decrypt(password); return 1; - } - catch (e) { + } catch (e) { return 0; } }; @@ -340,14 +334,13 @@ export function encryptSessionKey(sessionKey, symAlgo, publicKeys, passwords, wi const sum = (accumulator, currentValue) => accumulator + currentValue; const encryptPassword = async function(sessionKey, symAlgo, password) { - - var symEncryptedSessionKeyPacket = new packet.SymEncryptedSessionKey(); + const symEncryptedSessionKeyPacket = new packet.SymEncryptedSessionKey(); symEncryptedSessionKeyPacket.sessionKey = sessionKey; symEncryptedSessionKeyPacket.sessionKeyAlgorithm = symAlgo; await symEncryptedSessionKeyPacket.encrypt(password); if (config.password_collision_check) { - var results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); + const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); if (results.reduce(sum) !== 1) { return encryptPassword(sessionKey, symAlgo, password); } @@ -357,12 +350,10 @@ export function encryptSessionKey(sessionKey, symAlgo, publicKeys, passwords, wi return symEncryptedSessionKeyPacket; }; - results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symAlgo, pwd))); + const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symAlgo, pwd))); packetlist.concat(results); } - }).then(() => { - return new Message(packetlist); - }); + }).then(() => new Message(packetlist)); } /** @@ -372,24 +363,24 @@ export function encryptSessionKey(sessionKey, symAlgo, publicKeys, passwords, wi * @return {module:message~Message} new message with signed content */ Message.prototype.sign = async function(privateKeys=[], signature=null) { + const packetlist = new packet.List(); - var packetlist = new packet.List(); - - var literalDataPacket = this.packets.findPacket(enums.packet.literal); + const literalDataPacket = this.packets.findPacket(enums.packet.literal); if (!literalDataPacket) { throw new Error('No literal data packet to sign.'); } - var i; - var literalFormat = enums.write(enums.literal, literalDataPacket.format); - var signatureType = literalFormat === enums.literal.binary ? + let i; + let existingSigPacketlist; + const literalFormat = enums.write(enums.literal, literalDataPacket.format); + const signatureType = literalFormat === enums.literal.binary ? enums.signature.binary : enums.signature.text; if (signature) { - var existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); + existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); for (i = existingSigPacketlist.length - 1; i >= 0; i--) { - var signaturePacket = existingSigPacketlist[i]; - var onePassSig = new packet.OnePassSignature(); + const signaturePacket = existingSigPacketlist[i]; + const onePassSig = new packet.OnePassSignature(); onePassSig.type = signatureType; onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; @@ -406,12 +397,12 @@ Message.prototype.sign = async function(privateKeys=[], signature=null) { throw new Error('Need private key for signing'); } await privateKey.verifyPrimaryUser(); - var signingKeyPacket = privateKey.getSigningKeyPacket(); + const signingKeyPacket = privateKey.getSigningKeyPacket(); if (!signingKeyPacket) { throw new Error('Could not find valid key packet for signing in key ' + privateKey.primaryKey.getKeyId().toHex()); } - onePassSig = new packet.OnePassSignature(); + const onePassSig = new packet.OnePassSignature(); onePassSig.type = signatureType; //TODO get preferred hash algo from key signature onePassSig.hashAlgorithm = getPreferredHashAlgo(privateKey); @@ -428,8 +419,8 @@ Message.prototype.sign = async function(privateKeys=[], signature=null) { packetlist.push(literalDataPacket); await Promise.all(privateKeys.map(async function(privateKey) { - var signaturePacket = new packet.Signature(); - var signingKeyPacket = privateKey.getSigningKeyPacket(); + const signaturePacket = new packet.Signature(); + const signingKeyPacket = privateKey.getSigningKeyPacket(); if (!signingKeyPacket.isDecrypted) { throw new Error('Private key is not decrypted.'); } @@ -476,22 +467,21 @@ Message.prototype.compress = function(compression) { * @return {module:signature~Signature} new detached signature of message content */ Message.prototype.signDetached = async function(privateKeys=[], signature=null) { + const packetlist = new packet.List(); - var packetlist = new packet.List(); - - var literalDataPacket = this.packets.findPacket(enums.packet.literal); + const literalDataPacket = this.packets.findPacket(enums.packet.literal); if (!literalDataPacket) { throw new Error('No literal data packet to sign.'); } - var literalFormat = enums.write(enums.literal, literalDataPacket.format); - var signatureType = literalFormat === enums.literal.binary ? + const literalFormat = enums.write(enums.literal, literalDataPacket.format); + const signatureType = literalFormat === enums.literal.binary ? enums.signature.binary : enums.signature.text; await Promise.all(privateKeys.map(async function(privateKey) { - var signaturePacket = new packet.Signature(); + const signaturePacket = new packet.Signature(); await privateKey.verifyPrimaryUser(); - var signingKeyPacket = privateKey.getSigningKeyPacket(); + const signingKeyPacket = privateKey.getSigningKeyPacket(); if (!signingKeyPacket.isDecrypted) { throw new Error('Private key is not decrypted.'); } @@ -505,7 +495,7 @@ Message.prototype.signDetached = async function(privateKeys=[], signature=null) }); if (signature) { - var existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); + const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); packetlist.concat(existingSigPacketlist); } @@ -519,12 +509,12 @@ Message.prototype.signDetached = async function(privateKeys=[], signature=null) * @return {Array<({keyid: module:type/keyid, valid: Boolean})>} list of signer's keyid and validity of signature */ Message.prototype.verify = function(keys) { - var msg = this.unwrapCompressed(); - var literalDataList = msg.packets.filterByTag(enums.packet.literal); + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literal); if (literalDataList.length !== 1) { throw new Error('Can only verify message with one literal data packet.'); } - var signatureList = msg.packets.filterByTag(enums.packet.signature); + const signatureList = msg.packets.filterByTag(enums.packet.signature); return createVerificationObjects(signatureList, literalDataList, keys); }; @@ -535,12 +525,12 @@ Message.prototype.verify = function(keys) { * @return {Array<({keyid: module:type/keyid, valid: Boolean})>} list of signer's keyid and validity of signature */ Message.prototype.verifyDetached = function(signature, keys) { - var msg = this.unwrapCompressed(); - var literalDataList = msg.packets.filterByTag(enums.packet.literal); + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literal); if (literalDataList.length !== 1) { throw new Error('Can only verify message with one literal data packet.'); } - var signatureList = signature.packets; + const signatureList = signature.packets; return createVerificationObjects(signatureList, literalDataList, keys); }; @@ -553,23 +543,23 @@ Message.prototype.verifyDetached = function(signature, keys) { */ async function createVerificationObjects(signatureList, literalDataList, keys) { return Promise.all(signatureList.map(async function(signature) { - var keyPacket = null; + let keyPacket = null; await Promise.all(keys.map(async function(key) { await key.verifyPrimaryUser(); // Look for the unique key packet that matches issuerKeyId of signature - var result = key.getSigningKeyPacket(signature.issuerKeyId, config.verify_expired_keys); + const result = key.getSigningKeyPacket(signature.issuerKeyId, config.verify_expired_keys); if (result) { keyPacket = result; } })); // Look for the unique key packet that matches issuerKeyId of signature - var verifiedSig = { + const verifiedSig = { keyid: signature.issuerKeyId, valid: keyPacket ? await signature.verify(keyPacket, literalDataList[0]) : null }; - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.push(signature); verifiedSig.signature = new Signature(packetlist); @@ -582,12 +572,11 @@ async function createVerificationObjects(signatureList, literalDataList, keys) { * @return {module:message~Message} message Content of compressed message */ Message.prototype.unwrapCompressed = function() { - var compressed = this.packets.filterByTag(enums.packet.compressed); + const compressed = this.packets.filterByTag(enums.packet.compressed); if (compressed.length) { return new Message(compressed[0].packets); - } else { - return this; } + return this; }; /** @@ -607,7 +596,7 @@ Message.prototype.armor = function() { export function readArmored(armoredText) { //TODO how do we want to handle bad text? Exception throwing //TODO don't accept non-message armored texts - var input = armor.decode(armoredText).data; + const input = armor.decode(armoredText).data; return read(input); } @@ -618,7 +607,7 @@ export function readArmored(armoredText) { * @static */ export function read(input) { - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.read(input); return new Message(packetlist); } @@ -629,11 +618,11 @@ export function read(input) { * @param {String} detachedSignature The detached ascii armored PGP signature */ export function readSignedContent(content, detachedSignature) { - var literalDataPacket = new packet.Literal(); + const literalDataPacket = new packet.Literal(); literalDataPacket.setBytes(util.str2Uint8Array(content), enums.read(enums.literal, enums.literal.binary)); - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.push(literalDataPacket); - var input = armor.decode(detachedSignature).data; + const input = armor.decode(detachedSignature).data; packetlist.read(input); return new Message(packetlist); } @@ -646,13 +635,13 @@ export function readSignedContent(content, detachedSignature) { * @static */ export function fromText(text, filename) { - var literalDataPacket = new packet.Literal(); + const literalDataPacket = new packet.Literal(); // text will be converted to UTF8 literalDataPacket.setText(text); if (filename !== undefined) { literalDataPacket.setFilename(filename); } - var literalDataPacketlist = new packet.List(); + const literalDataPacketlist = new packet.List(); literalDataPacketlist.push(literalDataPacket); return new Message(literalDataPacketlist); } @@ -669,7 +658,7 @@ export function fromBinary(bytes, filename) { throw new Error('Data must be in the form of a Uint8Array'); } - var literalDataPacket = new packet.Literal(); + const literalDataPacket = new packet.Literal(); if (filename) { literalDataPacket.setFilename(filename); } @@ -677,7 +666,7 @@ export function fromBinary(bytes, filename) { if (filename !== undefined) { literalDataPacket.setFilename(filename); } - var literalDataPacketlist = new packet.List(); + const literalDataPacketlist = new packet.List(); literalDataPacketlist.push(literalDataPacket); return new Message(literalDataPacketlist); } diff --git a/src/openpgp.js b/src/openpgp.js index a82fc255..193434ce 100644 --- a/src/openpgp.js +++ b/src/openpgp.js @@ -101,9 +101,13 @@ export function destroyWorker() { * @static */ -export function generateKey({ userIds=[], passphrase, numBits=2048, unlocked=false, keyExpirationTime=0, curve="" } = {}) { +export function generateKey({ + userIds=[], passphrase, numBits=2048, unlocked=false, keyExpirationTime=0, curve="" +} = {}) { userIds = formatUserIds(userIds); - const options = {userIds, passphrase, numBits, unlocked, keyExpirationTime, curve}; + const options = { + userIds, passphrase, numBits, unlocked, keyExpirationTime, curve + }; if (util.getWebCryptoAll() && numBits < 2048) { throw new Error('numBits should be 2048 or 4096, found: ' + numBits); @@ -133,10 +137,14 @@ export function generateKey({ userIds=[], passphrase, numBits=2048, unlocked=fal * { key:Key, privateKeyArmored:String, publicKeyArmored:String } * @static */ -export function reformatKey({ privateKey, userIds=[], passphrase="", unlocked=false, keyExpirationTime=0 } = {}) { +export function reformatKey({ + privateKey, userIds=[], passphrase="", unlocked=false, keyExpirationTime=0 +} = {}) { userIds = formatUserIds(userIds); - const options = {privateKey, userIds, passphrase, unlocked, keyExpirationTime}; + const options = { + privateKey, userIds, passphrase, unlocked, keyExpirationTime + }; if (asyncProxy) { return asyncProxy.delegate('reformatKey', options); @@ -163,13 +171,11 @@ export function decryptKey({ privateKey, passphrase }) { } return Promise.resolve().then(async function() { - await privateKey.decrypt(passphrase); return { key: privateKey }; - }).catch(onError.bind(null, 'Error decrypting private key')); } @@ -201,22 +207,21 @@ export function decryptKey({ privateKey, passphrase }) { * message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true} * @static */ -export function encrypt({ data, publicKeys, privateKeys, passwords, sessionKey, filename, compression=config.compression, armor=true, detached=false, signature=null, returnSessionKey=false, wildcard=false}) { +export function encrypt({ data, publicKeys, privateKeys, passwords, sessionKey, filename, compression = config.compression, armor = true, detached = false, signature = null, returnSessionKey = false, wildcard = false}) { checkData(data); publicKeys = toArray(publicKeys); privateKeys = toArray(privateKeys); passwords = toArray(passwords); if (!nativeAEAD() && asyncProxy) { // use web worker if web crypto apis are not supported return asyncProxy.delegate('encrypt', { data, publicKeys, privateKeys, passwords, sessionKey, filename, armor, detached, signature, returnSessionKey, wildcard }); } - var result = {}; + const result = {}; return Promise.resolve().then(async function() { - let message = createMessage(data, filename); if (!privateKeys) { privateKeys = []; } if (privateKeys.length || signature) { // sign the message only if private keys or signature is specified if (detached) { - var detachedSignature = await message.signDetached(privateKeys, signature); + const detachedSignature = await message.signDetached(privateKeys, signature); result.signature = armor ? detachedSignature.armor() : detachedSignature; } else { message = await message.sign(privateKeys, signature); @@ -235,7 +240,6 @@ export function encrypt({ data, publicKeys, privateKeys, passwords, sessionKey, result.sessionKey = encrypted.sessionKey; } return result; - }).catch(onError.bind(null, 'Error encrypting message')); } @@ -270,7 +274,6 @@ export function decrypt({ message, privateKeys, passwords, sessionKeys, publicKe result.signatures = signature ? await message.verifyDetached(signature, publicKeys) : await message.verify(publicKeys); return result; - }).catch(onError.bind(null, 'Error decrypting message')); } @@ -293,20 +296,24 @@ export function decrypt({ message, privateKeys, passwords, sessionKeys, publicKe * message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true} * @static */ -export function sign({ data, privateKeys, armor=true, detached=false}) { +export function sign({ + data, privateKeys, armor=true, detached=false +}) { checkData(data); privateKeys = toArray(privateKeys); if (asyncProxy) { // use web worker if available - return asyncProxy.delegate('sign', { data, privateKeys, armor, detached }); + return asyncProxy.delegate('sign', { + data, privateKeys, armor, detached + }); } - var result = {}; + const result = {}; return Promise.resolve().then(async function() { - var message = util.isString(data) ? new CleartextMessage(data) : messageLib.fromBinary(data); + let message = util.isString(data) ? new CleartextMessage(data) : messageLib.fromBinary(data); if (detached) { - var signature = await message.signDetached(privateKeys); + const signature = await message.signDetached(privateKeys); result.signature = armor ? signature.armor() : signature; } else { message = await message.sign(privateKeys); @@ -317,7 +324,6 @@ export function sign({ data, privateKeys, armor=true, detached=false}) { } } return result; - }).catch(onError.bind(null, 'Error signing cleartext message')); } @@ -339,12 +345,10 @@ export function verify({ message, publicKeys, signature=null }) { } return Promise.resolve().then(async function() { - - var result = {}; + const result = {}; result.data = CleartextMessage.prototype.isPrototypeOf(message) ? message.getText() : message.getLiteralData(); result.signatures = signature ? await message.verifyDetached(signature, publicKeys) : await message.verify(publicKeys); return result; - }).catch(onError.bind(null, 'Error verifying cleartext signed message')); } @@ -520,9 +524,8 @@ function parseMessage(message, format) { data: message.getText(), filename: message.getFilename() }; - } else { - throw new Error('Invalid format'); } + throw new Error('Invalid format'); } /** diff --git a/src/packet/all_packets.js b/src/packet/all_packets.js index e16c41c9..ebdc1077 100644 --- a/src/packet/all_packets.js +++ b/src/packet/all_packets.js @@ -57,9 +57,9 @@ export function newPacketFromTag(tag) { * @returns {Object} new packet object with data from packet clone */ export function fromStructuredClone(packetClone) { - var tagName = enums.read(enums.packet, packetClone.tag); - var packet = newPacketFromTag(tagName); - for (var attr in packetClone) { + const tagName = enums.read(enums.packet, packetClone.tag); + const packet = newPacketFromTag(tagName); + for (const attr in packetClone) { if (packetClone.hasOwnProperty(attr)) { packet[attr] = packetClone[attr]; } diff --git a/src/packet/clone.js b/src/packet/clone.js index 8cd3f56e..ff120950 100644 --- a/src/packet/clone.js +++ b/src/packet/clone.js @@ -24,7 +24,7 @@ import { Key } from '../key'; import { Message } from '../message'; import { CleartextMessage } from '../cleartext'; -import { Signature } from '../signature' +import { Signature } from '../signature'; import Packetlist from './packetlist'; import type_keyid from '../type/keyid'; import util from '../util'; @@ -43,13 +43,13 @@ import util from '../util'; * @return {Object} a mutated version of the options optject */ export function clonePackets(options) { - if(options.publicKeys) { + if (options.publicKeys) { options.publicKeys = options.publicKeys.map(key => key.toPacketlist()); } - if(options.privateKeys) { + if (options.privateKeys) { options.privateKeys = options.privateKeys.map(key => key.toPacketlist()); } - if(options.privateKey) { + if (options.privateKey) { options.privateKey = options.privateKey.toPacketlist(); } if (options.key) { @@ -90,14 +90,14 @@ function verificationObjectToClone(verObject) { * @param {String} method the public api function name to be delegated to the worker * @return {Object} a mutated version of the options optject */ -export function parseClonedPackets(options, method) { - if(options.publicKeys) { +export function parseClonedPackets(options) { + if (options.publicKeys) { options.publicKeys = options.publicKeys.map(packetlistCloneToKey); } - if(options.privateKeys) { + if (options.privateKeys) { options.privateKeys = options.privateKeys.map(packetlistCloneToKey); } - if(options.privateKey) { + if (options.privateKey) { options.privateKey = packetlistCloneToKey(options.privateKey); } if (options.key) { @@ -128,7 +128,7 @@ function packetlistCloneToMessage(clone) { } function packetlistCloneToCleartextMessage(clone) { - var packetlist = Packetlist.fromStructuredClone(clone.signature); + const packetlist = Packetlist.fromStructuredClone(clone.signature); return new CleartextMessage(clone.text, new Signature(packetlist)); } @@ -144,6 +144,6 @@ function packetlistCloneToSignature(clone) { //signature is armored return clone; } - var packetlist = Packetlist.fromStructuredClone(clone); + const packetlist = Packetlist.fromStructuredClone(clone); return new Signature(packetlist); } diff --git a/src/packet/compressed.js b/src/packet/compressed.js index 991b7c97..b7c7af41 100644 --- a/src/packet/compressed.js +++ b/src/packet/compressed.js @@ -95,7 +95,8 @@ Compressed.prototype.write = function () { * read by read_packet */ Compressed.prototype.decompress = function () { - var decompressed, inflate; + let decompressed; + let inflate; switch (this.algorithm) { case 'uncompressed': @@ -127,11 +128,10 @@ Compressed.prototype.decompress = function () { * Compress the packet data (member decompressedData) */ Compressed.prototype.compress = function () { - var uncompressed, deflate; - uncompressed = this.packets.write(); + let deflate; + const uncompressed = this.packets.write(); switch (this.algorithm) { - case 'uncompressed': // - Uncompressed this.compressed = uncompressed; diff --git a/src/packet/index.js b/src/packet/index.js index 81fedb82..5531d316 100644 --- a/src/packet/index.js +++ b/src/packet/index.js @@ -9,7 +9,7 @@ const mod = { clone: clone }; -for (let i in packets) { +for (const i in packets) { mod[i] = packets[i]; } diff --git a/src/packet/literal.js b/src/packet/literal.js index 4d6c29d8..73838812 100644 --- a/src/packet/literal.js +++ b/src/packet/literal.js @@ -58,7 +58,7 @@ Literal.prototype.setText = function(text) { */ Literal.prototype.getText = function() { // decode UTF8 - var text = util.decode_utf8(util.Uint8Array2str(this.data)); + const text = util.decode_utf8(util.Uint8Array2str(this.data)); // normalize EOL to \n return text.replace(/\r\n/g, '\n'); }; @@ -109,14 +109,14 @@ Literal.prototype.getFilename = function() { */ Literal.prototype.read = function(bytes) { // - A one-octet field that describes how the data is formatted. - var format = enums.read(enums.literal, bytes[0]); + const format = enums.read(enums.literal, bytes[0]); - var filename_len = bytes[1]; + const filename_len = bytes[1]; this.filename = util.decode_utf8(util.Uint8Array2str(bytes.subarray(2, 2 + filename_len))); this.date = util.readDate(bytes.subarray(2 + filename_len, 2 + filename_len + 4)); - var data = bytes.subarray(6 + filename_len, bytes.length); + const data = bytes.subarray(6 + filename_len, bytes.length); this.setBytes(data, format); }; @@ -127,12 +127,12 @@ Literal.prototype.read = function(bytes) { * @return {Uint8Array} Uint8Array representation of the packet */ Literal.prototype.write = function() { - var filename = util.str2Uint8Array(util.encode_utf8(this.filename)); - var filename_length = new Uint8Array([filename.length]); + const filename = util.str2Uint8Array(util.encode_utf8(this.filename)); + const filename_length = new Uint8Array([filename.length]); - var format = new Uint8Array([enums.write(enums.literal, this.format)]); - var date = util.writeDate(this.date); - var data = this.getBytes(); + const format = new Uint8Array([enums.write(enums.literal, this.format)]); + const date = util.writeDate(this.date); + const data = this.getBytes(); return util.concatUint8Array([format, filename_length, filename, date, data]); }; diff --git a/src/packet/one_pass_signature.js b/src/packet/one_pass_signature.js index fa7fd2bd..b3dc74f6 100644 --- a/src/packet/one_pass_signature.js +++ b/src/packet/one_pass_signature.js @@ -52,7 +52,7 @@ export default function OnePassSignature() { * @return {module:packet/one_pass_signature} object representation */ OnePassSignature.prototype.read = function (bytes) { - var mypos = 0; + let mypos = 0; // A one-octet version number. The current version is 3. this.version = bytes[mypos++]; @@ -84,12 +84,11 @@ OnePassSignature.prototype.read = function (bytes) { * @return {Uint8Array} a Uint8Array representation of a one-pass signature packet */ OnePassSignature.prototype.write = function () { - - var start = new Uint8Array([3, enums.write(enums.signature, this.type), + const start = new Uint8Array([3, enums.write(enums.signature, this.type), enums.write(enums.hash, this.hashAlgorithm), enums.write(enums.publicKey, this.publicKeyAlgorithm)]); - var end = new Uint8Array([this.flags]); + const end = new Uint8Array([this.flags]); return util.concatUint8Array([start, this.signingKeyId.write(), end]); }; diff --git a/src/packet/packet.js b/src/packet/packet.js index 7accc016..cf226ae1 100644 --- a/src/packet/packet.js +++ b/src/packet/packet.js @@ -25,13 +25,13 @@ import util from '../util.js'; export default { readSimpleLength: function(bytes) { - var len = 0, - offset, - type = bytes[0]; + let len = 0; + let offset; + const type = bytes[0]; if (type < 192) { - len = bytes[0]; + [len] = bytes; offset = 1; } else if (type < 255) { len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; @@ -55,7 +55,6 @@ export default { * @return {Uint8Array} String with openpgp length representation */ writeSimpleLength: function(length) { - if (length < 192) { return new Uint8Array([length]); } else if (length > 191 && length < 8384) { @@ -64,9 +63,8 @@ export default { * representation of a let d = b + 192 */ return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); - } else { - return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); } + return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); }, /** @@ -91,14 +89,12 @@ export default { * @return {String} String of the header */ writeOldHeader: function(tag_type, length) { - if (length < 256) { return new Uint8Array([0x80 | (tag_type << 2), length]); } else if (length < 65536) { return util.concatUint8Array([new Uint8Array([0x80 | (tag_type << 2) | 1]), util.writeNumber(length, 2)]); - } else { - return util.concatUint8Array([new Uint8Array([0x80 | (tag_type << 2) | 2]), util.writeNumber(length, 4)]); } + return util.concatUint8Array([new Uint8Array([0x80 | (tag_type << 2) | 2]), util.writeNumber(length, 4)]); }, /** @@ -115,17 +111,17 @@ export default { 0x80) === 0) { throw new Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format."); } - var mypos = position; - var tag = -1; - var format = -1; - var packet_length; + let mypos = position; + let tag = -1; + let format = -1; + let packet_length; format = 0; // 0 = old format; 1 = new format if ((input[mypos] & 0x40) !== 0) { format = 1; } - var packet_length_type; + let packet_length_type; if (format) { // new format header tag = input[mypos] & 0x3F; // bit 5-0 @@ -139,10 +135,10 @@ export default { mypos++; // parsed length from length field - var bodydata = null; + let bodydata = null; // used for partial body lengths - var real_packet_length = -1; + let real_packet_length = -1; if (!format) { // 4.2.1. Old Format Packet Lengths switch (packet_length_type) { @@ -176,10 +172,7 @@ export default { packet_length = len; break; } - - } else // 4.2.2. New Format Packet Lengths - { - + } else { // 4.2.2. New Format Packet Lengths // 4.2.2.1. One-Octet Lengths if (input[mypos] < 192) { packet_length = input[mypos++]; @@ -193,9 +186,9 @@ export default { packet_length = 1 << (input[mypos++] & 0x1F); util.print_debug("4 byte length:" + packet_length); // EEEK, we're reading the full data here... - var mypos2 = mypos + packet_length; + let mypos2 = mypos + packet_length; bodydata = [input.subarray(mypos, mypos + packet_length)]; - var tmplen; + let tmplen; while (true) { if (input[mypos2] < 192) { tmplen = input[mypos2++]; @@ -240,8 +233,7 @@ export default { if (bodydata === null) { bodydata = input.subarray(mypos, mypos + real_packet_length); - } - else if(bodydata instanceof Array) { + } else if (bodydata instanceof Array) { bodydata = util.concatUint8Array(bodydata); } diff --git a/src/packet/packetlist.js b/src/packet/packetlist.js index 63aff6e7..41946213 100644 --- a/src/packet/packetlist.js +++ b/src/packet/packetlist.js @@ -30,20 +30,20 @@ export default function Packetlist() { * @param {Uint8Array} A Uint8Array of bytes. */ Packetlist.prototype.read = function (bytes) { - var i = 0; + let i = 0; while (i < bytes.length) { - var parsed = packetParser.read(bytes, i, bytes.length - i); + const parsed = packetParser.read(bytes, i, bytes.length - i); i = parsed.offset; - var pushed = false; + let pushed = false; try { - var tag = enums.read(enums.packet, parsed.tag); - var packet = packets.newPacketFromTag(tag); + const tag = enums.read(enums.packet, parsed.tag); + const packet = packets.newPacketFromTag(tag); this.push(packet); pushed = true; packet.read(parsed.packet); - } catch(e) { + } catch (e) { if (!config.tolerant || parsed.tag === enums.packet.symmetricallyEncrypted || parsed.tag === enums.packet.literal || @@ -63,10 +63,10 @@ Packetlist.prototype.read = function (bytes) { * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. */ Packetlist.prototype.write = function () { - var arr = []; + const arr = []; - for (var i = 0; i < this.length; i++) { - var packetbytes = this[i].write(); + for (let i = 0; i < this.length; i++) { + const packetbytes = this[i].write(); arr.push(packetParser.writeHeader(this[i].tag, packetbytes.length)); arr.push(packetbytes); } @@ -98,7 +98,7 @@ Packetlist.prototype.pop = function() { return; } - var packet = this[this.length - 1]; + const packet = this[this.length - 1]; delete this[this.length - 1]; this.length--; @@ -109,10 +109,9 @@ Packetlist.prototype.pop = function() { * Creates a new PacketList with all packets that pass the test implemented by the provided function. */ Packetlist.prototype.filter = function (callback) { + const filtered = new Packetlist(); - var filtered = new Packetlist(); - - for (var i = 0; i < this.length; i++) { + for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { filtered.push(this[i]); } @@ -124,14 +123,14 @@ Packetlist.prototype.filter = function (callback) { /** * Creates a new PacketList with all packets from the given types */ -Packetlist.prototype.filterByTag = function () { - var args = Array.prototype.slice.call(arguments); - var filtered = new Packetlist(); - var that = this; +Packetlist.prototype.filterByTag = function (...args) { + const filtered = new Packetlist(); + const that = this; - function handle(packetType) { return that[i].tag === packetType; } - for (var i = 0; i < this.length; i++) { - if (args.some(handle)) { + const handle = tag => packetType => tag === packetType; + + for (let i = 0; i < this.length; i++) { + if (args.some(handle(that[i].tag))) { filtered.push(this[i]); } } @@ -143,7 +142,7 @@ Packetlist.prototype.filterByTag = function () { * Executes the provided callback once for each element */ Packetlist.prototype.forEach = function (callback) { - for (var i = 0; i < this.length; i++) { + for (let i = 0; i < this.length; i++) { callback(this[i], i, this); } }; @@ -153,9 +152,9 @@ Packetlist.prototype.forEach = function (callback) { * on each element */ Packetlist.prototype.map = function (callback) { - var packetArray = []; + const packetArray = []; - for (var i = 0; i < this.length; i++) { + for (let i = 0; i < this.length; i++) { packetArray.push(callback(this[i], i, this)); } @@ -167,7 +166,7 @@ Packetlist.prototype.map = function (callback) { * until it finds one where callback returns a truthy value */ Packetlist.prototype.some = async function (callback) { - for (var i = 0; i < this.length; i++) { + for (let i = 0; i < this.length; i++) { // eslint-disable-next-line no-await-in-loop if (await callback(this[i], i, this)) { return true; @@ -182,34 +181,34 @@ Packetlist.prototype.some = async function (callback) { * @return {module:packet/packet|null} */ Packetlist.prototype.findPacket = function (type) { - var packetlist = this.filterByTag(type); + const packetlist = this.filterByTag(type); if (packetlist.length) { return packetlist[0]; - } else { - var found = null; - for (var i = 0; i < this.length; i++) { - if (this[i].packets.length) { - found = this[i].packets.findPacket(type); - if (found) { - return found; - } + } + let found = null; + for (let i = 0; i < this.length; i++) { + if (this[i].packets.length) { + found = this[i].packets.findPacket(type); + if (found) { + return found; } } } + return null; }; /** * Returns array of found indices by tag */ -Packetlist.prototype.indexOfTag = function () { - var args = Array.prototype.slice.call(arguments); - var tagIndex = []; - var that = this; +Packetlist.prototype.indexOfTag = function (...args) { + const tagIndex = []; + const that = this; - function handle(packetType) { return that[i].tag === packetType; } - for (var i = 0; i < this.length; i++) { - if (args.some(handle)) { + const handle = tag => packetType => tag === packetType; + + for (let i = 0; i < this.length; i++) { + if (args.some(handle(that[i].tag))) { tagIndex.push(i); } } @@ -223,8 +222,8 @@ Packetlist.prototype.slice = function (begin, end) { if (!end) { end = this.length; } - var part = new Packetlist(); - for (var i = begin; i < end; i++) { + const part = new Packetlist(); + for (let i = begin; i < end; i++) { part.push(this[i]); } return part; @@ -235,7 +234,7 @@ Packetlist.prototype.slice = function (begin, end) { */ Packetlist.prototype.concat = function (packetlist) { if (packetlist) { - for (var i = 0; i < packetlist.length; i++) { + for (let i = 0; i < packetlist.length; i++) { this.push(packetlist[i]); } } @@ -248,8 +247,8 @@ Packetlist.prototype.concat = function (packetlist) { * @returns {Object} new packetlist object with data from packetlist clone */ Packetlist.fromStructuredClone = function(packetlistClone) { - var packetlist = new Packetlist(); - for (var i = 0; i < packetlistClone.length; i++) { + const packetlist = new Packetlist(); + for (let i = 0; i < packetlistClone.length; i++) { packetlist.push(packets.fromStructuredClone(packetlistClone[i])); if (packetlist[i].packets.length !== 0) { packetlist[i].packets = this.fromStructuredClone(packetlist[i].packets); diff --git a/src/packet/public_key.js b/src/packet/public_key.js index 5e15edcf..246c5e95 100644 --- a/src/packet/public_key.js +++ b/src/packet/public_key.js @@ -66,7 +66,7 @@ export default function PublicKey() { * @return {Object} This object with attributes set by the parser */ PublicKey.prototype.read = function (bytes) { - var pos = 0; + let pos = 0; // A one-octet version number (3 or 4). this.version = bytes[pos++]; @@ -85,13 +85,13 @@ PublicKey.prototype.read = function (bytes) { // - A one-octet number denoting the public-key algorithm of this key. this.algorithm = enums.read(enums.publicKey, bytes[pos++]); - var types = crypto.getPubKeyParamTypes(this.algorithm); + const types = crypto.getPubKeyParamTypes(this.algorithm); this.params = crypto.constructParams(types); - var b = bytes.subarray(pos, bytes.length); - var p = 0; + const b = bytes.subarray(pos, bytes.length); + let p = 0; - for (var i = 0; i < types.length && p < b.length; i++) { + for (let i = 0; i < types.length && p < b.length; i++) { p += this.params[i].read(b.subarray(p, b.length)); if (p > b.length) { throw new Error('Error reading MPI @:' + p); @@ -99,9 +99,8 @@ PublicKey.prototype.read = function (bytes) { } return p + 6; - } else { - throw new Error('Version ' + this.version + ' of the key packet is unsupported.'); } + throw new Error('Version ' + this.version + ' of the key packet is unsupported.'); }; /** @@ -116,8 +115,7 @@ PublicKey.prototype.readPublicKey = PublicKey.prototype.read; * @return {Uint8Array} OpenPGP packet body contents, */ PublicKey.prototype.write = function () { - - var arr = []; + const arr = []; // Version arr.push(new Uint8Array([this.version])); arr.push(util.writeDate(this.created)); @@ -126,9 +124,9 @@ PublicKey.prototype.write = function () { } arr.push(new Uint8Array([enums.write(enums.publicKey, this.algorithm)])); - var paramCount = crypto.getPubKeyParamTypes(this.algorithm).length; + const paramCount = crypto.getPubKeyParamTypes(this.algorithm).length; - for (var i = 0; i < paramCount; i++) { + for (let i = 0; i < paramCount; i++) { arr.push(this.params[i].write()); } @@ -145,7 +143,7 @@ PublicKey.prototype.writePublicKey = PublicKey.prototype.write; * Write an old version packet - it's used by some of the internal routines. */ PublicKey.prototype.writeOld = function () { - var bytes = this.writePublicKey(); + const bytes = this.writePublicKey(); return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]); }; @@ -162,7 +160,7 @@ PublicKey.prototype.getKeyId = function () { if (this.version === 4) { this.keyid.read(util.str2Uint8Array(util.hex2bin(this.getFingerprint()).substr(12, 8))); } else if (this.version === 3) { - var arr = this.params[0].write(); + const arr = this.params[0].write(); this.keyid.read(arr.subarray(arr.length - 8, arr.length)); } return this.keyid; @@ -176,13 +174,13 @@ PublicKey.prototype.getFingerprint = function () { if (this.fingerprint) { return this.fingerprint; } - var toHash = ''; + let toHash = ''; if (this.version === 4) { toHash = this.writeOld(); this.fingerprint = util.Uint8Array2str(crypto.hash.sha1(toHash)); } else if (this.version === 3) { - var paramCount = crypto.getPubKeyParamTypes(this.algorithm).length; - for (var i = 0; i < paramCount; i++) { + const paramCount = crypto.getPubKeyParamTypes(this.algorithm).length; + for (let i = 0; i < paramCount; i++) { toHash += this.params[i].toBytes(); } this.fingerprint = util.Uint8Array2str(crypto.hash.md5(util.str2Uint8Array(toHash))); @@ -204,7 +202,7 @@ PublicKey.prototype.getBitSize = function () { */ PublicKey.prototype.postCloneTypeFix = function() { const types = crypto.getPubKeyParamTypes(this.algorithm); - for (var i = 0; i < types.length; i++) { + for (let i = 0; i < types.length; i++) { const param = this.params[i]; this.params[i] = types[i].fromClone(param); } diff --git a/src/packet/public_key_encrypted_session_key.js b/src/packet/public_key_encrypted_session_key.js index e6eebc9e..2a109974 100644 --- a/src/packet/public_key_encrypted_session_key.js +++ b/src/packet/public_key_encrypted_session_key.js @@ -69,17 +69,16 @@ export default function PublicKeyEncryptedSessionKey() { * @return {module:packet/public_key_encrypted_session_key} Object representation */ PublicKeyEncryptedSessionKey.prototype.read = function (bytes) { - this.version = bytes[0]; - this.publicKeyId.read(bytes.subarray(1,bytes.length)); + this.publicKeyId.read(bytes.subarray(1, bytes.length)); this.publicKeyAlgorithm = enums.read(enums.publicKey, bytes[9]); - var i = 10; + let i = 10; - var types = crypto.getEncSessionKeyParamTypes(this.publicKeyAlgorithm); + const types = crypto.getEncSessionKeyParamTypes(this.publicKeyAlgorithm); this.encrypted = crypto.constructParams(types); - for (var j = 0; j < types.length; j++) { + for (let j = 0; j < types.length; j++) { i += this.encrypted[j].read(bytes.subarray(i, bytes.length)); } }; @@ -90,10 +89,9 @@ PublicKeyEncryptedSessionKey.prototype.read = function (bytes) { * @return {Uint8Array} The Uint8Array representation */ PublicKeyEncryptedSessionKey.prototype.write = function () { + const arr = [new Uint8Array([this.version]), this.publicKeyId.write(), new Uint8Array([enums.write(enums.publicKey, this.publicKeyAlgorithm)])]; - var arr = [new Uint8Array([this.version]), this.publicKeyId.write(), new Uint8Array([enums.write(enums.publicKey, this.publicKeyAlgorithm)])]; - - for (var i = 0; i < this.encrypted.length; i++) { + for (let i = 0; i < this.encrypted.length; i++) { arr.push(this.encrypted[i].write()); } @@ -101,14 +99,13 @@ PublicKeyEncryptedSessionKey.prototype.write = function () { }; PublicKeyEncryptedSessionKey.prototype.encrypt = async function (key) { - var data = String.fromCharCode( - enums.write(enums.symmetric, this.sessionKeyAlgorithm)); + let data = String.fromCharCode(enums.write(enums.symmetric, this.sessionKeyAlgorithm)); data += util.Uint8Array2str(this.sessionKey); - var checksum = util.calc_checksum(this.sessionKey); + const checksum = util.calc_checksum(this.sessionKey); data += util.Uint8Array2str(util.writeNumber(checksum, 2)); - var toEncrypt; + let toEncrypt; if (this.publicKeyAlgorithm === 'ecdh') { toEncrypt = new type_mpi(crypto.pkcs5.encode(data)); } else { @@ -119,7 +116,8 @@ PublicKeyEncryptedSessionKey.prototype.encrypt = async function (key) { this.publicKeyAlgorithm, key.params, toEncrypt, - key.fingerprint); + key.fingerprint + ); }; /** @@ -131,14 +129,15 @@ PublicKeyEncryptedSessionKey.prototype.encrypt = async function (key) { * @return {String} The unencrypted session key */ PublicKeyEncryptedSessionKey.prototype.decrypt = async function (key) { - var result = (await crypto.publicKeyDecrypt( + const result = (await crypto.publicKeyDecrypt( this.publicKeyAlgorithm, key.params, this.encrypted, - key.fingerprint)).toBytes(); + key.fingerprint + )).toBytes(); - var checksum; - var decoded; + let checksum; + let decoded; if (this.publicKeyAlgorithm === 'ecdh') { decoded = crypto.pkcs5.decode(result); checksum = util.readNumber(util.str2Uint8Array(decoded.substr(decoded.length - 2))); @@ -162,8 +161,8 @@ PublicKeyEncryptedSessionKey.prototype.decrypt = async function (key) { */ PublicKeyEncryptedSessionKey.prototype.postCloneTypeFix = function() { this.publicKeyId = type_keyid.fromClone(this.publicKeyId); - var types = crypto.getEncSessionKeyParamTypes(this.publicKeyAlgorithm); - for (var i = 0; i < this.encrypted.length; i++) { + const types = crypto.getEncSessionKeyParamTypes(this.publicKeyAlgorithm); + for (let i = 0; i < this.encrypted.length; i++) { this.encrypted[i] = types[i].fromClone(this.encrypted[i]); } }; diff --git a/src/packet/secret_key.js b/src/packet/secret_key.js index f21880f4..1323d8eb 100644 --- a/src/packet/secret_key.js +++ b/src/packet/secret_key.js @@ -57,40 +57,38 @@ SecretKey.prototype.constructor = SecretKey; function get_hash_len(hash) { if (hash === 'sha1') { return 20; - } else { - return 2; } + return 2; } function get_hash_fn(hash) { if (hash === 'sha1') { return crypto.hash.sha1; - } else { - return function(c) { - return util.writeNumber(util.calc_checksum(c), 2); - }; } + return function(c) { + return util.writeNumber(util.calc_checksum(c), 2); + }; } // Helper function function parse_cleartext_params(hash_algorithm, cleartext, algorithm) { - var hashlen = get_hash_len(hash_algorithm), - hashfn = get_hash_fn(hash_algorithm); + const hashlen = get_hash_len(hash_algorithm); + const hashfn = get_hash_fn(hash_algorithm); - var hashtext = util.Uint8Array2str(cleartext.subarray(cleartext.length - hashlen, cleartext.length)); + const hashtext = util.Uint8Array2str(cleartext.subarray(cleartext.length - hashlen, cleartext.length)); cleartext = cleartext.subarray(0, cleartext.length - hashlen); - var hash = util.Uint8Array2str(hashfn(cleartext)); + const hash = util.Uint8Array2str(hashfn(cleartext)); if (hash !== hashtext) { return new Error("Hash mismatch."); } - var types = crypto.getPrivKeyParamTypes(algorithm); - var params = crypto.constructParams(types); - var p = 0; + const types = crypto.getPrivKeyParamTypes(algorithm); + const params = crypto.constructParams(types); + let p = 0; - for (var i = 0; i < types.length && p < cleartext.length; i++) { + for (let i = 0; i < types.length && p < cleartext.length; i++) { p += params[i].read(cleartext.subarray(p, cleartext.length)); if (p > cleartext.length) { throw new Error('Error reading param @:' + p); @@ -101,16 +99,16 @@ function parse_cleartext_params(hash_algorithm, cleartext, algorithm) { } function write_cleartext_params(hash_algorithm, algorithm, params) { - var arr = []; - var numPublicParams = crypto.getPubKeyParamTypes(algorithm).length; + const arr = []; + const numPublicParams = crypto.getPubKeyParamTypes(algorithm).length; - for (var i = numPublicParams; i < params.length; i++) { + for (let i = numPublicParams; i < params.length; i++) { arr.push(params[i].write()); } - var bytes = util.concatUint8Array(arr); + const bytes = util.concatUint8Array(arr); - var hash = get_hash_fn(hash_algorithm)(bytes); + const hash = get_hash_fn(hash_algorithm)(bytes); return util.concatUint8Array([bytes, hash]); } @@ -124,7 +122,7 @@ function write_cleartext_params(hash_algorithm, algorithm, params) { */ SecretKey.prototype.read = function (bytes) { // - A Public-Key or Public-Subkey packet, as described above. - var len = this.readPublicKey(bytes); + const len = this.readPublicKey(bytes); bytes = bytes.subarray(len, bytes.length); @@ -133,7 +131,7 @@ SecretKey.prototype.read = function (bytes) { // indicates that the secret-key data is not encrypted. 255 or 254 // indicates that a string-to-key specifier is being given. Any // other value is a symmetric-key encryption algorithm identifier. - var isEncrypted = bytes[0]; + const isEncrypted = bytes[0]; if (isEncrypted) { this.encrypted = bytes; @@ -141,21 +139,20 @@ SecretKey.prototype.read = function (bytes) { // - Plain or encrypted multiprecision integers comprising the secret // key data. These algorithm-specific fields are as described // below. - var privParams = parse_cleartext_params('mod', bytes.subarray(1, bytes.length), this.algorithm); + const privParams = parse_cleartext_params('mod', bytes.subarray(1, bytes.length), this.algorithm); if (privParams instanceof Error) { throw privParams; } this.params = this.params.concat(privParams); this.isDecrypted = true; } - }; /** Creates an OpenPGP key packet for the given key. * @return {String} A string of bytes containing the secret key OpenPGP packet */ SecretKey.prototype.write = function () { - var arr = [this.writePublicKey()]; + const arr = [this.writePublicKey()]; if (!this.encrypted) { arr.push(new Uint8Array([0])); @@ -182,14 +179,14 @@ SecretKey.prototype.encrypt = function (passphrase) { throw new Error('The key must be decrypted before removing passphrase protection.'); } - var s2k = new type_s2k(), - symmetric = 'aes256', - cleartext = write_cleartext_params('sha1', this.algorithm, this.params), - key = produceEncryptionKey(s2k, passphrase, symmetric), - blockLen = crypto.cipher[symmetric].blockSize, - iv = crypto.random.getRandomBytes(blockLen); + const s2k = new type_s2k(); + const symmetric = 'aes256'; + const cleartext = write_cleartext_params('sha1', this.algorithm, this.params); + const key = produceEncryptionKey(s2k, passphrase, symmetric); + const blockLen = crypto.cipher[symmetric].blockSize; + const iv = crypto.random.getRandomBytes(blockLen); - var arr = [new Uint8Array([254, enums.write(enums.symmetric, symmetric)])]; + const arr = [new Uint8Array([254, enums.write(enums.symmetric, symmetric)])]; arr.push(s2k.write()); arr.push(iv); arr.push(crypto.cfb.normalEncrypt(symmetric, key, cleartext, iv)); @@ -198,8 +195,10 @@ SecretKey.prototype.encrypt = function (passphrase) { }; function produceEncryptionKey(s2k, passphrase, algorithm) { - return s2k.produce_key(passphrase, - crypto.cipher[algorithm].keySize); + return s2k.produce_key( + passphrase, + crypto.cipher[algorithm].keySize + ); } /** @@ -217,11 +216,11 @@ SecretKey.prototype.decrypt = function (passphrase) { return true; } - var i = 0, - symmetric, - key; + let i = 0; + let symmetric; + let key; - var s2k_usage = this.encrypted[i++]; + const s2k_usage = this.encrypted[i++]; // - [Optional] If string-to-key usage octet was 255 or 254, a one- // octet symmetric encryption algorithm. @@ -232,7 +231,7 @@ SecretKey.prototype.decrypt = function (passphrase) { // - [Optional] If string-to-key usage octet was 255 or 254, a // string-to-key specifier. The length of the string-to-key // specifier is implied by its type, as described above. - var s2k = new type_s2k(); + const s2k = new type_s2k(); i += s2k.read(this.encrypted.subarray(i, this.encrypted.length)); key = produceEncryptionKey(s2k, passphrase, symmetric); @@ -245,21 +244,20 @@ SecretKey.prototype.decrypt = function (passphrase) { // - [Optional] If secret data is encrypted (string-to-key usage octet // not zero), an Initial Vector (IV) of the same length as the // cipher's block size. - var iv = this.encrypted.subarray(i, - i + crypto.cipher[symmetric].blockSize); + const iv = this.encrypted.subarray( + i, + i + crypto.cipher[symmetric].blockSize + ); i += iv.length; - var cleartext, - ciphertext = this.encrypted.subarray(i, this.encrypted.length); - - cleartext = crypto.cfb.normalDecrypt(symmetric, key, ciphertext, iv); - - var hash = s2k_usage === 254 ? + const ciphertext = this.encrypted.subarray(i, this.encrypted.length); + const cleartext = crypto.cfb.normalDecrypt(symmetric, key, ciphertext, iv); + const hash = s2k_usage === 254 ? 'sha1' : 'mod'; - var privParams = parse_cleartext_params(hash, cleartext, this.algorithm); + const privParams = parse_cleartext_params(hash, cleartext, this.algorithm); if (privParams instanceof Error) { return false; } @@ -270,7 +268,7 @@ SecretKey.prototype.decrypt = function (passphrase) { }; SecretKey.prototype.generate = function (bits, curve) { - var that = this; + const that = this; return crypto.generateParams(that.algorithm, bits, curve).then(function(params) { that.params = params; @@ -292,9 +290,9 @@ SecretKey.prototype.clearPrivateParams = function () { /** * Fix custom types after cloning */ - SecretKey.prototype.postCloneTypeFix = function() { +SecretKey.prototype.postCloneTypeFix = function() { const types = crypto.getPubKeyParamTypes(this.algorithm).concat(crypto.getPrivKeyParamTypes(this.algorithm)); - for (var i = 0; i < this.params.length; i++) { + for (let i = 0; i < this.params.length; i++) { const param = this.params[i]; this.params[i] = types[i].fromClone(param); } diff --git a/src/packet/signature.js b/src/packet/signature.js index 0bbbc47b..803a4f5f 100644 --- a/src/packet/signature.js +++ b/src/packet/signature.js @@ -95,20 +95,18 @@ export default function Signature() { * @return {module:packet/signature} object representation */ Signature.prototype.read = function (bytes) { - var i = 0; + let i = 0; this.version = bytes[i++]; function subpackets(bytes) { // Two-octet scalar octet count for following subpacket data. - var subpacket_length = util.readNumber( - bytes.subarray(0, 2)); + const subpacket_length = util.readNumber(bytes.subarray(0, 2)); - var i = 2; + let i = 2; // subpacket data set (zero or more subpackets) while (i < 2 + subpacket_length) { - - var len = packet.readSimpleLength(bytes.subarray(i, bytes.length)); + const len = packet.readSimpleLength(bytes.subarray(i, bytes.length)); i += len.offset; this.read_sub_packet(bytes.subarray(i, i + len.len)); @@ -121,7 +119,7 @@ Signature.prototype.read = function (bytes) { // switch on version (3 and 4) switch (this.version) { - case 3: + case 3: { // One-octet length of following hashed material. MUST be 5. if (bytes[i++] !== 5) { util.print_debug("packet/signature.js\n" + @@ -129,7 +127,7 @@ Signature.prototype.read = function (bytes) { 'MUST be 5. @:' + (i - 1)); } - var sigpos = i; + const sigpos = i; // One-octet signature type. this.signatureType = bytes[i++]; @@ -150,7 +148,8 @@ Signature.prototype.read = function (bytes) { // One-octet hash algorithm. this.hashAlgorithm = bytes[i++]; break; - case 4: + } + case 4: { this.signatureType = bytes[i++]; this.publicKeyAlgorithm = bytes[i++]; this.hashAlgorithm = bytes[i++]; @@ -165,13 +164,14 @@ Signature.prototype.read = function (bytes) { // hash algorithm, the hashed subpacket length, and the hashed // subpacket body. this.signatureData = bytes.subarray(0, i); - var sigDataLength = i; + const sigDataLength = i; // unhashed subpackets i += subpackets.call(this, bytes.subarray(i, bytes.length), false); this.unhashedSubpackets = bytes.subarray(sigDataLength, i); break; + } default: throw new Error('Version ' + this.version + ' of the signature is unsupported.'); } @@ -184,7 +184,7 @@ Signature.prototype.read = function (bytes) { }; Signature.prototype.write = function () { - var arr = []; + const arr = []; switch (this.version) { case 3: arr.push(new Uint8Array([3, 5])); // version, One-octet length of following hashed material. MUST be 5 @@ -212,11 +212,11 @@ Signature.prototype.write = function () { * @param {Object} data Contains packets to be signed. */ Signature.prototype.sign = async function (key, data) { - var signatureType = enums.write(enums.signature, this.signatureType), - publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm), - hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm); + const signatureType = enums.write(enums.signature, this.signatureType); + const publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm); + const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm); - var arr = [new Uint8Array([4, signatureType, publicKeyAlgorithm, hashAlgorithm])]; + const arr = [new Uint8Array([4, signatureType, publicKeyAlgorithm, hashAlgorithm])]; this.issuerKeyId = key.getKeyId(); @@ -225,9 +225,9 @@ Signature.prototype.sign = async function (key, data) { this.signatureData = util.concatUint8Array(arr); - var trailer = this.calculateTrailer(); + const trailer = this.calculateTrailer(); - var toHash = null; + let toHash = null; switch (this.version) { case 3: @@ -239,12 +239,14 @@ Signature.prototype.sign = async function (key, data) { default: throw new Error('Version ' + this.version + ' of the signature is unsupported.'); } - var hash = crypto.hash.digest(hashAlgorithm, toHash); + const hash = crypto.hash.digest(hashAlgorithm, toHash); this.signedHashValue = hash.subarray(0, 2); - this.signature = await crypto.signature.sign(hashAlgorithm, - publicKeyAlgorithm, key.params, toHash); + this.signature = await crypto.signature.sign( + hashAlgorithm, + publicKeyAlgorithm, key.params, toHash + ); }; /** @@ -252,9 +254,9 @@ Signature.prototype.sign = async function (key, data) { * @return {String} a string-representation of a all subpacket data */ Signature.prototype.write_all_sub_packets = function () { - var sub = enums.signatureSubpacket; - var arr = []; - var bytes; + const sub = enums.signatureSubpacket; + const arr = []; + let bytes; if (this.created !== null) { arr.push(write_sub_packet(sub.signature_creation_time, util.writeDate(this.created))); } @@ -265,7 +267,7 @@ Signature.prototype.write_all_sub_packets = function () { arr.push(write_sub_packet(sub.exportable_certification, new Uint8Array([this.exportable ? 1 : 0]))); } if (this.trustLevel !== null) { - bytes = new Uint8Array([this.trustLevel,this.trustAmount]); + bytes = new Uint8Array([this.trustLevel, this.trustAmount]); arr.push(write_sub_packet(sub.trust_signature, bytes)); } if (this.regularExpression !== null) { @@ -282,7 +284,6 @@ Signature.prototype.write_all_sub_packets = function () { arr.push(write_sub_packet(sub.preferred_symmetric_algorithms, bytes)); } if (this.revocationKeyClass !== null) { - bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); bytes = util.concatUint8Array([bytes, this.revocationKeyFingerprint]); arr.push(write_sub_packet(sub.revocation_key, bytes)); @@ -291,9 +292,9 @@ Signature.prototype.write_all_sub_packets = function () { arr.push(write_sub_packet(sub.issuer, this.issuerKeyId.write())); } if (this.notation !== null) { - for (var name in this.notation) { + for (const name in this.notation) { if (this.notation.hasOwnProperty(name)) { - var value = this.notation[name]; + const value = this.notation[name]; bytes = [new Uint8Array([0x80, 0, 0, 0])]; // 2 octets of name length bytes.push(util.writeNumber(name.length, 2)); @@ -351,8 +352,8 @@ Signature.prototype.write_all_sub_packets = function () { arr.push(write_sub_packet(sub.embedded_signature, this.embeddedSignature.write())); } - var result = util.concatUint8Array(arr); - var length = util.writeNumber(result.length, 2); + const result = util.concatUint8Array(arr); + const length = util.writeNumber(result.length, 2); return util.concatUint8Array([length, result]); }; @@ -365,7 +366,7 @@ Signature.prototype.write_all_sub_packets = function () { * @return {String} a string-representation of a sub signature packet (See {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC 4880 5.2.3.1}) */ function write_sub_packet(type, data) { - var arr = []; + const arr = []; arr.push(packet.writeSimpleLength(data.length + 1)); arr.push(new Uint8Array([type])); arr.push(data); @@ -375,19 +376,19 @@ function write_sub_packet(type, data) { // V4 signature sub packets Signature.prototype.read_sub_packet = function (bytes) { - var mypos = 0; + let mypos = 0; function read_array(prop, bytes) { this[prop] = []; - for (var i = 0; i < bytes.length; i++) { + for (let i = 0; i < bytes.length; i++) { this[prop].push(bytes[i]); } } // The leftwost bit denotes a "critical" packet, but we ignore it. - var type = bytes[mypos++] & 0x7F; - var seconds; + const type = bytes[mypos++] & 0x7F; + let seconds; // subpacket type switch (type) { @@ -451,16 +452,15 @@ Signature.prototype.read_sub_packet = function (bytes) { // Notation Data // We don't know how to handle anything but a text flagged data. if (bytes[mypos] === 0x80) { - // We extract key/value tuple from the byte stream. mypos += 4; - var m = util.readNumber(bytes.subarray(mypos, mypos + 2)); + const m = util.readNumber(bytes.subarray(mypos, mypos + 2)); mypos += 2; - var n = util.readNumber(bytes.subarray(mypos, mypos + 2)); + const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); mypos += 2; - var name = util.Uint8Array2str(bytes.subarray(mypos, mypos + m)), - value = util.Uint8Array2str(bytes.subarray(mypos + m, mypos + m + n)); + const name = util.Uint8Array2str(bytes.subarray(mypos, mypos + m)); + const value = util.Uint8Array2str(bytes.subarray(mypos + m, mypos + m + n)); this.notation = this.notation || {}; this.notation[name] = value; @@ -509,16 +509,17 @@ Signature.prototype.read_sub_packet = function (bytes) { // Features read_array.call(this, 'features', bytes.subarray(mypos, bytes.length)); break; - case 31: + case 31: { // Signature Target // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; this.signatureTargetHashAlgorithm = bytes[mypos++]; - var len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm); + const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm); this.signatureTargetHash = util.Uint8Array2str(bytes.subarray(mypos, mypos + len)); break; + } case 32: // Embedded Signature this.embeddedSignature = new Signature(); @@ -531,7 +532,7 @@ Signature.prototype.read_sub_packet = function (bytes) { // Produces data to produce signature on Signature.prototype.toSign = function (type, data) { - var t = enums.signature; + const t = enums.signature; switch (type) { case t.binary: @@ -545,8 +546,9 @@ Signature.prototype.toSign = function (type, data) { case t.cert_persona: case t.cert_casual: case t.cert_positive: - case t.cert_revocation: - var packet, tag; + case t.cert_revocation: { + let packet; + let tag; if (data.userid !== undefined) { tag = 0xB4; @@ -559,7 +561,7 @@ Signature.prototype.toSign = function (type, data) { 'supplied for certification.'); } - var bytes = packet.write(); + const bytes = packet.write(); if (this.version === 4) { return util.concatUint8Array([this.toSign(t.key, data), @@ -571,11 +573,11 @@ Signature.prototype.toSign = function (type, data) { bytes]); } break; - + } case t.subkey_binding: case t.subkey_revocation: case t.key_binding: - return util.concatUint8Array([this.toSign(t.key, data),this.toSign(t.key, { + return util.concatUint8Array([this.toSign(t.key, data), this.toSign(t.key, { key: data.bind })]); @@ -603,7 +605,7 @@ Signature.prototype.calculateTrailer = function () { if (this.version === 3) { return new Uint8Array(0); } - var first = new Uint8Array([4, 0xFF]); //Version, ? + const first = new Uint8Array([4, 0xFF]); //Version, ? return util.concatUint8Array([first, util.writeNumber(this.signatureData.length, 4)]); }; @@ -616,42 +618,43 @@ Signature.prototype.calculateTrailer = function () { * @return {boolean} True if message is verified, else false. */ Signature.prototype.verify = async function (key, data) { - var signatureType = enums.write(enums.signature, this.signatureType), - publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm), - hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm); + const signatureType = enums.write(enums.signature, this.signatureType); + const publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm); + const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm); - var bytes = this.toSign(signatureType, data), - trailer = this.calculateTrailer(); + const bytes = this.toSign(signatureType, data); + const trailer = this.calculateTrailer(); - - var mpicount = 0; + let mpicount = 0; // Algorithm-Specific Fields for RSA signatures: // - multiprecision number (MPI) of RSA signature value m**d mod n. if (publicKeyAlgorithm > 0 && publicKeyAlgorithm < 4) { mpicount = 1; - } + // Algorithm-Specific Fields for DSA, ECDSA, and EdDSA signatures: // - MPI of DSA value r. // - MPI of DSA value s. - else if (publicKeyAlgorithm === enums.publicKey.dsa || + } else if (publicKeyAlgorithm === enums.publicKey.dsa || publicKeyAlgorithm === enums.publicKey.ecdsa || publicKeyAlgorithm === enums.publicKey.eddsa) { mpicount = 2; } - // EdDSA signature parameters are encoded in litte-endian format + // EdDSA signature parameters are encoded in little-endian format // https://tools.ietf.org/html/rfc8032#section-5.1.2 - var endian = publicKeyAlgorithm === enums.publicKey.eddsa ? 'le' : 'be'; - var mpi = [], - i = 0; - for (var j = 0; j < mpicount; j++) { + const endian = publicKeyAlgorithm === enums.publicKey.eddsa ? 'le' : 'be'; + const mpi = []; + let i = 0; + for (let j = 0; j < mpicount; j++) { mpi[j] = new type_mpi(); i += mpi[j].read(this.signature.subarray(i, this.signature.length), endian); } - this.verified = await crypto.signature.verify(publicKeyAlgorithm, + this.verified = await crypto.signature.verify( + publicKeyAlgorithm, hashAlgorithm, mpi, key.params, - util.concatUint8Array([bytes, this.signatureData, trailer])); + util.concatUint8Array([bytes, this.signatureData, trailer]) + ); return this.verified; }; diff --git a/src/packet/sym_encrypted_integrity_protected.js b/src/packet/sym_encrypted_integrity_protected.js index c236b44d..dfddfaa2 100644 --- a/src/packet/sym_encrypted_integrity_protected.js +++ b/src/packet/sym_encrypted_integrity_protected.js @@ -93,7 +93,7 @@ SymEncryptedIntegrityProtected.prototype.encrypt = function (sessionKeyAlgorithm const hash = crypto.hash.sha1(util.concatUint8Array([prefix, tohash])); tohash = util.concatUint8Array([tohash, hash]); - if(sessionKeyAlgorithm.substr(0,3) === 'aes') { // AES optimizations. Native code for node, asmCrypto for browser. + if (sessionKeyAlgorithm.substr(0, 3) === 'aes') { // AES optimizations. Native code for node, asmCrypto for browser. this.encrypted = aesEncrypt(sessionKeyAlgorithm, prefix, tohash, key); } else { this.encrypted = crypto.cfb.encrypt(prefixrandom, sessionKeyAlgorithm, tohash, key, false); @@ -111,7 +111,7 @@ SymEncryptedIntegrityProtected.prototype.encrypt = function (sessionKeyAlgorithm */ SymEncryptedIntegrityProtected.prototype.decrypt = function (sessionKeyAlgorithm, key) { let decrypted; - if(sessionKeyAlgorithm.substr(0,3) === 'aes') { // AES optimizations. Native code for node, asmCrypto for browser. + if (sessionKeyAlgorithm.substr(0, 3) === 'aes') { // AES optimizations. Native code for node, asmCrypto for browser. decrypted = aesDecrypt(sessionKeyAlgorithm, this.encrypted, key); } else { decrypted = crypto.cfb.decrypt(sessionKeyAlgorithm, key, this.encrypted, false); @@ -143,16 +143,15 @@ SymEncryptedIntegrityProtected.prototype.decrypt = function (sessionKeyAlgorithm function aesEncrypt(algo, prefix, pt, key) { - if(nodeCrypto) { // Node crypto library. + if (nodeCrypto) { // Node crypto library. return nodeEncrypt(algo, prefix, pt, key); - } else { // asm.js fallback - return asmCrypto.AES_CFB.encrypt(util.concatUint8Array([prefix, pt]), key); - } + } // asm.js fallback + return asmCrypto.AES_CFB.encrypt(util.concatUint8Array([prefix, pt]), key); } function aesDecrypt(algo, ct, key) { let pt; - if(nodeCrypto) { // Node crypto library. + if (nodeCrypto) { // Node crypto library. pt = nodeDecrypt(algo, ct, key); } else { // asm.js fallback pt = asmCrypto.AES_CFB.decrypt(ct, key); @@ -163,7 +162,7 @@ function aesDecrypt(algo, ct, key) { function nodeEncrypt(algo, prefix, pt, key) { key = new Buffer(key); const iv = new Buffer(new Uint8Array(crypto.cipher[algo].blockSize)); - const cipherObj = new nodeCrypto.createCipheriv('aes-' + algo.substr(3,3) + '-cfb', key, iv); + const cipherObj = new nodeCrypto.createCipheriv('aes-' + algo.substr(3, 3) + '-cfb', key, iv); const ct = cipherObj.update(new Buffer(util.concatUint8Array([prefix, pt]))); return new Uint8Array(ct); } @@ -172,7 +171,7 @@ function nodeDecrypt(algo, ct, key) { ct = new Buffer(ct); key = new Buffer(key); const iv = new Buffer(new Uint8Array(crypto.cipher[algo].blockSize)); - const decipherObj = new nodeCrypto.createDecipheriv('aes-' + algo.substr(3,3) + '-cfb', key, iv); + const decipherObj = new nodeCrypto.createDecipheriv('aes-' + algo.substr(3, 3) + '-cfb', key, iv); const pt = decipherObj.update(ct); return new Uint8Array(pt); } diff --git a/src/packet/sym_encrypted_session_key.js b/src/packet/sym_encrypted_session_key.js index f7603af0..3ef36fde 100644 --- a/src/packet/sym_encrypted_session_key.js +++ b/src/packet/sym_encrypted_session_key.js @@ -66,17 +66,17 @@ export default function SymEncryptedSessionKey() { */ SymEncryptedSessionKey.prototype.read = function(bytes) { // A one-octet version number. The only currently defined version is 4. - this.version = bytes[0]; + [this.version] = bytes; // A one-octet number describing the symmetric algorithm used. - var algo = enums.read(enums.symmetric, bytes[1]); + const algo = enums.read(enums.symmetric, bytes[1]); // A string-to-key (S2K) specifier, length as defined above. - var s2klength = this.s2k.read(bytes.subarray(2, bytes.length)); + const s2klength = this.s2k.read(bytes.subarray(2, bytes.length)); // Optionally, the encrypted session key itself, which is decrypted // with the string-to-key object. - var done = s2klength + 2; + const done = s2klength + 2; if (done < bytes.length) { this.encrypted = bytes.subarray(done, bytes.length); @@ -87,11 +87,11 @@ SymEncryptedSessionKey.prototype.read = function(bytes) { }; SymEncryptedSessionKey.prototype.write = function() { - var algo = this.encrypted === null ? + const algo = this.encrypted === null ? this.sessionKeyAlgorithm : this.sessionKeyEncryptionAlgorithm; - var bytes = util.concatUint8Array([new Uint8Array([this.version, enums.write(enums.symmetric, algo)]), this.s2k.write()]); + let bytes = util.concatUint8Array([new Uint8Array([this.version, enums.write(enums.symmetric, algo)]), this.s2k.write()]); if (this.encrypted !== null) { bytes = util.concatUint8Array([bytes, this.encrypted]); @@ -106,42 +106,39 @@ SymEncryptedSessionKey.prototype.write = function() { * @return {Uint8Array} The unencrypted session key */ SymEncryptedSessionKey.prototype.decrypt = function(passphrase) { - var algo = this.sessionKeyEncryptionAlgorithm !== null ? + const algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; - var length = crypto.cipher[algo].keySize; - var key = this.s2k.produce_key(passphrase, length); + const length = crypto.cipher[algo].keySize; + const key = this.s2k.produce_key(passphrase, length); if (this.encrypted === null) { this.sessionKey = key; - } else { - var decrypted = crypto.cfb.normalDecrypt( - algo, key, this.encrypted, null); + const decrypted = crypto.cfb.normalDecrypt(algo, key, this.encrypted, null); this.sessionKeyAlgorithm = enums.read(enums.symmetric, decrypted[0]); - this.sessionKey = decrypted.subarray(1,decrypted.length); + this.sessionKey = decrypted.subarray(1, decrypted.length); } }; SymEncryptedSessionKey.prototype.encrypt = function(passphrase) { - var algo = this.sessionKeyEncryptionAlgorithm !== null ? + const algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; this.sessionKeyEncryptionAlgorithm = algo; - var length = crypto.cipher[algo].keySize; - var key = this.s2k.produce_key(passphrase, length); + const length = crypto.cipher[algo].keySize; + const key = this.s2k.produce_key(passphrase, length); - var algo_enum = new Uint8Array([enums.write(enums.symmetric, this.sessionKeyAlgorithm)]); + const algo_enum = new Uint8Array([enums.write(enums.symmetric, this.sessionKeyAlgorithm)]); - var private_key; - if(this.sessionKey === null) { + if (this.sessionKey === null) { this.sessionKey = crypto.getRandomBytes(crypto.cipher[this.sessionKeyAlgorithm].keySize); } - private_key = util.concatUint8Array([algo_enum, this.sessionKey]); + const private_key = util.concatUint8Array([algo_enum, this.sessionKey]); this.encrypted = crypto.cfb.normalEncrypt(algo, key, private_key, null); }; diff --git a/src/packet/symmetrically_encrypted.js b/src/packet/symmetrically_encrypted.js index c1f6a356..cb3efbb6 100644 --- a/src/packet/symmetrically_encrypted.js +++ b/src/packet/symmetrically_encrypted.js @@ -62,7 +62,7 @@ SymmetricallyEncrypted.prototype.write = function () { * algorithm */ SymmetricallyEncrypted.prototype.decrypt = function (sessionKeyAlgorithm, key) { - var decrypted = crypto.cfb.decrypt(sessionKeyAlgorithm, key, this.encrypted, true); + const decrypted = crypto.cfb.decrypt(sessionKeyAlgorithm, key, this.encrypted, true); // for modern cipher (blocklength != 64 bit, except for Twofish) MDC is required if (!this.ignore_mdc_error && (sessionKeyAlgorithm === 'aes128' || @@ -76,7 +76,7 @@ SymmetricallyEncrypted.prototype.decrypt = function (sessionKeyAlgorithm, key) { }; SymmetricallyEncrypted.prototype.encrypt = function (algo, key) { - var data = this.packets.write(); + const data = this.packets.write(); this.encrypted = crypto.cfb.encrypt(crypto.getPrefixRandom(algo), algo, data, key, true); diff --git a/src/packet/user_attribute.js b/src/packet/user_attribute.js index efd57f99..d671153f 100644 --- a/src/packet/user_attribute.js +++ b/src/packet/user_attribute.js @@ -53,9 +53,9 @@ export default function UserAttribute() { * @param {Uint8Array} input payload of a tag 17 packet */ UserAttribute.prototype.read = function(bytes) { - var i = 0; + let i = 0; while (i < bytes.length) { - var len = packet.readSimpleLength(bytes.subarray(i, bytes.length)); + const len = packet.readSimpleLength(bytes.subarray(i, bytes.length)); i += len.offset; this.attributes.push(util.Uint8Array2str(bytes.subarray(i, i + len.len))); @@ -68,8 +68,8 @@ UserAttribute.prototype.read = function(bytes) { * @return {Uint8Array} string representation */ UserAttribute.prototype.write = function() { - var arr = []; - for (var i = 0; i < this.attributes.length; i++) { + const arr = []; + for (let i = 0; i < this.attributes.length; i++) { arr.push(packet.writeSimpleLength(this.attributes[i].length)); arr.push(util.str2Uint8Array(this.attributes[i])); } diff --git a/src/signature.js b/src/signature.js index 368809b6..81f916f2 100644 --- a/src/signature.js +++ b/src/signature.js @@ -57,7 +57,7 @@ Signature.prototype.armor = function() { * @static */ export function readArmored(armoredText) { - var input = armor.decode(armoredText).data; + const input = armor.decode(armoredText).data; return read(input); } @@ -68,7 +68,7 @@ export function readArmored(armoredText) { * @static */ export function read(input) { - var packetlist = new packet.List(); + const packetlist = new packet.List(); packetlist.read(input); return new Signature(packetlist); } diff --git a/src/type/ecdh_symkey.js b/src/type/ecdh_symkey.js index ced69679..ec38430d 100644 --- a/src/type/ecdh_symkey.js +++ b/src/type/ecdh_symkey.js @@ -46,11 +46,9 @@ function ECDHSymmetricKey(data) { * @return {Number} Number of read bytes */ ECDHSymmetricKey.prototype.read = function (input) { - if (input.length >= 1) - { - var length = input[0]; - if (input.length >= 1+length) - { + if (input.length >= 1) { + const length = input[0]; + if (input.length >= 1+length) { this.data = input.subarray(1, 1+length); return 1+this.data.length; } diff --git a/src/type/keyid.js b/src/type/keyid.js index 9d404324..b256a3bb 100644 --- a/src/type/keyid.js +++ b/src/type/keyid.js @@ -68,19 +68,19 @@ Keyid.mapToHex = function (keyId) { }; Keyid.fromClone = function (clone) { - var keyid = new Keyid(); + const keyid = new Keyid(); keyid.bytes = clone.bytes; return keyid; }; Keyid.fromId = function (hex) { - var keyid = new Keyid(); + const keyid = new Keyid(); keyid.read(util.str2Uint8Array(util.hex2bin(hex))); return keyid; }; Keyid.wildcard = function () { - var keyid = new Keyid(); + const keyid = new Keyid(); keyid.read(new Uint8Array(8)); return keyid; }; diff --git a/src/type/mpi.js b/src/type/mpi.js index d8da6d0f..08d7973d 100644 --- a/src/type/mpi.js +++ b/src/type/mpi.js @@ -58,12 +58,11 @@ export default function MPI(data) { * @return {Integer} Length of data read */ MPI.prototype.read = function (bytes, endian='be') { - - if(util.isString(bytes)) { + if (util.isString(bytes)) { bytes = util.str2Uint8Array(bytes); } - var bits = (bytes[0] << 8) | bytes[1]; + const bits = (bytes[0] << 8) | bytes[1]; // Additional rules: // @@ -75,12 +74,12 @@ MPI.prototype.read = function (bytes, endian='be') { // TODO: Verification of this size method! This size calculation as // specified above is not applicable in JavaScript - var bytelen = Math.ceil(bits / 8); - var payload = bytes.subarray(2, 2 + bytelen); + const bytelen = Math.ceil(bits / 8); + let payload = bytes.subarray(2, 2 + bytelen); if (endian === 'le') { payload = new Uint8Array(payload).reverse(); } - var raw = util.Uint8Array2str(payload); + const raw = util.Uint8Array2str(payload); this.fromBytes(raw); return 2 + bytelen; @@ -91,7 +90,7 @@ MPI.prototype.fromBytes = function (bytes) { }; MPI.prototype.toBytes = function () { - var bytes = util.Uint8Array2str(this.write()); + const bytes = util.Uint8Array2str(this.write()); return bytes.substr(2); }; @@ -117,9 +116,9 @@ MPI.prototype.fromBigInteger = function (bn) { MPI.fromClone = function (clone) { clone.data.copyTo = BigInteger.prototype.copyTo; - var bn = new BigInteger(); + const bn = new BigInteger(); clone.data.copyTo(bn); - var mpi = new MPI(); + const mpi = new MPI(); mpi.data = bn; return mpi; }; diff --git a/src/type/oid.js b/src/type/oid.js index d46f306a..e4ba3e8b 100644 --- a/src/type/oid.js +++ b/src/type/oid.js @@ -48,7 +48,7 @@ function OID(oid) { */ OID.prototype.read = function (input) { if (input.length >= 1) { - var length = input[0]; + const length = input[0]; if (input.length >= 1+length) { this.oid = util.Uint8Array2str(input.subarray(1, 1+length)); return 1+this.oid.length; @@ -62,8 +62,7 @@ OID.prototype.read = function (input) { * @return {Uint8Array} Array with the serialized value the OID */ OID.prototype.write = function () { - return util.str2Uint8Array( - String.fromCharCode(this.oid.length)+this.oid); + return util.str2Uint8Array(String.fromCharCode(this.oid.length)+this.oid); }; /** @@ -75,6 +74,6 @@ OID.prototype.toHex = function() { }; OID.fromClone = function (clone) { - var oid = new OID(clone.oid); + const oid = new OID(clone.oid); return oid; }; diff --git a/src/type/s2k.js b/src/type/s2k.js index bcb8228f..74aa0f60 100644 --- a/src/type/s2k.js +++ b/src/type/s2k.js @@ -50,7 +50,7 @@ export default function S2K() { S2K.prototype.get_count = function () { // Exponent bias, defined in RFC4880 - var expbias = 6; + const expbias = 6; return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); }; @@ -61,7 +61,7 @@ S2K.prototype.get_count = function () { * @return {Integer} Actual length of the object */ S2K.prototype.read = function (bytes) { - var i = 0; + let i = 0; this.type = enums.read(enums.s2k, bytes[i++]); this.algorithm = enums.read(enums.hash, bytes[i++]); @@ -85,7 +85,7 @@ S2K.prototype.read = function (bytes) { case 'gnu': if (util.Uint8Array2str(bytes.subarray(i, 3)) === "GNU") { i += 3; // GNU - var gnuExtType = 1000 + bytes[i++]; + const gnuExtType = 1000 + bytes[i++]; if (gnuExtType === 1001) { this.type = gnuExtType; // GnuPG extension mode 1001 -- don't write secret key at all @@ -110,8 +110,7 @@ S2K.prototype.read = function (bytes) { * @return {Uint8Array} binary representation of s2k */ S2K.prototype.write = function () { - - var arr = [new Uint8Array([enums.write(enums.s2k, this.type), enums.write(enums.hash, this.algorithm)])]; + const arr = [new Uint8Array([enums.write(enums.s2k, this.type), enums.write(enums.hash, this.algorithm)])]; switch (this.type) { case 'simple': @@ -143,20 +142,22 @@ S2K.prototype.produce_key = function (passphrase, numBytes) { passphrase = util.str2Uint8Array(util.encode_utf8(passphrase)); function round(prefix, s2k) { - var algorithm = enums.write(enums.hash, s2k.algorithm); + const algorithm = enums.write(enums.hash, s2k.algorithm); switch (s2k.type) { case 'simple': - return crypto.hash.digest(algorithm, util.concatUint8Array([prefix,passphrase])); + return crypto.hash.digest(algorithm, util.concatUint8Array([prefix, passphrase])); case 'salted': - return crypto.hash.digest(algorithm, - util.concatUint8Array([prefix, s2k.salt, passphrase])); + return crypto.hash.digest( + algorithm, + util.concatUint8Array([prefix, s2k.salt, passphrase]) + ); - case 'iterated': - var count = s2k.get_count(), - data = util.concatUint8Array([s2k.salt,passphrase]), - isp = new Array(Math.ceil(count / data.length)); + case 'iterated': { + const count = s2k.get_count(); + const data = util.concatUint8Array([s2k.salt, passphrase]); + let isp = new Array(Math.ceil(count / data.length)); isp = util.concatUint8Array(isp.fill(data)); @@ -164,8 +165,8 @@ S2K.prototype.produce_key = function (passphrase, numBytes) { isp = isp.subarray(0, count); } - return crypto.hash.digest(algorithm, util.concatUint8Array([prefix,isp])); - + return crypto.hash.digest(algorithm, util.concatUint8Array([prefix, isp])); + } case 'gnu': throw new Error("GNU s2k type not supported."); @@ -174,17 +175,17 @@ S2K.prototype.produce_key = function (passphrase, numBytes) { } } - var arr = [], - rlength = 0, - prefix = new Uint8Array(numBytes); + const arr = []; + let rlength = 0; + const prefix = new Uint8Array(numBytes); - for(var i = 0; i> (8 * (bytes - i - 1))) & 0xFF; } @@ -99,24 +99,24 @@ export default { }, readDate: function (bytes) { - var n = this.readNumber(bytes); - var d = new Date(); + const n = this.readNumber(bytes); + const d = new Date(); d.setTime(n * 1000); return d; }, writeDate: function (time) { - var numeric = Math.round(time.getTime() / 1000); + const numeric = Math.round(time.getTime() / 1000); return this.writeNumber(numeric, 4); }, hexdump: function (str) { - var r = []; - var e = str.length; - var c = 0; - var h; - var i = 0; + const r = []; + const e = str.length; + let c = 0; + let h; + let i = 0; while (c < e) { h = str.charCodeAt(c++).toString(16); while (h.length < 2) { @@ -140,10 +140,10 @@ export default { if (str === null) { return ""; } - var r = []; - var e = str.length; - var c = 0; - var h; + const r = []; + const e = str.length; + let c = 0; + let h; while (c < e) { h = str.charCodeAt(c++).toString(16); while (h.length < 2) { @@ -160,8 +160,8 @@ export default { * @return {String} String containing the binary values */ hex2bin: function (hex) { - var str = ''; - for (var i = 0; i < hex.length; i += 2) { + let str = ''; + for (let i = 0; i < hex.length; i += 2) { str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); } return str; @@ -169,8 +169,8 @@ export default { hex2Uint8Array: function (hex) { - var result = new Uint8Array(hex.length/2); - for (var k=0; k} An array of (binary) integers */ str2bin: function (str) { - var result = []; - for (var i = 0; i < str.length; i++) { + const result = []; + for (let i = 0; i < str.length; i++) { result[i] = str.charCodeAt(i); } return result; @@ -255,12 +255,12 @@ export default { * @return {Uint8Array} The array of (binary) integers */ str2Uint8Array: function (str) { - if(typeof str !== 'string' && !String.prototype.isPrototypeOf(str)) { + if (typeof str !== 'string' && !String.prototype.isPrototypeOf(str)) { throw new Error('str2Uint8Array: Data must be in the form of a string'); } - var result = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { + const result = new Uint8Array(str.length); + for (let i = 0; i < str.length; i++) { result[i] = str.charCodeAt(i); } return result; @@ -274,15 +274,15 @@ export default { * @return {String} String representation of the array */ Uint8Array2str: function (bin) { - if(!Uint8Array.prototype.isPrototypeOf(bin)) { + if (!Uint8Array.prototype.isPrototypeOf(bin)) { throw new Error('Uint8Array2str: Data must be in the form of a Uint8Array'); } - var result = [], - bs = 16384, - j = bin.length; + const result = []; + const bs = 16384; + const j = bin.length; - for (var i = 0; i < j; i += bs) { + for (let i = 0; i < j; i += bs) { result.push(String.fromCharCode.apply(String, bin.subarray(i, i+bs < j ? i+bs : j))); } return result.join(''); @@ -290,8 +290,8 @@ export default { // returns bit length of the integer x nbits: function (x) { - var r = 1, - t = x >>> 16; + let r = 1; + let t = x >>> 16; if (t !== 0) { x = t; r += 16; @@ -326,7 +326,7 @@ export default { * @return {Array} MPI-formatted array */ Uint8Array2MPI: function (bin) { - var size = (bin.length - 1) * 8 + this.nbits(bin[0]); + const size = (bin.length - 1) * 8 + this.nbits(bin[0]); return [(size & 0xFF00) >> 8, size & 0xFF].concat(Array.from(bin)); }, @@ -337,19 +337,19 @@ export default { * @return {Uint8array} Concatenated array */ concatUint8Array: function (arrays) { - var totalLength = 0; + let totalLength = 0; arrays.forEach(function (element) { - if(!Uint8Array.prototype.isPrototypeOf(element)) { + if (!Uint8Array.prototype.isPrototypeOf(element)) { throw new Error('concatUint8Array: Data must be in the form of a Uint8Array'); } totalLength += element.length; }); - var result = new Uint8Array(totalLength); - var pos = 0; + const result = new Uint8Array(totalLength); + let pos = 0; arrays.forEach(function (element) { - result.set(element,pos); + result.set(element, pos); pos += element.length; }); @@ -363,11 +363,11 @@ export default { * @return {Uint8Array} new Uint8Array */ copyUint8Array: function (array) { - if(!Uint8Array.prototype.isPrototypeOf(array)) { + if (!Uint8Array.prototype.isPrototypeOf(array)) { throw new Error('Data must be in the form of a Uint8Array'); } - var copy = new Uint8Array(array.length); + const copy = new Uint8Array(array.length); copy.set(array); return copy; }, @@ -380,16 +380,16 @@ export default { * @return {Boolean} equality */ equalsUint8Array: function (array1, array2) { - if(!Uint8Array.prototype.isPrototypeOf(array1) || !Uint8Array.prototype.isPrototypeOf(array2)) { + if (!Uint8Array.prototype.isPrototypeOf(array1) || !Uint8Array.prototype.isPrototypeOf(array2)) { throw new Error('Data must be in the form of a Uint8Array'); } - if(array1.length !== array2.length) { + if (array1.length !== array2.length) { return false; } - for(var i = 0; i < array1.length; i++) { - if(array1[i] !== array2[i]) { + for (let i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) { return false; } } @@ -404,13 +404,13 @@ export default { * codes % 65535 */ calc_checksum: function (text) { - var checksum = { + const checksum = { s: 0, add: function (sadd) { this.s = (this.s + sadd) % 65536; } }; - for (var i = 0; i < text.length; i++) { + for (let i = 0; i < text.length; i++) { checksum.add(text[i]); } return checksum.s; @@ -437,18 +437,18 @@ export default { */ print_debug_hexstr_dump: function (str, strToHex) { if (config.debug) { - str = str + this.hexstrdump(strToHex); + str += this.hexstrdump(strToHex); console.log(str); } }, getLeftNBits: function (string, bitcount) { - var rest = bitcount % 8; + const rest = bitcount % 8; if (rest === 0) { return string.substring(0, bitcount / 8); } - var bytes = (bitcount - rest) / 8 + 1; - var result = string.substring(0, bytes); + const bytes = (bitcount - rest) / 8 + 1; + const result = string.substring(0, bytes); return this.shiftRight(result, 8 - rest); // +String.fromCharCode(string.charCodeAt(bytes -1) << (8-rest) & 0xFF); }, @@ -460,9 +460,9 @@ export default { * @return {String} Resulting string. */ shiftRight: function (value, bitcount) { - var temp = this.str2bin(value); + const temp = this.str2bin(value); if (bitcount % 8 !== 0) { - for (var i = temp.length - 1; i >= 0; i--) { + for (let i = temp.length - 1; i >= 0; i--) { temp[i] >>= bitcount % 8; if (i > 0) { temp[i] |= (temp[i - 1] << (8 - (bitcount % 8))) & 0xFF; diff --git a/src/worker/async_proxy.js b/src/worker/async_proxy.js index 0453db13..4e68e25c 100644 --- a/src/worker/async_proxy.js +++ b/src/worker/async_proxy.js @@ -19,8 +19,8 @@ import util from '../util.js'; import crypto from '../crypto'; import packet from '../packet'; -const INITIAL_RANDOM_SEED = 50000, // random bytes seeded to worker - RANDOM_SEED_REQUEST = 20000; // random bytes seeded after worker request +const INITIAL_RANDOM_SEED = 50000; // random bytes seeded to worker +const RANDOM_SEED_REQUEST = 20000; // random bytes seeded after worker request /** * Initializes a new proxy and loads the web worker diff --git a/src/worker/worker.js b/src/worker/worker.js index a7850b4a..b0354aac 100644 --- a/src/worker/worker.js +++ b/src/worker/worker.js @@ -16,6 +16,8 @@ // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /* eslint-disable no-restricted-globals */ +/* eslint-disable no-var */ +/* eslint-disable vars-on-top */ self.window = {}; // to make UMD bundles work @@ -86,7 +88,9 @@ function delegate(id, method, options) { // clone packets (for web worker structured cloning algorithm) response({ id:id, event:'method-return', data:openpgp.packet.clone.clonePackets(data) }); }).catch(function(e) { - response({ id:id, event:'method-return', err:e.message, stack:e.stack }); + response({ + id:id, event:'method-return', err:e.message, stack:e.stack + }); }); } @@ -96,7 +100,7 @@ function delegate(id, method, options) { */ function response(event) { if (openpgp.crypto.random.randomBuffer.size < MIN_SIZE_RANDOM_BUFFER) { - self.postMessage({event: 'request-seed'}); + self.postMessage({ event: 'request-seed' }); } self.postMessage(event, openpgp.util.getTransferables(event.data)); } diff --git a/test/crypto/aes_kw.js b/test/crypto/aes_kw.js index 9c6085df..3627da0a 100644 --- a/test/crypto/aes_kw.js +++ b/test/crypto/aes_kw.js @@ -1,9 +1,9 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var expect = require('chai').expect; +const expect = require('chai').expect; describe('AES Key Wrap and Unwrap', function () { - var test_vectors = [ + const test_vectors = [ [ "128 bits of Key Data with a 128-bit KEK", "000102030405060708090A0B0C0D0E0F", @@ -44,11 +44,11 @@ describe('AES Key Wrap and Unwrap', function () { test_vectors.forEach(function(test) { it(test[0], function(done) { - var kek = openpgp.util.hex2Uint8Array(test[1]); - var input = test[2].replace(/\s/g, ""); - var input_bin = openpgp.util.hex2bin(input); - var output = test[3].replace(/\s/g, ""); - var output_bin = openpgp.util.hex2bin(output); + const kek = openpgp.util.hex2Uint8Array(test[1]); + const input = test[2].replace(/\s/g, ""); + const input_bin = openpgp.util.hex2bin(input); + const output = test[3].replace(/\s/g, ""); + const output_bin = openpgp.util.hex2bin(output); expect(openpgp.util.hexidump(openpgp.crypto.aes_kw.wrap(kek, input_bin)).toUpperCase()).to.equal(output); expect(openpgp.util.hexidump(openpgp.crypto.aes_kw.unwrap(kek, output_bin)).toUpperCase()).to.equal(input); done(); diff --git a/test/crypto/cipher/aes.js b/test/crypto/cipher/aes.js index fbc345f7..c7324383 100644 --- a/test/crypto/cipher/aes.js +++ b/test/crypto/cipher/aes.js @@ -1,19 +1,20 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); -var util = openpgp.util, - chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { util } = openpgp; +const { expect } = chai; describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function() { function test_aes(input, key, output) { - var aes = new openpgp.crypto.cipher.aes128(key); + const aes = new openpgp.crypto.cipher.aes128(key); - var result = util.bin2str(aes.encrypt(new Uint8Array(input))); + const result = util.bin2str(aes.encrypt(new Uint8Array(input))); - return util.hexstrdump(result) == util.hexstrdump(util.bin2str(output)); + return util.hexstrdump(result) === util.hexstrdump(util.bin2str(output)); } - var testvectors128 = [[[0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12],[0x50,0x68,0x12,0xA4,0x5F,0x08,0xC8,0x89,0xB9,0x7F,0x59,0x80,0x03,0x8B,0x83,0x59],[0xD8,0xF5,0x32,0x53,0x82,0x89,0xEF,0x7D,0x06,0xB5,0x06,0xA4,0xFD,0x5B,0xE9,0xC9]], + const testvectors128 = [[[0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12],[0x50,0x68,0x12,0xA4,0x5F,0x08,0xC8,0x89,0xB9,0x7F,0x59,0x80,0x03,0x8B,0x83,0x59],[0xD8,0xF5,0x32,0x53,0x82,0x89,0xEF,0x7D,0x06,0xB5,0x06,0xA4,0xFD,0x5B,0xE9,0xC9]], [[0x14,0x15,0x16,0x17,0x19,0x1A,0x1B,0x1C,0x1E,0x1F,0x20,0x21,0x23,0x24,0x25,0x26],[0x5C,0x6D,0x71,0xCA,0x30,0xDE,0x8B,0x8B,0x00,0x54,0x99,0x84,0xD2,0xEC,0x7D,0x4B],[0x59,0xAB,0x30,0xF4,0xD4,0xEE,0x6E,0x4F,0xF9,0x90,0x7E,0xF6,0x5B,0x1F,0xB6,0x8C]], [[0x28,0x29,0x2A,0x2B,0x2D,0x2E,0x2F,0x30,0x32,0x33,0x34,0x35,0x37,0x38,0x39,0x3A],[0x53,0xF3,0xF4,0xC6,0x4F,0x86,0x16,0xE4,0xE7,0xC5,0x61,0x99,0xF4,0x8F,0x21,0xF6],[0xBF,0x1E,0xD2,0xFC,0xB2,0xAF,0x3F,0xD4,0x14,0x43,0xB5,0x6D,0x85,0x02,0x5C,0xB1]], [[0x3C,0x3D,0x3E,0x3F,0x41,0x42,0x43,0x44,0x46,0x47,0x48,0x49,0x4B,0x4C,0x4D,0x4E],[0xA1,0xEB,0x65,0xA3,0x48,0x71,0x65,0xFB,0x0F,0x1C,0x27,0xFF,0x99,0x59,0xF7,0x03],[0x73,0x16,0x63,0x2D,0x5C,0x32,0x23,0x3E,0xDC,0xB0,0x78,0x05,0x60,0xEA,0xE8,0xB2]], @@ -29,7 +30,7 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function [[0x04,0x05,0x06,0x07,0x09,0x0A,0x0B,0x0C,0x0E,0x0F,0x10,0x11,0x13,0x14,0x15,0x16],[0xBC,0xAF,0x32,0x41,0x5E,0x83,0x08,0xB3,0x72,0x3E,0x5F,0xDD,0x85,0x3C,0xCC,0x80],[0x69,0x36,0xF2,0xB9,0x3A,0xF8,0x39,0x7F,0xD3,0xA7,0x71,0xFC,0x01,0x1C,0x8C,0x37]], [[0x2C,0x2D,0x2E,0x2F,0x31,0x32,0x33,0x34,0x36,0x37,0x38,0x39,0x3B,0x3C,0x3D,0x3E],[0x89,0xAF,0xAE,0x68,0x5D,0x80,0x1A,0xD7,0x47,0xAC,0xE9,0x1F,0xC4,0x9A,0xDD,0xE0],[0xF3,0xF9,0x2F,0x7A,0x9C,0x59,0x17,0x9C,0x1F,0xCC,0x2C,0x2B,0xA0,0xB0,0x82,0xCD]]]; - var testvectors192 = [[[0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12,0x14,0x15,0x16,0x17,0x19,0x1A,0x1B,0x1C],[0x2D,0x33,0xEE,0xF2,0xC0,0x43,0x0A,0x8A,0x9E,0xBF,0x45,0xE8,0x09,0xC4,0x0B,0xB6],[0xDF,0xF4,0x94,0x5E,0x03,0x36,0xDF,0x4C,0x1C,0x56,0xBC,0x70,0x0E,0xFF,0x83,0x7F]], + const testvectors192 = [[[0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12,0x14,0x15,0x16,0x17,0x19,0x1A,0x1B,0x1C],[0x2D,0x33,0xEE,0xF2,0xC0,0x43,0x0A,0x8A,0x9E,0xBF,0x45,0xE8,0x09,0xC4,0x0B,0xB6],[0xDF,0xF4,0x94,0x5E,0x03,0x36,0xDF,0x4C,0x1C,0x56,0xBC,0x70,0x0E,0xFF,0x83,0x7F]], [[0x1E,0x1F,0x20,0x21,0x23,0x24,0x25,0x26,0x28,0x29,0x2A,0x2B,0x2D,0x2E,0x2F,0x30,0x32,0x33,0x34,0x35,0x37,0x38,0x39,0x3A],[0x6A,0xA3,0x75,0xD1,0xFA,0x15,0x5A,0x61,0xFB,0x72,0x35,0x3E,0x0A,0x5A,0x87,0x56],[0xB6,0xFD,0xDE,0xF4,0x75,0x27,0x65,0xE3,0x47,0xD5,0xD2,0xDC,0x19,0x6D,0x12,0x52]], [[0x3C,0x3D,0x3E,0x3F,0x41,0x42,0x43,0x44,0x46,0x47,0x48,0x49,0x4B,0x4C,0x4D,0x4E,0x50,0x51,0x52,0x53,0x55,0x56,0x57,0x58],[0xBC,0x37,0x36,0x51,0x8B,0x94,0x90,0xDC,0xB8,0xED,0x60,0xEB,0x26,0x75,0x8E,0xD4],[0xD2,0x36,0x84,0xE3,0xD9,0x63,0xB3,0xAF,0xCF,0x1A,0x11,0x4A,0xCA,0x90,0xCB,0xD6]], [[0x5A,0x5B,0x5C,0x5D,0x5F,0x60,0x61,0x62,0x64,0x65,0x66,0x67,0x69,0x6A,0x6B,0x6C,0x6E,0x6F,0x70,0x71,0x73,0x74,0x75,0x76],[0xAA,0x21,0x44,0x02,0xB4,0x6C,0xFF,0xB9,0xF7,0x61,0xEC,0x11,0x26,0x3A,0x31,0x1E],[0x3A,0x7A,0xC0,0x27,0x75,0x3E,0x2A,0x18,0xC2,0xCE,0xAB,0x9E,0x17,0xC1,0x1F,0xD0]], @@ -45,7 +46,7 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function [[0x86,0x87,0x88,0x89,0x8B,0x8C,0x8D,0x8E,0x90,0x91,0x92,0x93,0x95,0x96,0x97,0x98,0x9A,0x9B,0x9C,0x9D,0x9F,0xA0,0xA1,0xA2],[0x7F,0xDC,0x2B,0x74,0x6F,0x3F,0x66,0x52,0x96,0x94,0x3B,0x83,0x71,0x0D,0x1F,0x82],[0xDF,0x0B,0x49,0x31,0x03,0x8B,0xAD,0xE8,0x48,0xDE,0xE3,0xB4,0xB8,0x5A,0xA4,0x4B]], [[0xA4,0xA5,0xA6,0xA7,0xA9,0xAA,0xAB,0xAC,0xAE,0xAF,0xB0,0xB1,0xB3,0xB4,0xB5,0xB6,0xB8,0xB9,0xBA,0xBB,0xBD,0xBE,0xBF,0xC0],[0x8F,0xBA,0x15,0x10,0xA3,0xC5,0xB8,0x7E,0x2E,0xAA,0x3F,0x7A,0x91,0x45,0x5C,0xA2],[0x59,0x2D,0x5F,0xDE,0xD7,0x65,0x82,0xE4,0x14,0x3C,0x65,0x09,0x93,0x09,0x47,0x7C]]]; - var testvectors256 = [[[0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12,0x14,0x15,0x16,0x17,0x19,0x1A,0x1B,0x1C,0x1E,0x1F,0x20,0x21,0x23,0x24,0x25,0x26],[0x83,0x4E,0xAD,0xFC,0xCA,0xC7,0xE1,0xB3,0x06,0x64,0xB1,0xAB,0xA4,0x48,0x15,0xAB],[0x19,0x46,0xDA,0xBF,0x6A,0x03,0xA2,0xA2,0xC3,0xD0,0xB0,0x50,0x80,0xAE,0xD6,0xFC]], + const testvectors256 = [[[0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12,0x14,0x15,0x16,0x17,0x19,0x1A,0x1B,0x1C,0x1E,0x1F,0x20,0x21,0x23,0x24,0x25,0x26],[0x83,0x4E,0xAD,0xFC,0xCA,0xC7,0xE1,0xB3,0x06,0x64,0xB1,0xAB,0xA4,0x48,0x15,0xAB],[0x19,0x46,0xDA,0xBF,0x6A,0x03,0xA2,0xA2,0xC3,0xD0,0xB0,0x50,0x80,0xAE,0xD6,0xFC]], [[0x28,0x29,0x2A,0x2B,0x2D,0x2E,0x2F,0x30,0x32,0x33,0x34,0x35,0x37,0x38,0x39,0x3A,0x3C,0x3D,0x3E,0x3F,0x41,0x42,0x43,0x44,0x46,0x47,0x48,0x49,0x4B,0x4C,0x4D,0x4E],[0xD9,0xDC,0x4D,0xBA,0x30,0x21,0xB0,0x5D,0x67,0xC0,0x51,0x8F,0x72,0xB6,0x2B,0xF1],[0x5E,0xD3,0x01,0xD7,0x47,0xD3,0xCC,0x71,0x54,0x45,0xEB,0xDE,0xC6,0x2F,0x2F,0xB4]], [[0x50,0x51,0x52,0x53,0x55,0x56,0x57,0x58,0x5A,0x5B,0x5C,0x5D,0x5F,0x60,0x61,0x62,0x64,0x65,0x66,0x67,0x69,0x6A,0x6B,0x6C,0x6E,0x6F,0x70,0x71,0x73,0x74,0x75,0x76],[0xA2,0x91,0xD8,0x63,0x01,0xA4,0xA7,0x39,0xF7,0x39,0x21,0x73,0xAA,0x3C,0x60,0x4C],[0x65,0x85,0xC8,0xF4,0x3D,0x13,0xA6,0xBE,0xAB,0x64,0x19,0xFC,0x59,0x35,0xB9,0xD0]], [[0x78,0x79,0x7A,0x7B,0x7D,0x7E,0x7F,0x80,0x82,0x83,0x84,0x85,0x87,0x88,0x89,0x8A,0x8C,0x8D,0x8E,0x8F,0x91,0x92,0x93,0x94,0x96,0x97,0x98,0x99,0x9B,0x9C,0x9D,0x9E],[0x42,0x64,0xB2,0x69,0x64,0x98,0xDE,0x4D,0xF7,0x97,0x88,0xA9,0xF8,0x3E,0x93,0x90],[0x2A,0x5B,0x56,0xA5,0x96,0x68,0x0F,0xCC,0x0E,0x05,0xF5,0xE0,0xF1,0x51,0xEC,0xAE]], @@ -62,8 +63,8 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function [[0x30,0x31,0x32,0x33,0x35,0x36,0x37,0x38,0x3A,0x3B,0x3C,0x3D,0x3F,0x40,0x41,0x42,0x44,0x45,0x46,0x47,0x49,0x4A,0x4B,0x4C,0x4E,0x4F,0x50,0x51,0x53,0x54,0x55,0x56],[0x72,0x61,0x65,0xC1,0x72,0x3F,0xBC,0xF6,0xC0,0x26,0xD7,0xD0,0x0B,0x09,0x10,0x27],[0x7C,0x17,0x00,0x21,0x1A,0x39,0x91,0xFC,0x0E,0xCD,0xED,0x0A,0xB3,0xE5,0x76,0xB0]]]; it('128 bit key', function (done) { - for (var i = 0; i < testvectors128.length; i++) { - var res = test_aes(testvectors128[i][1],testvectors128[i][0],testvectors128[i][2]); + for (let i = 0; i < testvectors128.length; i++) { + const res = test_aes(testvectors128[i][1],testvectors128[i][0],testvectors128[i][2]); expect(res, 'block ' + util.hexidump(testvectors128[i][1]) + ' and key '+util.hexidump(testvectors128[i][0]) + ' should be '+util.hexidump(testvectors128[i][2])).to.be.true; @@ -72,8 +73,8 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function }); it('192 bit key', function (done) { - for (var i = 0; i < testvectors192.length; i++) { - var res = test_aes(testvectors192[i][1],testvectors192[i][0],testvectors192[i][2]); + for (let i = 0; i < testvectors192.length; i++) { + const res = test_aes(testvectors192[i][1],testvectors192[i][0],testvectors192[i][2]); expect(res, 'block ' + util.hexidump(testvectors192[i][1]) + ' and key ' + util.hexidump(testvectors192[i][0])+ ' should be ' + util.hexidump(testvectors192[i][2])).to.be.true; @@ -82,8 +83,8 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function }); it('256 bit key', function (done) { - for (var i = 0; i < testvectors256.length; i++) { - var res = test_aes(testvectors256[i][1],testvectors256[i][0],testvectors256[i][2]); + for (let i = 0; i < testvectors256.length; i++) { + const res = test_aes(testvectors256[i][1],testvectors256[i][0],testvectors256[i][2]); expect(res, 'block ' + util.hexidump(testvectors256[i][1]) + ' and key ' + util.hexidump(testvectors256[i][0]) + ' should be ' + util.hexidump(testvectors256[i][2])).to.be.true; diff --git a/test/crypto/cipher/blowfish.js b/test/crypto/cipher/blowfish.js index b35c0b72..384738f3 100644 --- a/test/crypto/cipher/blowfish.js +++ b/test/crypto/cipher/blowfish.js @@ -1,19 +1,20 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); -var util = openpgp.util, - BFencrypt = openpgp.crypto.cipher.blowfish, - chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { util } = openpgp; +const BFencrypt = openpgp.crypto.cipher.blowfish; +const { expect } = chai; it('Blowfish cipher test with test vectors from https://www.schneier.com/code/vectors.txt', function(done) { function test_bf(input, key, output) { - var blowfish = new openpgp.crypto.cipher.blowfish(util.bin2str(key)); - var result = util.bin2str(blowfish.encrypt(input)); + const blowfish = new openpgp.crypto.cipher.blowfish(util.bin2str(key)); + const result = util.bin2str(blowfish.encrypt(input)); - return (util.hexstrdump(result) == util.hexstrdump(util.bin2str(output))); + return (util.hexstrdump(result) === util.hexstrdump(util.bin2str(output))); } - var testvectors = [[[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x4E,0xF9,0x97,0x45,0x61,0x98,0xDD,0x78]], + const testvectors = [[[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x4E,0xF9,0x97,0x45,0x61,0x98,0xDD,0x78]], [[0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF],[0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF],[0x51,0x86,0x6F,0xD5,0xB8,0x5E,0xCB,0x8A]], [[0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x01],[0x7D,0x85,0x6F,0x9A,0x61,0x30,0x63,0xF2]], [[0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11],[0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11],[0x24,0x66,0xDD,0x87,0x8B,0x96,0x3C,0x9D]], @@ -48,8 +49,8 @@ it('Blowfish cipher test with test vectors from https://www.schneier.com/code/ve [[0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF],[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x24,0x59,0x46,0x88,0x57,0x54,0x36,0x9A]], [[0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10],[0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF],[0x6B,0x5C,0x5A,0x9C,0x5D,0x9E,0x0A,0x5A]]]; - for (var i = 0; i < testvectors.length; i++) { - var res = test_bf(testvectors[i][1],testvectors[i][0],testvectors[i][2]); + for (let i = 0; i < testvectors.length; i++) { + const res = test_bf(testvectors[i][1],testvectors[i][0],testvectors[i][2]); expect(res, 'vector '+ i + '" with block ' + util.hexidump(testvectors[i][0])+ ' and key ' + util.hexidump(testvectors[i][1]) + ' should be ' + util.hexidump(testvectors[i][2]), false); diff --git a/test/crypto/cipher/cast5.js b/test/crypto/cipher/cast5.js index 1f8e61c9..4cbf82c4 100644 --- a/test/crypto/cipher/cast5.js +++ b/test/crypto/cipher/cast5.js @@ -1,24 +1,25 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); -var util = openpgp.util, - chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { util } = openpgp; +const { expect } = chai; it('CAST-128 cipher test with test vectors from RFC2144', function (done) { - function test_cast(input, key, output) { - var cast5 = new openpgp.crypto.cipher.cast5(key); - var result = util.bin2str(cast5.encrypt(input)); + function test_cast(input, key, output) { + const cast5 = new openpgp.crypto.cipher.cast5(key); + const result = util.bin2str(cast5.encrypt(input)); - return util.hexstrdump(result) == util.hexstrdump(util.bin2str(output)); - } + return util.hexstrdump(result) === util.hexstrdump(util.bin2str(output)); + } - var testvectors = [[[0x01,0x23,0x45,0x67,0x12,0x34,0x56,0x78,0x23,0x45,0x67,0x89,0x34,0x56,0x78,0x9A],[0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF],[0x23,0x8B,0x4F,0xE5,0x84,0x7E,0x44,0xB2]]]; + const testvectors = [[[0x01,0x23,0x45,0x67,0x12,0x34,0x56,0x78,0x23,0x45,0x67,0x89,0x34,0x56,0x78,0x9A],[0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF],[0x23,0x8B,0x4F,0xE5,0x84,0x7E,0x44,0xB2]]]; - for (var i = 0; i < testvectors.length; i++) { - var res = test_cast(testvectors[i][1],testvectors[i][0],testvectors[i][2]); - expect(res, 'vector with block ' + util.hexidump(testvectors[i][0]) + + for (let i = 0; i < testvectors.length; i++) { + const res = test_cast(testvectors[i][1],testvectors[i][0],testvectors[i][2]); + expect(res, 'vector with block ' + util.hexidump(testvectors[i][0]) + ' and key ' + util.hexidump(testvectors[i][1]) + ' should be ' + util.hexidump(testvectors[i][2])).to.be.true; - } + } done(); }); diff --git a/test/crypto/cipher/des.js b/test/crypto/cipher/des.js index 0c80366d..5b418293 100644 --- a/test/crypto/cipher/des.js +++ b/test/crypto/cipher/des.js @@ -1,13 +1,14 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); -var util = openpgp.util, - chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { util } = openpgp; +const { expect } = chai; describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', function() { // see https://csrc.nist.gov/publications/nistpubs/800-20/800-20.pdf - var key = new Uint8Array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]); - var testvectors = [[[0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x95,0xF8,0xA5,0xE5,0xDD,0x31,0xD9,0x00]], + const key = new Uint8Array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]); + const testvectors = [[[0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x95,0xF8,0xA5,0xE5,0xDD,0x31,0xD9,0x00]], [[0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0xDD,0x7F,0x12,0x1C,0xA5,0x01,0x56,0x19]], [[0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x2E,0x86,0x53,0x10,0x4F,0x38,0x34,0xEA]], [[0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x4B,0xD3,0x88,0xFF,0x6C,0xD8,0x1D,0x4F]], @@ -73,10 +74,10 @@ describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', fu [[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01],[0x16,0x6B,0x40,0xB4,0x4A,0xBA,0x4B,0xD6]]]; it('3DES EDE test vectors', function (done) { - for (var i = 0; i < testvectors.length; i++) { - var des = new openpgp.crypto.cipher.tripledes(key); + for (let i = 0; i < testvectors.length; i++) { + const des = new openpgp.crypto.cipher.tripledes(key); - var encr = util.bin2str(des.encrypt(testvectors[i][0], key)); + const encr = util.bin2str(des.encrypt(testvectors[i][0], key)); expect(encr, 'vector with block ' + util.hexidump(testvectors[i][0]) + ' and key ' + util.hexstrdump(util.Uint8Array2str(key)) + @@ -87,41 +88,41 @@ describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', fu }); it('DES encrypt/decrypt padding tests', function (done) { - var key = new Uint8Array([0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF]); - var testvectors = new Array(); + const key = new Uint8Array([0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF]); + const testvectors = new Array(); testvectors[0] = [[[0x01], [0x24, 0xC7, 0x4A, 0x9A, 0x79, 0x75, 0x4B, 0xC7]], - [[0x02, 0x03], [0xA7, 0x7A, 0x9A, 0x59, 0x8A, 0x86, 0x85, 0xC5]], - [[0x03, 0x04, 0x05], [0x01, 0xCF, 0xEB, 0x6A, 0x74, 0x60, 0xF5, 0x02]], - [[0x04, 0x05, 0x06, 0x07], [0xA8, 0xF0, 0x3D, 0x59, 0xBA, 0x6B, 0x0E, 0x76]], - [[0x05, 0x06, 0x07, 0x08, 0x09], [0x86, 0x40, 0x33, 0x61, 0x3F, 0x55, 0x73, 0x49]], - [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0x13, 0x21, 0x3E, 0x0E, 0xCE, 0x2C, 0x94, 0x01]], - [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0x30, 0x49, 0x97, 0xC1, 0xDA, 0xD5, 0x59, 0xA5]], - [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9]]]; + [[0x02, 0x03], [0xA7, 0x7A, 0x9A, 0x59, 0x8A, 0x86, 0x85, 0xC5]], + [[0x03, 0x04, 0x05], [0x01, 0xCF, 0xEB, 0x6A, 0x74, 0x60, 0xF5, 0x02]], + [[0x04, 0x05, 0x06, 0x07], [0xA8, 0xF0, 0x3D, 0x59, 0xBA, 0x6B, 0x0E, 0x76]], + [[0x05, 0x06, 0x07, 0x08, 0x09], [0x86, 0x40, 0x33, 0x61, 0x3F, 0x55, 0x73, 0x49]], + [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0x13, 0x21, 0x3E, 0x0E, 0xCE, 0x2C, 0x94, 0x01]], + [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0x30, 0x49, 0x97, 0xC1, 0xDA, 0xD5, 0x59, 0xA5]], + [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9]]]; testvectors[1] = [[[0x01], [0xF2, 0xAB, 0x1C, 0x9E, 0x70, 0x7D, 0xCC, 0x92]], - [[0x02, 0x03], [0x6B, 0x4C, 0x67, 0x24, 0x9F, 0xB7, 0x4D, 0xAC]], - [[0x03, 0x04, 0x05], [0x68, 0x95, 0xAB, 0xA8, 0xEA, 0x53, 0x13, 0x23]], - [[0x04, 0x05, 0x06, 0x07], [0xC8, 0xDE, 0x60, 0x8F, 0xF6, 0x09, 0x90, 0xB5]], - [[0x05, 0x06, 0x07, 0x08, 0x09], [0x19, 0x13, 0x50, 0x20, 0x70, 0x40, 0x2E, 0x09]], - [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0xA8, 0x23, 0x40, 0xC6, 0x17, 0xA6, 0x31, 0x4A]], - [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0x36, 0x62, 0xF2, 0x99, 0x68, 0xD4, 0xBF, 0x7C]], - [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9, 0x08, 0x6F, 0x9A, 0x1D, 0x74, 0xC9, 0x4D, 0x4E]]]; + [[0x02, 0x03], [0x6B, 0x4C, 0x67, 0x24, 0x9F, 0xB7, 0x4D, 0xAC]], + [[0x03, 0x04, 0x05], [0x68, 0x95, 0xAB, 0xA8, 0xEA, 0x53, 0x13, 0x23]], + [[0x04, 0x05, 0x06, 0x07], [0xC8, 0xDE, 0x60, 0x8F, 0xF6, 0x09, 0x90, 0xB5]], + [[0x05, 0x06, 0x07, 0x08, 0x09], [0x19, 0x13, 0x50, 0x20, 0x70, 0x40, 0x2E, 0x09]], + [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0xA8, 0x23, 0x40, 0xC6, 0x17, 0xA6, 0x31, 0x4A]], + [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0x36, 0x62, 0xF2, 0x99, 0x68, 0xD4, 0xBF, 0x7C]], + [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9, 0x08, 0x6F, 0x9A, 0x1D, 0x74, 0xC9, 0x4D, 0x4E]]]; testvectors[2] = [[[0x01], [0x83, 0x68, 0xE4, 0x9C, 0x84, 0xCC, 0xCB, 0xF0]], - [[0x02, 0x03], [0xBB, 0xA8, 0x0B, 0x66, 0x1B, 0x62, 0xC4, 0xC8]], - [[0x03, 0x04, 0x05], [0x9A, 0xD7, 0x5A, 0x24, 0xFD, 0x3F, 0xBF, 0x22]], - [[0x04, 0x05, 0x06, 0x07], [0x14, 0x4E, 0x68, 0x6D, 0x2E, 0xC1, 0xB7, 0x52]], - [[0x05, 0x06, 0x07, 0x08, 0x09], [0x12, 0x0A, 0x51, 0x08, 0xF9, 0xA3, 0x03, 0x74]], - [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0xB2, 0x07, 0xD1, 0x05, 0xF6, 0x67, 0xAF, 0xBA]], - [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0xCA, 0x59, 0x61, 0x3A, 0x83, 0x23, 0x26, 0xDD]], - [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9]]]; + [[0x02, 0x03], [0xBB, 0xA8, 0x0B, 0x66, 0x1B, 0x62, 0xC4, 0xC8]], + [[0x03, 0x04, 0x05], [0x9A, 0xD7, 0x5A, 0x24, 0xFD, 0x3F, 0xBF, 0x22]], + [[0x04, 0x05, 0x06, 0x07], [0x14, 0x4E, 0x68, 0x6D, 0x2E, 0xC1, 0xB7, 0x52]], + [[0x05, 0x06, 0x07, 0x08, 0x09], [0x12, 0x0A, 0x51, 0x08, 0xF9, 0xA3, 0x03, 0x74]], + [[0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B], [0xB2, 0x07, 0xD1, 0x05, 0xF6, 0x67, 0xAF, 0xBA]], + [[0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D], [0xCA, 0x59, 0x61, 0x3A, 0x83, 0x23, 0x26, 0xDD]], + [[0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F], [0x83, 0x25, 0x79, 0x06, 0x54, 0xA4, 0x44, 0xD9]]]; - var des = new openpgp.crypto.cipher.des(key); + const des = new openpgp.crypto.cipher.des(key); - for (var padding = 0; padding < 3; padding++) { - var thisVectorSet = testvectors[padding]; + for (let padding = 0; padding < 3; padding++) { + const thisVectorSet = testvectors[padding]; - for (var i = 0; i < thisVectorSet.length; i++) { - var encrypted = des.encrypt(thisVectorSet[i][0], padding); - var decrypted = des.decrypt(encrypted, padding); + for (let i = 0; i < thisVectorSet.length; i++) { + const encrypted = des.encrypt(thisVectorSet[i][0], padding); + const decrypted = des.decrypt(encrypted, padding); expect(util.bin2str(encrypted), 'vector with block [' + util.hexidump(thisVectorSet[i][0]) + '] and key [' + util.hexstrdump(util.Uint8Array2str(key)) + diff --git a/test/crypto/cipher/twofish.js b/test/crypto/cipher/twofish.js index 723d4aa4..157e64cf 100644 --- a/test/crypto/cipher/twofish.js +++ b/test/crypto/cipher/twofish.js @@ -1,19 +1,20 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); -var util = openpgp.util, - chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { util } = openpgp; +const { expect } = chai; it('Twofish with test vectors from https://www.schneier.com/code/ecb_ival.txt', function(done) { function TFencrypt(block, key) { - var tf = new openpgp.crypto.cipher.twofish(util.str2Uint8Array(key)); + const tf = new openpgp.crypto.cipher.twofish(util.str2Uint8Array(key)); return tf.encrypt(block); } - var start = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; - var start_short = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; - var testvectors = [[0x57,0xFF,0x73,0x9D,0x4D,0xC9,0x2C,0x1B,0xD7,0xFC,0x01,0x70,0x0C,0xC8,0x21,0x6F], + const start = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; + const start_short = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; + const testvectors = [[0x57,0xFF,0x73,0x9D,0x4D,0xC9,0x2C,0x1B,0xD7,0xFC,0x01,0x70,0x0C,0xC8,0x21,0x6F], [0xD4,0x3B,0xB7,0x55,0x6E,0xA3,0x2E,0x46,0xF2,0xA2,0x82,0xB7,0xD4,0x5B,0x4E,0x0D], [0x90,0xAF,0xE9,0x1B,0xB2,0x88,0x54,0x4F,0x2C,0x32,0xDC,0x23,0x9B,0x26,0x35,0xE6], [0x6C,0xB4,0x56,0x1C,0x40,0xBF,0x0A,0x97,0x05,0x93,0x1C,0xB6,0xD4,0x08,0xE7,0xFA], @@ -23,11 +24,16 @@ it('Twofish with test vectors from https://www.schneier.com/code/ecb_ival.txt', [0xDC,0x09,0x6B,0xCD,0x99,0xFC,0x72,0xF7,0x99,0x36,0xD4,0xC7,0x48,0xE7,0x5A,0xF7], [0xC5,0xA3,0xE7,0xCE,0xE0,0xF1,0xB7,0x26,0x05,0x28,0xA6,0x8F,0xB4,0xEA,0x05,0xF2], [0x43,0xD5,0xCE,0xC3,0x27,0xB2,0x4A,0xB9,0x0A,0xD3,0x4A,0x79,0xD0,0x46,0x91,0x51]]; - testvectors[47] = [0x43,0x10,0x58,0xF4,0xDB,0xC7,0xF7,0x34,0xDA,0x4F,0x02,0xF0,0x4C,0xC4,0xF4,0x59]; - testvectors[48] = [0x37,0xFE,0x26,0xFF,0x1C,0xF6,0x61,0x75,0xF5,0xDD,0xF4,0xC3,0x3B,0x97,0xA2,0x05]; + testvectors[47] = [0x43,0x10,0x58,0xF4,0xDB,0xC7,0xF7,0x34,0xDA,0x4F,0x02,0xF0,0x4C,0xC4,0xF4,0x59]; + testvectors[48] = [0x37,0xFE,0x26,0xFF,0x1C,0xF6,0x61,0x75,0xF5,0xDD,0xF4,0xC3,0x3B,0x97,0xA2,0x05]; + + for (let i = 0; i < 49; i++) { + let res; + let exp; + let blk; + let key; + let ct; - for (var i = 0; i < 49; i++) { - var res, exp, blk, key, ct; if (i === 0) { blk = start_short; key = util.bin2str(start); diff --git a/test/crypto/crypto.js b/test/crypto/crypto.js index e9ad19d9..fe49756f 100644 --- a/test/crypto/crypto.js +++ b/test/crypto/crypto.js @@ -1,12 +1,13 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'); +const chai = require('chai'); chai.use(require('chai-as-promised')); -var expect = chai.expect; + +const expect = chai.expect; describe('API functional testing', function() { - var util = openpgp.util; - var RSApubMPIstrs = [ + const util = openpgp.util; + const RSApubMPIstrs = [ new Uint8Array([0x08,0x00,0xac,0x15,0xb3,0xd6,0xd2,0x0f,0xf0,0x7a,0xdd,0x21,0xb7, 0xbf,0x61,0xfa,0xca,0x93,0x86,0xc8,0x55,0x5a,0x4b,0xa6,0xa4,0x1a, 0x60,0xa2,0x3a,0x37,0x06,0x08,0xd8,0x15,0x8e,0x85,0x45,0xaa,0xb7, @@ -27,8 +28,9 @@ describe('API functional testing', function() { 0x29,0xc1,0xf3,0xa9,0x0b,0xfc,0x31,0x75,0x58,0x74,0x2a,0x88,0xaf, 0xee,0xc9,0xa4,0xcd,0x15,0xdc,0x1b,0x8d,0x64,0xc1,0x36,0x17,0xc4, 0x8d,0x5e,0x99,0x7a,0x5b,0x9f,0x39,0xd0,0x00,0x6e,0xf9]), - new Uint8Array([0x00,0x11,0x01,0x00,0x01])]; - var RSAsecMPIstrs = [ + new Uint8Array([0x00,0x11,0x01,0x00,0x01]) +]; + const RSAsecMPIstrs = [ new Uint8Array([0x07,0xfe,0x23,0xff,0xce,0x45,0x6c,0x60,0x65,0x40,0x6e,0xae,0x35, 0x10,0x56,0x60,0xee,0xab,0xfa,0x10,0x42,0xba,0xc7,0x04,0xaf,0x63, 0xcd,0x3f,0x62,0xca,0x4b,0xfa,0xe1,0xa9,0x70,0xcd,0x34,0x8b,0xc8, @@ -78,9 +80,10 @@ describe('API functional testing', function() { 0x0c,0x6f,0xcf,0xd9,0x6d,0x68,0xf7,0x00,0x4f,0x0e,0xc8,0x0b,0xfa, 0x51,0xe0,0x22,0xf0,0xff,0xa7,0x42,0xd4,0xde,0x0b,0x47,0x8f,0x2b, 0xf5,0x4d,0x04,0x32,0x91,0x89,0x4b,0x0e,0x05,0x8d,0x70,0xf9,0xbb, - 0xe7,0xd6,0x76,0xea,0x0e,0x1a,0x90,0x30,0xf5,0x98,0x01,0xc5,0x73])]; + 0xe7,0xd6,0x76,0xea,0x0e,0x1a,0x90,0x30,0xf5,0x98,0x01,0xc5,0x73]) +]; - var DSApubMPIstrs = [ + const DSApubMPIstrs = [ new Uint8Array([0x08,0x00,0xa8,0x85,0x5c,0x28,0x05,0x94,0x03,0xbe,0x07,0x6c,0x13,0x3e,0x65, 0xfb,0xb5,0xe1,0x99,0x7c,0xfa,0x84,0xe3,0xac,0x47,0xa5,0xc4,0x46,0xd8,0x5f, 0x44,0xe9,0xc1,0x6b,0x69,0xf7,0x10,0x76,0x49,0xa7,0x25,0x85,0xf4,0x1b,0xed, @@ -137,13 +140,15 @@ describe('API functional testing', function() { 0x02,0x07,0xc3,0xa3,0x0f,0x09,0x18,0x7f,0xf7,0x6b,0x90,0x70,0xc0,0xf9,0x0c, 0x67,0x8d,0x9d,0x14,0xb6,0x9d,0x32,0x82,0xd0,0xb5,0xc6,0x57,0xf0,0x91,0xd9, 0xc3,0x26,0xae,0x9f,0xa9,0x67,0x49,0x96,0x5c,0x07,0x3e,0x47,0x5c,0xed,0x60, - 0x07,0xac,0x6a])]; - var DSAsecMPIstrs = [ + 0x07,0xac,0x6a]) +]; + const DSAsecMPIstrs = [ new Uint8Array([0x01,0x00,0x9b,0x58,0xa8,0xf4,0x04,0xb1,0xd5,0x14,0x09,0xe1,0xe1,0xa1,0x8a, 0x0b,0xa3,0xc3,0xa3,0x66,0xaa,0x27,0x99,0x50,0x1c,0x4d,0xba,0x24,0xee,0xdf, - 0xdf,0xb8,0x8e,0x8e])]; + 0xdf,0xb8,0x8e,0x8e]) +]; - var ElgamalpubMPIstrs = [ + const ElgamalpubMPIstrs = [ new Uint8Array([0x08,0x00,0xea,0xcc,0xbe,0xe2,0xe4,0x5a,0x51,0x18,0x93,0xa1,0x12,0x2f,0x00, 0x99,0x42,0xd8,0x5c,0x1c,0x2f,0xb6,0x3c,0xd9,0x94,0x61,0xb4,0x55,0x8d,0x4e, 0x73,0xe6,0x69,0xbc,0x1d,0x33,0xe3,0x2d,0x91,0x23,0x69,0x95,0x98,0xd7,0x18, @@ -180,50 +185,52 @@ describe('API functional testing', function() { 0xd5,0xd5,0xbe,0x1f,0xf0,0x19,0xe6,0x81,0xfd,0x5d,0xe1,0xf8,0x76,0x5f,0xe3, 0xda,0xba,0x19,0xf3,0xcb,0x10,0xa0,0x6b,0xd0,0x2d,0xbe,0x40,0x42,0x7b,0x9b, 0x15,0xa4,0x2d,0xec,0xcf,0x09,0xd6,0xe3,0x92,0xc3,0x8d,0x65,0x6b,0x60,0x97, - 0xda,0x6b,0xca])]; + 0xda,0x6b,0xca]) +]; - var ElgamalsecMPIstrs = [ + const ElgamalsecMPIstrs = [ new Uint8Array([0x01,0x52,0x02,0x80,0x87,0xf6,0xe4,0x49,0xd7,0x2e,0x3e,0xfe,0x60,0xb9,0xa3, 0x2a,0xf0,0x67,0x58,0xe9,0xf6,0x47,0x83,0xde,0x7e,0xfb,0xbb,0xbd,0xdf,0x48, - 0x12,0x1b,0x06,0x7d,0x13,0xbc,0x3b,0x49,0xf9,0x86,0xd4,0x53,0xed,0x2d,0x68])]; + 0x12,0x1b,0x06,0x7d,0x13,0xbc,0x3b,0x49,0xf9,0x86,0xd4,0x53,0xed,0x2d,0x68]) +]; - var RSApubMPIs = []; - var i; + const RSApubMPIs = []; + let i; for (i = 0; i < 2; i++) { RSApubMPIs[i] = new openpgp.MPI(); RSApubMPIs[i].read(RSApubMPIstrs[i]); } - var RSAsecMPIs = []; + const RSAsecMPIs = []; for (i = 0; i < 4; i++) { RSAsecMPIs[i] = new openpgp.MPI(); RSAsecMPIs[i].read(RSAsecMPIstrs[i]); } - var DSAsecMPIs = []; + const DSAsecMPIs = []; for (i = 0; i < 1; i++) { DSAsecMPIs[i] = new openpgp.MPI(); DSAsecMPIs[i].read(DSAsecMPIstrs[i]); } - var DSApubMPIs = []; + const DSApubMPIs = []; for (i = 0; i < 4; i++) { DSApubMPIs[i] = new openpgp.MPI(); DSApubMPIs[i].read(DSApubMPIstrs[i]); } - var ElgamalsecMPIs = []; + const ElgamalsecMPIs = []; for (i = 0; i < 1; i++) { ElgamalsecMPIs[i] = new openpgp.MPI(); ElgamalsecMPIs[i].read(ElgamalsecMPIstrs[i]); } - var ElgamalpubMPIs = []; + const ElgamalpubMPIs = []; for (i = 0; i < 3; i++) { ElgamalpubMPIs[i] = new openpgp.MPI(); ElgamalpubMPIs[i].read(ElgamalpubMPIstrs[i]); } - var data = util.str2Uint8Array("foobar"); + const data = util.str2Uint8Array("foobar"); describe('Sign and verify', function () { it('RSA', function () { @@ -232,7 +239,7 @@ describe('API functional testing', function() { return openpgp.crypto.signature.sign( 2, 1, RSApubMPIs.concat(RSAsecMPIs), data ).then(RSAsignedData => { - var RSAsignedDataMPI = new openpgp.MPI(); + const RSAsignedDataMPI = new openpgp.MPI(); RSAsignedDataMPI.read(RSAsignedData); return openpgp.crypto.signature.verify( 1, 2, [RSAsignedDataMPI], RSApubMPIs, data @@ -247,8 +254,8 @@ describe('API functional testing', function() { return openpgp.crypto.signature.sign( 2, 17, DSApubMPIs.concat(DSAsecMPIs), data ).then(DSAsignedData => { - var DSAsignedData = util.Uint8Array2str(DSAsignedData); - var DSAmsgMPIs = []; + DSAsignedData = util.Uint8Array2str(DSAsignedData); + const DSAmsgMPIs = []; DSAmsgMPIs[0] = new openpgp.MPI(); DSAmsgMPIs[1] = new openpgp.MPI(); DSAmsgMPIs[0].read(DSAsignedData.substring(0,34)); @@ -263,16 +270,16 @@ describe('API functional testing', function() { }); describe('Encrypt and decrypt', function () { - var symmAlgos = Object.keys(openpgp.enums.symmetric); + let symmAlgos = Object.keys(openpgp.enums.symmetric); symmAlgos = symmAlgos.filter(function(algo) { return algo !== 'idea' && algo !== 'plaintext'; }); function testCFB(plaintext, resync) { symmAlgos.forEach(function(algo) { - var symmKey = openpgp.crypto.generateSessionKey(algo); - var symmencData = openpgp.crypto.cfb.encrypt(openpgp.crypto.getPrefixRandom(algo), algo, util.str2Uint8Array(plaintext), symmKey, resync); - var text = util.Uint8Array2str(openpgp.crypto.cfb.decrypt(algo, symmKey, symmencData, resync)); + const symmKey = openpgp.crypto.generateSessionKey(algo); + const symmencData = openpgp.crypto.cfb.encrypt(openpgp.crypto.getPrefixRandom(algo), algo, util.str2Uint8Array(plaintext), symmKey, resync); + const text = util.Uint8Array2str(openpgp.crypto.cfb.decrypt(algo, symmKey, symmencData, resync)); expect(text).to.equal(plaintext); }); } @@ -280,17 +287,17 @@ describe('API functional testing', function() { function testAESCFB(plaintext) { symmAlgos.forEach(function(algo) { if(algo.substr(0,3) === 'aes') { - var symmKey = openpgp.crypto.generateSessionKey(algo); - var rndm = openpgp.crypto.getPrefixRandom(algo); + const symmKey = openpgp.crypto.generateSessionKey(algo); + const rndm = openpgp.crypto.getPrefixRandom(algo); - var symmencData = openpgp.crypto.cfb.encrypt(rndm, algo, util.str2Uint8Array(plaintext), symmKey, false); - var symmencData2 = asmCrypto.AES_CFB.encrypt(util.str2Uint8Array(plaintext), key); + const symmencData = openpgp.crypto.cfb.encrypt(rndm, algo, util.str2Uint8Array(plaintext), symmKey, false); + const symmencData2 = asmCrypto.AES_CFB.encrypt(util.str2Uint8Array(plaintext), key); - var decrypted = asmCrypto.AES_CFB.decrypt(symmencData, key); + let decrypted = asmCrypto.AES_CFB.decrypt(symmencData, key); decrypted = decrypted.subarray(openpgp.crypto.cipher[algo].blockSize + 2, decrypted.length); expect(symmencData).to.equal(symmencData2); - var text = util.Uint8Array2str(decrypted); + const text = util.Uint8Array2str(decrypted); expect(text).to.equal(plaintext); } }); @@ -300,13 +307,13 @@ describe('API functional testing', function() { symmAlgos.forEach(function(algo) { if(algo.substr(0,3) === 'aes') { it(algo, function(done) { - var key = openpgp.crypto.generateSessionKey(algo); - var iv = openpgp.crypto.random.getRandomValues(new Uint8Array(openpgp.crypto.gcm.ivLength)); + const key = openpgp.crypto.generateSessionKey(algo); + const iv = openpgp.crypto.random.getRandomValues(new Uint8Array(openpgp.crypto.gcm.ivLength)); openpgp.crypto.gcm.encrypt(algo, util.str2Uint8Array(plaintext), key, iv).then(function(ciphertext) { return openpgp.crypto.gcm.decrypt(algo, ciphertext, key, iv); }).then(function(decrypted) { - var decryptedStr = util.Uint8Array2str(decrypted); + const decryptedStr = util.Uint8Array2str(decrypted); expect(decryptedStr).to.equal(plaintext); done(); }); @@ -337,7 +344,7 @@ describe('API functional testing', function() { }); describe('Symmetric AES-GCM (native)', function() { - var use_nativeVal; + let use_nativeVal; beforeEach(function() { use_nativeVal = openpgp.config.use_native; openpgp.config.use_native = true; @@ -350,7 +357,7 @@ describe('API functional testing', function() { }); describe('Symmetric AES-GCM (asm.js fallback)', function() { - var use_nativeVal; + let use_nativeVal; beforeEach(function() { use_nativeVal = openpgp.config.use_native; openpgp.config.use_native = false; @@ -363,8 +370,8 @@ describe('API functional testing', function() { }); it('Asymmetric using RSA with eme_pkcs1 padding', function (done) { - var symmKey = util.Uint8Array2str(openpgp.crypto.generateSessionKey('aes256')); - var RSAUnencryptedData = new openpgp.MPI(); + const symmKey = util.Uint8Array2str(openpgp.crypto.generateSessionKey('aes256')); + const RSAUnencryptedData = new openpgp.MPI(); RSAUnencryptedData.fromBytes(openpgp.crypto.pkcs1.eme.encode(symmKey, RSApubMPIs[0].byteLength())); openpgp.crypto.publicKeyEncrypt( "rsa_encrypt_sign", RSApubMPIs, RSAUnencryptedData @@ -374,7 +381,7 @@ describe('API functional testing', function() { data = data.write(); data = util.Uint8Array2str(data.subarray(2, data.length)); - var result = openpgp.crypto.pkcs1.eme.decode(data, RSApubMPIs[0].byteLength()); + const result = openpgp.crypto.pkcs1.eme.decode(data, RSApubMPIs[0].byteLength()); expect(result).to.equal(symmKey); done(); }); @@ -382,18 +389,18 @@ describe('API functional testing', function() { }); it('Asymmetric using Elgamal with eme_pkcs1 padding', function (done) { - var symmKey = util.Uint8Array2str(openpgp.crypto.generateSessionKey('aes256')); - var ElgamalUnencryptedData = new openpgp.MPI(); + const symmKey = util.Uint8Array2str(openpgp.crypto.generateSessionKey('aes256')); + const ElgamalUnencryptedData = new openpgp.MPI(); ElgamalUnencryptedData.fromBytes(openpgp.crypto.pkcs1.eme.encode(symmKey, ElgamalpubMPIs[0].byteLength())); openpgp.crypto.publicKeyEncrypt( "elgamal", ElgamalpubMPIs, ElgamalUnencryptedData ).then(ElgamalEncryptedData => { - var data = openpgp.crypto.publicKeyDecrypt("elgamal", ElgamalpubMPIs.concat(ElgamalsecMPIs), ElgamalEncryptedData).then(data => { + const data = openpgp.crypto.publicKeyDecrypt("elgamal", ElgamalpubMPIs.concat(ElgamalsecMPIs), ElgamalEncryptedData).then(data => { data = data.write(); data = util.Uint8Array2str(data.subarray(2, data.length)); - var result = openpgp.crypto.pkcs1.eme.decode(data, ElgamalpubMPIs[0].byteLength()); + const result = openpgp.crypto.pkcs1.eme.decode(data, ElgamalpubMPIs[0].byteLength()); expect(result).to.equal(symmKey); done(); }); diff --git a/test/crypto/elliptic.js b/test/crypto/elliptic.js index 70f8465f..ef3b10d1 100644 --- a/test/crypto/elliptic.js +++ b/test/crypto/elliptic.js @@ -1,25 +1,27 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'); +const chai = require('chai'); chai.use(require('chai-as-promised')); -var expect = chai.expect; -var bin2bi = function (bytes) { - var mpi = new openpgp.MPI(); +const expect = chai.expect; + +const bin2bi = function (bytes) { + const mpi = new openpgp.MPI(); bytes = openpgp.util.bin2str(bytes); mpi.fromBytes(bytes); return mpi.toBigInteger(); }; describe('Elliptic Curve Cryptography', function () { - var elliptic_curves = openpgp.crypto.publicKey.elliptic; - var key_data = { + const elliptic_curves = openpgp.crypto.publicKey.elliptic; + const key_data = { p256: { priv: new Uint8Array([ 0x2B, 0x48, 0x2B, 0xE9, 0x88, 0x74, 0xE9, 0x49, 0x1F, 0x89, 0xCC, 0xFF, 0x0A, 0x26, 0x05, 0xA2, 0x3C, 0x2A, 0x35, 0x25, 0x26, 0x11, 0xD7, 0xEA, - 0xA1, 0xED, 0x29, 0x95, 0xB5, 0xE1, 0x5F, 0x1D]), + 0xA1, 0xED, 0x29, 0x95, 0xB5, 0xE1, 0x5F, 0x1D +]), pub: new Uint8Array([0x04, 0x80, 0x2C, 0x40, 0x76, 0x31, 0x20, 0xB6, 0x9B, 0x48, 0x3B, 0x05, 0xEB, 0x6C, 0x1E, 0x3F, 0x49, @@ -37,7 +39,8 @@ describe('Elliptic Curve Cryptography', function () { 0x97, 0xB0, 0x54, 0x26, 0x10, 0xB4, 0xEC, 0x2A, 0xA7, 0xC1, 0xA3, 0x4B, 0xC0, 0xBD, 0xFE, 0x3E, 0xF1, 0xBE, 0x76, 0xCB, 0xE8, 0xAB, 0x3B, 0xBD, - 0xB6, 0x84, 0xC7, 0x8B, 0x91, 0x2F, 0x76, 0x8B]), + 0xB6, 0x84, 0xC7, 0x8B, 0x91, 0x2F, 0x76, 0x8B +]), pub: new Uint8Array([0x04, 0x44, 0x83, 0xA0, 0x3E, 0x5B, 0x0A, 0x0D, 0x9B, 0xA0, 0x06, 0xDF, 0x38, 0xC7, 0x64, 0xCD, 0x62, @@ -62,7 +65,8 @@ describe('Elliptic Curve Cryptography', function () { 0x25, 0x5A, 0x95, 0x38, 0xDC, 0xEB, 0x59, 0x8E, 0x33, 0xAD, 0xC0, 0x0B, 0x56, 0xB1, 0x06, 0x8C, 0x57, 0x48, 0xA3, 0x73, 0xDB, 0xE0, 0x19, 0x50, - 0x2E, 0x79]), + 0x2E, 0x79 +]), pub: new Uint8Array([0x04, 0x01, 0x0D, 0xD5, 0xCA, 0xD8, 0xB0, 0xEF, 0x9F, 0x2B, 0x7E, 0x58, 0x99, 0xDE, 0x05, 0xF6, 0xF6, @@ -87,7 +91,8 @@ describe('Elliptic Curve Cryptography', function () { 0x9E, 0xB0, 0x30, 0xD6, 0xE1, 0xCE, 0xAA, 0x0B, 0x7B, 0x8F, 0xDE, 0x5D, 0x91, 0x4D, 0xDC, 0xA0, 0xAD, 0x05, 0xAB, 0x8F, 0x87, 0x9B, 0x57, 0x48, - 0xAE, 0x8A, 0xE0, 0xF9, 0x39, 0xBD, 0x24, 0x00]), + 0xAE, 0x8A, 0xE0, 0xF9, 0x39, 0xBD, 0x24, 0x00 +]), pub: new Uint8Array([0x04, 0xA8, 0x02, 0x35, 0x2C, 0xB7, 0x24, 0x95, 0x51, 0x0A, 0x65, 0x26, 0x7D, 0xDF, 0xEA, 0x64, 0xB3, @@ -99,12 +104,13 @@ describe('Elliptic Curve Cryptography', function () { 0x4B, 0x92, 0x26, 0xFC, 0xAA, 0x7A, 0x7C, 0x3F]) } }; - var signature_data = { + const signature_data = { priv: new Uint8Array([ 0x14, 0x2B, 0xE2, 0xB7, 0x4D, 0xBD, 0x1B, 0x22, 0x4D, 0xDF, 0x96, 0xA4, 0xED, 0x8E, 0x5B, 0xF9, 0xBD, 0xD3, 0xFE, 0xAE, 0x3F, 0xB2, 0xCF, 0xEE, - 0xA7, 0xDB, 0xD0, 0x58, 0xA7, 0x47, 0xF8, 0x7C]), + 0xA7, 0xDB, 0xD0, 0x58, 0xA7, 0x47, 0xF8, 0x7C +]), pub: new Uint8Array([0x04, 0xD3, 0x36, 0x11, 0xF9, 0xF9, 0xAB, 0x39, 0x23, 0x15, 0xB9, 0x71, 0x7B, 0x2A, 0x0B, 0xA6, 0x6D, @@ -116,97 +122,100 @@ describe('Elliptic Curve Cryptography', function () { 0x8E, 0x95, 0x24, 0x10, 0x1F, 0x0F, 0x13, 0xE4]), message: new Uint8Array([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]), + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F +]), signature: { r: new Uint8Array([ 0xF1, 0x78, 0x1C, 0xA5, 0x13, 0x21, 0x0C, 0xBA, 0x6F, 0x18, 0x5D, 0xB3, 0x01, 0xE2, 0x17, 0x1B, 0x67, 0x65, 0x7F, 0xC6, 0x1F, 0x50, 0x12, 0xFB, - 0x2F, 0xD3, 0xA4, 0x29, 0xE3, 0xC2, 0x44, 0x9F]), + 0x2F, 0xD3, 0xA4, 0x29, 0xE3, 0xC2, 0x44, 0x9F +]), s: new Uint8Array([ 0x7F, 0x08, 0x69, 0x6D, 0xBB, 0x1B, 0x9B, 0xF2, 0x62, 0x1C, 0xCA, 0x80, 0xC6, 0x15, 0xB2, 0xAE, 0x60, 0x50, 0xD1, 0xA7, 0x1B, 0x32, 0xF3, 0xB1, - 0x01, 0x0B, 0xDF, 0xC6, 0xAB, 0xF0, 0xEB, 0x01]) + 0x01, 0x0B, 0xDF, 0xC6, 0xAB, 0xF0, 0xEB, 0x01 +]) } }; describe('Basic Operations', function () { it('Creating curve with name', function (done) { - var names = ['p256', 'p384', 'p521', 'secp256k1', 'curve25519']; + const names = ['p256', 'p384', 'p521', 'secp256k1', 'curve25519']; names.forEach(function (name) { expect(elliptic_curves.get(name)).to.exist; }); done(); }); it('Creating curve from oid', function (done) { - var oids = ['2A8648CE3D030107', '2B81040022', '2B81040023', '2B8104000A']; + const oids = ['2A8648CE3D030107', '2B81040022', '2B81040023', '2B8104000A']; oids.forEach(function (oid) { expect(elliptic_curves.get(openpgp.util.hex2bin(oid))).to.exist; }); done(); }); it('Creating KeyPair', function () { - var names = ['p256', 'p384', 'p521', 'secp256k1', 'curve25519']; + const names = ['p256', 'p384', 'p521', 'secp256k1', 'curve25519']; return Promise.all(names.map(function (name) { - var curve = elliptic_curves.get(name); + const curve = elliptic_curves.get(name); return curve.genKeyPair().then(keyPair => { expect(keyPair).to.exist; }); })); }); it('Creating KeyPair from data', function (done) { - for (var name in key_data) { - var pair = key_data[name]; - var curve = elliptic_curves.get(name); + for (const name in key_data) { + const pair = key_data[name]; + const curve = elliptic_curves.get(name); expect(curve).to.exist; - var keyPair = curve.keyFromPrivate(pair.priv); + const keyPair = curve.keyFromPrivate(pair.priv); expect(keyPair).to.exist; - var pub = keyPair.getPublic(); + const pub = keyPair.getPublic(); expect(pub).to.exist; expect(openpgp.util.hexidump(pub)).to.equal(openpgp.util.hexidump(pair.pub)); } done(); }); it('Signature verification', function (done) { - var curve = elliptic_curves.get('p256'); - var key = curve.keyFromPublic(signature_data.pub); + const curve = elliptic_curves.get('p256'); + const key = curve.keyFromPublic(signature_data.pub); expect(key.verify(signature_data.message, signature_data.signature, 8)).to.eventually.be.true; done(); }); it('Invalid signature', function (done) { - var curve = elliptic_curves.get('p256'); - var key = curve.keyFromPublic(key_data.p256.pub); + const curve = elliptic_curves.get('p256'); + const key = curve.keyFromPublic(key_data.p256.pub); expect(key.verify(signature_data.message, signature_data.signature, 8)).to.eventually.be.false; done(); }); it('Signature generation', function () { - var curve = elliptic_curves.get('p256'); - var key = curve.keyFromPrivate(key_data.p256.priv); + const curve = elliptic_curves.get('p256'); + let key = curve.keyFromPrivate(key_data.p256.priv); return key.sign(signature_data.message, 8).then(signature => { key = curve.keyFromPublic(key_data.p256.pub); expect(key.verify(signature_data.message, signature, 8)).to.eventually.be.true; }); }); it('Shared secret generation', function (done) { - var curve = elliptic_curves.get('p256'); - var key1 = curve.keyFromPrivate(key_data.p256.priv); - var key2 = curve.keyFromPublic(signature_data.pub); - var shared1 = openpgp.util.hexidump(key1.derive(key2)); + const curve = elliptic_curves.get('p256'); + let key1 = curve.keyFromPrivate(key_data.p256.priv); + let key2 = curve.keyFromPublic(signature_data.pub); + const shared1 = openpgp.util.hexidump(key1.derive(key2)); key1 = curve.keyFromPublic(key_data.p256.pub); key2 = curve.keyFromPrivate(signature_data.priv); - var shared2 = openpgp.util.hexidump(key2.derive(key1)); + const shared2 = openpgp.util.hexidump(key2.derive(key1)); expect(shared1).to.equal(shared2); done(); }); }); describe('ECDSA signature', function () { - var verify_signature = function (oid, hash, r, s, message, pub) { + const verify_signature = function (oid, hash, r, s, message, pub) { if (openpgp.util.isString(message)) { message = openpgp.util.str2Uint8Array(message); } else if (!openpgp.util.isUint8Array(message)) { message = new Uint8Array(message); } - var ecdsa = elliptic_curves.ecdsa; + const ecdsa = elliptic_curves.ecdsa; return ecdsa.verify( oid, hash, @@ -215,12 +224,13 @@ describe('Elliptic Curve Cryptography', function () { bin2bi(pub) ); }; - var secp256k1_dummy_value = new Uint8Array([ + const secp256k1_dummy_value = new Uint8Array([ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); - var secp256k1_dummy_point = new Uint8Array([0x04, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +]); + const secp256k1_dummy_point = new Uint8Array([0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -229,7 +239,7 @@ describe('Elliptic Curve Cryptography', function () { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); - var secp256k1_invalid_point = new Uint8Array([0x04, + const secp256k1_invalid_point = new Uint8Array([0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -260,34 +270,37 @@ describe('Elliptic Curve Cryptography', function () { )).to.eventually.be.false.notify(done); }); - var p384_message = new Uint8Array([ + const p384_message = new Uint8Array([ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]); - var p384_r = new Uint8Array([ + 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF +]); + const p384_r = new Uint8Array([ 0x9D, 0x07, 0xCA, 0xA5, 0x9F, 0xBE, 0xB8, 0x76, 0xA9, 0xB9, 0x66, 0x0F, 0xA0, 0x64, 0x70, 0x5D, 0xE6, 0x37, 0x40, 0x43, 0xD0, 0x8E, 0x40, 0xA8, 0x8B, 0x37, 0x83, 0xE7, 0xBC, 0x1C, 0x4C, 0x86, 0xCB, 0x3C, 0xD5, 0x9B, 0x68, 0xF0, 0x65, 0xEB, - 0x3A, 0xB6, 0xD6, 0xA6, 0xCF, 0x85, 0x3D, 0xA9]); - var p384_s = new Uint8Array([ + 0x3A, 0xB6, 0xD6, 0xA6, 0xCF, 0x85, 0x3D, 0xA9 +]); + const p384_s = new Uint8Array([ 0x32, 0x85, 0x78, 0xCC, 0xEA, 0xC5, 0x22, 0x83, 0x10, 0x73, 0x1C, 0xCF, 0x10, 0x8A, 0x52, 0x11, 0x8E, 0x49, 0x9E, 0xCF, 0x7E, 0x17, 0x18, 0xC3, 0x11, 0x11, 0xBC, 0x0F, 0x6D, 0x98, 0xE2, 0x16, 0x68, 0x58, 0x23, 0x1D, 0x11, 0xEF, 0x3D, 0x21, - 0x30, 0x75, 0x24, 0x39, 0x48, 0x89, 0x03, 0xDC]); + 0x30, 0x75, 0x24, 0x39, 0x48, 0x89, 0x03, 0xDC +]); it('Valid signature', function (done) { expect(verify_signature('p384', 8, p384_r, p384_s, p384_message, key_data.p384.pub)) .to.eventually.be.true.notify(done); }); it('Sign and verify message', function () { - var curve = elliptic_curves.get('p521'); + const curve = elliptic_curves.get('p521'); return curve.genKeyPair().then(keyPair => { - var keyPublic = bin2bi(keyPair.getPublic()); - var keyPrivate = bin2bi(keyPair.getPrivate()); - var oid = curve.oid; - var message = p384_message; + const keyPublic = bin2bi(keyPair.getPublic()); + const keyPrivate = bin2bi(keyPair.getPrivate()); + const oid = curve.oid; + const message = p384_message; return elliptic_curves.ecdsa.sign(oid, 10, message, keyPrivate).then(signature => { expect(elliptic_curves.ecdsa.verify(oid, 10, signature, message, keyPublic)) .to.eventually.be.true; @@ -296,14 +309,14 @@ describe('Elliptic Curve Cryptography', function () { }); }); describe('ECDH key exchange', function () { - var decrypt_message = function (oid, hash, cipher, priv, ephemeral, data, fingerprint) { + const decrypt_message = function (oid, hash, cipher, priv, ephemeral, data, fingerprint) { if (openpgp.util.isString(data)) { data = openpgp.util.str2Uint8Array(data); } else { data = new Uint8Array(data); } return Promise.resolve().then(() => { - var ecdh = elliptic_curves.ecdh; + const ecdh = elliptic_curves.ecdh; return ecdh.decrypt( oid, cipher, @@ -315,12 +328,13 @@ describe('Elliptic Curve Cryptography', function () { ); }); }; - var secp256k1_value = new Uint8Array([ + const secp256k1_value = new Uint8Array([ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); - var secp256k1_point = new Uint8Array([0x04, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +]); + const secp256k1_point = new Uint8Array([0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -329,9 +343,10 @@ describe('Elliptic Curve Cryptography', function () { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); - var secp256k1_data = new Uint8Array([ + const secp256k1_data = new Uint8Array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +]); it('Invalid curve oid', function (done) { expect(decrypt_message( @@ -341,7 +356,7 @@ describe('Elliptic Curve Cryptography', function () { it('Invalid ephemeral key', function (done) { expect(decrypt_message( 'secp256k1', 2, 7, [], [], [], '' - )).to.be.rejectedWith(Error, /Unknown point format/).notify(done);; + )).to.be.rejectedWith(Error, /Unknown point format/).notify(done); }); it('Invalid key data integrity', function (done) { expect(decrypt_message( diff --git a/test/crypto/hash/md5.js b/test/crypto/hash/md5.js index 54e9dc42..ecf01f2d 100644 --- a/test/crypto/hash/md5.js +++ b/test/crypto/hash/md5.js @@ -1,16 +1,17 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); -var util = openpgp.util, - MD5 = openpgp.crypto.hash.md5, - chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { util } = openpgp; +const MD5 = openpgp.crypto.hash.md5; +const { expect } = chai; it('MD5 with test vectors from RFC 1321', function(done) { expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array(''))), 'MD5("") = d41d8cd98f00b204e9800998ecf8427e')).to.equal('d41d8cd98f00b204e9800998ecf8427e'); - expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('abc'))), 'MD5("a") = 0cc175b9c0f1b6a831c399e269772661')).to.equal('900150983cd24fb0d6963f7d28e17f72'); - expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('message digest'))), 'MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0')).to.equal('f96b697d7cb7938d525a2f31aaf161d0'); - expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('abcdefghijklmnopqrstuvwxyz'))), 'MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b')).to.equal('c3fcd3d76192e4007dfb496cca67e13b'); - expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'))), 'MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = d174ab98d277d9f5a5611c2c9f419d9f')).to.equal('d174ab98d277d9f5a5611c2c9f419d9f'); - expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('12345678901234567890123456789012345678901234567890123456789012345678901234567890'))), 'MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890") = 57edf4a22be3c955ac49da2e2107b67a')).to.equal('57edf4a22be3c955ac49da2e2107b67a'); - done(); + expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('abc'))), 'MD5("a") = 0cc175b9c0f1b6a831c399e269772661')).to.equal('900150983cd24fb0d6963f7d28e17f72'); + expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('message digest'))), 'MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0')).to.equal('f96b697d7cb7938d525a2f31aaf161d0'); + expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('abcdefghijklmnopqrstuvwxyz'))), 'MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b')).to.equal('c3fcd3d76192e4007dfb496cca67e13b'); + expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'))), 'MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = d174ab98d277d9f5a5611c2c9f419d9f')).to.equal('d174ab98d277d9f5a5611c2c9f419d9f'); + expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('12345678901234567890123456789012345678901234567890123456789012345678901234567890'))), 'MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890") = 57edf4a22be3c955ac49da2e2107b67a')).to.equal('57edf4a22be3c955ac49da2e2107b67a'); + done(); }); diff --git a/test/crypto/hash/ripemd.js b/test/crypto/hash/ripemd.js index 8db2ba63..2cb94e00 100644 --- a/test/crypto/hash/ripemd.js +++ b/test/crypto/hash/ripemd.js @@ -1,9 +1,10 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); -var util = openpgp.util, - RMDstring = openpgp.crypto.hash.ripemd, - chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { util } = openpgp; +const RMDstring = openpgp.crypto.hash.ripemd; +const { expect } = chai; it("RIPE-MD 160 bits with test vectors from https://homes.esat.kuleuven.be/~bosselae/ripemd160.html", function(done) { expect(util.hexstrdump(util.Uint8Array2str(RMDstring(util.str2Uint8Array(''))), 'RMDstring("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31')).to.equal('9c1185a5c5e9fc54612808977ee8f548b2258d31'); diff --git a/test/crypto/hash/sha.js b/test/crypto/hash/sha.js index 3d1cba29..e782b822 100644 --- a/test/crypto/hash/sha.js +++ b/test/crypto/hash/sha.js @@ -1,12 +1,13 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../../dist/openpgp'); -var util = openpgp.util, - hash = openpgp.crypto.hash, - chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { util } = openpgp; +const { hash } = openpgp.crypto; +const { expect } = chai; it('SHA* with test vectors from NIST FIPS 180-2', function(done) { - expect(util.hexstrdump(util.Uint8Array2str(hash.sha1(util.str2Uint8Array('abc'))), 'hash.sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d')).to.equal('a9993e364706816aba3e25717850c26c9cd0d89d'); + expect(util.hexstrdump(util.Uint8Array2str(hash.sha1(util.str2Uint8Array('abc'))), 'hash.sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d')).to.equal('a9993e364706816aba3e25717850c26c9cd0d89d'); expect(util.hexstrdump(util.Uint8Array2str(hash.sha1(util.str2Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 84983e441c3bd26ebaae4aa1f95129e5e54670f1')).to.equal('84983e441c3bd26ebaae4aa1f95129e5e54670f1'); expect(util.hexstrdump(util.Uint8Array2str(hash.sha224(util.str2Uint8Array('abc'))), 'hash.sha224("abc") = 23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7')).to.equal('23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7'); expect(util.hexstrdump(util.Uint8Array2str(hash.sha224(util.str2Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha224("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525')).to.equal('75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525'); @@ -16,5 +17,5 @@ it('SHA* with test vectors from NIST FIPS 180-2', function(done) { expect(util.hexstrdump(util.Uint8Array2str(hash.sha384(util.str2Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha384("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b')).to.equal('3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b'); expect(util.hexstrdump(util.Uint8Array2str(hash.sha512(util.str2Uint8Array('abc'))), 'hash.sha512("abc") = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f')).to.equal('ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f'); expect(util.hexstrdump(util.Uint8Array2str(hash.sha512(util.str2Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445')).to.equal('204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445'); - done(); + done(); }); diff --git a/test/crypto/pkcs5.js b/test/crypto/pkcs5.js index b2562c5f..c0a8cfc8 100644 --- a/test/crypto/pkcs5.js +++ b/test/crypto/pkcs5.js @@ -1,23 +1,23 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var expect = require('chai').expect; +const expect = require('chai').expect; describe('PKCS5 padding', function() { function repeat(pattern, count) { - var result = ''; - for (var k=0; k 8, 8..15 -> 16 - var l = Math.ceil((s.length+1)/8)*8; - var c = l - s.length; + const l = Math.ceil((s.length+1)/8)*8; + const c = l - s.length; expect(r.length).to.equal(l); expect(c).is.at.least(1).is.at.most(8); expect(r.substr(-1)).to.equal(String.fromCharCode(c)); @@ -25,15 +25,15 @@ describe('PKCS5 padding', function() { } }); it('Remove padding', function () { - for (var k=1; k<=8; ++k) { - var s = repeat(' ', 8-k); - var r = s + repeat(String.fromCharCode(k), k); - var t = pkcs5.decode(r); + for (let k=1; k<=8; ++k) { + const s = repeat(' ', 8-k); + const r = s + repeat(String.fromCharCode(k), k); + const t = pkcs5.decode(r); expect(t).to.equal(s); } }); it('Invalid padding', function () { - expect(function () {pkcs5.decode(' ');}).to.throw(Error, /Invalid padding/); - expect(function () {pkcs5.decode('');}).to.throw(Error, /Invalid padding/); + expect(function () { pkcs5.decode(' '); }).to.throw(Error, /Invalid padding/); + expect(function () { pkcs5.decode(''); }).to.throw(Error, /Invalid padding/); }); }); diff --git a/test/crypto/random.js b/test/crypto/random.js index e10bc3df..3e53fa12 100644 --- a/test/crypto/random.js +++ b/test/crypto/random.js @@ -1,10 +1,11 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { expect } = chai; describe('Random Buffer', function() { - var randomBuffer; + let randomBuffer; before(function() { randomBuffer = new openpgp.crypto.random.randomBuffer.constructor(); @@ -24,7 +25,7 @@ describe('Random Buffer', function() { }); function equal(buf, arr) { - for (var i = 0; i < buf.length; i++) { + for (let i = 0; i < buf.length; i++) { if (buf[i] !== arr[i]) { return false; } @@ -34,7 +35,7 @@ describe('Random Buffer', function() { it('Set Method', function () { randomBuffer.init(5); - var buf = new Uint32Array(2); + let buf = new Uint32Array(2); expect(randomBuffer.set.bind(randomBuffer, buf)).to.throw('Invalid type: buf not an Uint8Array'); buf = new Uint8Array(2); buf[0] = 1; buf[1] = 2; @@ -57,7 +58,7 @@ describe('Random Buffer', function() { it('Get Method', function () { randomBuffer.init(5); - var buf = new Uint8Array(5); + let buf = new Uint8Array(5); buf[0] = 1; buf[1] = 2; buf[2] = 5; buf[3] = 7; buf[4] = 8; randomBuffer.set(buf); buf = new Uint32Array(2); diff --git a/test/general/armor.js b/test/general/armor.js index 9f56b684..03d814fd 100644 --- a/test/general/armor.js +++ b/test/general/armor.js @@ -1,8 +1,8 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); +const { expect } = chai; describe("ASCII armor", function() { @@ -27,61 +27,61 @@ describe("ASCII armor", function() { } it('Parse cleartext signed message', function () { - var msg = getArmor(['Hash: SHA1']); + let msg = getArmor(['Hash: SHA1']); msg = openpgp.cleartext.readArmored(msg); expect(msg).to.be.an.instanceof(openpgp.cleartext.CleartextMessage); }); it('Exception if mismatch in armor header and signature', function () { - var msg = getArmor(['Hash: SHA256']); + let msg = getArmor(['Hash: SHA256']); msg = openpgp.cleartext.readArmored.bind(null, msg); expect(msg).to.throw(Error, /Hash algorithm mismatch in armor header and signature/); }); it('Exception if no header and non-MD5 signature', function () { - var msg = getArmor(null); + let msg = getArmor(null); msg = openpgp.cleartext.readArmored.bind(null, msg); expect(msg).to.throw(Error, /If no "Hash" header in cleartext signed message, then only MD5 signatures allowed/); }); it('Exception if unknown hash algorithm', function () { - var msg = getArmor(['Hash: LAV750']); + let msg = getArmor(['Hash: LAV750']); msg = openpgp.cleartext.readArmored.bind(null, msg); expect(msg).to.throw(Error, /Unknown hash algorithm in armor header/); }); it('Multiple hash values', function () { - var msg = getArmor(['Hash: SHA1, SHA256']); + let msg = getArmor(['Hash: SHA1, SHA256']); msg = openpgp.cleartext.readArmored(msg); expect(msg).to.be.an.instanceof(openpgp.cleartext.CleartextMessage); }); it('Multiple hash header lines', function () { - var msg = getArmor(['Hash: SHA1', 'Hash: SHA256']); + let msg = getArmor(['Hash: SHA1', 'Hash: SHA256']); msg = openpgp.cleartext.readArmored(msg); expect(msg).to.be.an.instanceof(openpgp.cleartext.CleartextMessage); }); it('Non-hash header line throws exception', function () { - var msg = getArmor(['Hash: SHA1', 'Comment: could be anything']); + let msg = getArmor(['Hash: SHA1', 'Comment: could be anything']); msg = openpgp.cleartext.readArmored.bind(null, msg); expect(msg).to.throw(Error, /Only "Hash" header allowed in cleartext signed message/); }); it('Multiple wrong hash values', function () { - var msg = getArmor(['Hash: SHA512, SHA256']); + let msg = getArmor(['Hash: SHA512, SHA256']); msg = openpgp.cleartext.readArmored.bind(null, msg); expect(msg).to.throw(Error, /Hash algorithm mismatch in armor header and signature/); }); it('Multiple wrong hash values', function () { - var msg = getArmor(['Hash: SHA512, SHA256']); + let msg = getArmor(['Hash: SHA512, SHA256']); msg = openpgp.cleartext.readArmored.bind(null, msg); expect(msg).to.throw(Error, /Hash algorithm mismatch in armor header and signature/); }); it('Filter whitespace in blank line', function () { - var msg = + let msg = ['-----BEGIN PGP SIGNED MESSAGE-----', 'Hash: SHA1', ' \f\r\t\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000', @@ -101,7 +101,7 @@ describe("ASCII armor", function() { }); it('Exception if improperly formatted armor header - plaintext section', function () { - var msg = getArmor(['Hash:SHA256']); + let msg = getArmor(['Hash:SHA256']); msg = openpgp.cleartext.readArmored.bind(null, msg); expect(msg).to.throw(Error, /Improperly formatted armor header/); msg = getArmor(['Ha sh: SHA256']); @@ -119,7 +119,7 @@ describe("ASCII armor", function() { }); it('Ignore unknown armor header - signature section', function () { - var validHeaders = ['Version: BCPG C# v1.7.4114.6375', 'Independent Reserve Pty. Ltd. 2017: 1.0.0.0']; + const validHeaders = ['Version: BCPG C# v1.7.4114.6375', 'Independent Reserve Pty. Ltd. 2017: 1.0.0.0']; expect(openpgp.cleartext.readArmored(getArmor(['Hash: SHA1'], validHeaders))).to.be.an.instanceof(openpgp.cleartext.CleartextMessage); ['A: Hello', 'Ab: 1.2.3', 'Abcd: #!/yah', 'Acd 123 5.6.$.8: Hello', '_: Hello', '*: Hello', '* & ## ?? ()(): Hello', '( ): Weird'].forEach(function (validHeader) { expect(openpgp.cleartext.readArmored(getArmor(['Hash: SHA1'], [validHeader]))).to.be.an.instanceof(openpgp.cleartext.CleartextMessage); @@ -127,7 +127,7 @@ describe("ASCII armor", function() { }); it('Exception if wrong armor header type', function () { - var msg = + let msg = ['-----BEGIN PGP SIGNED MESSAGE\u2010\u2010\u2010\u2010\u2010\nHash:SHA1\n\nIs this properly-----', '', 'sign this', @@ -146,7 +146,7 @@ describe("ASCII armor", function() { }); it('Armor checksum validation - mismatch', function () { - var privKey = + const privKey = ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: OpenPGP.js v0.3.0', 'Comment: https://openpgpjs.org', @@ -167,13 +167,13 @@ describe("ASCII armor", function() { '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); // try with default config - var result_1 = openpgp.key.readArmored(privKey); + const result_1 = openpgp.key.readArmored(privKey); expect(result_1.err).to.exist; expect(result_1.err[0].message).to.match(/Ascii armor integrity check on message failed/); // try opposite config openpgp.config.checksum_required = !openpgp.config.checksum_required; - var result_2 = openpgp.key.readArmored(privKey); + const result_2 = openpgp.key.readArmored(privKey); expect(result_2.err).to.exist; expect(result_2.err[0].message).to.match(/Ascii armor integrity check on message failed/); @@ -182,7 +182,7 @@ describe("ASCII armor", function() { }); it('Armor checksum validation - valid', function () { - var privKey = + const privKey = ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: OpenPGP.js v0.3.0', 'Comment: https://openpgpjs.org', @@ -203,12 +203,12 @@ describe("ASCII armor", function() { '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); // try with default config - var result_1 = openpgp.key.readArmored(privKey); + const result_1 = openpgp.key.readArmored(privKey); expect(result_1.err).to.not.exist; // try opposite config openpgp.config.checksum_required = !openpgp.config.checksum_required; - var result_2 = openpgp.key.readArmored(privKey); + const result_2 = openpgp.key.readArmored(privKey); expect(result_2.err).to.not.exist; // back to default @@ -216,7 +216,7 @@ describe("ASCII armor", function() { }); it('Armor checksum validation - missing', function () { - var privKeyNoCheckSum = + const privKeyNoCheckSum = ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: OpenPGP.js v0.3.0', 'Comment: https://openpgpjs.org', @@ -236,7 +236,7 @@ describe("ASCII armor", function() { '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); // try with default config - var result_1 = openpgp.key.readArmored(privKeyNoCheckSum); + const result_1 = openpgp.key.readArmored(privKeyNoCheckSum); if(openpgp.config.checksum_required) { expect(result_1.err).to.exist; expect(result_1.err[0].message).to.match(/Ascii armor integrity check on message failed/); @@ -246,7 +246,7 @@ describe("ASCII armor", function() { // try opposite config openpgp.config.checksum_required = !openpgp.config.checksum_required; - var result_2 = openpgp.key.readArmored(privKeyNoCheckSum); + const result_2 = openpgp.key.readArmored(privKeyNoCheckSum); if(openpgp.config.checksum_required) { expect(result_2.err).to.exist; expect(result_2.err[0].message).to.match(/Ascii armor integrity check on message failed/); @@ -259,7 +259,7 @@ describe("ASCII armor", function() { }); it('Armor checksum validation - missing - trailing newline', function () { - var privKeyNoCheckSumWithTrailingNewline = + const privKeyNoCheckSumWithTrailingNewline = ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: OpenPGP.js v0.3.0', 'Comment: https://openpgpjs.org', @@ -280,7 +280,7 @@ describe("ASCII armor", function() { ''].join('\n'); // try with default config - var result_1 = openpgp.key.readArmored(privKeyNoCheckSumWithTrailingNewline); + const result_1 = openpgp.key.readArmored(privKeyNoCheckSumWithTrailingNewline); if(openpgp.config.checksum_required) { expect(result_1.err).to.exist; expect(result_1.err[0].message).to.match(/Ascii armor integrity check on message failed/); @@ -290,7 +290,7 @@ describe("ASCII armor", function() { // try opposite config openpgp.config.checksum_required = !openpgp.config.checksum_required; - var result_2 = openpgp.key.readArmored(privKeyNoCheckSumWithTrailingNewline); + const result_2 = openpgp.key.readArmored(privKeyNoCheckSumWithTrailingNewline); if(openpgp.config.checksum_required) { expect(result_2.err).to.exist; expect(result_2.err[0].message).to.match(/Ascii armor integrity check on message failed/); @@ -303,7 +303,7 @@ describe("ASCII armor", function() { }); it('Accept header with trailing whitespace', function () { - var privKey = + const privKey = ['-----BEGIN PGP PRIVATE KEY BLOCK-----\t \r', 'Version: OpenPGP.js v0.3.0', 'Comment: https://openpgpjs.org', @@ -323,17 +323,16 @@ describe("ASCII armor", function() { '=wJNM', '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); - var result = openpgp.key.readArmored(privKey); + const result = openpgp.key.readArmored(privKey); expect(result.err).to.not.exist; expect(result.keys[0]).to.be.an.instanceof(openpgp.key.Key); }); it('Do not filter blank lines after header', function () { - var msg = getArmor(['Hash: SHA1', '']); + let msg = getArmor(['Hash: SHA1', '']); msg = openpgp.cleartext.readArmored(msg); expect(msg.text).to.equal('\r\nsign this'); }); }); - diff --git a/test/general/ecc_nist.js b/test/general/ecc_nist.js index fa4adbbc..2b75c685 100644 --- a/test/general/ecc_nist.js +++ b/test/general/ecc_nist.js @@ -1,11 +1,12 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'); +const chai = require('chai'); chai.use(require('chai-as-promised')); -var expect = chai.expect; + +const expect = chai.expect; describe('Elliptic Curve Cryptography', function () { - var data = { + const data = { romeo: { id: 'c2b12389b401a43d', pass: 'juliet', @@ -25,7 +26,8 @@ describe('Elliptic Curve Cryptography', function () { 'gwEA4B3lysFe/3+KE/PgCSZkUfx7n7xlKqMiqrX+VNyPej8BAMQJgtMVdslQ', 'HLr5fhoGnRots3JSC0j20UQQOKVOXaW3', '=VpL9', - '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'), + '-----END PGP PUBLIC KEY BLOCK-----' +].join('\n'), priv: [ '-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: OpenPGP.js 1.3+secp256k1', @@ -46,7 +48,8 @@ describe('Elliptic Curve Cryptography', function () { '4AkmZFH8e5+8ZSqjIqq1/lTcj3o/AQDECYLTFXbJUBy6+X4aBp0aLbNyUgtI', '9tFEEDilTl2ltw==', '=C3TW', - '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'), + '-----END PGP PRIVATE KEY BLOCK-----' +].join('\n'), message: 'Shall I hear more, or shall I speak at this?' }, juliet: { @@ -68,7 +71,8 @@ describe('Elliptic Curve Cryptography', function () { '7FoA/1Y4xDYO49u21I7aqjPyTygLoObdLMAtK6xht+DDc0YKAQDNp2wv0HOJ', '+0kjoUNu6PRIll/jMgTVAXn0Mov6HqJ95A==', '=ISmy', - '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'), + '-----END PGP PUBLIC KEY BLOCK-----' +].join('\n'), priv: [ '-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: OpenPGP.js 1.3+secp256k1', @@ -89,7 +93,8 @@ describe('Elliptic Curve Cryptography', function () { '2qoz8k8oC6Dm3SzALSusYbfgw3NGCgEAzadsL9BziftJI6FDbuj0SJZf4zIE', '1QF59DKL+h6ifeQ=', '=QvXN', - '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'), + '-----END PGP PRIVATE KEY BLOCK-----' +].join('\n'), message: 'O Romeo, Romeo! Wherefore art thou Romeo?', message_signed: [ '-----BEGIN PGP SIGNED MESSAGE-----', @@ -103,7 +108,8 @@ describe('Elliptic Curve Cryptography', function () { 'iF4EARMIAAYFAlYxF8oACgkQZBFgIZWb3+BfTwD/b1yKtFnKrRjELuD6/gOH9/er', '6yc7nzn1FBYFzMz8aFIA/3FlcIvR+eLvRTVmfiEatB6IU6JviBnzxR1gA/SOdyS2', '=GCiR', - '-----END PGP SIGNATURE-----'].join('\n'), + '-----END PGP SIGNATURE-----' +].join('\n'), message_encrypted: [ '-----BEGIN PGP MESSAGE-----', 'Version: GnuPG v2', @@ -118,14 +124,15 @@ describe('Elliptic Curve Cryptography', function () { 'j5FhrMbD3Z+TPlrNjJqidAV28XwSBFvhw8Jf5WpaewOxVlxLjUHnnkUGHyvfdEr/', 'DP/V1yLuBUZuRg==', '=GEAB', - '-----END PGP MESSAGE-----'].join('\n') + '-----END PGP MESSAGE-----' +].join('\n') } }; function load_pub_key(name) { if (data[name].pub_key) { return data[name].pub_key; } - var pub = openpgp.key.readArmored(data[name].pub); + const pub = openpgp.key.readArmored(data[name].pub); expect(pub).to.exist; expect(pub.err).to.not.exist; expect(pub.keys).to.have.length(1); @@ -137,7 +144,7 @@ describe('Elliptic Curve Cryptography', function () { if (data[name].priv_key) { return data[name].priv_key; } - var pk = openpgp.key.readArmored(data[name].priv); + const pk = openpgp.key.readArmored(data[name].priv); expect(pk).to.exist; expect(pk.err).to.not.exist; expect(pk.keys).to.have.length(1); @@ -157,8 +164,8 @@ describe('Elliptic Curve Cryptography', function () { done(); }); it('Verify clear signed message', function () { - var pub = load_pub_key('juliet'); - var msg = openpgp.cleartext.readArmored(data.juliet.message_signed); + const pub = load_pub_key('juliet'); + const msg = openpgp.cleartext.readArmored(data.juliet.message_signed); return openpgp.verify({publicKeys: [pub], message: msg}).then(function(result) { expect(result).to.exist; expect(result.data.trim()).to.equal(data.juliet.message); @@ -167,10 +174,10 @@ describe('Elliptic Curve Cryptography', function () { }); }); it('Sign message', function () { - var romeo = load_priv_key('romeo'); + const romeo = load_priv_key('romeo'); return openpgp.sign({privateKeys: [romeo], data: data.romeo.message + "\n"}).then(function (signed) { - var romeo = load_pub_key('romeo'); - var msg = openpgp.cleartext.readArmored(signed.data); + const romeo = load_pub_key('romeo'); + const msg = openpgp.cleartext.readArmored(signed.data); return openpgp.verify({publicKeys: [romeo], message: msg}).then(function (result) { expect(result).to.exist; expect(result.data.trim()).to.equal(data.romeo.message); @@ -180,9 +187,9 @@ describe('Elliptic Curve Cryptography', function () { }); }); it('Decrypt and verify message', function () { - var juliet = load_pub_key('juliet'); - var romeo = load_priv_key('romeo'); - var msg = openpgp.message.readArmored(data.juliet.message_encrypted); + const juliet = load_pub_key('juliet'); + const romeo = load_priv_key('romeo'); + const msg = openpgp.message.readArmored(data.juliet.message_encrypted); return openpgp.decrypt( {privateKeys: romeo, publicKeys: [juliet], message: msg} ).then(function (result) { @@ -194,15 +201,15 @@ describe('Elliptic Curve Cryptography', function () { }); }); it('Encrypt and sign message', function () { - var romeo = load_priv_key('romeo'); - var juliet = load_pub_key('juliet'); - expect(romeo.decrypt(data['romeo'].pass)).to.be.true; + const romeo = load_priv_key('romeo'); + const juliet = load_pub_key('juliet'); + expect(romeo.decrypt(data.romeo.pass)).to.be.true; return openpgp.encrypt( {publicKeys: [juliet], privateKeys: [romeo], data: data.romeo.message + "\n"} ).then(function (encrypted) { - var message = openpgp.message.readArmored(encrypted.data); - var romeo = load_pub_key('romeo'); - var juliet = load_priv_key('juliet'); + const message = openpgp.message.readArmored(encrypted.data); + const romeo = load_pub_key('romeo'); + const juliet = load_priv_key('juliet'); return openpgp.decrypt( {privateKeys: juliet, publicKeys: [romeo], message: message} ).then(function (result) { @@ -214,7 +221,7 @@ describe('Elliptic Curve Cryptography', function () { }); }); it('Generate key', function () { - var options = { + const options = { userIds: {name: "Hamlet (secp256k1)", email: "hamlet@example.net"}, curve: "secp256k1", passphrase: "ophelia" diff --git a/test/general/hkp.js b/test/general/hkp.js index 2e2ce2f5..0d5370d2 100644 --- a/test/general/hkp.js +++ b/test/general/hkp.js @@ -1,14 +1,15 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { expect } = chai; describe('HKP unit tests', function() { this.timeout(60000); - var hkp; + let hkp; - var pub_key = '-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n' + + const pub_key = '-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n' + 'Version: SKS 1.1.5\r\n' + 'Comment: Hostname: keyserver.ubuntu.com\r\n' + '\r\n' + diff --git a/test/general/key.js b/test/general/key.js index 38ccfd98..ea7a1147 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -1,11 +1,12 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'); +const chai = require('chai'); chai.use(require('chai-as-promised')); -var expect = chai.expect; + +const { expect } = chai; describe('Key', function() { - var twoKeys = + const twoKeys = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', @@ -55,7 +56,7 @@ describe('Key', function() { '=w6wd', '-----END PGP PUBLIC KEY BLOCK-----'].join("\n"); - var pub_revoked = + const pub_revoked = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', @@ -107,7 +108,7 @@ describe('Key', function() { '=ok+o', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var pub_v3 = + const pub_v3 = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: SKS 1.1.3', '', @@ -136,7 +137,7 @@ describe('Key', function() { '=eoGb', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var pub_sig_test = + const pub_sig_test = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', @@ -220,7 +221,7 @@ describe('Key', function() { '=e8xo', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var priv_key_rsa = + const priv_key_rsa = ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', @@ -260,7 +261,7 @@ describe('Key', function() { '=lw5e', '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); - var user_attr_key = + const user_attr_key = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.22 (GNU/Linux)', '', @@ -302,7 +303,7 @@ describe('Key', function() { '=MVfN', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var pgp_desktop_pub = + const pgp_desktop_pub = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: Encryption Desktop 10.3.0 (Build 9307)', '', @@ -341,7 +342,7 @@ describe('Key', function() { '=dVeR', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var pgp_desktop_priv = + const pgp_desktop_priv = ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: Encryption Desktop 10.3.0 (Build 9307)', '', @@ -390,7 +391,7 @@ describe('Key', function() { '=63Nq', '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); - var rsa_ecc_pub = + const rsa_ecc_pub = ['pub rsa4096/C9DEDC77 2015-10-17 [expires: 2018-10-16]', 'uid Google Security Team ', 'sub nistp384/70C16E3C 2015-10-17 [expires: 2018-10-16]', @@ -526,7 +527,7 @@ describe('Key', function() { '=Q/kB', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var valid_binding_sig_among_many_expired_sigs_pub = [ + const valid_binding_sig_among_many_expired_sigs_pub = [ '-----BEGIN PGP PUBLIC KEY BLOCK-----', '', 'mQENBFFHU9EBCAC2JjXCZOB43KUiU6V7bbMQWKFCWBmtaSTOgdEixUJKmaEyWbVd', @@ -579,9 +580,10 @@ describe('Key', function() { 'lhwmDcbAPbER1lIeU1K1TTWU92XCUaVuA/fPMKISlmb7UBDKWAE7904iOYOg4xsk', '4z6aN5G1sT5159GF', '=yzZh', - '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); + '-----END PGP PUBLIC KEY BLOCK-----' +].join('\n'); - var key_without_subkey = [ + const key_without_subkey = [ '-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: OpenPGP.js v2.6.2', 'Comment: https://openpgpjs.org', @@ -615,11 +617,12 @@ describe('Key', function() { '3LrYpnYepvMUitQ/Y2pBAYygUExZ0dPC2uGFdPISbDGLg3DhGcyy1MvbLuNh', 'EyjB8RncAfSIwK4dSGVh+PD5dkc=', '=w6Dj', - '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); + '-----END PGP PRIVATE KEY BLOCK-----' +].join('\n'); it('Parsing armored text with RSA key and ECC subkey', function(done) { openpgp.config.tolerant = true; - var pubKeys = openpgp.key.readArmored(rsa_ecc_pub); + const pubKeys = openpgp.key.readArmored(rsa_ecc_pub); expect(pubKeys).to.exist; expect(pubKeys.err).to.not.exist; expect(pubKeys.keys).to.have.length(1); @@ -627,7 +630,7 @@ describe('Key', function() { done(); }); - var multi_uid_key = + const multi_uid_key = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v1', '', @@ -666,7 +669,7 @@ describe('Key', function() { '=qxBI', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var wrong_key = + const wrong_key = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: OpenPGP.js v0.9.0', '', @@ -679,7 +682,7 @@ describe('Key', function() { '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); it('Parsing armored text with two keys', function(done) { - var pubKeys = openpgp.key.readArmored(twoKeys); + const pubKeys = openpgp.key.readArmored(twoKeys); expect(pubKeys).to.exist; expect(pubKeys.err).to.not.exist; expect(pubKeys.keys).to.have.length(2); @@ -689,21 +692,21 @@ describe('Key', function() { }); it('Testing key ID and fingerprint for V3 and V4 keys', function(done) { - var pubKeysV4 = openpgp.key.readArmored(twoKeys); + const pubKeysV4 = openpgp.key.readArmored(twoKeys); expect(pubKeysV4).to.exist; expect(pubKeysV4.err).to.not.exist; expect(pubKeysV4.keys).to.have.length(2); - var pubKeyV4 = pubKeysV4.keys[0]; + const pubKeyV4 = pubKeysV4.keys[0]; expect(pubKeyV4).to.exist; - var pubKeysV3 = openpgp.key.readArmored(pub_v3); + const pubKeysV3 = openpgp.key.readArmored(pub_v3); expect(pubKeysV3).to.exist; expect(pubKeysV3.err).to.not.exist; expect(pubKeysV3.keys).to.have.length(1); - var pubKeyV3 = pubKeysV3.keys[0]; + const pubKeyV3 = pubKeysV3.keys[0]; expect(pubKeyV3).to.exist; expect(pubKeyV4.primaryKey.getKeyId().toHex()).to.equal('4a63613a4d6e4094'); @@ -714,27 +717,27 @@ describe('Key', function() { }); it('Create new key ID with fromId()', function() { - var pubKeyV4 = openpgp.key.readArmored(twoKeys).keys[0]; - var keyId = pubKeyV4.primaryKey.getKeyId(); - var newKeyId = keyId.constructor.fromId(keyId.toHex()); + const pubKeyV4 = openpgp.key.readArmored(twoKeys).keys[0]; + const keyId = pubKeyV4.primaryKey.getKeyId(); + const newKeyId = keyId.constructor.fromId(keyId.toHex()); expect(newKeyId.toHex()).to.equal(keyId.toHex()); }); it('Testing key method getSubkeyPackets', function(done) { - var pubKeys = openpgp.key.readArmored(pub_sig_test); + const pubKeys = openpgp.key.readArmored(pub_sig_test); expect(pubKeys).to.exist; expect(pubKeys.err).to.not.exist; expect(pubKeys.keys).to.have.length(1); - var pubKey = pubKeys.keys[0]; + const pubKey = pubKeys.keys[0]; expect(pubKey).to.exist; - var packetlist = new openpgp.packet.List(); + const packetlist = new openpgp.packet.List(); packetlist.read(openpgp.armor.decode(pub_sig_test).data); - var subkeys = pubKey.getSubkeyPackets(); + const subkeys = pubKey.getSubkeyPackets(); expect(subkeys).to.exist; expect(subkeys).to.have.length(2); expect(subkeys[0].getKeyId().equals(packetlist[8].getKeyId())).to.be.true; @@ -743,12 +746,12 @@ describe('Key', function() { }); it('Verify status of revoked subkey', function(done) { - var pubKeys = openpgp.key.readArmored(pub_sig_test); + const pubKeys = openpgp.key.readArmored(pub_sig_test); expect(pubKeys).to.exist; expect(pubKeys.err).to.not.exist; expect(pubKeys.keys).to.have.length(1); - var pubKey = pubKeys.keys[0]; + const pubKey = pubKeys.keys[0]; expect(pubKey).to.exist; expect(pubKey.subKeys).to.exist; expect(pubKey.subKeys).to.have.length(2); @@ -759,21 +762,21 @@ describe('Key', function() { }); it('Evaluate key flags to find valid encryption key packet', function() { - var pubKeys = openpgp.key.readArmored(pub_sig_test); + const pubKeys = openpgp.key.readArmored(pub_sig_test); expect(pubKeys).to.exist; expect(pubKeys.err).to.not.exist; expect(pubKeys.keys).to.have.length(1); - var pubKey = pubKeys.keys[0]; + const pubKey = pubKeys.keys[0]; // remove subkeys pubKey.subKeys = null; // primary key has only key flags for signing - var keyPacket = pubKey.getEncryptionKeyPacket(); + const keyPacket = pubKey.getEncryptionKeyPacket(); expect(keyPacket).to.not.exist; }); it('Method getExpirationTime V4 Key', function() { - var pubKey = openpgp.key.readArmored(twoKeys).keys[1]; + const pubKey = openpgp.key.readArmored(twoKeys).keys[1]; expect(pubKey).to.exist; expect(pubKey).to.be.an.instanceof(openpgp.key.Key); return pubKey.verifyPrimaryUser().then(() => { @@ -782,22 +785,22 @@ describe('Key', function() { }); it('Method getExpirationTime V4 SubKey', function() { - var pubKey = openpgp.key.readArmored(twoKeys).keys[1]; + const pubKey = openpgp.key.readArmored(twoKeys).keys[1]; expect(pubKey).to.exist; expect(pubKey).to.be.an.instanceof(openpgp.key.Key); expect(pubKey.subKeys[0].getExpirationTime().toISOString()).to.be.equal('2018-11-26T10:58:29.000Z'); }); it('update() - throw error if fingerprints not equal', function(done) { - var keys = openpgp.key.readArmored(twoKeys).keys; + const keys = openpgp.key.readArmored(twoKeys).keys; expect(keys[0].update.bind( keys[0], keys[1] )()).to.be.rejectedWith('Key update method: fingerprints of keys not equal').notify(done); }); it('update() - merge revocation signature', function(done) { - var source = openpgp.key.readArmored(pub_revoked).keys[0]; - var dest = openpgp.key.readArmored(pub_revoked).keys[0]; + const source = openpgp.key.readArmored(pub_revoked).keys[0]; + const dest = openpgp.key.readArmored(pub_revoked).keys[0]; expect(source.revocationSignature).to.exist; dest.revocationSignature = null; dest.update(source).then(() => { @@ -807,8 +810,8 @@ describe('Key', function() { }); it('update() - merge user', function(done) { - var source = openpgp.key.readArmored(pub_sig_test).keys[0]; - var dest = openpgp.key.readArmored(pub_sig_test).keys[0]; + const source = openpgp.key.readArmored(pub_sig_test).keys[0]; + const dest = openpgp.key.readArmored(pub_sig_test).keys[0]; expect(source.users[1]).to.exist; dest.users.pop(); dest.update(source).then(() => { @@ -819,8 +822,8 @@ describe('Key', function() { }); it('update() - merge user - other and revocation certification', function(done) { - var source = openpgp.key.readArmored(pub_sig_test).keys[0]; - var dest = openpgp.key.readArmored(pub_sig_test).keys[0]; + const source = openpgp.key.readArmored(pub_sig_test).keys[0]; + const dest = openpgp.key.readArmored(pub_sig_test).keys[0]; expect(source.users[1].otherCertifications).to.exist; expect(source.users[1].revocationCertifications).to.exist; dest.users[1].otherCertifications = null; @@ -835,8 +838,8 @@ describe('Key', function() { }); it('update() - merge subkey', function(done) { - var source = openpgp.key.readArmored(pub_sig_test).keys[0]; - var dest = openpgp.key.readArmored(pub_sig_test).keys[0]; + const source = openpgp.key.readArmored(pub_sig_test).keys[0]; + const dest = openpgp.key.readArmored(pub_sig_test).keys[0]; expect(source.subKeys[1]).to.exist; dest.subKeys.pop(); dest.update(source).then(() => { @@ -849,8 +852,8 @@ describe('Key', function() { }); it('update() - merge subkey - revocation signature', function(done) { - var source = openpgp.key.readArmored(pub_sig_test).keys[0]; - var dest = openpgp.key.readArmored(pub_sig_test).keys[0]; + const source = openpgp.key.readArmored(pub_sig_test).keys[0]; + const dest = openpgp.key.readArmored(pub_sig_test).keys[0]; expect(source.subKeys[0].revocationSignature).to.exist; dest.subKeys[0].revocationSignature = null; dest.update(source).then(() => { @@ -861,8 +864,8 @@ describe('Key', function() { }); it('update() - merge private key into public key', function() { - var source = openpgp.key.readArmored(priv_key_rsa).keys[0]; - var dest = openpgp.key.readArmored(twoKeys).keys[0]; + const source = openpgp.key.readArmored(priv_key_rsa).keys[0]; + const dest = openpgp.key.readArmored(twoKeys).keys[0]; expect(dest.isPublic()).to.be.true; return dest.update(source).then(() => { expect(dest.isPrivate()).to.be.true; @@ -881,8 +884,8 @@ describe('Key', function() { }); it('update() - merge private key into public key - no subkeys', function() { - var source = openpgp.key.readArmored(priv_key_rsa).keys[0]; - var dest = openpgp.key.readArmored(twoKeys).keys[0]; + const source = openpgp.key.readArmored(priv_key_rsa).keys[0]; + const dest = openpgp.key.readArmored(twoKeys).keys[0]; source.subKeys = null; dest.subKeys = null; expect(dest.isPublic()).to.be.true; @@ -900,8 +903,8 @@ describe('Key', function() { }); it('update() - merge private key into public key - mismatch throws error', function(done) { - var source = openpgp.key.readArmored(priv_key_rsa).keys[0]; - var dest = openpgp.key.readArmored(twoKeys).keys[0]; + const source = openpgp.key.readArmored(priv_key_rsa).keys[0]; + const dest = openpgp.key.readArmored(twoKeys).keys[0]; source.subKeys = null; expect(dest.subKeys).to.exist; expect(dest.isPublic()).to.be.true; @@ -910,8 +913,8 @@ describe('Key', function() { }); it('update() - merge subkey binding signatures', function(done) { - var source = openpgp.key.readArmored(pgp_desktop_pub).keys[0]; - var dest = openpgp.key.readArmored(pgp_desktop_priv).keys[0]; + const source = openpgp.key.readArmored(pgp_desktop_pub).keys[0]; + const dest = openpgp.key.readArmored(pgp_desktop_priv).keys[0]; expect(source.subKeys[0].bindingSignatures[0]).to.exist; expect(source.subKeys[0].verify(source.primaryKey)) .to.eventually.equal(openpgp.enums.keyStatus.valid); @@ -925,52 +928,52 @@ describe('Key', function() { }); it('getPreferredSymAlgo() - one key - AES256', function() { - var key1 = openpgp.key.readArmored(twoKeys).keys[0]; + const key1 = openpgp.key.readArmored(twoKeys).keys[0]; return key1.verifyPrimaryUser().then(() => { - var prefAlgo = openpgp.key.getPreferredSymAlgo([key1]); + const prefAlgo = openpgp.key.getPreferredSymAlgo([key1]); expect(prefAlgo).to.equal(openpgp.enums.symmetric.aes256); }); }); it('getPreferredSymAlgo() - two key - AES128', function() { - var keys = openpgp.key.readArmored(twoKeys).keys; - var key1 = keys[0]; - var key2 = keys[1]; + const keys = openpgp.key.readArmored(twoKeys).keys; + const key1 = keys[0]; + const key2 = keys[1]; return Promise.all([key1.verifyPrimaryUser(), key2.verifyPrimaryUser()]).then(() => { key2.getPrimaryUser().selfCertificate.preferredSymmetricAlgorithms = [6,7,3]; - var prefAlgo = openpgp.key.getPreferredSymAlgo([key1, key2]); + const prefAlgo = openpgp.key.getPreferredSymAlgo([key1, key2]); expect(prefAlgo).to.equal(openpgp.enums.symmetric.aes128); }); }); it('getPreferredSymAlgo() - two key - one without pref', function() { - var keys = openpgp.key.readArmored(twoKeys).keys; - var key1 = keys[0]; - var key2 = keys[1]; + const keys = openpgp.key.readArmored(twoKeys).keys; + const key1 = keys[0]; + const key2 = keys[1]; return Promise.all([key1.verifyPrimaryUser(), key2.verifyPrimaryUser()]).then(() => { key2.getPrimaryUser().selfCertificate.preferredSymmetricAlgorithms = null; - var prefAlgo = openpgp.key.getPreferredSymAlgo([key1, key2]); + const prefAlgo = openpgp.key.getPreferredSymAlgo([key1, key2]); expect(prefAlgo).to.equal(openpgp.config.encryption_cipher); }); }); it('Preferences of generated key', function() { - var testPref = function(key) { + const testPref = function(key) { // key flags - var keyFlags = openpgp.enums.keyFlags; + const keyFlags = openpgp.enums.keyFlags; expect(key.users[0].selfCertifications[0].keyFlags[0] & keyFlags.certify_keys).to.equal(keyFlags.certify_keys); expect(key.users[0].selfCertifications[0].keyFlags[0] & keyFlags.sign_data).to.equal(keyFlags.sign_data); expect(key.subKeys[0].bindingSignatures[0].keyFlags[0] & keyFlags.encrypt_communication).to.equal(keyFlags.encrypt_communication); expect(key.subKeys[0].bindingSignatures[0].keyFlags[0] & keyFlags.encrypt_storage).to.equal(keyFlags.encrypt_storage); - var sym = openpgp.enums.symmetric; + const sym = openpgp.enums.symmetric; expect(key.users[0].selfCertifications[0].preferredSymmetricAlgorithms).to.eql([sym.aes256, sym.aes128, sym.aes192, sym.cast5, sym.tripledes]); - var hash = openpgp.enums.hash; + const hash = openpgp.enums.hash; expect(key.users[0].selfCertifications[0].preferredHashAlgorithms).to.eql([hash.sha256, hash.sha512, hash.sha1]); - var compr = openpgp.enums.compression; + const compr = openpgp.enums.compression; expect(key.users[0].selfCertifications[0].preferredCompressionAlgorithms).to.eql([compr.zlib, compr.zip]); expect(key.users[0].selfCertifications[0].features).to.eql(openpgp.config.integrity_protect ? [1] : null); // modification detection }; - var opt = {numBits: 512, userIds: 'test ', passphrase: 'hello'}; + const opt = {numBits: 512, userIds: 'test ', passphrase: 'hello'}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { testPref(key.key); @@ -979,15 +982,15 @@ describe('Key', function() { }); it('User attribute packet read & write', function() { - var key = openpgp.key.readArmored(user_attr_key).keys[0]; - var key2 = openpgp.key.readArmored(key.armor()).keys[0]; + const key = openpgp.key.readArmored(user_attr_key).keys[0]; + const key2 = openpgp.key.readArmored(key.armor()).keys[0]; expect(key.users[1].userAttribute).eql(key2.users[1].userAttribute); }); it('getPrimaryUser()', function() { - var key = openpgp.key.readArmored(pub_sig_test).keys[0]; + const key = openpgp.key.readArmored(pub_sig_test).keys[0]; return key.verifyPrimaryUser().then(() => { - var primUser = key.getPrimaryUser(); + const primUser = key.getPrimaryUser(); expect(primUser).to.exist; expect(primUser.user.userId.userid).to.equal('Signature Test '); expect(primUser.selfCertificate).to.be.an.instanceof(openpgp.packet.Signature); @@ -995,9 +998,9 @@ describe('Key', function() { }); it('Generated key is not unlocked by default', function() { - var opt = {numBits: 512, userIds: 'test ', passphrase: '123'}; + const opt = {numBits: 512, userIds: 'test ', passphrase: '123'}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys - var key; + let key; return openpgp.generateKey(opt).then(function(newKey) { key = newKey; return openpgp.message.fromText('hello').encrypt([key.key]); @@ -1009,8 +1012,8 @@ describe('Key', function() { }); it('Generate key - single userid', function() { - var userId = 'test '; - var opt = {numBits: 512, userIds: userId, passphrase: '123'}; + const userId = 'test '; + const opt = {numBits: 512, userIds: userId, passphrase: '123'}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { key = key.key; @@ -1020,9 +1023,9 @@ describe('Key', function() { }); it('Generate key - multi userid', function() { - var userId1 = 'test '; - var userId2 = 'test '; - var opt = {numBits: 512, userIds: [userId1, userId2], passphrase: '123'}; + const userId1 = 'test '; + const userId2 = 'test '; + const opt = {numBits: 512, userIds: [userId1, userId2], passphrase: '123'}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { key = key.key; @@ -1035,13 +1038,13 @@ describe('Key', function() { }); it('Encrypt key with new passphrase', function() { - var userId = 'test '; - var opt = {numBits: 512, userIds: userId, passphrase: 'passphrase'}; + const userId = 'test '; + const opt = {numBits: 512, userIds: userId, passphrase: 'passphrase'}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { key = key.key; - var armor1 = key.armor(); - var armor2 = key.armor(); + const armor1 = key.armor(); + const armor2 = key.armor(); expect(armor1).to.equal(armor2); expect(key.decrypt('passphrase')).to.be.true; expect(key.primaryKey.isDecrypted).to.be.true; @@ -1051,44 +1054,44 @@ describe('Key', function() { expect(key.primaryKey.isDecrypted).to.be.false; expect(key.decrypt('new_passphrase')).to.be.true; expect(key.primaryKey.isDecrypted).to.be.true; - var armor3 = key.armor(); + const armor3 = key.armor(); expect(armor3).to.not.equal(armor1); }); }); it('Generate key - ensure keyExpirationTime works', function() { - var expect_delta = 365 * 24 * 60 * 60; - var userId = 'test '; - var opt = {numBits: 512, userIds: userId, passphrase: '123', keyExpirationTime: expect_delta}; + const expect_delta = 365 * 24 * 60 * 60; + const userId = 'test '; + const opt = {numBits: 512, userIds: userId, passphrase: '123', keyExpirationTime: expect_delta}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { key = key.key; return key.verifyPrimaryUser().then(() => { - var expiration = key.getExpirationTime(); + const expiration = key.getExpirationTime(); expect(expiration).to.exist; - var actual_delta = (new Date(expiration) - new Date()) / 1000; + const actual_delta = (new Date(expiration) - new Date()) / 1000; expect(Math.abs(actual_delta - expect_delta)).to.be.below(60); - var subKeyExpiration = key.subKeys[0].getExpirationTime(); + const subKeyExpiration = key.subKeys[0].getExpirationTime(); expect(subKeyExpiration).to.exist; - var actual_subKeyDelta = (new Date(subKeyExpiration) - new Date()) / 1000; + const actual_subKeyDelta = (new Date(subKeyExpiration) - new Date()) / 1000; expect(Math.abs(actual_subKeyDelta - expect_delta)).to.be.below(60); }); }); }); it('Sign and verify key - primary user', function() { - var key = openpgp.key.readArmored(pub_sig_test).keys[0]; - var privateKey = openpgp.key.readArmored(priv_key_rsa).keys[0]; + const key = openpgp.key.readArmored(pub_sig_test).keys[0]; + const privateKey = openpgp.key.readArmored(priv_key_rsa).keys[0]; privateKey.decrypt('hello world'); return key.signPrimaryUser([privateKey]).then(key => { return Promise.all( [key.verifyPrimaryUser([privateKey]), privateKey.verifyPrimaryUser()] ).then(results => { - var signatures = results[0]; + const signatures = results[0]; expect(signatures.length).to.equal(2); expect(signatures[0].keyid.toHex()).to.equal(key.getSigningKeyPacket().getKeyId().toHex()); expect(signatures[0].valid).to.be.null; @@ -1099,15 +1102,15 @@ describe('Key', function() { }); it('Sign key and verify with wrong key - primary user', function() { - var key = openpgp.key.readArmored(pub_sig_test).keys[0]; - var privateKey = openpgp.key.readArmored(priv_key_rsa).keys[0]; - var wrongKey = openpgp.key.readArmored(wrong_key).keys[0]; + const key = openpgp.key.readArmored(pub_sig_test).keys[0]; + const privateKey = openpgp.key.readArmored(priv_key_rsa).keys[0]; + const wrongKey = openpgp.key.readArmored(wrong_key).keys[0]; privateKey.decrypt('hello world'); return key.signPrimaryUser([privateKey]).then(key => { return Promise.all( [key.verifyPrimaryUser([wrongKey]), privateKey.verifyPrimaryUser()] ).then(results => { - var signatures = results[0]; + const signatures = results[0]; expect(signatures.length).to.equal(2); expect(signatures[0].keyid.toHex()).to.equal(key.getSigningKeyPacket().getKeyId().toHex()); expect(signatures[0].valid).to.be.null; @@ -1118,14 +1121,14 @@ describe('Key', function() { }); it('Sign and verify key - all users', function() { - var key = openpgp.key.readArmored(multi_uid_key).keys[0]; - var privateKey = openpgp.key.readArmored(priv_key_rsa).keys[0]; + const key = openpgp.key.readArmored(multi_uid_key).keys[0]; + const privateKey = openpgp.key.readArmored(priv_key_rsa).keys[0]; privateKey.decrypt('hello world'); return key.signAllUsers([privateKey]).then(key => { return Promise.all( [key.verifyAllUsers([privateKey]), key.verifyPrimaryUser(), privateKey.verifyPrimaryUser()] ).then(results => { - var signatures = results[0]; + const signatures = results[0]; expect(signatures.length).to.equal(4); expect(signatures[0].userid).to.equal(key.users[0].userId.userid); expect(signatures[0].keyid.toHex()).to.equal(key.getSigningKeyPacket().getKeyId().toHex()); @@ -1144,15 +1147,15 @@ describe('Key', function() { }); it('Sign key and verify with wrong key - all users', function() { - var key = openpgp.key.readArmored(multi_uid_key).keys[0]; - var privateKey = openpgp.key.readArmored(priv_key_rsa).keys[0]; - var wrongKey = openpgp.key.readArmored(wrong_key).keys[0]; + const key = openpgp.key.readArmored(multi_uid_key).keys[0]; + const privateKey = openpgp.key.readArmored(priv_key_rsa).keys[0]; + const wrongKey = openpgp.key.readArmored(wrong_key).keys[0]; privateKey.decrypt('hello world'); return key.signAllUsers([privateKey]).then(key => { return Promise.all( [key.verifyAllUsers([wrongKey]), key.verifyPrimaryUser(), privateKey.verifyPrimaryUser()] ).then(results => { - var signatures = results[0]; + const signatures = results[0]; expect(signatures.length).to.equal(4); expect(signatures[0].userid).to.equal(key.users[0].userId.userid); expect(signatures[0].keyid.toHex()).to.equal(key.getSigningKeyPacket().getKeyId().toHex()); @@ -1171,9 +1174,9 @@ describe('Key', function() { }); it('Reformat key without passphrase', function() { - var userId1 = 'test1 '; - var userId2 = 'test2 '; - var opt = {numBits: 512, userIds: userId1}; + const userId1 = 'test1 '; + const userId2 = 'test2 '; + const opt = {numBits: 512, userIds: userId1}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { key = key.key; @@ -1192,9 +1195,9 @@ describe('Key', function() { }); it('Reformat key with no subkey with passphrase', function() { - var userId = 'test1 '; - var keys = openpgp.key.readArmored(key_without_subkey).keys; - var opt = {privateKey: keys[0], userIds: [userId], passphrase: "test"} + const userId = 'test1 '; + const keys = openpgp.key.readArmored(key_without_subkey).keys; + const opt = {privateKey: keys[0], userIds: [userId], passphrase: "test"}; return openpgp.reformatKey(opt).then(function(newKey) { newKey = newKey.key; expect(newKey.users.length).to.equal(1); @@ -1204,9 +1207,9 @@ describe('Key', function() { }); it('Reformat key with no subkey without passphrase', function() { - var userId = 'test1 '; - var keys = openpgp.key.readArmored(key_without_subkey).keys; - var opt = {privateKey: keys[0], userIds: [userId]} + const userId = 'test1 '; + const keys = openpgp.key.readArmored(key_without_subkey).keys; + const opt = {privateKey: keys[0], userIds: [userId]}; return openpgp.reformatKey(opt).then(function(newKey) { newKey = newKey.key; expect(newKey.users.length).to.equal(1); @@ -1223,10 +1226,10 @@ describe('Key', function() { }); it('Reformat and encrypt key', function() { - var userId1 = 'test1 '; - var userId2 = 'test2 '; - var userId3 = 'test3 '; - var opt = {numBits: 512, userIds: userId1}; + const userId1 = 'test1 '; + const userId2 = 'test2 '; + const userId3 = 'test3 '; + const opt = {numBits: 512, userIds: userId1}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { key = key.key; @@ -1245,9 +1248,9 @@ describe('Key', function() { }); it('Sign and encrypt with reformatted key', function() { - var userId1 = 'test1 '; - var userId2 = 'test2 '; - var opt = {numBits: 512, userIds: userId1}; + const userId1 = 'test1 '; + const userId2 = 'test2 '; + const opt = {numBits: 512, userIds: userId1}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { key = key.key; @@ -1266,7 +1269,7 @@ describe('Key', function() { }); it('Throw user friendly error when reformatting encrypted key', function() { - var opt = {numBits: 512, userIds: 'test1 ', passphrase: '1234'}; + const opt = {numBits: 512, userIds: 'test1 ', passphrase: '1234'}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(original) { return openpgp.reformatKey({privateKey: original.key, userIds: 'test2 ', passphrase: '1234'}).then(function() { @@ -1278,7 +1281,7 @@ describe('Key', function() { }); it('Find a valid subkey binding signature among many invalid ones', function(done) { - var k = openpgp.key.readArmored(valid_binding_sig_among_many_expired_sigs_pub).keys[0]; + const k = openpgp.key.readArmored(valid_binding_sig_among_many_expired_sigs_pub).keys[0]; expect(k.getEncryptionKeyPacket()).to.not.be.null; done(); }); diff --git a/test/general/keyring.js b/test/general/keyring.js index e135ce83..44566aad 100644 --- a/test/general/keyring.js +++ b/test/general/keyring.js @@ -1,16 +1,17 @@ -var openpgp = typeof window != 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var keyring = new openpgp.Keyring(), - chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { expect } = chai; +const keyring = new openpgp.Keyring(); describe("Keyring", function() { - var user = 'whiteout.test@t-online.de', - passphrase = 'asdf', - keySize = 512, - keyId = 'f6f60e9b42cdff4c', - keyFingerP = '5856cef789c3a307e8a1b976f6f60e9b42cdff4c', - pubkey = '-----BEGIN PGP PUBLIC KEY BLOCK-----\n' + + const user = 'whiteout.test@t-online.de'; + const passphrase = 'asdf'; + const keySize = 512; + const keyId = 'f6f60e9b42cdff4c'; + const keyFingerP = '5856cef789c3a307e8a1b976f6f60e9b42cdff4c'; + const pubkey = '-----BEGIN PGP PUBLIC KEY BLOCK-----\n' + 'Version: OpenPGP.js v.1.20131011\n' + 'Comment: https://openpgpjs.org\n' + '\n' + @@ -20,8 +21,8 @@ describe("Keyring", function() { 'vQkQ9vYOm0LN/0wAAAW4Af9C+kYW1AvNWmivdtr0M0iYCUjM9DNOQH1fcvXq\n' + 'IiN602mWrkd8jcEzLsW5IUNzVPLhrFIuKyBDTpLnC07Loce1\n' + '=6XMW\n' + - '-----END PGP PUBLIC KEY BLOCK-----', - privkey = '-----BEGIN PGP PRIVATE KEY BLOCK-----\n' + + '-----END PGP PUBLIC KEY BLOCK-----'; + const privkey = '-----BEGIN PGP PRIVATE KEY BLOCK-----\n' + 'Version: OpenPGP.js v.1.20131011\n' + 'Comment: https://openpgpjs.org\n' + '\n' + @@ -36,12 +37,12 @@ describe("Keyring", function() { 'Af9C+kYW1AvNWmivdtr0M0iYCUjM9DNOQH1fcvXqIiN602mWrkd8jcEzLsW5\n' + 'IUNzVPLhrFIuKyBDTpLnC07Loce1\n' + '=ULta\n' + - '-----END PGP PRIVATE KEY BLOCK-----', - keyId2 = 'ba993fc2aee18a3a', - keyFingerP2 = '560b7a7f3f9ab516b233b299ba993fc2aee18a3a', - subkeyId2 = 'f47c5210a8cc2740', - subkeyFingerP2 = '2a20c371141e000833848d85f47c5210a8cc2740', - pubkey2 = + '-----END PGP PRIVATE KEY BLOCK-----'; + const keyId2 = 'ba993fc2aee18a3a'; + const keyFingerP2 = '560b7a7f3f9ab516b233b299ba993fc2aee18a3a'; + const subkeyId2 = 'f47c5210a8cc2740'; + const subkeyFingerP2 = '2a20c371141e000833848d85f47c5210a8cc2740'; + const pubkey2 = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.22 (GNU/Linux)', '', @@ -80,10 +81,10 @@ describe("Keyring", function() { 'y61IhKbJCOlQxyem+kepjNapkhKDAQDIDL38bZWU4Rm0nq82Xb4yaI0BCWDcFkHV', 'og2umGfGng==', '=v3+L', - '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'), - user3 = 'plain@email.org', - keyFingerP3 = 'f9972bf320a86a93c6614711ed241e1de755d53c', - pubkey3 = + '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); + const user3 = 'plain@email.org'; + const keyFingerP3 = 'f9972bf320a86a93c6614711ed241e1de755d53c'; + const pubkey3 = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', '', 'xo0EVe6wawEEAKG4LDE9946jdvvbfVTF9qWtOyxHYjb40z7hgcZsPEGd6QfN', @@ -114,117 +115,117 @@ describe("Keyring", function() { }); it('getKeysForId() - unknown id', function() { - var keys = keyring.getKeysForId('01234567890123456'); + const keys = keyring.getKeysForId('01234567890123456'); expect(keys).to.be.null; }); it('getKeysForId() - valid id', function() { - var keys = keyring.getKeysForId(keyId); + const keys = keyring.getKeysForId(keyId); // we get public and private key expect(keys).to.exist.and.have.length(2); expect(keys[0].primaryKey.getKeyId().toHex()).equals(keyId); }); it('publicKeys.getForId() - unknown id', function() { - var key = keyring.publicKeys.getForId('01234567890123456'); + const key = keyring.publicKeys.getForId('01234567890123456'); expect(key).to.be.null; }); it('publicKeys.getForId() - valid id', function() { - var key = keyring.publicKeys.getForId(keyId); + const key = keyring.publicKeys.getForId(keyId); expect(key).to.exist.and.be.an.instanceof(openpgp.key.Key); expect(key.primaryKey.getKeyId().toHex()).equals(keyId); }); it('privateKeys.getForId() - unknown id', function() { - var key = keyring.privateKeys.getForId('01234567890123456'); + const key = keyring.privateKeys.getForId('01234567890123456'); expect(key).to.be.null; }); it('privateKeys.getForId() - valid id', function() { - var key = keyring.privateKeys.getForId(keyId); + const key = keyring.privateKeys.getForId(keyId); expect(key).to.exist.and.be.an.instanceof(openpgp.key.Key); expect(key.primaryKey.getKeyId().toHex()).equals(keyId); }); it('publicKeys.getForId() - subkey id', function() { - var key = keyring.publicKeys.getForId(subkeyId2); + const key = keyring.publicKeys.getForId(subkeyId2); expect(key).to.be.null; }); it('publicKeys.getForId() - deep, including subkeys - subkey id', function() { - var key = keyring.publicKeys.getForId(subkeyId2, true); + const key = keyring.publicKeys.getForId(subkeyId2, true); expect(key).to.exist.and.be.an.instanceof(openpgp.key.Key); expect(key.primaryKey.getKeyId().toHex()).equals(keyId2); }); it('getKeysForId() - unknown fingerprint', function() { - var keys = keyring.getKeysForId('71130e8383bef9526e062600d5e9f93acbbc7275'); + const keys = keyring.getKeysForId('71130e8383bef9526e062600d5e9f93acbbc7275'); expect(keys).to.be.null; }); it('getKeysForId() - valid fingerprint', function() { - var keys = keyring.getKeysForId(keyFingerP2); + const keys = keyring.getKeysForId(keyFingerP2); expect(keys).to.exist.and.have.length(1); expect(keys[0].primaryKey.getKeyId().toHex()).equals(keyId2); }); it('publicKeys.getForId() - unknown fingerprint', function() { - var key = keyring.publicKeys.getForId('71130e8383bef9526e062600d5e9f93acbbc7275'); + const key = keyring.publicKeys.getForId('71130e8383bef9526e062600d5e9f93acbbc7275'); expect(key).to.be.null; }); it('publicKeys.getForId() - valid fingerprint', function() { - var key = keyring.publicKeys.getForId(keyFingerP2); + const key = keyring.publicKeys.getForId(keyFingerP2); expect(key).to.exist.and.be.an.instanceof(openpgp.key.Key); expect(key.primaryKey.getKeyId().toHex()).equals(keyId2); }); it('publicKeys.getForId() - subkey fingerprint', function() { - var key = keyring.publicKeys.getForId(subkeyFingerP2); + const key = keyring.publicKeys.getForId(subkeyFingerP2); expect(key).to.be.null; }); it('publicKeys.getForId() - deep, including subkeys - subkey fingerprint', function() { - var key = keyring.publicKeys.getForId(subkeyFingerP2, true); + const key = keyring.publicKeys.getForId(subkeyFingerP2, true); expect(key).to.exist.and.be.an.instanceof(openpgp.key.Key); expect(key.primaryKey.getKeyId().toHex()).equals(keyId2); }); it('publicKeys.getForAddress() - unknown address', function() { - var keys = keyring.publicKeys.getForAddress('nobody@example.com'); + const keys = keyring.publicKeys.getForAddress('nobody@example.com'); expect(keys).to.be.empty; }); it('publicKeys.getForAddress() - valid address', function() { - var keys = keyring.publicKeys.getForAddress(user); + const keys = keyring.publicKeys.getForAddress(user); expect(keys).to.exist.and.have.length(1); }); it('publicKeys.getForAddress() - valid address, plain email user id', function() { keyring.publicKeys.importKey(pubkey3); - var keys = keyring.publicKeys.getForAddress(user3); + const keys = keyring.publicKeys.getForAddress(user3); keyring.removeKeysForId(keyFingerP3); expect(keys).to.exist.and.have.length(1); }); it('publicKeys.getForAddress() - address with regex special char |', function() { - var keys = keyring.publicKeys.getForAddress('whiteout.test|not@t-online.de'); + const keys = keyring.publicKeys.getForAddress('whiteout.test|not@t-online.de'); expect(keys).to.be.empty; }); it('publicKeys.getForAddress() - address with regex special char .', function() { - var keys = keyring.publicKeys.getForAddress('wh.t.out.test@t-online.de'); + const keys = keyring.publicKeys.getForAddress('wh.t.out.test@t-online.de'); expect(keys).to.be.empty; }); it('privateKeys.getForAddress() - unknown address', function() { - var key = keyring.privateKeys.getForAddress('nobody@example.com'); + const key = keyring.privateKeys.getForAddress('nobody@example.com'); expect(key).to.be.empty; }); it('privateKeys.getForAddress() - valid address', function() { - var key = keyring.privateKeys.getForAddress(user); + const key = keyring.privateKeys.getForAddress(user); expect(key).to.exist.and.have.length(1); }); @@ -233,52 +234,52 @@ describe("Keyring", function() { }); it('after loading from localstorage: getKeysForKeyId() - valid id', function() { - var keyring = new openpgp.Keyring(), - keys = keyring.getKeysForId(keyId); + const keyring = new openpgp.Keyring(); + const keys = keyring.getKeysForId(keyId); // we expect public and private key expect(keys).to.exist.and.have.length(2); }); it('publicKeys.removeForId() - unknown id', function() { - var key = keyring.publicKeys.removeForId('01234567890123456'); + const key = keyring.publicKeys.removeForId('01234567890123456'); expect(key).to.be.null; }); it('publicKeys.removeForId() - valid id', function() { - var key = keyring.publicKeys.removeForId(keyId); + const key = keyring.publicKeys.removeForId(keyId); expect(key).to.exist.and.be.an.instanceof(openpgp.key.Key); expect(key.primaryKey.getKeyId().toHex()).equals(keyId); expect(keyring.publicKeys.keys).to.exist.and.have.length(1); }); it('publicKeys.removeForId() - unknown fingerprint', function() { - var key = keyring.publicKeys.removeForId('71130e8383bef9526e062600d5e9f93acbbc7275'); + const key = keyring.publicKeys.removeForId('71130e8383bef9526e062600d5e9f93acbbc7275'); expect(key).to.be.null; expect(keyring.publicKeys.keys).to.exist.and.have.length(1); }); it('publicKeys.removeForId() - valid fingerprint', function() { - var key = keyring.publicKeys.removeForId(keyFingerP2); + const key = keyring.publicKeys.removeForId(keyFingerP2); expect(key).to.exist.and.be.an.instanceof(openpgp.key.Key); expect(key.primaryKey.getKeyId().toHex()).equals(keyId2); expect(keyring.publicKeys.keys).to.be.empty; }); it('customize localstorage itemname', function() { - var localstore1 = new openpgp.Keyring.localstore('my-custom-prefix-'); - var localstore2 = new openpgp.Keyring.localstore('my-custom-prefix-'); - var localstore3 = new openpgp.Keyring.localstore(); + const localstore1 = new openpgp.Keyring.localstore('my-custom-prefix-'); + const localstore2 = new openpgp.Keyring.localstore('my-custom-prefix-'); + const localstore3 = new openpgp.Keyring.localstore(); localstore3.storePublic([]); - var key = openpgp.key.readArmored(pubkey).keys[0]; + const key = openpgp.key.readArmored(pubkey).keys[0]; localstore1.storePublic([key]); expect(localstore2.loadPublic()[0].primaryKey.getKeyId().equals(key.primaryKey.getKeyId())).to.be.true; expect(localstore3.loadPublic()).to.have.length(0); }); it('emptying keyring and storing removes keys', function() { - var key = openpgp.key.readArmored(pubkey).keys[0]; + const key = openpgp.key.readArmored(pubkey).keys[0]; - var localstore = new openpgp.Keyring.localstore('remove-prefix-'); + const localstore = new openpgp.Keyring.localstore('remove-prefix-'); localstore.storePublic([]); expect(localstore.storage.getItem('remove-prefix-public-keys')).to.be.null; @@ -296,14 +297,14 @@ describe("Keyring", function() { keyring.privateKeys.importKey(privkey); expect(keyring.publicKeys.keys).to.have.length(2); expect(keyring.privateKeys.keys).to.have.length(1); - var keys = keyring.removeKeysForId('01234567890123456'); + const keys = keyring.removeKeysForId('01234567890123456'); expect(keys).to.be.null; expect(keyring.publicKeys.keys).to.have.length(2); expect(keyring.privateKeys.keys).to.have.length(1); }); it('removeKeysForId() - valid id', function() { - var keys = keyring.removeKeysForId(keyId); + const keys = keyring.removeKeysForId(keyId); expect(keys).to.have.length(2); expect(keyring.publicKeys.keys).to.have.length(1); expect(keyring.privateKeys.keys).to.have.length(0); @@ -315,14 +316,14 @@ describe("Keyring", function() { keyring.privateKeys.importKey(privkey); expect(keyring.publicKeys.keys).to.have.length(2); expect(keyring.privateKeys.keys).to.have.length(1); - var keys = keyring.removeKeysForId('71130e8383bef9526e062600d5e9f93acbbc7275'); + const keys = keyring.removeKeysForId('71130e8383bef9526e062600d5e9f93acbbc7275'); expect(keys).to.be.null; expect(keyring.publicKeys.keys).to.have.length(2); expect(keyring.privateKeys.keys).to.have.length(1); }); it('removeKeysForId() - valid fingerprint', function() { - var keys = keyring.removeKeysForId(keyFingerP); + const keys = keyring.removeKeysForId(keyFingerP); expect(keys).to.have.length(2); expect(keyring.publicKeys.keys).to.have.length(1); expect(keyring.privateKeys.keys).to.have.length(0); diff --git a/test/general/oid.js b/test/general/oid.js index fe0fe85b..f08c0d79 100644 --- a/test/general/oid.js +++ b/test/general/oid.js @@ -1,16 +1,16 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var expect = require('chai').expect; +const expect = require('chai').expect; describe('Oid tests', function() { - var OID = openpgp.OID; - var p256_oid = new Uint8Array([0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07]); - var p384_oid = new Uint8Array([0x2B, 0x81, 0x04, 0x00, 0x22]); - var p521_oid = new Uint8Array([0x2B, 0x81, 0x04, 0x00, 0x23]); + const OID = openpgp.OID; + const p256_oid = new Uint8Array([0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07]); + const p384_oid = new Uint8Array([0x2B, 0x81, 0x04, 0x00, 0x22]); + const p521_oid = new Uint8Array([0x2B, 0x81, 0x04, 0x00, 0x23]); it('Constructing', function() { - var oids = [p256_oid, p384_oid, p521_oid]; + const oids = [p256_oid, p384_oid, p521_oid]; oids.forEach(function (data) { - var oid = new OID(data); + const oid = new OID(data); expect(oid).to.exist; expect(oid.oid).to.exist; expect(oid.oid).to.have.length(data.length); @@ -18,15 +18,15 @@ describe('Oid tests', function() { }); }); it('Reading and writing', function() { - var oids = [p256_oid, p384_oid, p521_oid]; + const oids = [p256_oid, p384_oid, p521_oid]; oids.forEach(function (data) { data = openpgp.util.concatUint8Array([new Uint8Array([data.length]), data]); - var oid = new OID(); + const oid = new OID(); expect(oid.read(data)).to.equal(data.length); expect(oid.oid).to.exist; expect(oid.oid).to.have.length(data.length-1); expect(oid.oid).to.equal(openpgp.util.Uint8Array2str(data.subarray(1))); - var result = oid.write(); + const result = oid.write(); expect(result).to.exist; expect(result).to.have.length(data.length); expect(result[0]).to.equal(data.length-1); diff --git a/test/general/openpgp.js b/test/general/openpgp.js index b9943d9b..fb3f6118 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -1,13 +1,14 @@ /* globals tryTests: true */ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var sinon = require('sinon'), - chai = require('chai'); +const sinon = require('sinon'); +const chai = require('chai'); chai.use(require('chai-as-promised')); -var expect = chai.expect; -var pub_key = +const expect = chai.expect; + +const pub_key = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', @@ -32,7 +33,7 @@ var pub_key = '=h/aX', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); -var priv_key = +const priv_key = ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', @@ -72,7 +73,7 @@ var priv_key = '=lw5e', '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); -var pub_key_de = +const pub_key_de = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.22 (GNU/Linux)', '', @@ -113,7 +114,7 @@ var pub_key_de = '=v3+L', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); -var priv_key_de = +const priv_key_de = ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: GnuPG v2.0.22 (GNU/Linux)', '', @@ -157,13 +158,13 @@ var priv_key_de = '=kyeP', '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); -var passphrase = 'hello world'; -var plaintext = 'short message\nnext line\n한국어/조선말'; -var password1 = 'I am a password'; -var password2 = 'I am another password'; -var password3 = 'I am a third password'; +const passphrase = 'hello world'; +const plaintext = 'short message\nnext line\n한국어/조선말'; +const password1 = 'I am a password'; +const password2 = 'I am another password'; +const password3 = 'I am a third password'; -var twoPasswordGPGFail = ['-----BEGIN PGP MESSAGE-----', +const twoPasswordGPGFail = ['-----BEGIN PGP MESSAGE-----', 'Version: OpenPGP.js v3.0.0', 'Comment: https://openpgpjs.org', '', @@ -237,7 +238,7 @@ describe('OpenPGP.js public api tests', function() { }); it('should work', function() { - var workerStub = { + const workerStub = { postMessage: function() {} }; openpgp.initWorker({ @@ -250,7 +251,9 @@ describe('OpenPGP.js public api tests', function() { }); describe('generateKey - unit tests', function() { - var keyGenStub, keyObjStub, getWebCryptoAllStub; + let keyGenStub; + let keyObjStub; + let getWebCryptoAllStub; beforeEach(function() { keyObjStub = { @@ -277,89 +280,89 @@ describe('OpenPGP.js public api tests', function() { }); it('should fail for invalid user name', function() { - var opt = { + const opt = { userIds: [{ name: {}, email: 'text@example.com' }] }; - var test = openpgp.generateKey.bind(null, opt); + const test = openpgp.generateKey.bind(null, opt); expect(test).to.throw(/Invalid user id format/); }); it('should fail for invalid user email address', function() { - var opt = { + const opt = { userIds: [{ name: 'Test User', email: 'textexample.com' }] }; - var test = openpgp.generateKey.bind(null, opt); + const test = openpgp.generateKey.bind(null, opt); expect(test).to.throw(/Invalid user id format/); }); it('should fail for invalid user email address', function() { - var opt = { + const opt = { userIds: [{ name: 'Test User', email: 'text@examplecom' }] }; - var test = openpgp.generateKey.bind(null, opt); + const test = openpgp.generateKey.bind(null, opt); expect(test).to.throw(/Invalid user id format/); }); it('should fail for invalid string user id', function() { - var opt = { + const opt = { userIds: ['Test User text@example.com>'] }; - var test = openpgp.generateKey.bind(null, opt); + const test = openpgp.generateKey.bind(null, opt); expect(test).to.throw(/Invalid user id format/); }); it('should fail for invalid single string user id', function() { - var opt = { + const opt = { userIds: 'Test User text@example.com>' }; - var test = openpgp.generateKey.bind(null, opt); + const test = openpgp.generateKey.bind(null, opt); expect(test).to.throw(/Invalid user id format/); }); it('should work for valid single string user id', function() { - var opt = { + const opt = { userIds: 'Test User ' }; return openpgp.generateKey(opt); }); it('should work for valid string user id', function() { - var opt = { + const opt = { userIds: ['Test User '] }; return openpgp.generateKey(opt); }); it('should work for valid single user id hash', function() { - var opt = { + const opt = { userIds: { name: 'Test User', email: 'text@example.com' } }; return openpgp.generateKey(opt); }); it('should work for valid single user id hash', function() { - var opt = { + const opt = { userIds: [{ name: 'Test User', email: 'text@example.com' }] }; return openpgp.generateKey(opt); }); it('should work for an empty name', function() { - var opt = { + const opt = { userIds: { email: 'text@example.com' } }; return openpgp.generateKey(opt); }); it('should work for an empty email address', function() { - var opt = { + const opt = { userIds: { name: 'Test User' } }; return openpgp.generateKey(opt); }); it('should have default params set', function() { - var opt = { + const opt = { userIds: { name: 'Test User', email: 'text@example.com' }, passphrase: 'secret', unlocked: true @@ -394,13 +397,13 @@ describe('OpenPGP.js public api tests', function() { }); it('should delegate to async proxy', function() { - var workerStub = { + const workerStub = { postMessage: function() {} }; openpgp.initWorker({ worker: workerStub }); - var proxyGenStub = sinon.stub(openpgp.getWorker(), 'delegate'); + const proxyGenStub = sinon.stub(openpgp.getWorker(), 'delegate'); getWebCryptoAllStub.returns(); openpgp.generateKey(); @@ -410,7 +413,7 @@ describe('OpenPGP.js public api tests', function() { }); describe('generateKey - integration tests', function() { - var use_nativeVal; + let use_nativeVal; beforeEach(function() { use_nativeVal = openpgp.config.use_native; @@ -424,7 +427,7 @@ describe('OpenPGP.js public api tests', function() { it('should work in JS (without worker)', function() { openpgp.config.use_native = false; openpgp.destroyWorker(); - var opt = { + const opt = { userIds: [{ name: 'Test User', email: 'text@example.com' }], numBits: 512 }; @@ -439,7 +442,7 @@ describe('OpenPGP.js public api tests', function() { it('should work in JS (with worker)', function() { openpgp.config.use_native = false; openpgp.initWorker({ path:'../dist/openpgp.worker.js' }); - var opt = { + const opt = { userIds: [{ name: 'Test User', email: 'text@example.com' }], numBits: 512 }; @@ -453,7 +456,7 @@ describe('OpenPGP.js public api tests', function() { it('should work in with native crypto', function() { openpgp.config.use_native = true; - var opt = { + const opt = { userIds: [{ name: 'Test User', email: 'text@example.com' }], numBits: 512 }; @@ -468,7 +471,11 @@ describe('OpenPGP.js public api tests', function() { }); describe('encrypt, decrypt, sign, verify - integration tests', function() { - var privateKey, publicKey, zero_copyVal, use_nativeVal, aead_protectVal; + let privateKey; + let publicKey; + let zero_copyVal; + let use_nativeVal; + let aead_protectVal; beforeEach(function(done) { publicKey = openpgp.key.readArmored(pub_key); @@ -542,11 +549,11 @@ describe('OpenPGP.js public api tests', function() { }); it('Calling decrypt with not decrypted key leads to exception', function() { - var encOpt = { + const encOpt = { data: plaintext, - publicKeys: publicKey.keys, + publicKeys: publicKey.keys }; - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0] }; return openpgp.encrypt(encOpt).then(function(encrypted) { @@ -579,7 +586,7 @@ describe('OpenPGP.js public api tests', function() { }); describe('encryptSessionKey, decryptSessionKeys', function() { - var sk = new Uint8Array([0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01]); + const sk = new Uint8Array([0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01]); beforeEach(function(done) { expect(privateKey.keys[0].decrypt(passphrase)).to.be.true; @@ -618,7 +625,7 @@ describe('OpenPGP.js public api tests', function() { withCompression(function (modifyCompressionEncryptOptions, verifyCompressionDecrypted) { it('roundtrip workflow: encrypt, decryptSessionKeys, decrypt with pgp key pair', function () { - var msgAsciiArmored; + let msgAsciiArmored; return openpgp.encrypt(modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys @@ -642,7 +649,7 @@ describe('OpenPGP.js public api tests', function() { }); it('roundtrip workflow: encrypt, decryptSessionKeys, decrypt with password', function () { - var msgAsciiArmored; + let msgAsciiArmored; return openpgp.encrypt(modifyCompressionEncryptOptions({ data: plaintext, passwords: password1 @@ -666,7 +673,7 @@ describe('OpenPGP.js public api tests', function() { }); it('roundtrip workflow: encrypt with multiple passwords, decryptSessionKeys, decrypt with multiple passwords', function () { - var msgAsciiArmored; + let msgAsciiArmored; return openpgp.encrypt(modifyCompressionEncryptOptions({ data: plaintext, passwords: [password1, password2] @@ -690,7 +697,7 @@ describe('OpenPGP.js public api tests', function() { }); it('roundtrip workflow: encrypt twice with one password, decryptSessionKeys, only one session key', function () { - var msgAsciiArmored; + let msgAsciiArmored; return openpgp.encrypt(modifyCompressionEncryptOptions({ data: plaintext, passwords: [password1, password1] @@ -715,7 +722,7 @@ describe('OpenPGP.js public api tests', function() { }); describe('AES / RSA encrypt, decrypt, sign, verify', function() { - var wrong_pubkey = '-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n' + + const wrong_pubkey = '-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n' + 'Version: OpenPGP.js v0.9.0\r\n' + 'Comment: Hoodiecrow - https://hoodiecrow.com\r\n' + '\r\n' + @@ -734,11 +741,11 @@ describe('OpenPGP.js public api tests', function() { withCompression(function (modifyCompressionEncryptOptions, verifyCompressionDecrypted) { it('should encrypt then decrypt', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, - publicKeys: publicKey.keys, + publicKeys: publicKey.keys }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -754,11 +761,11 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt then decrypt', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, - publicKeys: publicKey.keys, + publicKeys: publicKey.keys }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -774,14 +781,14 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt then decrypt with multiple private keys', function () { - var privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; + const privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; privKeyDE.decrypt(passphrase); - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, - publicKeys: publicKey.keys, + publicKeys: publicKey.keys }); - var decOpt = { + const decOpt = { privateKeys: [privKeyDE, privateKey.keys[0]] }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -797,12 +804,12 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt then decrypt with wildcard', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, wildcard: true }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -818,15 +825,15 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt then decrypt with wildcard with multiple private keys', function () { - var privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; + const privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; privKeyDE.decrypt(passphrase); - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, wildcard: true }); - var decOpt = { + const decOpt = { privateKeys: [privKeyDE, privateKey.keys[0]] }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -842,7 +849,7 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt then decrypt using returned session key', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, returnSessionKey: true @@ -850,7 +857,7 @@ describe('OpenPGP.js public api tests', function() { return openpgp.encrypt(encOpt).then(function (encrypted) { expect(encrypted.data).to.match(/^-----BEGIN PGP MESSAGE/); - var decOpt = { + const decOpt = { sessionKeys: encrypted.sessionKey, message: openpgp.message.readArmored(encrypted.data) }; @@ -864,16 +871,16 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt using custom session key and decrypt using session key', function () { - var sessionKey = { + const sessionKey = { data: openpgp.crypto.generateSessionKey('aes256'), algorithm: 'aes256' }; - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, sessionKey: sessionKey, publicKeys: publicKey.keys }); - var decOpt = { + const decOpt = { sessionKeys: sessionKey }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -887,16 +894,16 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt using custom session key and decrypt using private key', function () { - var sessionKey = { + const sessionKey = { data: openpgp.crypto.generateSessionKey('aes128'), algorithm: 'aes128' }; - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, sessionKeys: sessionKey, publicKeys: publicKey.keys }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0] }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -910,12 +917,12 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt/sign and decrypt/verify', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, privateKeys: privateKey.keys }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: publicKey.keys }; @@ -932,12 +939,12 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt/sign and decrypt/verify with null string input', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: '', publicKeys: publicKey.keys, privateKeys: privateKey.keys }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: publicKey.keys }; @@ -954,13 +961,13 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt/sign and decrypt/verify with detached signatures', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, privateKeys: privateKey.keys, detached: true }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: publicKey.keys }; @@ -978,19 +985,19 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt and decrypt/verify with detached signature input and detached flag set for encryption', function () { - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privateKey.keys[0], detached: true }; - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, detached: true }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: publicKey.keys[0] }; @@ -1012,24 +1019,24 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt and decrypt/verify with detached signature as input and detached flag not set for encryption', function () { - var privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; + const privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; privKeyDE.decrypt(passphrase); - var pubKeyDE = openpgp.key.readArmored(pub_key_de).keys[0]; + const pubKeyDE = openpgp.key.readArmored(pub_key_de).keys[0]; - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privKeyDE, detached: true }; - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, privateKeys: privateKey.keys[0] }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: [publicKey.keys[0], pubKeyDE] }; @@ -1055,19 +1062,19 @@ describe('OpenPGP.js public api tests', function() { }); it('should fail to encrypt and decrypt/verify with detached signature input and detached flag set for encryption with wrong public key', function () { - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privateKey.keys, detached: true }; - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, detached: true }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: openpgp.key.readArmored(wrong_pubkey).keys }; @@ -1089,18 +1096,18 @@ describe('OpenPGP.js public api tests', function() { }); it('should fail to encrypt and decrypt/verify with detached signature as input and detached flag not set for encryption with wrong public key', function () { - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privateKey.keys, detached: true }; - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: openpgp.key.readArmored(wrong_pubkey).keys }; @@ -1121,12 +1128,12 @@ describe('OpenPGP.js public api tests', function() { }); it('should fail to verify decrypted data with wrong public pgp key', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, privateKeys: privateKey.keys }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: openpgp.key.readArmored(wrong_pubkey).keys }; @@ -1143,12 +1150,12 @@ describe('OpenPGP.js public api tests', function() { }); it('should fail to verify decrypted null string with wrong public pgp key', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: '', publicKeys: publicKey.keys, privateKeys: privateKey.keys }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: openpgp.key.readArmored(wrong_pubkey).keys }; @@ -1165,13 +1172,13 @@ describe('OpenPGP.js public api tests', function() { }); it('should successfully decrypt signed message without public keys to verify', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, privateKeys: privateKey.keys }); - var decOpt = { - privateKeys: privateKey.keys[0], + const decOpt = { + privateKeys: privateKey.keys[0] }; return openpgp.encrypt(encOpt).then(function (encrypted) { decOpt.message = openpgp.message.readArmored(encrypted.data); @@ -1186,13 +1193,13 @@ describe('OpenPGP.js public api tests', function() { }); it('should fail to verify decrypted data with wrong public pgp key with detached signatures', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, privateKeys: privateKey.keys, detached: true }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: openpgp.key.readArmored(wrong_pubkey).keys }; @@ -1210,18 +1217,18 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt and decrypt/verify both signatures when signed with two private keys', function () { - var privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; + const privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; privKeyDE.decrypt(passphrase); - var pubKeyDE = openpgp.key.readArmored(pub_key_de).keys[0]; + const pubKeyDE = openpgp.key.readArmored(pub_key_de).keys[0]; - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, publicKeys: publicKey.keys, privateKeys: [privateKey.keys[0], privKeyDE] }); - var decOpt = { + const decOpt = { privateKeys: privateKey.keys[0], publicKeys: [publicKey.keys[0], pubKeyDE] }; @@ -1244,11 +1251,11 @@ describe('OpenPGP.js public api tests', function() { }); it('should sign and verify cleartext data', function () { - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privateKey.keys }; - var verifyOpt = { + const verifyOpt = { publicKeys: publicKey.keys }; return openpgp.sign(signOpt).then(function (signed) { @@ -1264,12 +1271,12 @@ describe('OpenPGP.js public api tests', function() { }); it('should sign and verify cleartext data with detached signatures', function () { - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privateKey.keys, detached: true }; - var verifyOpt = { + const verifyOpt = { publicKeys: publicKey.keys }; return openpgp.sign(signOpt).then(function (signed) { @@ -1285,11 +1292,11 @@ describe('OpenPGP.js public api tests', function() { }); it('should sign and fail to verify cleartext data with wrong public pgp key', function () { - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privateKey.keys }; - var verifyOpt = { + const verifyOpt = { publicKeys: openpgp.key.readArmored(wrong_pubkey).keys }; return openpgp.sign(signOpt).then(function (signed) { @@ -1304,12 +1311,12 @@ describe('OpenPGP.js public api tests', function() { }); it('should sign and fail to verify cleartext data with wrong public pgp key with detached signature', function () { - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privateKey.keys, detached: true }; - var verifyOpt = { + const verifyOpt = { publicKeys: openpgp.key.readArmored(wrong_pubkey).keys }; return openpgp.sign(signOpt).then(function (signed) { @@ -1325,12 +1332,12 @@ describe('OpenPGP.js public api tests', function() { }); it('should sign and verify cleartext data and not armor', function () { - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privateKey.keys, armor: false }; - var verifyOpt = { + const verifyOpt = { publicKeys: publicKey.keys }; return openpgp.sign(signOpt).then(function (signed) { @@ -1345,13 +1352,13 @@ describe('OpenPGP.js public api tests', function() { }); it('should sign and verify cleartext data and not armor with detached signatures', function () { - var signOpt = { + const signOpt = { data: plaintext, privateKeys: privateKey.keys, detached: true, armor: false }; - var verifyOpt = { + const verifyOpt = { publicKeys: publicKey.keys }; return openpgp.sign(signOpt).then(function (signed) { @@ -1371,8 +1378,8 @@ describe('OpenPGP.js public api tests', function() { describe('ELG / DSA encrypt, decrypt, sign, verify', function() { withCompression(function (modifyCompressionEncryptOptions, verifyCompressionDecrypted) { it('round trip test', function () { - var pubKeyDE = openpgp.key.readArmored(pub_key_de).keys[0]; - var privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; + const pubKeyDE = openpgp.key.readArmored(pub_key_de).keys[0]; + const privKeyDE = openpgp.key.readArmored(priv_key_de).keys[0]; privKeyDE.decrypt(passphrase); return openpgp.encrypt(modifyCompressionEncryptOptions({ publicKeys: pubKeyDE, @@ -1398,7 +1405,7 @@ describe('OpenPGP.js public api tests', function() { }); describe("3DES decrypt", function() { - var pgp_msg = + const pgp_msg = ['-----BEGIN PGP MESSAGE-----', 'Version: GnuPG/MacGPG2 v2.0.19 (Darwin)', 'Comment: GPGTools - https://gpgtools.org', @@ -1411,7 +1418,7 @@ describe('OpenPGP.js public api tests', function() { '=JyIa', '-----END PGP MESSAGE-----'].join('\n'); - var priv_key = + const priv_key = ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: GnuPG/MacGPG2 v2.0.19 (Darwin)', 'Comment: GPGTools - https://gpgtools.org', @@ -1450,11 +1457,9 @@ describe('OpenPGP.js public api tests', function() { '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); it('Decrypt message', function() { - var privKey, message; - - privKey = openpgp.key.readArmored(priv_key).keys[0]; + const privKey = openpgp.key.readArmored(priv_key).keys[0]; privKey.decrypt('1234'); - message = openpgp.message.readArmored(pgp_msg); + const message = openpgp.message.readArmored(pgp_msg); return openpgp.decrypt({ privateKeys:privKey, message:message }).then(function(decrypted) { expect(decrypted.data).to.equal('hello 3des\n'); @@ -1466,11 +1471,11 @@ describe('OpenPGP.js public api tests', function() { describe('AES encrypt, decrypt', function() { withCompression(function (modifyCompressionEncryptOptions, verifyCompressionDecrypted) { it('should encrypt and decrypt with one password', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, passwords: password1 }); - var decOpt = { + const decOpt = { passwords: password1 }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -1484,11 +1489,11 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt and decrypt with two passwords', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, passwords: [password1, password2] }); - var decOpt = { + const decOpt = { passwords: password2 }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -1503,7 +1508,7 @@ describe('OpenPGP.js public api tests', function() { it('should decrypt with two passwords message which GPG fails on', function () { - var decOpt = { + const decOpt = { message: openpgp.message.readArmored(twoPasswordGPGFail), passwords: password2 }; @@ -1514,12 +1519,12 @@ describe('OpenPGP.js public api tests', function() { }); it('should encrypt and decrypt with password and not ascii armor', function () { - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: plaintext, passwords: password1, armor: false }); - var decOpt = { + const decOpt = { passwords: password1 }; return openpgp.encrypt(encOpt).then(function (encrypted) { @@ -1534,12 +1539,12 @@ describe('OpenPGP.js public api tests', function() { it('should encrypt and decrypt with binary data and transferable objects', function () { openpgp.config.zero_copy = true; // activate transferable objects - var encOpt = modifyCompressionEncryptOptions({ + const encOpt = modifyCompressionEncryptOptions({ data: new Uint8Array([0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]), passwords: password1, armor: false }); - var decOpt = { + const decOpt = { passwords: password1, format: 'binary' }; diff --git a/test/general/packet.js b/test/general/packet.js index 37c692f4..35276a4f 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -1,23 +1,24 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'); +const chai = require('chai'); chai.use(require('chai-as-promised')); -var expect = chai.expect; + +const { expect } = chai; function stringify(array) { if(!Uint8Array.prototype.isPrototypeOf(array)) { throw new Error('Data must be in the form of a Uint8Array'); } - var result = []; - for (var i = 0; i < array.length; i++) { + const result = []; + for (let i = 0; i < array.length; i++) { result[i] = String.fromCharCode(array[i]); } return result.join(''); } describe("Packet", function() { - var armored_key = + const armored_key = '-----BEGIN PGP PRIVATE KEY BLOCK-----\n' + 'Version: GnuPG v2.0.19 (GNU/Linux)\n' + '\n' + @@ -55,21 +56,21 @@ describe("Packet", function() { '-----END PGP PRIVATE KEY BLOCK-----'; it('Symmetrically encrypted packet', function(done) { - var message = new openpgp.packet.List(); + const message = new openpgp.packet.List(); - var literal = new openpgp.packet.Literal(); + const literal = new openpgp.packet.Literal(); literal.setText('Hello world'); - var enc = new openpgp.packet.SymmetricallyEncrypted(); + const enc = new openpgp.packet.SymmetricallyEncrypted(); message.push(enc); enc.packets.push(literal); - var key = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]), - algo = 'aes256'; + const key = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); + const algo = 'aes256'; enc.encrypt(algo, key); - var msg2 = new openpgp.packet.List(); + const msg2 = new openpgp.packet.List(); msg2.read(message.write()); msg2[0].ignore_mdc_error = true; msg2[0].decrypt(algo, key); @@ -79,39 +80,39 @@ describe("Packet", function() { }); it('Symmetrically encrypted packet - MDC error for modern cipher', function() { - var message = new openpgp.packet.List(); + const message = new openpgp.packet.List(); - var literal = new openpgp.packet.Literal(); + const literal = new openpgp.packet.Literal(); literal.setText('Hello world'); - var enc = new openpgp.packet.SymmetricallyEncrypted(); + const enc = new openpgp.packet.SymmetricallyEncrypted(); message.push(enc); enc.packets.push(literal); - var key = '12345678901234567890123456789012', - algo = 'aes256'; + const key = '12345678901234567890123456789012'; + const algo = 'aes256'; enc.encrypt(algo, key); - var msg2 = new openpgp.packet.List(); + const msg2 = new openpgp.packet.List(); msg2.read(message.write()); expect(msg2[0].decrypt.bind(msg2[0], algo, key)).to.throw('Decryption failed due to missing MDC in combination with modern cipher.'); }); it('Sym. encrypted integrity protected packet', function(done) { - var key = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]), - algo = 'aes256'; + const key = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); + const algo = 'aes256'; - var literal = new openpgp.packet.Literal(), - enc = new openpgp.packet.SymEncryptedIntegrityProtected(), - msg = new openpgp.packet.List(); + const literal = new openpgp.packet.Literal(); + const enc = new openpgp.packet.SymEncryptedIntegrityProtected(); + const msg = new openpgp.packet.List(); msg.push(enc); literal.setText('Hello world!'); enc.packets.push(literal); enc.encrypt(algo, key); - var msg2 = new openpgp.packet.List(); + const msg2 = new openpgp.packet.List(); msg2.read(msg.write()); msg2[0].decrypt(algo, key); @@ -121,18 +122,18 @@ describe("Packet", function() { }); it('Sym. encrypted AEAD protected packet', function() { - var key = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]), - algo = 'aes256'; + const key = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); + const algo = 'aes256'; - var literal = new openpgp.packet.Literal(), - enc = new openpgp.packet.SymEncryptedAEADProtected(), - msg = new openpgp.packet.List(); + const literal = new openpgp.packet.Literal(); + const enc = new openpgp.packet.SymEncryptedAEADProtected(); + const msg = new openpgp.packet.List(); msg.push(enc); literal.setText('Hello world!'); enc.packets.push(literal); - var msg2 = new openpgp.packet.List(); + const msg2 = new openpgp.packet.List(); return enc.encrypt(algo, key).then(function() { msg2.read(msg.write()); @@ -143,7 +144,7 @@ describe("Packet", function() { }); it('Sym encrypted session key with a compressed packet', function(done) { - var msg = + const msg = '-----BEGIN PGP MESSAGE-----\n' + 'Version: GnuPG v2.0.19 (GNU/Linux)\n' + '\n' + @@ -152,39 +153,39 @@ describe("Packet", function() { '=VZ0/\n' + '-----END PGP MESSAGE-----'; - var msgbytes = openpgp.armor.decode(msg).data; + const msgbytes = openpgp.armor.decode(msg).data; - var parsed = new openpgp.packet.List(); + const parsed = new openpgp.packet.List(); parsed.read(msgbytes); parsed[0].decrypt('test'); - var key = parsed[0].sessionKey; + const key = parsed[0].sessionKey; parsed[1].decrypt(parsed[0].sessionKeyAlgorithm, key); - var compressed = parsed[1].packets[0]; + const compressed = parsed[1].packets[0]; - var result = stringify(compressed.packets[0].data); + const result = stringify(compressed.packets[0].data); expect(result).to.equal('Hello world!\n'); done(); }); it('Public key encrypted symmetric key packet', function() { - var rsa = new openpgp.crypto.publicKey.rsa(); - var keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys + const rsa = new openpgp.crypto.publicKey.rsa(); + const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys return rsa.generate(keySize, "10001").then(function(mpiGen) { - var mpi = [mpiGen.n, mpiGen.ee, mpiGen.d, mpiGen.p, mpiGen.q, mpiGen.u]; + let mpi = [mpiGen.n, mpiGen.ee, mpiGen.d, mpiGen.p, mpiGen.q, mpiGen.u]; mpi = mpi.map(function(k) { - var mpi = new openpgp.MPI(); + const mpi = new openpgp.MPI(); mpi.fromBigInteger(k); return mpi; }); - var enc = new openpgp.packet.PublicKeyEncryptedSessionKey(), - msg = new openpgp.packet.List(), - msg2 = new openpgp.packet.List(); + const enc = new openpgp.packet.PublicKeyEncryptedSessionKey(); + const msg = new openpgp.packet.List(); + const msg2 = new openpgp.packet.List(); enc.sessionKey = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); enc.publicKeyAlgorithm = 'rsa_encrypt'; @@ -206,7 +207,7 @@ describe("Packet", function() { }); it('Secret key packet (reading, unencrypted)', function(done) { - var armored_key = + const armored_key = '-----BEGIN PGP PRIVATE KEY BLOCK-----\n' + 'Version: GnuPG v2.0.19 (GNU/Linux)\n' + '\n' + @@ -228,12 +229,12 @@ describe("Packet", function() { '=lKiS\n' + '-----END PGP PRIVATE KEY BLOCK-----'; - var key = new openpgp.packet.List(); + let key = new openpgp.packet.List(); key.read(openpgp.armor.decode(armored_key).data); key = key[0]; - var enc = new openpgp.packet.PublicKeyEncryptedSessionKey(), - secret = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); + const enc = new openpgp.packet.PublicKeyEncryptedSessionKey(); + const secret = new Uint8Array([1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]); enc.sessionKey = secret; enc.publicKeyAlgorithm = 'rsa_encrypt'; @@ -251,7 +252,7 @@ describe("Packet", function() { }); it('Public key encrypted packet (reading, GPG)', function(done) { - var armored_key = + const armored_key = '-----BEGIN PGP PRIVATE KEY BLOCK-----\n' + 'Version: GnuPG v2.0.19 (GNU/Linux)\n' + '\n' + @@ -286,7 +287,7 @@ describe("Packet", function() { '=FSwA\n' + '-----END PGP PRIVATE KEY BLOCK-----'; - var armored_msg = + const armored_msg = '-----BEGIN PGP MESSAGE-----\n' + 'Version: GnuPG v2.0.19 (GNU/Linux)\n' + '\n' + @@ -298,17 +299,17 @@ describe("Packet", function() { '=iSaK\n' + '-----END PGP MESSAGE-----'; - var key = new openpgp.packet.List(); + let key = new openpgp.packet.List(); key.read(openpgp.armor.decode(armored_key).data); key = key[3]; - var msg = new openpgp.packet.List(); + const msg = new openpgp.packet.List(); msg.read(openpgp.armor.decode(armored_msg).data); msg[0].decrypt(key).then(() => { msg[1].decrypt(msg[0].sessionKeyAlgorithm, msg[0].sessionKey); - var text = stringify(msg[1].packets[0].packets[0].data); + const text = stringify(msg[1].packets[0].packets[0].data); expect(text).to.equal('Hello world!'); done(); @@ -316,13 +317,13 @@ describe("Packet", function() { }); it('Sym encrypted session key reading/writing', function(done) { - var passphrase = 'hello', - algo = 'aes256'; + const passphrase = 'hello'; + const algo = 'aes256'; - var literal = new openpgp.packet.Literal(), - key_enc = new openpgp.packet.SymEncryptedSessionKey(), - enc = new openpgp.packet.SymEncryptedIntegrityProtected(), - msg = new openpgp.packet.List(); + const literal = new openpgp.packet.Literal(); + const key_enc = new openpgp.packet.SymEncryptedSessionKey(); + const enc = new openpgp.packet.SymEncryptedIntegrityProtected(); + const msg = new openpgp.packet.List(); msg.push(key_enc); msg.push(enc); @@ -330,17 +331,17 @@ describe("Packet", function() { key_enc.sessionKeyAlgorithm = algo; key_enc.decrypt(passphrase); - var key = key_enc.sessionKey; + const key = key_enc.sessionKey; literal.setText('Hello world!'); enc.packets.push(literal); enc.encrypt(algo, key); - var msg2 = new openpgp.packet.List(); + const msg2 = new openpgp.packet.List(); msg2.read(msg.write()); msg2[0].decrypt(passphrase); - var key2 = msg2[0].sessionKey; + const key2 = msg2[0].sessionKey; msg2[1].decrypt(msg2[0].sessionKeyAlgorithm, key2); expect(stringify(msg2[1].packets[0].data)).to.equal(stringify(literal.data)); @@ -348,7 +349,7 @@ describe("Packet", function() { }); it('Secret key encryption/decryption test', function(done) { - var armored_msg = + const armored_msg = '-----BEGIN PGP MESSAGE-----\n' + 'Version: GnuPG v2.0.19 (GNU/Linux)\n' + '\n' + @@ -360,18 +361,18 @@ describe("Packet", function() { '=pR+C\n' + '-----END PGP MESSAGE-----'; - var key = new openpgp.packet.List(); + let key = new openpgp.packet.List(); key.read(openpgp.armor.decode(armored_key).data); key = key[3]; key.decrypt('test'); - var msg = new openpgp.packet.List(); + const msg = new openpgp.packet.List(); msg.read(openpgp.armor.decode(armored_msg).data); msg[0].decrypt(key).then(() => { msg[1].decrypt(msg[0].sessionKeyAlgorithm, msg[0].sessionKey); - var text = stringify(msg[1].packets[0].packets[0].data); + const text = stringify(msg[1].packets[0].packets[0].data); expect(text).to.equal('Hello world!'); done(); @@ -379,7 +380,7 @@ describe("Packet", function() { }); it('Secret key reading with signature verification.', function() { - var key = new openpgp.packet.List(); + const key = new openpgp.packet.List(); key.read(openpgp.armor.decode(armored_key).data); return Promise.all([ expect(key[2].verify(key[0], @@ -396,7 +397,7 @@ describe("Packet", function() { }); it('Reading a signed, encrypted message.', function(done) { - var armored_msg = + const armored_msg = '-----BEGIN PGP MESSAGE-----\n' + 'Version: GnuPG v2.0.19 (GNU/Linux)\n' + '\n' + @@ -412,17 +413,17 @@ describe("Packet", function() { '=htrB\n' + '-----END PGP MESSAGE-----'; - var key = new openpgp.packet.List(); + const key = new openpgp.packet.List(); key.read(openpgp.armor.decode(armored_key).data); key[3].decrypt('test'); - var msg = new openpgp.packet.List(); + const msg = new openpgp.packet.List(); msg.read(openpgp.armor.decode(armored_msg).data); msg[0].decrypt(key[3]).then(() => { msg[1].decrypt(msg[0].sessionKeyAlgorithm, msg[0].sessionKey); - var payload = msg[1].packets[0].packets; + const payload = msg[1].packets[0].packets; expect(payload[2].verify( key[0], payload[1] @@ -431,16 +432,16 @@ describe("Packet", function() { }); it('Writing and encryption of a secret key packet.', function() { - var key = new openpgp.packet.List(); + const key = new openpgp.packet.List(); key.push(new openpgp.packet.SecretKey()); - var rsa = new openpgp.crypto.publicKey.rsa(); - var keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys + const rsa = new openpgp.crypto.publicKey.rsa(); + const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys return rsa.generate(keySize, "10001").then(function(mpiGen) { - var mpi = [mpiGen.n, mpiGen.ee, mpiGen.d, mpiGen.p, mpiGen.q, mpiGen.u]; + let mpi = [mpiGen.n, mpiGen.ee, mpiGen.d, mpiGen.p, mpiGen.q, mpiGen.u]; mpi = mpi.map(function(k) { - var mpi = new openpgp.MPI(); + const mpi = new openpgp.MPI(); mpi.fromBigInteger(k); return mpi; }); @@ -449,9 +450,9 @@ describe("Packet", function() { key[0].algorithm = "rsa_sign"; key[0].encrypt('hello'); - var raw = key.write(); + const raw = key.write(); - var key2 = new openpgp.packet.List(); + const key2 = new openpgp.packet.List(); key2.read(raw); key2[0].decrypt('hello'); @@ -460,15 +461,15 @@ describe("Packet", function() { }); it('Writing and verification of a signature packet.', function() { - var key = new openpgp.packet.SecretKey(); + const key = new openpgp.packet.SecretKey(); - var rsa = new openpgp.crypto.publicKey.rsa(); - var keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys + const rsa = new openpgp.crypto.publicKey.rsa(); + const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys return rsa.generate(keySize, "10001").then(function(mpiGen) { - var mpi = [mpiGen.n, mpiGen.ee, mpiGen.d, mpiGen.p, mpiGen.q, mpiGen.u]; + let mpi = [mpiGen.n, mpiGen.ee, mpiGen.d, mpiGen.p, mpiGen.q, mpiGen.u]; mpi = mpi.map(function(k) { - var mpi = new openpgp.MPI(); + const mpi = new openpgp.MPI(); mpi.fromBigInteger(k); return mpi; }); @@ -476,9 +477,9 @@ describe("Packet", function() { key.params = mpi; key.algorithm = "rsa_sign"; - var signed = new openpgp.packet.List(), - literal = new openpgp.packet.Literal(), - signature = new openpgp.packet.Signature(); + const signed = new openpgp.packet.List(); + const literal = new openpgp.packet.Literal(); + const signature = new openpgp.packet.Signature(); literal.setText('Hello world'); @@ -491,9 +492,9 @@ describe("Packet", function() { signed.push(literal); signed.push(signature); - var raw = signed.write(); + const raw = signed.write(); - var signed2 = new openpgp.packet.List(); + const signed2 = new openpgp.packet.List(); signed2.read(raw); expect(signed2[1].verify(key, signed2[0])).to.eventually.be.true; diff --git a/test/general/signature.js b/test/general/signature.js index 0c399121..08439af8 100644 --- a/test/general/signature.js +++ b/test/general/signature.js @@ -1,12 +1,13 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'); +const chai = require('chai'); chai.use(require('chai-as-promised')); -var expect = chai.expect; + +const expect = chai.expect; describe("Signature", function() { - var priv_key_arm1 = - [ '-----BEGIN PGP PRIVATE KEY BLOCK-----', + const priv_key_arm1 = + ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: GnuPG v1.4.11 (GNU/Linux)', '', 'lQHhBFERnrMRBADmM0hIfkI3yosjgbWo9v0Lnr3CCE+8KsMszgVS+hBu0XfGraKm', @@ -32,11 +33,10 @@ describe("Signature", function() { 'AgAJBQJREZ6zAhsMAAoJEBEnlAPLFp74QbMAn3V4857xwnO9/+vzIVnL93W3k0/8', 'AKC8omYPPomN1E/UJFfXdLDIMi5LoA==', '=LSrW', - '-----END PGP PRIVATE KEY BLOCK-----' - ].join("\n"); + '-----END PGP PRIVATE KEY BLOCK-----'].join("\n"); - var pub_key_arm1 = - [ '-----BEGIN PGP PUBLIC KEY BLOCK-----', + const pub_key_arm1 = + ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v1.4.11 (GNU/Linux)', '', 'mQGiBFERlw4RBAD6Bmcf2w1dtUmtCLkdxeqZLArk3vYoQAjdibxA3gXVyur7fsWb', @@ -52,11 +52,10 @@ describe("Signature", function() { 'HgECF4AACgkQikDlZK/UvLSspgCfcNaOpTg1W2ucR1JwBbBGvaERfuMAnRgt3/rs', 'EplqEakMckCtikEnpxYe', '=b2Ln', - '-----END PGP PUBLIC KEY BLOCK-----' - ].join("\n"); + '-----END PGP PUBLIC KEY BLOCK-----'].join("\n"); - var msg_arm1 = - [ '-----BEGIN PGP MESSAGE-----', + const msg_arm1 = + ['-----BEGIN PGP MESSAGE-----', 'Version: GnuPG v1.4.11 (GNU/Linux)', '', 'hQEOA1N4OCSSjECBEAP/diDJCQn4e88193PgqhbfAkohk9RQ0v0MPnXpJbCRTHKO', @@ -70,11 +69,10 @@ describe("Signature", function() { '0Dqnp0yfefrkjQ0nuvubgB6Rv89mHpnvuJfFJRInpg4lrHwLvRwdpN2HDozFHcKK', 'aOU=', '=4iGt', - '-----END PGP MESSAGE-----' - ].join("\n"); + '-----END PGP MESSAGE-----'].join("\n"); - var priv_key_arm2 = - [ '-----BEGIN PGP PRIVATE KEY BLOCK-----', + const priv_key_arm2 = + ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', 'lQH+BFJhL04BBADclrUEDDsm0PSZbQ6pml9FpzTyXiyCyDN+rMOsy9J300Oc10kt', @@ -111,11 +109,10 @@ describe("Signature", function() { 'SXuqKcWqoEuO7OBSEFThCXBfUYMC01OrqKEswPm/V3zZkLu01q12UMwZach28QwK', '/YZly4ioND2tdazj17u2rU2dwtiHPe1iMqGgVMoQirfLc+k=', '=lw5e', - '-----END PGP PRIVATE KEY BLOCK-----' - ].join('\n'); + '-----END PGP PRIVATE KEY BLOCK-----'].join('\n'); - var pub_key_arm2 = - [ '-----BEGIN PGP PUBLIC KEY BLOCK-----', + const pub_key_arm2 = + ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', 'mI0EUmEvTgEEANyWtQQMOybQ9JltDqmaX0WnNPJeLILIM36sw6zL0nfTQ5zXSS3+', @@ -137,11 +134,10 @@ describe("Signature", function() { 'AtNTq6ihLMD5v1d82ZC7tNatdlDMGWnIdvEMCv2GZcuIqDQ9rXWs49e7tq1NncLY', 'hz3tYjKhoFTKEIq3y3Pp', '=h/aX', - '-----END PGP PUBLIC KEY BLOCK-----' - ].join('\n'); + '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var pub_key_arm3 = - [ '-----BEGIN PGP PUBLIC KEY BLOCK-----', + const pub_key_arm3 = + ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', 'mQENBFKV0FUBCACtZliApy01KBGbGNB36YGH4lpr+5KoqF1I8A5IT0YeNjyGisOk', @@ -170,11 +166,10 @@ describe("Signature", function() { 'znN6qtN5gMlGY1ofWDY+I02gO4qzaZ/FxRZfittCw7v5dmQYKot9qRi2Kx3Fvw+h', 'ivFBpC4TWgppFBnJJnAsFXZJQcejMW4nEmOViRQXY8N8PepQmgsu', '=ummy', - '-----END PGP PUBLIC KEY BLOCK-----' - ].join('\n'); + '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var pub_revoked = - [ '-----BEGIN PGP PUBLIC KEY BLOCK-----', + const pub_revoked = + ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', 'mQENBFKpincBCADhZjIihK15f3l+j87JgeLp9eUTSbn+g3gOFSR73TOMyBHMPt8O', @@ -223,11 +218,10 @@ describe("Signature", function() { 'jgvGbcTzxnvrRmDevmJUdXBSAE11OYQuDGlhgFCU0o9cdX+k+QqP5wNycXhoJ+yk', 'pMiJM+NJAQ==', '=ok+o', - '-----END PGP PUBLIC KEY BLOCK-----' - ].join('\n'); + '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var pub_v3 = - [ '-----BEGIN PGP PUBLIC KEY BLOCK-----', + const pub_v3 = + ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: SKS 1.1.3', '', 'mQENAy9J/w4AAAEIALBDDD4vWqG/Jg59ghhMYAa+E7ECCTv2At8hxsM5cMP8P9sMLjs+GMfD', @@ -253,11 +247,10 @@ describe("Signature", function() { 'O+Ag4qwKKH+y/ke9CeZL6AnrU9c0pux150dHsDeHtpTPyInkjgKI7BofprydvpiFNd0nlAi4', 'J4SAEYr3q92Qn/IiKpnLgo6Ls/GFb7q6y1O/2LL8PC2zrYU=', '=eoGb', - '-----END PGP PUBLIC KEY BLOCK-----' - ].join('\n'); + '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var pub_expired = - [ '-----BEGIN PGP PUBLIC KEY BLOCK-----', + const pub_expired = + ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Comment: GPGTools - https://gpgtools.org', '', 'mQINBFpcwc8BEAC3ywtlTJ1inmifeTrC85b2j+WRySworAUKobk/jmswSoLt720R', @@ -309,11 +302,10 @@ describe("Signature", function() { '1Ze66O/1dHY4rt0l0IoMxHL93P3plUiy7wflxuSwLthPybAu7I4QGPC8qP0vm2Cm', '2g==', '=X7/F', - '-----END PGP PUBLIC KEY BLOCK-----' - ].join('\n'); + '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); - var msg_sig_expired = - [ '-----BEGIN PGP MESSAGE-----', + const msg_sig_expired = + ['-----BEGIN PGP MESSAGE-----', 'Comment: GPGTools - https://gpgtools.org', '', 'owEBWwKk/ZANAwAKAeyAexA3gWZ0AawUYgloZWxsby50eHRaX2WpaGVsbG+JAjME', @@ -330,13 +322,12 @@ describe("Signature", function() { 'kLlUC1zKjFPpRhO27ImTJuImil4lR2/CFjB1duG3JGJQaYIq8RFJOjvTVY29wl0i', 'pFy6y1Ofv2lLHB9K7N7dvvee2nvpUMkLEL52oFQ6Jc7sdg==', '=Q4tk', - '-----END PGP MESSAGE-----' - ].join('\n'); + '-----END PGP MESSAGE-----'].join('\n'); it('Testing signature checking on CAST5-enciphered message', function() { - var priv_key = openpgp.key.readArmored(priv_key_arm1).keys[0]; - var pub_key = openpgp.key.readArmored(pub_key_arm1).keys[0]; - var msg = openpgp.message.readArmored(msg_arm1); + const priv_key = openpgp.key.readArmored(priv_key_arm1).keys[0]; + const pub_key = openpgp.key.readArmored(pub_key_arm1).keys[0]; + const msg = openpgp.message.readArmored(msg_arm1); priv_key.decrypt("abcd"); return openpgp.decrypt({ privateKeys: priv_key, publicKeys:[pub_key], message:msg }).then(function(decrypted) { expect(decrypted.data).to.exist; @@ -348,8 +339,8 @@ describe("Signature", function() { it('Testing GnuPG stripped-key extensions', function() { // exercises the GnuPG s2k type 1001 extension: // the secrets on the primary key have been stripped. - var priv_key_gnupg_ext = openpgp.key.readArmored( - [ '-----BEGIN PGP PRIVATE KEY BLOCK-----', + const priv_key_gnupg_ext = openpgp.key.readArmored( + ['-----BEGIN PGP PRIVATE KEY BLOCK-----', 'Version: GnuPG v1.4.11 (GNU/Linux)', '', 'lQGqBFERnrMRBADmM0hIfkI3yosjgbWo9v0Lnr3CCE+8KsMszgVS+hBu0XfGraKm', @@ -374,10 +365,9 @@ describe("Signature", function() { 'nrMCGwwACgkQESeUA8sWnvhBswCfdXjznvHCc73/6/MhWcv3dbeTT/wAoLyiZg8+', 'iY3UT9QkV9d0sMgyLkug', '=GQsY', - '-----END PGP PRIVATE KEY BLOCK-----' - ].join("\n")).keys[0]; - var pub_key = openpgp.key.readArmored(pub_key_arm1).keys[0]; - var msg = openpgp.message.readArmored(msg_arm1); + '-----END PGP PRIVATE KEY BLOCK-----'].join("\n")).keys[0]; + const pub_key = openpgp.key.readArmored(pub_key_arm1).keys[0]; + const msg = openpgp.message.readArmored(msg_arm1); priv_key_gnupg_ext.subKeys[0].subKey.decrypt("abcd"); return msg.decrypt([priv_key_gnupg_ext]).then(function(msg) { @@ -391,8 +381,8 @@ describe("Signature", function() { }); it('Verify V4 signature. Hash: SHA1. PK: RSA. Signature Type: 0x00 (binary document)', function() { - var signedArmor = - [ '-----BEGIN PGP MESSAGE-----', + const signedArmor = + ['-----BEGIN PGP MESSAGE-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', 'owGbwMvMwMT4oOW7S46CznTGNeZJLCWpFSVBU3ZGF2fkF5Uo5KYWFyemp3LlAUUV', @@ -401,11 +391,10 @@ describe("Signature", function() { 'cw6U57n3/Z4X0pEZ68C5/o/6NpPICD7fuEOz3936raZ6wXGzueY8pfPnVjY0ajAc', 'PtJzvvqj+ubYaT1sK9wWhd9lL3/V+9Zuua9QjOWC22buchsCroh8fLoZAA==', '=VH8F', - '-----END PGP MESSAGE-----' - ].join('\n'); + '-----END PGP MESSAGE-----'].join('\n'); - var sMsg = openpgp.message.readArmored(signedArmor); - var pub_key = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const sMsg = openpgp.message.readArmored(signedArmor); + const pub_key = openpgp.key.readArmored(pub_key_arm2).keys[0]; return sMsg.verify([pub_key]).then(verified => { expect(verified).to.exist; expect(verified).to.have.length(1); @@ -415,8 +404,8 @@ describe("Signature", function() { }); it('Verify V3 signature. Hash: MD5. PK: RSA. Signature Type: 0x01 (text document)', function() { - var signedArmor = - [ '-----BEGIN PGP MESSAGE-----', + const signedArmor = + ['-----BEGIN PGP MESSAGE-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', 'owGbwMvMyMj4oOW7S46CznTG09YlLCWpFSVBU47xFGfkF5Uo5KYWFyemp/Jy5QGF', @@ -425,11 +414,10 @@ describe("Signature", function() { 'aPJyvm9TTpobW/O+P1n2THLS4UCvWt12Oa2lJ04GLwk/bDF1u+8ZpfPCpsxLVzcs', 'ZGtbq/f23XxV/jkL47hr3s3Ic4yoZTW4oZO27GYf37TPp9L3VboCAA==', '=pa6B', - '-----END PGP MESSAGE-----' - ].join('\n'); + '-----END PGP MESSAGE-----'].join('\n'); - var sMsg = openpgp.message.readArmored(signedArmor); - var pub_key = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const sMsg = openpgp.message.readArmored(signedArmor); + const pub_key = openpgp.key.readArmored(pub_key_arm2).keys[0]; return sMsg.verify([pub_key]).then(verified => { expect(verified).to.exist; expect(verified).to.have.length(1); @@ -439,8 +427,8 @@ describe("Signature", function() { }); it('Verify signature of signed and encrypted message from GPG2 with openpgp.decrypt', function() { - var msg_armor = - [ '-----BEGIN PGP MESSAGE-----', + const msg_armor = + ['-----BEGIN PGP MESSAGE-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', 'hIwD4IT3RGwgLJcBBADEBdm+GEW7IV1K/Bykg0nB0WYO08ai7/8/+Y/O9xu6RiU0', @@ -453,15 +441,14 @@ describe("Signature", function() { 'ifxyV4zia9RvaCUY8vXGM+gQJ3NNXx2LkZA3kWUEyxFVL1Vl/XUQY0M6U+uccSk4', 'eMXm6eyEWDcj0lBRckqKoKo1w/uan11jPuHsnRz6jO9DsuKEz79UDgI=', '=cFi7', - '-----END PGP MESSAGE-----' - ].join('\n'); + '-----END PGP MESSAGE-----'].join('\n'); - var plaintext = 'short message\nnext line\n한국어/조선말'; - var esMsg = openpgp.message.readArmored(msg_armor); - var pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; - var privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; + const plaintext = 'short message\nnext line\n한국어/조선말'; + const esMsg = openpgp.message.readArmored(msg_armor); + const pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; - var keyids = esMsg.getEncryptionKeyIds(); + const keyids = esMsg.getEncryptionKeyIds(); privKey.decryptKeyPacket(keyids, 'hello world'); return openpgp.decrypt({ privateKeys: privKey, publicKeys:[pubKey], message:esMsg }).then(function(decrypted) { @@ -474,8 +461,8 @@ describe("Signature", function() { }); it('Verify signature of signed and encrypted message from PGP 10.3.0 with openpgp.decrypt', function() { - var msg_armor = - [ '-----BEGIN PGP MESSAGE-----', + const msg_armor = + ['-----BEGIN PGP MESSAGE-----', 'Version: Encryption Desktop 10.3.0 (Build 9307)', 'Charset: utf-8', '', @@ -489,15 +476,14 @@ describe("Signature", function() { 'oyqzb9Vsgu1gS7SCb6qTbnbV9PlSyU4wJB6siX8hz/U0urokT5se3uYRjiV0KbkA', 'zl1/r/wCrmwX4Gl9VN9+33cQgYZAlJLsRw8N82GhbVweZS8qwv24GQ==', '=nx90', - '-----END PGP MESSAGE-----' - ].join('\n'); + '-----END PGP MESSAGE-----'].join('\n'); - var plaintext = 'short message\nnext line\n한국어/조선말\n\n'; - var esMsg = openpgp.message.readArmored(msg_armor); - var pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; - var privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; + const plaintext = 'short message\nnext line\n한국어/조선말\n\n'; + const esMsg = openpgp.message.readArmored(msg_armor); + const pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; - var keyids = esMsg.getEncryptionKeyIds(); + const keyids = esMsg.getEncryptionKeyIds(); privKey.decryptKeyPacket(keyids, 'hello world'); return openpgp.decrypt({ privateKeys: privKey, publicKeys:[pubKey], message:esMsg }).then(function(decrypted) { @@ -511,8 +497,8 @@ describe("Signature", function() { }); it('Verify signed message with two one pass signatures', function() { - var msg_armor = - [ '-----BEGIN PGP MESSAGE-----', + const msg_armor = + ['-----BEGIN PGP MESSAGE-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', 'owGbwMvMwMF4+5Pyi4Jg3y8ME8DcBy3fXXIUdKYzrjFNYilJrSgJmsXDXJyRX1Si', @@ -527,15 +513,14 @@ describe("Signature", function() { 'axdLZ9yd0OJNZv4P501If24W4vTGz6nI7Ser8Yd2PiOvE5MWMT0wLZQ+zPX1sv0/', 's8PvkyWmVM0O0fB/ZSHovHNNPffDg/rWhzOmXQ9/7vTn477F+aWm5sYzJ75/BQA=', '=+L0S', - '-----END PGP MESSAGE-----' - ].join('\n'); + '-----END PGP MESSAGE-----'].join('\n'); - var plaintext = 'short message\nnext line\n한국어/조선말'; - var sMsg = openpgp.message.readArmored(msg_armor); - var pubKey2 = openpgp.key.readArmored(pub_key_arm2).keys[0]; - var pubKey3 = openpgp.key.readArmored(pub_key_arm3).keys[0]; + const plaintext = 'short message\nnext line\n한국어/조선말'; + const sMsg = openpgp.message.readArmored(msg_armor); + const pubKey2 = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const pubKey3 = openpgp.key.readArmored(pub_key_arm3).keys[0]; - var keyids = sMsg.getSigningKeyIds(); + const keyids = sMsg.getSigningKeyIds(); expect(pubKey2.getKeyPackets(keyids[1])).to.not.be.empty; expect(pubKey3.getKeyPackets(keyids[0])).to.not.be.empty; @@ -553,8 +538,8 @@ describe("Signature", function() { }); it('Verify cleartext signed message with two signatures with openpgp.verify', function() { - var msg_armor = - [ '-----BEGIN PGP SIGNED MESSAGE-----', + const msg_armor = + ['-----BEGIN PGP SIGNED MESSAGE-----', 'Hash: SHA256', '', 'short message', @@ -574,15 +559,14 @@ describe("Signature", function() { 'vCCq7fgaUz8ksxvQ9bSwv0iIIbbBdTP7Z8y2c1Oof6NDl7irH+QCeNT7IIGs8Smn', 'BEzv/FqkQAhjy3Krxg==', '=3Pkl', - '-----END PGP SIGNATURE-----' - ].join('\n'); + '-----END PGP SIGNATURE-----'].join('\n'); - var plaintext = 'short message\nnext line\n한국어/조선말'; - var csMsg = openpgp.cleartext.readArmored(msg_armor); - var pubKey2 = openpgp.key.readArmored(pub_key_arm2).keys[0]; - var pubKey3 = openpgp.key.readArmored(pub_key_arm3).keys[0]; + const plaintext = 'short message\nnext line\n한국어/조선말'; + const csMsg = openpgp.cleartext.readArmored(msg_armor); + const pubKey2 = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const pubKey3 = openpgp.key.readArmored(pub_key_arm3).keys[0]; - var keyids = csMsg.getSigningKeyIds(); + const keyids = csMsg.getSigningKeyIds(); expect(pubKey2.getKeyPackets(keyids[0])).to.not.be.empty; expect(pubKey3.getKeyPackets(keyids[1])).to.not.be.empty; @@ -599,14 +583,14 @@ describe("Signature", function() { }); it('Sign text with openpgp.sign and verify with openpgp.verify leads to same string cleartext and valid signatures', function() { - var plaintext = 'short message\nnext line\n한국어/조선말'; - var pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; - var privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; + const plaintext = 'short message\nnext line\n한국어/조선말'; + const pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; privKey.primaryKey.decrypt('hello world'); return openpgp.sign({ privateKeys:[privKey], data:plaintext }).then(function(signed) { - var csMsg = openpgp.cleartext.readArmored(signed.data); + const csMsg = openpgp.cleartext.readArmored(signed.data); return openpgp.verify({ publicKeys:[pubKey], message:csMsg }); }).then(function(cleartextSig) { @@ -619,14 +603,14 @@ describe("Signature", function() { }); it('Sign text with openpgp.sign and verify with openpgp.verify leads to same bytes cleartext and valid signatures - armored', function() { - var plaintext = openpgp.util.str2Uint8Array('short message\nnext line\n한국어/조선말'); - var pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; - var privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; + const plaintext = openpgp.util.str2Uint8Array('short message\nnext line\n한국어/조선말'); + const pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; privKey.primaryKey.decrypt('hello world'); return openpgp.sign({ privateKeys:[privKey], data:plaintext }).then(function(signed) { - var csMsg = openpgp.message.readArmored(signed.data); + const csMsg = openpgp.message.readArmored(signed.data); return openpgp.verify({ publicKeys:[pubKey], message:csMsg }); }).then(function(cleartextSig) { @@ -639,14 +623,14 @@ describe("Signature", function() { }); it('Sign text with openpgp.sign and verify with openpgp.verify leads to same bytes cleartext and valid signatures - not armored', function() { - var plaintext = openpgp.util.str2Uint8Array('short message\nnext line\n한국어/조선말'); - var pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; - var privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; + const plaintext = openpgp.util.str2Uint8Array('short message\nnext line\n한국어/조선말'); + const pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const privKey = openpgp.key.readArmored(priv_key_arm2).keys[0]; privKey.primaryKey.decrypt('hello world'); return openpgp.sign({ privateKeys:[privKey], data:plaintext, armor:false }).then(function(signed) { - var csMsg = signed.message; + const csMsg = signed.message; return openpgp.verify({ publicKeys:[pubKey], message:csMsg }); }).then(function(cleartextSig) { @@ -660,8 +644,8 @@ describe("Signature", function() { it('Verify test with expired verification public key and verify_expired_keys set to false', function() { openpgp.config.verify_expired_keys = false; - var pubKey = openpgp.key.readArmored(pub_expired).keys[0]; - var message = openpgp.message.readArmored(msg_sig_expired); + const pubKey = openpgp.key.readArmored(pub_expired).keys[0]; + const message = openpgp.message.readArmored(msg_sig_expired); return openpgp.verify({ publicKeys:[pubKey], message:message }).then(function(verified) { expect(verified).to.exist; expect(verified.signatures).to.have.length(1); @@ -673,8 +657,8 @@ describe("Signature", function() { it('Verify test with expired verification public key and verify_expired_keys set to true', function() { openpgp.config.verify_expired_keys = true; - var pubKey = openpgp.key.readArmored(pub_expired).keys[0]; - var message = openpgp.message.readArmored(msg_sig_expired); + const pubKey = openpgp.key.readArmored(pub_expired).keys[0]; + const message = openpgp.message.readArmored(msg_sig_expired); return openpgp.verify({ publicKeys:[pubKey], message:message }).then(function(verified) { expect(verified).to.exist; expect(verified.signatures).to.have.length(1); @@ -686,8 +670,8 @@ describe("Signature", function() { it('Verify test with expired verification public key and verify_expired_keys set to false', function() { openpgp.config.verify_expired_keys = false; - var pubKey = openpgp.key.readArmored(pub_expired).keys[0]; - var message = openpgp.message.readArmored(msg_sig_expired); + const pubKey = openpgp.key.readArmored(pub_expired).keys[0]; + const message = openpgp.message.readArmored(msg_sig_expired); return openpgp.verify({ publicKeys:[pubKey], message:message }).then(function(verified) { expect(verified).to.exist; expect(verified.signatures).to.have.length(1); @@ -699,8 +683,8 @@ describe("Signature", function() { it('Verify test with expired verification public key and verify_expired_keys set to true', function() { openpgp.config.verify_expired_keys = true; - var pubKey = openpgp.key.readArmored(pub_expired).keys[0]; - var message = openpgp.message.readArmored(msg_sig_expired); + const pubKey = openpgp.key.readArmored(pub_expired).keys[0]; + const message = openpgp.message.readArmored(msg_sig_expired); return openpgp.verify({ publicKeys:[pubKey], message:message }).then(function(verified) { expect(verified).to.exist; expect(verified.signatures).to.have.length(1); @@ -711,21 +695,21 @@ describe("Signature", function() { }); it('Verify primary key revocation signature', function(done) { - var pubKey = openpgp.key.readArmored(pub_revoked).keys[0]; + const pubKey = openpgp.key.readArmored(pub_revoked).keys[0]; expect(pubKey.revocationSignature.verify( pubKey.primaryKey, {key: pubKey.primaryKey} )).to.eventually.be.true.notify(done); }); it('Verify subkey revocation signature', function(done) { - var pubKey = openpgp.key.readArmored(pub_revoked).keys[0]; + const pubKey = openpgp.key.readArmored(pub_revoked).keys[0]; expect(pubKey.subKeys[0].revocationSignature.verify( pubKey.primaryKey, {key: pubKey.primaryKey, bind: pubKey.subKeys[0].subKey} )).to.eventually.be.true.notify(done); }); it('Verify key expiration date', function(done) { - var pubKey = openpgp.key.readArmored(pub_revoked).keys[0]; + const pubKey = openpgp.key.readArmored(pub_revoked).keys[0]; expect(pubKey).to.exist; expect(pubKey.users[0].selfCertifications[0].keyNeverExpires).to.be.false; @@ -734,33 +718,33 @@ describe("Signature", function() { }); it('Verify V3 certification signature', function(done) { - var pubKey = openpgp.key.readArmored(pub_v3).keys[0]; + const pubKey = openpgp.key.readArmored(pub_v3).keys[0]; expect(pubKey.users[0].selfCertifications[0].verify(pubKey.primaryKey, {key: pubKey.primaryKey, userid: pubKey.users[0].userId})).to.eventually.be.true.notify(done); }); it('Write unhashed subpackets', function() { - var pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; + let pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; expect(pubKey.users[0].selfCertifications).to.exist; pubKey = openpgp.key.readArmored(pubKey.armor()).keys[0]; expect(pubKey.users[0].selfCertifications).to.exist; }); it('Write V3 signatures', function() { - var pubKey = openpgp.key.readArmored(pub_v3).keys[0]; - var pubKey2 = openpgp.key.readArmored(pubKey.armor()).keys[0]; + const pubKey = openpgp.key.readArmored(pub_v3).keys[0]; + const pubKey2 = openpgp.key.readArmored(pubKey.armor()).keys[0]; expect(pubKey2).to.exist; expect(pubKey.users[0].selfCertifications).to.eql(pubKey2.users[0].selfCertifications); }); it('Write V4 signatures', function() { - var pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; - var pubKey2 = openpgp.key.readArmored(pubKey.armor()).keys[0]; + const pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const pubKey2 = openpgp.key.readArmored(pubKey.armor()).keys[0]; expect(pubKey2).to.exist; expect(pubKey.users[0].selfCertifications).to.eql(pubKey2.users[0].selfCertifications); }); it('Verify a detached signature using readSignedContent', function() { - var detachedSig = ['-----BEGIN PGP SIGNATURE-----', + const detachedSig = ['-----BEGIN PGP SIGNATURE-----', 'Version: GnuPG v1.4.13 (Darwin)', 'Comment: GPGTools - https://gpgtools.org', 'Comment: Using GnuPG with Thunderbird - https://www.enigmail.net/', @@ -772,10 +756,9 @@ describe("Signature", function() { '7xms9D6Er+MhspSl+1dlRdHjtXiRqC5Ld1hi2KBKc6YzgOLpVw5l9sffbnH+aRG4', 'dH+2J5U3elqBDK1i3GyG8ixLSB0FGW9+lhYNosZne2xy8SbQKdgsnTBnWSGevP0=', '=xiih', - '-----END PGP SIGNATURE-----' - ].join('\r\n'); + '-----END PGP SIGNATURE-----'].join('\r\n'); - var content = ['Content-Type: multipart/mixed;', + const content = ['Content-Type: multipart/mixed;', ' boundary="------------070307080002050009010403"', '', 'This is a multi-part message in MIME format.', @@ -794,28 +777,27 @@ describe("Signature", function() { '', 'dGVzdGF0dGFjaG1lbnQ=', '--------------070307080002050009010403--', - '' - ].join('\r\n'); + ''].join('\r\n'); - var publicKeyArmored = '-----BEGIN PGP PUBLIC KEY BLOCK-----\r\nVersion: OpenPGP.js v.1.20131116\r\nComment: Whiteout Mail - https://whiteout.io\r\n\r\nxsBNBFKODs4BB/9iOF4THsjQMY+WEpT7ShgKxj4bHzRRaQkqczS4nZvP0U3g\r\nqeqCnbpagyeKXA+bhWFQW4GmXtgAoeD5PXs6AZYrw3tWNxLKu2Oe6Tp9K/XI\r\nxTMQ2wl4qZKDXHvuPsJ7cmgaWqpPyXtxA4zHHS3WrkI/6VzHAcI/y6x4szSB\r\nKgSuhI3hjh3s7TybUC1U6AfoQGx/S7e3WwlCOrK8GTClirN/2mCPRC5wuIft\r\nnkoMfA6jK8d2OPrJ63shy5cgwHOjQg/xuk46dNS7tkvGmbaa+X0PgqSKB+Hf\r\nYPPNS/ylg911DH9qa8BqYU2QpNh9jUKXSF+HbaOM+plWkCSAL7czV+R3ABEB\r\nAAHNLVdoaXRlb3V0IFVzZXIgPHNhZmV3aXRobWUudGVzdHVzZXJAZ21haWwu\r\nY29tPsLAXAQQAQgAEAUCUo4O2gkQ1/uT/N+/wjwAAN2cB/9gFRmAfvEQ2qz+\r\nWubmT2EsSSnjPMxzG4uyykFoa+TaZCWo2Xa2tQghmU103kEkQb1OEjRjpgwJ\r\nYX9Kghnl8DByM686L5AXnRyHP78qRJCLXSXl0AGicboUDp5sovaa4rswQceH\r\nvcdWgZ/mgHTRoiQeJddy9k+H6MPFiyFaVcFwegVsmpc+dCcC8yT+qh8ZIbyG\r\nRJU60PmKKN7LUusP+8DbSv39zCGJCBlVVKyA4MzdF5uM+sqTdXbKzOrT5DGd\r\nCZaox4s+w16Sq1rHzZKFWfQPfKLDB9pyA0ufCVRA3AF6BUi7G3ZqhZiHNhMP\r\nNvE45V/hS1PbZcfPVoUjE2qc1Ix1\r\n=7Wpe\r\n-----END PGP PUBLIC KEY BLOCK-----'; - var publicKeys = openpgp.key.readArmored(publicKeyArmored).keys; + const publicKeyArmored = '-----BEGIN PGP PUBLIC KEY BLOCK-----\r\nVersion: OpenPGP.js v.1.20131116\r\nComment: Whiteout Mail - https://whiteout.io\r\n\r\nxsBNBFKODs4BB/9iOF4THsjQMY+WEpT7ShgKxj4bHzRRaQkqczS4nZvP0U3g\r\nqeqCnbpagyeKXA+bhWFQW4GmXtgAoeD5PXs6AZYrw3tWNxLKu2Oe6Tp9K/XI\r\nxTMQ2wl4qZKDXHvuPsJ7cmgaWqpPyXtxA4zHHS3WrkI/6VzHAcI/y6x4szSB\r\nKgSuhI3hjh3s7TybUC1U6AfoQGx/S7e3WwlCOrK8GTClirN/2mCPRC5wuIft\r\nnkoMfA6jK8d2OPrJ63shy5cgwHOjQg/xuk46dNS7tkvGmbaa+X0PgqSKB+Hf\r\nYPPNS/ylg911DH9qa8BqYU2QpNh9jUKXSF+HbaOM+plWkCSAL7czV+R3ABEB\r\nAAHNLVdoaXRlb3V0IFVzZXIgPHNhZmV3aXRobWUudGVzdHVzZXJAZ21haWwu\r\nY29tPsLAXAQQAQgAEAUCUo4O2gkQ1/uT/N+/wjwAAN2cB/9gFRmAfvEQ2qz+\r\nWubmT2EsSSnjPMxzG4uyykFoa+TaZCWo2Xa2tQghmU103kEkQb1OEjRjpgwJ\r\nYX9Kghnl8DByM686L5AXnRyHP78qRJCLXSXl0AGicboUDp5sovaa4rswQceH\r\nvcdWgZ/mgHTRoiQeJddy9k+H6MPFiyFaVcFwegVsmpc+dCcC8yT+qh8ZIbyG\r\nRJU60PmKKN7LUusP+8DbSv39zCGJCBlVVKyA4MzdF5uM+sqTdXbKzOrT5DGd\r\nCZaox4s+w16Sq1rHzZKFWfQPfKLDB9pyA0ufCVRA3AF6BUi7G3ZqhZiHNhMP\r\nNvE45V/hS1PbZcfPVoUjE2qc1Ix1\r\n=7Wpe\r\n-----END PGP PUBLIC KEY BLOCK-----'; + const publicKeys = openpgp.key.readArmored(publicKeyArmored).keys; - var msg = openpgp.message.readSignedContent(content, detachedSig); + const msg = openpgp.message.readSignedContent(content, detachedSig); return msg.verify(publicKeys).then(result => { expect(result[0].valid).to.be.true; }); }); it('Detached signature signing and verification', function() { - var msg = openpgp.message.fromText('hello'); - var pubKey2 = openpgp.key.readArmored(pub_key_arm2).keys[0]; - var privKey2 = openpgp.key.readArmored(priv_key_arm2).keys[0]; + const msg = openpgp.message.fromText('hello'); + const pubKey2 = openpgp.key.readArmored(pub_key_arm2).keys[0]; + const privKey2 = openpgp.key.readArmored(priv_key_arm2).keys[0]; privKey2.decrypt('hello world'); - var opt = {numBits: 512, userIds: { name:'test', email:'a@b.com' }, passphrase: null}; + const opt = {numBits: 512, userIds: { name:'test', email:'a@b.com' }, passphrase: null}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(gen) { - var generatedKey = gen.key; + const generatedKey = gen.key; return msg.signDetached([generatedKey, privKey2]).then(detachedSig => { return msg.verifyDetached(detachedSig, [generatedKey.toPublic(), pubKey2]).then(result => { expect(result[0].valid).to.be.true; @@ -826,18 +808,18 @@ describe("Signature", function() { }); it('Sign message with key without password', function() { - var opt = {numBits: 512, userIds: { name:'test', email:'a@b.com' }, passphrase: null}; + const opt = {numBits: 512, userIds: { name:'test', email:'a@b.com' }, passphrase: null}; if (openpgp.util.getWebCryptoAll()) { opt.numBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(gen) { - var key = gen.key; - var message = openpgp.message.fromText('hello world'); + const key = gen.key; + let message = openpgp.message.fromText('hello world'); message = message.sign([key]); expect(message).to.exist; }); }); it('Verify signed key', function() { - var signedArmor = [ + const signedArmor = [ '-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v1', '', @@ -864,8 +846,8 @@ describe("Signature", function() { '-----END PGP PUBLIC KEY BLOCK-----' ].join('\n'); - var signedKey = openpgp.key.readArmored(signedArmor).keys[0]; - var signerKey = openpgp.key.readArmored(priv_key_arm1).keys[0]; + const signedKey = openpgp.key.readArmored(signedArmor).keys[0]; + const signerKey = openpgp.key.readArmored(priv_key_arm1).keys[0]; return signedKey.verifyPrimaryUser([signerKey]).then(signatures => { expect(signatures[0].valid).to.be.null; expect(signatures[0].keyid.toHex()).to.equal(signedKey.primaryKey.getKeyId().toHex()); diff --git a/test/general/util.js b/test/general/util.js index 3db13100..bcc96f8c 100644 --- a/test/general/util.js +++ b/test/general/util.js @@ -1,156 +1,157 @@ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); + +const { expect } = chai; describe('Util unit tests', function() { describe('isString', function() { it('should return true for type "string"', function() { - var data = 'foo'; + const data = 'foo'; expect(openpgp.util.isString(data)).to.be.true; }); it('should return true for type String', function() { - var data = String('foo'); + const data = String('foo'); expect(openpgp.util.isString(data)).to.be.true; }); it('should return true for inherited type of String', function() { function MyString() {} MyString.prototype = Object.create(String.prototype); - var data = new MyString(); + const data = new MyString(); expect(openpgp.util.isString(data)).to.be.true; }); it('should return true for empty string', function() { - var data = ''; + const data = ''; expect(openpgp.util.isString(data)).to.be.true; }); it('should return false for undefined', function() { - var data; + let data; expect(openpgp.util.isString(data)).to.be.false; }); it('should return false for Object', function() { - var data = {}; + const data = {}; expect(openpgp.util.isString(data)).to.be.false; }); }); describe('isArray', function() { it('should return true for []', function() { - var data = []; + const data = []; expect(openpgp.util.isArray(data)).to.be.true; }); it('should return true for type Array', function() { - var data = Array(); + const data = Array(); expect(openpgp.util.isArray(data)).to.be.true; }); it('should return true for inherited type of Array', function() { function MyArray() {} MyArray.prototype = Object.create(Array.prototype); - var data = new MyArray(); + const data = new MyArray(); expect(openpgp.util.isArray(data)).to.be.true; }); it('should return false for undefined', function() { - var data; + let data; expect(openpgp.util.isArray(data)).to.be.false; }); it('should return false for Object', function() { - var data = {}; + const data = {}; expect(openpgp.util.isArray(data)).to.be.false; }); }); describe('isUint8Array', function() { it('should return true for type Uint8Array', function() { - var data = new Uint8Array(); + const data = new Uint8Array(); expect(openpgp.util.isUint8Array(data)).to.be.true; }); it('should return true for inherited type of Uint8Array', function() { function MyUint8Array() {} MyUint8Array.prototype = new Uint8Array(); - var data = new MyUint8Array(); + const data = new MyUint8Array(); expect(openpgp.util.isUint8Array(data)).to.be.true; }); it('should return false for undefined', function() { - var data; + let data; expect(openpgp.util.isUint8Array(data)).to.be.false; }); it('should return false for Object', function() { - var data = {}; + const data = {}; expect(openpgp.util.isUint8Array(data)).to.be.false; }); }); describe('isEmailAddress', function() { it('should return true for valid email address', function() { - var data = 'test@example.com'; + const data = 'test@example.com'; expect(openpgp.util.isEmailAddress(data)).to.be.true; }); it('should return true for valid email address', function() { - var data = 'test@xn--wgv.xn--q9jyb4c'; + const data = 'test@xn--wgv.xn--q9jyb4c'; expect(openpgp.util.isEmailAddress(data)).to.be.true; }); it('should return false for invalid email address', function() { - var data = 'Test User '; + const data = 'Test User '; expect(openpgp.util.isEmailAddress(data)).to.be.false; }); it('should return false for invalid email address', function() { - var data = 'test@examplecom'; + const data = 'test@examplecom'; expect(openpgp.util.isEmailAddress(data)).to.be.false; }); it('should return false for invalid email address', function() { - var data = 'testexamplecom'; + const data = 'testexamplecom'; expect(openpgp.util.isEmailAddress(data)).to.be.false; }); it('should return false for empty string', function() { - var data = ''; + const data = ''; expect(openpgp.util.isEmailAddress(data)).to.be.false; }); it('should return false for undefined', function() { - var data; + let data; expect(openpgp.util.isEmailAddress(data)).to.be.false; }); it('should return false for Object', function() { - var data = {}; + const data = {}; expect(openpgp.util.isEmailAddress(data)).to.be.false; }); }); describe('isUserId', function() { it('should return true for valid user id', function() { - var data = 'Test User '; + const data = 'Test User '; expect(openpgp.util.isUserId(data)).to.be.true; }); it('should return false for invalid user id', function() { - var data = 'Test User test@example.com>'; + const data = 'Test User test@example.com>'; expect(openpgp.util.isUserId(data)).to.be.false; }); it('should return false for invalid user id', function() { - var data = 'Test User { + bye.toPublic().signPrimaryUser([hi]).then(trustedBye => { expect(trustedBye.users[0].otherCertifications[0].verify( primaryKey, { userid: user.userId, key: bye.toPublic().primaryKey } )).to.eventually.be.true; @@ -265,7 +280,7 @@ describe('X25519 Cryptography', function () { openpgp.sign( { data: 'Hi, this is me, Hi!', privateKeys: hi } ).then(signed => { - var msg = openpgp.cleartext.readArmored(signed.data); + const msg = openpgp.cleartext.readArmored(signed.data); // Verifying signed message return Promise.all([ openpgp.verify( @@ -282,15 +297,15 @@ describe('X25519 Cryptography', function () { // Encrypting and signing openpgp.encrypt( { data: 'Hi, Hi wrote this but only Bye can read it!', - publicKeys: [ bye.toPublic() ], - privateKeys: [ hi ] } + publicKeys: [bye.toPublic()], + privateKeys: [hi] } ).then(encrypted => { - var msg = openpgp.message.readArmored(encrypted.data) + const msg = openpgp.message.readArmored(encrypted.data); // Decrypting and verifying return openpgp.decrypt( { message: msg, privateKeys: bye, - publicKeys: [ hi.toPublic() ] } + publicKeys: [hi.toPublic()] } ).then(output => { expect(output.data).to.equal('Hi, Hi wrote this but only Bye can read it!'); expect(output.signatures[0].valid).to.be.true; @@ -307,22 +322,22 @@ describe('X25519 Cryptography', function () { const curve = openpgp.crypto.publicKey.elliptic.get('ed25519'); const util = openpgp.util; function testVector(vector) { - var S = curve.keyFromSecret(vector.SECRET_KEY); - var P = curve.keyFromPublic(vector.PUBLIC_KEY); + const S = curve.keyFromSecret(vector.SECRET_KEY); + const P = curve.keyFromPublic(vector.PUBLIC_KEY); expect(S.getPublic()).to.deep.equal(P.getPublic()); - var data = util.str2Uint8Array(vector.MESSAGE); - var keyIntegers = [ + const data = util.str2Uint8Array(vector.MESSAGE); + const keyIntegers = [ openpgp.OID.fromClone(curve), new openpgp.MPI(util.hex2bin(vector.PUBLIC_KEY)), new openpgp.MPI(util.hex2bin(vector.SECRET_KEY)) ]; - var msg_MPIs = [ + const msg_MPIs = [ new openpgp.MPI(util.Uint8Array2str(util.hex2Uint8Array(vector.SIGNATURE.R).reverse())), - new openpgp.MPI(util.Uint8Array2str(util.hex2Uint8Array(vector.SIGNATURE.S).reverse())), + new openpgp.MPI(util.Uint8Array2str(util.hex2Uint8Array(vector.SIGNATURE.S).reverse())) ]; return Promise.all([ crypto.sign(undefined, 22, keyIntegers, data).then(signature => { - var len = ((signature[0] << 8| signature[1]) + 7) / 8; + const len = ((signature[0] << 8 | signature[1]) + 7) / 8; expect(util.hex2Uint8Array(vector.SIGNATURE.R)).to.deep.eq(signature.slice(2, 2 + len)); expect(util.hex2Uint8Array(vector.SIGNATURE.S)).to.deep.eq(signature.slice(4 + len)); }), @@ -330,7 +345,7 @@ describe('X25519 Cryptography', function () { expect(result).to.be.true; }) ]); - }; + } it('Signature of empty string', function () { return testVector({ @@ -455,7 +470,8 @@ describe('X25519 Cryptography', function () { 'b2eaaa707b4c4185c32eddcdd306705e', '4dc1ffc872eeee475a64dfac86aba41c', '0618983f8741c5ef68d3a101e8a3b8ca', - 'c60c905c15fc910840b94c00a0b9d0'].join('')), + 'c60c905c15fc910840b94c00a0b9d0' + ].join('')), SIGNATURE: { R: ['0aab4c900501b3e24d7cdf4663326a3a', '87df5e4843b2cbdb67cbf6e460fec350'].join(''), @@ -476,7 +492,8 @@ describe('X25519 Cryptography', function () { 'ddaf35a193617abacc417349ae204131', '12e6fa4e89a97ea20a9eeee64b55d39a', '2192992a274fc1a836ba3c23a3feebbd', - '454d4423643ce80e2a9ac94fa54ca49f'].join('')), + '454d4423643ce80e2a9ac94fa54ca49f' + ].join('')), SIGNATURE: { R: ['dc2a4459e7369633a52b1bf277839a00', '201009a3efbf3ecb69bea2186c26b589'].join(''), diff --git a/test/worker/async_proxy.js b/test/worker/async_proxy.js index 5e781bcf..f7bcd4de 100644 --- a/test/worker/async_proxy.js +++ b/test/worker/async_proxy.js @@ -1,11 +1,12 @@ /* globals tryTests: true */ -var openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); +const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../dist/openpgp'); -var chai = require('chai'), - expect = chai.expect; +const chai = require('chai'); -var pub_key = +const { expect } = chai; + +const pub_key = ['-----BEGIN PGP PUBLIC KEY BLOCK-----', 'Version: GnuPG v2.0.19 (GNU/Linux)', '', @@ -30,8 +31,8 @@ var pub_key = '=h/aX', '-----END PGP PUBLIC KEY BLOCK-----'].join('\n'); -var plaintext = 'short message\nnext line\n한국어/조선말'; -var pubKey; +const plaintext = 'short message\nnext line\n한국어/조선말'; +let pubKey; tryTests('Async Proxy', tests, { if: typeof window !== 'undefined' && window.Worker, @@ -48,7 +49,7 @@ function tests() { describe('Error handling', function() { it('Depleted random buffer in worker gives error', function() { - var wProxy = new openpgp.AsyncProxy({ path:'../dist/openpgp.worker.js' }); + const wProxy = new openpgp.AsyncProxy({ path:'../dist/openpgp.worker.js' }); wProxy.worker = new Worker('../dist/openpgp.worker.js'); wProxy.worker.onmessage = wProxy.onMessage.bind(wProxy); wProxy.seedRandom(10); From 5519f2ae30a3402d7e1ad1ee2ddd7f357e7699fd Mon Sep 17 00:00:00 2001 From: BafS Date: Tue, 13 Feb 2018 23:30:39 +0100 Subject: [PATCH 4/4] Update packages, add lint script, remove useless eslint-plugins --- package.json | 15 ++- src/crypto/cipher/twofish.js | 2 + src/crypto/hash/sha.js | 13 ++- src/crypto/public_key/jsbn.js | 187 ++++++++++++++++++---------------- 4 files changed, 115 insertions(+), 102 deletions(-) diff --git a/package.json b/package.json index a1d89ea8..5b685b44 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,8 @@ ], "scripts": { "pretest": "grunt", - "test": "grunt test" + "test": "grunt test", + "lint": "eslint src" }, "devDependencies": { "babel-core": "^6.26.0", @@ -47,12 +48,10 @@ "chai": "^4.1.2", "chai-as-promised": "^7.1.1", "core-js": "^2.5.3", - "eslint": "^4.16.0", + "eslint": "^4.17.0", "eslint-config-airbnb": "^16.1.0", "eslint-config-airbnb-base": "^12.1.0", "eslint-plugin-import": "^2.8.0", - "eslint-plugin-jsx-a11y": "^6.0.3", - "eslint-plugin-react": "^7.6.1", "grunt": "~1.0.1", "grunt-browserify": "~5.2.0", "grunt-contrib-clean": "~1.1.0", @@ -69,17 +68,17 @@ "grunt-text-replace": "~0.4.0", "gruntify-eslint": "^4.0.0", "istanbul": "^0.4.5", - "mocha": "^4.1.0", - "sinon": "^4.2.2", + "mocha": "^5.0.0", + "sinon": "^4.3.0", "whatwg-fetch": "^2.0.3", "zlibjs": "~0.3.1" }, "dependencies": { - "asmcrypto-lite": "git+https://github.com/openpgpjs/asmcrypto-lite.git", + "asmcrypto-lite": "github:openpgpjs/asmcrypto-lite", "asn1.js": "^5.0.0", "bn.js": "^4.11.8", "buffer": "^5.0.8", - "elliptic": "git+https://github.com/openpgpjs/elliptic.git", + "elliptic": "github:openpgpjs/elliptic.git", "jwk-to-pem": "^1.2.6", "node-fetch": "^1.7.3", "node-localstorage": "~1.3.0", diff --git a/src/crypto/cipher/twofish.js b/src/crypto/cipher/twofish.js index 9692ab0d..5ad10c01 100644 --- a/src/crypto/cipher/twofish.js +++ b/src/crypto/cipher/twofish.js @@ -22,6 +22,8 @@ * @module crypto/cipher/twofish */ + /* eslint-disable no-mixed-operators */ + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Math //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/crypto/hash/sha.js b/src/crypto/hash/sha.js index 023863d4..10997513 100644 --- a/src/crypto/hash/sha.js +++ b/src/crypto/hash/sha.js @@ -132,7 +132,7 @@ function hex2binb(str) { for (let i = 0; i < length; i += 2) { num = parseInt(str.substr(i, 2), 16); - if (!isNaN(num)) { + if (!Number.isNaN(num)) { offset = i >>> 3; while (bin.length <= offset) { bin.push(0); @@ -216,14 +216,13 @@ function b642binb(str) { let j; let tmpInt; let strPart; - let firstEqual; let offset; const b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; if (str.search(/^[a-zA-Z0-9=+\/]+$/) === -1) { throw new Error('Invalid character in base-64 string'); } - firstEqual = str.indexOf('='); + const firstEqual = str.indexOf('='); str = str.replace(/\=/g, ''); if ((firstEqual !== -1) && (firstEqual < str.length)) { throw new Error('Invalid \'=\' found in base-64 string'); @@ -472,7 +471,7 @@ function shr_64(x, n) { if (n <= 32) { retVal = new Int_64( x.highOrder >>> n, - x.lowOrder >>> n | ((x.highOrder << (32 - n)) & 0xFFFFFFFF) + (x.lowOrder >>> n) | ((x.highOrder << (32 - n)) & 0xFFFFFFFF) ); } else { retVal = new Int_64( @@ -1067,7 +1066,7 @@ function coreSHA2(message, messageLen, variant) { ]; } } else { - throw "Unexpected error in SHA-2 implementation"; + throw new Error("Unexpected error in SHA-2 implementation"); } while (message.length <= lengthPosition) { @@ -1148,7 +1147,7 @@ function coreSHA2(message, messageLen, variant) { H[7].highOrder, H[7].lowOrder ]; } else { /* This should never be reached */ - throw "Unexpected error in SHA-2 implementation"; + throw new Error("Unexpected error in SHA-2 implementation"); } return retVal; @@ -1239,7 +1238,7 @@ const jsSHA = function(srcString, inputFormat, encoding) { } /* Validate the numRounds argument */ - if ((numRounds !== parseInt(numRounds)) || (numRounds < 1)) { + if ((numRounds !== parseInt(numRounds, 10)) || (numRounds < 1)) { throw new Error('numRounds must a integer >= 1'); } diff --git a/src/crypto/public_key/jsbn.js b/src/crypto/public_key/jsbn.js index 43cb588c..bd550d6d 100644 --- a/src/crypto/public_key/jsbn.js +++ b/src/crypto/public_key/jsbn.js @@ -31,6 +31,11 @@ * and disclaimer. */ +/* eslint-disable no-mixed-operators */ +/* eslint-disable no-eq-null */ +/* eslint-disable eqeqeq */ +/* eslint-disable no-cond-assign */ +/* eslint-disable one-var */ /** * @requires util @@ -84,8 +89,8 @@ function am1(i, x, w, j, c, n) { // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { - let xl = x & 0x7fff, - xh = x >> 15; + const xl = x & 0x7fff; + const xh = x >> 15; while (--n >= 0) { let l = this[i] & 0x7fff; const h = this[i++] >> 15; @@ -100,8 +105,8 @@ function am2(i, x, w, j, c, n) { // browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { - let xl = x & 0x3fff, - xh = x >> 14; + const xl = x & 0x3fff; + const xh = x >> 14; while (--n >= 0) { let l = this[i] & 0x3fff; const h = this[i++] >> 14; @@ -119,7 +124,7 @@ function am3(i, x, w, j, c, n) { } else if(j_lm && (navigator != undefined && navigator.appName != "Netscape")) {*/ BigInteger.prototype.am = am1; -dbits = 26; +dbits = 26; // eslint-disable-line /*} else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; @@ -131,14 +136,15 @@ BigInteger.prototype.DM = ((1 << dbits) - 1); BigInteger.prototype.DV = (1 << dbits); const BI_FP = 52; -BigInteger.prototype.FV = Math.pow(2, BI_FP); +BigInteger.prototype.FV = (2 ** BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions const BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; const BI_RC = new Array(); -let rr, vv; +let rr; +let vv; rr = "0".charCodeAt(0); for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); @@ -197,9 +203,9 @@ function bnpFromString(s, b) { } this.t = 0; this.s = 0; - let i = s.length, - mi = false, - sh = 0; + let i = s.length; + let mi = false; + let sh = 0; while (--i >= 0) { const x = (k == 8) ? s[i] & 0xff : intAt(s, i); if (x < 0) { @@ -241,10 +247,11 @@ function bnToString(b) { else if (b == 32) k = 5; else if (b == 4) k = 2; else return this.toRadix(b); - let km = (1 << k) - 1, - d, m = false, - r = "", - i = this.t; + const km = (1 << k) - 1; + let d = false; + let m = false; + let r = ""; + let i = this.t; let p = this.DB - (i * this.DB) % k; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { @@ -298,8 +305,8 @@ function bnCompareTo(a) { // returns bit length of the integer x function nbits(x) { - let r = 1, - t; + let r = 1; + let t; if ((t = x >>> 16) != 0) { x = t; r += 16; @@ -354,9 +361,9 @@ function bnpLShiftTo(n, r) { const bs = n % this.DB; const cbs = this.DB - bs; const bm = (1 << cbs) - 1; - let ds = Math.floor(n / this.DB), - c = (this.s << bs) & this.DM, - i; + const ds = Math.floor(n / this.DB); + let c = (this.s << bs) & this.DM; + let i; for (i = this.t - 1; i >= 0; --i) { r[i + ds + 1] = (this[i] >> cbs) | c; c = (this[i] & bm) << bs; @@ -393,9 +400,9 @@ function bnpRShiftTo(n, r) { // (protected) r = this - a function bnpSubTo(a, r) { - let i = 0, - c = 0, - m = Math.min(a.t, this.t); + let i = 0; + let c = 0; + const m = Math.min(a.t, this.t); while (i < m) { c += this[i] - a[i]; r[i++] = c & this.DM; @@ -429,8 +436,8 @@ function bnpSubTo(a, r) { // "this" should be the larger one if appropriate. function bnpMultiplyTo(a, r) { - let x = this.abs(), - y = a.abs(); + const x = this.abs(); + const y = a.abs(); let i = x.t; r.t = i + y.t; while (--i >= 0) r[i] = 0; @@ -471,9 +478,9 @@ function bnpDivRemTo(m, q, r) { return; } if (r == null) r = nbi(); - let y = nbi(), - ts = this.s, - ms = m.s; + const y = nbi(); + const ts = this.s; + const ms = m.s; const nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); @@ -486,12 +493,12 @@ function bnpDivRemTo(m, q, r) { const y0 = y[ys - 1]; if (y0 == 0) return; const yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); - let d1 = this.FV / yt, - d2 = (1 << this.F1) / yt, - e = 1 << this.F2; - let i = r.t, - j = i - ys, - t = (q == null) ? nbi() : q; + const d1 = this.FV / yt; + const d2 = (1 << this.F1) / yt; + const e = 1 << this.F2; + let i = r.t; + let j = i - ys; + const t = (q == null) ? nbi() : q; y.dlShiftTo(j, t); if (r.compareTo(t) >= 0) { r[r.t++] = 1; @@ -672,10 +679,10 @@ function bnpIsEven() { function bnpExp(e, z) { if (e > 0xffffffff || e < 1) return BigInteger.ONE; - let r = nbi(), - r2 = nbi(), - g = z.convert(this), - i = nbits(e) - 1; + let r = nbi(); + let r2 = nbi(); + const g = z.convert(this); + let i = nbits(e) - 1; g.copyTo(r); while (--i >= 0) { z.sqrTo(r, r2); @@ -820,11 +827,11 @@ function bnpToRadix(b) { if (b == null) b = 10; if (this.signum() == 0 || b < 2 || b > 36) return "0"; const cs = this.chunkSize(b); - const a = Math.pow(b, cs); - let d = nbv(a), - y = nbi(), - z = nbi(), - r = ""; + const a = (b ** cs); + const d = nbv(a); + const y = nbi(); + const z = nbi(); + let r = ""; this.divRemTo(d, y, z); while (y.signum() > 0) { r = (a + z.intValue()).toString(b).substr(1) + r; @@ -839,10 +846,10 @@ function bnpFromRadix(s, b) { this.fromInt(0); if (b == null) b = 10; const cs = this.chunkSize(b); - let d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0; + const d = (b ** cs); + let mi = false; + let j = 0; + let w = 0; for (let i = 0; i < s.length; ++i) { const x = intAt(s, i); if (x < 0) { @@ -858,7 +865,7 @@ function bnpFromRadix(s, b) { } } if (j > 0) { - this.dMultiply(Math.pow(b, j)); + this.dMultiply((b ** j)); this.dAddOffset(w, 0); } if (mi) BigInteger.ZERO.subTo(this, this); @@ -882,8 +889,8 @@ function bnpFromNumber(a, b, c) { } } else { // new BigInteger(int,RNG) - let x = new Array(), - t = a & 7; + const x = new Array(); + const t = a & 7; x.length = (a >> 3) + 1; b.nextBytes(x); if (t > 0) x[0] &= ((1 << t) - 1); @@ -895,11 +902,12 @@ function bnpFromNumber(a, b, c) { // (public) convert to bigendian byte array function bnToByteArray() { - let i = this.t, - r = new Array(); + let i = this.t; + const r = new Array(); r[0] = this.s; - let p = this.DB - (i * this.DB) % 8, - d, k = 0; + let p = this.DB - (i * this.DB) % 8; + let d = 0; + let k = 0; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) r[k++] = d | (this.s << (this.DB - p)); while (i >= 0) { @@ -936,7 +944,9 @@ function bnMax(a) { // (protected) r = this op a (bitwise) function bnpBitwiseTo(a, op, r) { - let i, f, m = Math.min(a.t, this.t); + let i = Math.min(a.t, this.t); + let f = i; + const m = i; for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); if (a.t < this.t) { f = a.s & this.DM; @@ -1074,8 +1084,8 @@ function cbit(x) { // (public) return number of set bits function bnBitCount() { - let r = 0, - x = this.s & this.DM; + let r = 0; + const x = this.s & this.DM; for (let i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); return r; } @@ -1117,9 +1127,9 @@ function bnFlipBit(n) { // (protected) r = this + a function bnpAddTo(a, r) { - let i = 0, - c = 0, - m = Math.min(a.t, this.t); + let i = 0; + let c = 0; + const m = Math.min(a.t, this.t); while (i < m) { c += this[i] + a[i]; r[i++] = c & this.DM; @@ -1200,8 +1210,8 @@ function bnRemainder(a) { // (public) [this/a,this%a] function bnDivideAndRemainder(a) { - let q = nbi(), - r = nbi(); + const q = nbi(); + const r = nbi(); this.divRemTo(a, q, r); return new Array(q, r); } @@ -1345,9 +1355,9 @@ Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e, m) { - let i = e.bitLength(), - k, r = nbv(1), - z; + let i = e.bitLength(); + let k, r = nbv(1); + let z; if (i <= 0) return r; else if (i < 18) k = 1; else if (i < 48) k = 3; @@ -1359,10 +1369,10 @@ function bnModPow(e, m) { else z = new Montgomery(m); // precomputation - let g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1; + const g = new Array(); + let n = 3; + const k1 = k - 1; + const km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { const g2 = nbi(); @@ -1374,10 +1384,10 @@ function bnModPow(e, m) { } } - let j = e.t - 1, - w, is1 = true, - r2 = nbi(), - t; + let j = e.t - 1; + let w, is1 = true; + let r2 = nbi(); + let t; i = nbits(e[j]) - 1; while (j >= 0) { if (i >= k1) w = (e[j] >> (i - k1)) & km; @@ -1464,8 +1474,8 @@ function bnGCD(a) { function bnpModInt(n) { if (n <= 0) return 0; - let d = this.DV % n, - r = (this.s < 0) ? n - 1 : 0; + const d = this.DV % n; + let r = (this.s < 0) ? n - 1 : 0; if (this.t > 0) { if (d == 0) r = this[0] % n; else for (let i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; } return r; @@ -1476,12 +1486,12 @@ function bnpModInt(n) { function bnModInverse(m) { const ac = m.isEven(); if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - let u = m.clone(), - v = this.clone(); - let a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1); + const u = m.clone(); + const v = this.clone(); + const a = nbv(1); + const b = nbv(0); + const c = nbv(0); + const d = nbv(1); while (u.signum() != 0) { while (u.isEven()) { u.rShiftTo(1, u); @@ -1536,7 +1546,8 @@ const lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { - let i, x = this.abs(); + let i; + const x = this.abs(); if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { for (i = 0; i < lowprimes.length; ++i) if (x[0] == lowprimes[i]) return true; return false; @@ -1544,8 +1555,8 @@ function bnIsProbablePrime(t) { if (x.isEven()) return false; i = 1; while (i < lowprimes.length) { - let m = lowprimes[i], - j = i + 1; + let m = lowprimes[i]; + let j = i + 1; while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while (i < j) if (m % lowprimes[i++] == 0) return false; @@ -1555,9 +1566,10 @@ function bnIsProbablePrime(t) { /* added by Recurity Labs */ +/* eslint-disable no-redeclare */ function nbits(x) { - let n = 1, - t; + let n = 1; + let t; if ((t = x >>> 16) != 0) { x = t; n += 16; @@ -1601,7 +1613,8 @@ function bnpMillerRabin(t) { t = (t + 1) >> 1; if (t > lowprimes.length) t = lowprimes.length; const a = nbi(); - var j, bases = []; + let j; + const bases = []; for (let i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 for (;;) { @@ -1612,7 +1625,7 @@ function bnpMillerRabin(t) { a.fromInt(j); let y = a.modPow(r, this); if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; + let j = 1; while (j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2, this); if (y.compareTo(BigInteger.ONE) == 0) return false;