From 238248209009e76d3169c73913c068f1e9012c20 Mon Sep 17 00:00:00 2001 From: Daniel Huigens Date: Mon, 16 Nov 2020 07:13:50 +0100 Subject: [PATCH] [v5] Unexport openpgp.util, openpgp.crypto, and low-level types (#1175) --- package-lock.json | 6 ++ package.json | 8 +- rollup.config.js | 5 + src/crypto/public_key/elliptic/curves.js | 13 +-- src/crypto/public_key/elliptic/ecdh.js | 3 +- src/crypto/public_key/rsa.js | 31 +++--- src/encoding/base64.js | 25 +++++ src/index.js | 42 --------- src/util.js | 26 ----- test/crypto/aes_kw.js | 12 ++- test/crypto/cipher/aes.js | 4 +- test/crypto/cipher/blowfish.js | 6 +- test/crypto/cipher/cast5.js | 6 +- test/crypto/cipher/des.js | 8 +- test/crypto/cipher/twofish.js | 6 +- test/crypto/crypto.js | 4 +- test/crypto/eax.js | 26 ++--- test/crypto/ecdh.js | 22 +++-- test/crypto/elliptic.js | 49 +++++----- test/crypto/hash/md5.js | 5 +- test/crypto/hash/ripemd.js | 5 +- test/crypto/hash/sha.js | 5 +- test/crypto/ocb.js | 40 ++++---- test/crypto/pkcs5.js | 3 +- test/crypto/random.js | 4 +- test/crypto/rsa.js | 78 +++++++-------- test/general/biginteger.js | 7 +- test/general/brainpool.js | 5 +- test/general/ecc_secp256k1.js | 3 +- test/general/key.js | 14 +-- test/general/oid.js | 7 +- test/general/openpgp.js | 60 ++++-------- test/general/packet.js | 62 ++++++------ test/general/signature.js | 15 +-- test/general/streaming.js | 110 ++++++++++++---------- test/general/util.js | 55 +++++------ test/general/x25519.js | 12 ++- test/security/message_signature_bypass.js | 12 +-- test/security/subkey_trust.js | 5 +- 39 files changed, 396 insertions(+), 413 deletions(-) diff --git a/package-lock.json b/package-lock.json index c729c550..ec26807e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1312,6 +1312,12 @@ "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", "dev": true }, + "esm": { + "version": "3.2.25", + "resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz", + "integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==", + "dev": true + }, "esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", diff --git a/package.json b/package.json index 85149d31..b9fec847 100644 --- a/package.json +++ b/package.json @@ -26,11 +26,16 @@ "dist/", "lightweight/" ], + "esm": { + "cjs": { + "dedefault": true + } + }, "scripts": { "build": "rollup --config", "build-test": "npm run build --build-only=test", "prepare": "npm run build", - "test": "mocha --timeout 120000 test/unittests.js", + "test": "mocha --require esm --timeout 120000 test/unittests.js", "start": "http-server", "prebrowsertest": "npm run build-test", "browsertest": "npm start -- -o test/unittests.html", @@ -59,6 +64,7 @@ "eslint-config-airbnb-base": "^12.1.0", "eslint-plugin-chai-friendly": "^0.5.0", "eslint-plugin-import": "^2.8.0", + "esm": "^3.2.25", "hash.js": "^1.1.3", "http-server": "^0.12.3", "jsdoc": "github:openpgpjs/jsdoc#0f1816eb4553856647b4ca9561b9307b11ec4f9e", diff --git a/rollup.config.js b/rollup.config.js index 7c8364fe..c1143978 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -95,12 +95,17 @@ export default Object.assign([ output: [ { file: 'test/lib/unittests-bundle.js', format: 'es', sourcemap: true }, ], + inlineDynamicImports: true, plugins: [ resolve({ browser: true }), commonjs({ ignore: builtinModules.concat(nodeDependencies).concat(['../..', '../../..']) + }), + replace({ + 'require(': 'void(', + delimiters: ['', ''] }) ] } diff --git a/src/crypto/public_key/elliptic/curves.js b/src/crypto/public_key/elliptic/curves.js index 53d69fa1..7370f970 100644 --- a/src/crypto/public_key/elliptic/curves.js +++ b/src/crypto/public_key/elliptic/curves.js @@ -31,6 +31,7 @@ import nacl from 'tweetnacl/nacl-fast-light.js'; import { getRandomBytes } from '../../random'; import enums from '../../../enums'; import util from '../../../util'; +import { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64'; import OID from '../../../type/oid'; import { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey'; @@ -311,7 +312,7 @@ async function webGenKeyPair(name) { return { publicKey: jwkToRawPublic(publicKey), - privateKey: util.b64ToUint8Array(privateKey.d, true) + privateKey: b64ToUint8Array(privateKey.d, true) }; } @@ -337,8 +338,8 @@ async function nodeGenKeyPair(name) { * @returns {Uint8Array} raw public key */ function jwkToRawPublic(jwk) { - const bufX = util.b64ToUint8Array(jwk.x); - const bufY = util.b64ToUint8Array(jwk.y); + const bufX = b64ToUint8Array(jwk.x); + const bufY = b64ToUint8Array(jwk.y); const publicKey = new Uint8Array(bufX.length + bufY.length + 1); publicKey[0] = 0x04; publicKey.set(bufX, 1); @@ -361,8 +362,8 @@ function rawPublicToJwk(payloadSize, name, publicKey) { const jwk = { kty: "EC", crv: name, - x: util.uint8ArrayToB64(bufX, true), - y: util.uint8ArrayToB64(bufY, true), + x: uint8ArrayToB64(bufX, true), + y: uint8ArrayToB64(bufY, true), ext: true }; return jwk; @@ -378,6 +379,6 @@ function rawPublicToJwk(payloadSize, name, publicKey) { */ function privateToJwk(payloadSize, name, publicKey, privateKey) { const jwk = rawPublicToJwk(payloadSize, name, publicKey); - jwk.d = util.uint8ArrayToB64(privateKey, true); + jwk.d = uint8ArrayToB64(privateKey, true); return jwk; } diff --git a/src/crypto/public_key/elliptic/ecdh.js b/src/crypto/public_key/elliptic/ecdh.js index 9e1a90af..04c97c18 100644 --- a/src/crypto/public_key/elliptic/ecdh.js +++ b/src/crypto/public_key/elliptic/ecdh.js @@ -37,6 +37,7 @@ import { getRandomBytes } from '../../random'; import hash from '../../hash'; import enums from '../../../enums'; import util from '../../../util'; +import { b64ToUint8Array } from '../../../encoding/base64'; import * as pkcs5 from '../../pkcs5'; import { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey'; @@ -262,7 +263,7 @@ async function webPrivateEphemeralKey(curve, V, Q, d) { ); [S, secret] = await Promise.all([S, secret]); const sharedKey = new Uint8Array(S); - const secretKey = util.b64ToUint8Array(secret.d, true); + const secretKey = b64ToUint8Array(secret.d, true); return { secretKey, sharedKey }; } diff --git a/src/crypto/public_key/rsa.js b/src/crypto/public_key/rsa.js index 412bc52d..9bb7e2f2 100644 --- a/src/crypto/public_key/rsa.js +++ b/src/crypto/public_key/rsa.js @@ -28,6 +28,7 @@ import { randomProbablePrime } from './prime'; import { getRandomBigInteger } from '../random'; import config from '../../config'; import util from '../../util'; +import { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64'; import { emsaEncode, emeEncode, emeDecode } from '../pkcs1'; import enums from '../../enums'; @@ -221,14 +222,14 @@ export async function generate(bits, e) { } // map JWK parameters to corresponding OpenPGP names return { - n: util.b64ToUint8Array(jwk.n), + n: b64ToUint8Array(jwk.n), e: e.toUint8Array(), - d: util.b64ToUint8Array(jwk.d), + d: b64ToUint8Array(jwk.d), // switch p and q - p: util.b64ToUint8Array(jwk.q), - q: util.b64ToUint8Array(jwk.p), + p: b64ToUint8Array(jwk.q), + q: b64ToUint8Array(jwk.p), // Since p and q are switched in places, u is the inverse of jwk.q - u: util.b64ToUint8Array(jwk.qi) + u: b64ToUint8Array(jwk.qi) }; } else if (util.getNodeCrypto() && nodeCrypto.generateKeyPair && RSAPrivateKey) { const opts = { @@ -570,16 +571,16 @@ async function privateToJwk(n, e, d, p, q, u) { dq = dq.toUint8Array(); return { kty: 'RSA', - n: util.uint8ArrayToB64(n, true), - e: util.uint8ArrayToB64(e, true), - d: util.uint8ArrayToB64(d, true), + n: uint8ArrayToB64(n, true), + e: uint8ArrayToB64(e, true), + d: uint8ArrayToB64(d, true), // switch p and q - p: util.uint8ArrayToB64(q, true), - q: util.uint8ArrayToB64(p, true), + p: uint8ArrayToB64(q, true), + q: uint8ArrayToB64(p, true), // switch dp and dq - dp: util.uint8ArrayToB64(dq, true), - dq: util.uint8ArrayToB64(dp, true), - qi: util.uint8ArrayToB64(u, true), + dp: uint8ArrayToB64(dq, true), + dq: uint8ArrayToB64(dp, true), + qi: uint8ArrayToB64(u, true), ext: true }; } @@ -593,8 +594,8 @@ async function privateToJwk(n, e, d, p, q, u) { function publicToJwk(n, e) { return { kty: 'RSA', - n: util.uint8ArrayToB64(n, true), - e: util.uint8ArrayToB64(e, true), + n: uint8ArrayToB64(n, true), + e: uint8ArrayToB64(e, true), ext: true }; } diff --git a/src/encoding/base64.js b/src/encoding/base64.js index c3727ffc..ba2e84ba 100644 --- a/src/encoding/base64.js +++ b/src/encoding/base64.js @@ -92,3 +92,28 @@ export function decode(data) { return decoded; }, () => decodeChunk(buf)); } + +/** + * Convert a Base-64 encoded string an array of 8-bit integer + * + * Note: accepts both Radix-64 and URL-safe strings + * @param {String} base64 Base-64 encoded string to convert + * @returns {Uint8Array} An array of 8-bit integers + */ +export function b64ToUint8Array(base64) { + return decode(base64.replace(/-/g, '+').replace(/_/g, '/')); +} + +/** + * Convert an array of 8-bit integer to a Base-64 encoded string + * @param {Uint8Array} bytes An array of 8-bit integers to convert + * @param {bool} url If true, output is URL-safe + * @returns {String} Base-64 encoded string + */ +export function uint8ArrayToB64(bytes, url) { + let encoded = encode(bytes).replace(/[\r\n]/g, ''); + if (url) { + encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, ''); + } + return encoded; +} diff --git a/src/index.js b/src/index.js index 6d512fd3..316f5a51 100644 --- a/src/index.js +++ b/src/index.js @@ -40,48 +40,12 @@ export { */ export * from './cleartext'; -/** - * @see module:util - * @name module:openpgp.util - */ -export { default as util } from './util'; - /** * @see module:packet * @name module:openpgp.packet */ export * from './packet'; -/** - * @see module:type/s2k - * @name module:openpgp.S2K - */ -export { default as S2K } from './type/s2k'; - -/** - * @see module:type/keyid - * @name module:openpgp.Keyid - */ -export { default as Keyid } from './type/keyid'; - -/** - * @see module:type/ecdh_symkey - * @name module:openpgp.ECDHSymmetricKey - */ -export { default as ECDHSymmetricKey } from './type/ecdh_symkey'; - -/** - * @see module:type/kdf_params - * @name module:openpgp.KDFParams - */ -export { default as KDFParams } from './type/kdf_params'; - -/** - * @see module:type/oid - * @name module:openpgp.OID - */ -export { default as OID } from './type/oid'; - /** * @see streams * @name module:openpgp.stream @@ -106,12 +70,6 @@ export { default as enums } from './enums'; */ export { default as config } from './config/config'; -/** - * @see module:crypto - * @name module:openpgp.crypto - */ -export { default as crypto } from './crypto'; - /** * @see module:keyring * @name module:openpgp.Keyring diff --git a/src/util.js b/src/util.js index fe9991fd..1a3a14de 100644 --- a/src/util.js +++ b/src/util.js @@ -30,7 +30,6 @@ import emailAddresses from 'email-addresses'; import stream from 'web-stream-tools'; import config from './config'; import util from './util'; // re-import module to access util functions -import * as b64 from './encoding/base64'; import { getBigInteger } from './biginteger'; export default { @@ -203,31 +202,6 @@ export default { return util.concatUint8Array([prefix, bin]); }, - /** - * Convert a Base-64 encoded string an array of 8-bit integer - * - * Note: accepts both Radix-64 and URL-safe strings - * @param {String} base64 Base-64 encoded string to convert - * @returns {Uint8Array} An array of 8-bit integers - */ - b64ToUint8Array: function (base64) { - return b64.decode(base64.replace(/-/g, '+').replace(/_/g, '/')); - }, - - /** - * Convert an array of 8-bit integer to a Base-64 encoded string - * @param {Uint8Array} bytes An array of 8-bit integers to convert - * @param {bool} url If true, output is URL-safe - * @returns {String} Base-64 encoded string - */ - uint8ArrayToB64: function (bytes, url) { - let encoded = b64.encode(bytes).replace(/[\r\n]/g, ''); - if (url) { - encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, ''); - } - return encoded; - }, - /** * Convert a hex string to an array of 8-bit integers * @param {String} hex A hex string to convert diff --git a/test/crypto/aes_kw.js b/test/crypto/aes_kw.js index c1ee1461..c967c1ec 100644 --- a/test/crypto/aes_kw.js +++ b/test/crypto/aes_kw.js @@ -1,4 +1,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const aes_kw = require('../../src/crypto/aes_kw'); +const util = require('../../src/util'); const expect = require('chai').expect; @@ -44,13 +46,13 @@ module.exports = () => describe('AES Key Wrap and Unwrap', function () { test_vectors.forEach(function(test) { it(test[0], function(done) { - const kek = openpgp.util.hexToUint8Array(test[1]); + const kek = util.hexToUint8Array(test[1]); const input = test[2].replace(/\s/g, ""); - const input_bin = openpgp.util.hexToStr(input); + const input_bin = util.hexToStr(input); const output = test[3].replace(/\s/g, ""); - const output_bin = openpgp.util.hexToStr(output); - expect(openpgp.util.uint8ArrayToHex(openpgp.crypto.aes_kw.wrap(kek, input_bin)).toUpperCase()).to.equal(output); - expect(openpgp.util.uint8ArrayToHex(openpgp.crypto.aes_kw.unwrap(kek, output_bin)).toUpperCase()).to.equal(input); + const output_bin = util.hexToStr(output); + expect(util.uint8ArrayToHex(aes_kw.wrap(kek, input_bin)).toUpperCase()).to.equal(output); + expect(util.uint8ArrayToHex(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 e44f109e..5d39fd5a 100644 --- a/test/crypto/cipher/aes.js +++ b/test/crypto/cipher/aes.js @@ -1,4 +1,4 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../..'); +const { aes128 } = require('../../../src/crypto/cipher'); const chai = require('chai'); @@ -6,7 +6,7 @@ const { expect } = chai; module.exports = () => describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function() { function test_aes(input, key, output) { - const aes = new openpgp.crypto.cipher.aes128(new Uint8Array(key)); + const aes = new aes128(new Uint8Array(key)); const encrypted = aes.encrypt(new Uint8Array(input)); expect(encrypted).to.deep.equal(new Uint8Array(output)); diff --git a/test/crypto/cipher/blowfish.js b/test/crypto/cipher/blowfish.js index c8ff17f6..1d2dc3b0 100644 --- a/test/crypto/cipher/blowfish.js +++ b/test/crypto/cipher/blowfish.js @@ -1,13 +1,13 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../..'); +const BF = require('../../../src/crypto/cipher/blowfish'); +const util = require('../../../src/util'); const chai = require('chai'); -const { util } = openpgp; const { expect } = chai; module.exports = () => it('Blowfish cipher test with test vectors from https://www.schneier.com/code/vectors.txt', function(done) { function test_bf(input, key, output) { - const blowfish = new openpgp.crypto.cipher.blowfish(util.uint8ArrayToStr(key)); + const blowfish = new BF(util.uint8ArrayToStr(key)); const result = util.uint8ArrayToStr(blowfish.encrypt(input)); return (util.strToHex(result) === util.strToHex(util.uint8ArrayToStr(output))); diff --git a/test/crypto/cipher/cast5.js b/test/crypto/cipher/cast5.js index f6b3883e..513af642 100644 --- a/test/crypto/cipher/cast5.js +++ b/test/crypto/cipher/cast5.js @@ -1,13 +1,13 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../..'); +const Cast5 = require('../../../src/crypto/cipher/cast5'); +const util = require('../../../src/util'); const chai = require('chai'); -const { util } = openpgp; const { expect } = chai; module.exports = () => it('CAST-128 cipher test with test vectors from RFC2144', function (done) { function test_cast(input, key, output) { - const cast5 = new openpgp.crypto.cipher.cast5(key); + const cast5 = new Cast5(key); const result = util.uint8ArrayToStr(cast5.encrypt(input)); return util.strToHex(result) === util.strToHex(util.uint8ArrayToStr(output)); diff --git a/test/crypto/cipher/des.js b/test/crypto/cipher/des.js index bef5b9e6..9bcbb20f 100644 --- a/test/crypto/cipher/des.js +++ b/test/crypto/cipher/des.js @@ -1,8 +1,8 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../..'); +const { DES, TripleDES } = require('../../../src/crypto/cipher/des'); +const util = require('../../../src/util'); const chai = require('chai'); -const { util } = openpgp; const { expect } = chai; module.exports = () => describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', function() { @@ -75,7 +75,7 @@ module.exports = () => describe('TripleDES (EDE) cipher test with test vectors f it('3DES EDE test vectors', function (done) { for (let i = 0; i < testvectors.length; i++) { - const des = new openpgp.crypto.cipher.tripledes(key); + const des = new TripleDES(key); const encr = util.uint8ArrayToStr(des.encrypt(testvectors[i][0], key)); @@ -115,7 +115,7 @@ module.exports = () => describe('TripleDES (EDE) cipher test with test vectors f [[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]]]; - const des = new openpgp.crypto.cipher.des(key); + const des = new DES(key); for (let padding = 0; padding < 3; padding++) { const thisVectorSet = testvectors[padding]; diff --git a/test/crypto/cipher/twofish.js b/test/crypto/cipher/twofish.js index ff63a8df..838c37f4 100644 --- a/test/crypto/cipher/twofish.js +++ b/test/crypto/cipher/twofish.js @@ -1,13 +1,13 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../..'); +const TF = require('../../../src/crypto/cipher/twofish'); +const util = require('../../../src/util'); const chai = require('chai'); -const { util } = openpgp; const { expect } = chai; module.exports = () => it('Twofish with test vectors from https://www.schneier.com/code/ecb_ival.txt', function(done) { function tfencrypt(block, key) { - const tf = new openpgp.crypto.cipher.twofish(util.strToUint8Array(key)); + const tf = new TF(util.strToUint8Array(key)); return tf.encrypt(block); } diff --git a/test/crypto/crypto.js b/test/crypto/crypto.js index c8f2c313..4cc9c674 100644 --- a/test/crypto/crypto.js +++ b/test/crypto/crypto.js @@ -1,4 +1,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const crypto = require('../../src/crypto'); +const util = require('../../src/util'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -6,8 +8,6 @@ chai.use(require('chai-as-promised')); const expect = chai.expect; module.exports = () => describe('API functional testing', function() { - const util = openpgp.util; - const crypto = openpgp.crypto; const RSAPublicKeyMaterial = util.concatUint8Array([ 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, diff --git a/test/crypto/eax.js b/test/crypto/eax.js index 71eb696d..9094000a 100644 --- a/test/crypto/eax.js +++ b/test/crypto/eax.js @@ -3,6 +3,8 @@ // Adapted from https://github.com/artjomb/cryptojs-extension/blob/8c61d159/test/eax.js const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const EAX = require('../../src/crypto/eax'); +const util = require('../../src/util'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -88,21 +90,21 @@ function testAESEAX() { const cipher = 'aes128'; await Promise.all(vectors.map(async vec => { - const keyBytes = openpgp.util.hexToUint8Array(vec.key); - const msgBytes = openpgp.util.hexToUint8Array(vec.msg); - const nonceBytes = openpgp.util.hexToUint8Array(vec.nonce); - const headerBytes = openpgp.util.hexToUint8Array(vec.header); - const ctBytes = openpgp.util.hexToUint8Array(vec.ct); + const keyBytes = util.hexToUint8Array(vec.key); + const msgBytes = util.hexToUint8Array(vec.msg); + const nonceBytes = util.hexToUint8Array(vec.nonce); + const headerBytes = util.hexToUint8Array(vec.header); + const ctBytes = util.hexToUint8Array(vec.ct); - const eax = await openpgp.crypto.eax(cipher, keyBytes); + const eax = await EAX(cipher, keyBytes); // encryption test let ct = await eax.encrypt(msgBytes, nonceBytes, headerBytes); - expect(openpgp.util.uint8ArrayToHex(ct)).to.equal(vec.ct.toLowerCase()); + expect(util.uint8ArrayToHex(ct)).to.equal(vec.ct.toLowerCase()); // decryption test with verification let pt = await eax.decrypt(ctBytes, nonceBytes, headerBytes); - expect(openpgp.util.uint8ArrayToHex(pt)).to.equal(vec.msg.toLowerCase()); + expect(util.uint8ArrayToHex(pt)).to.equal(vec.msg.toLowerCase()); // tampering detection test ct = await eax.encrypt(msgBytes, nonceBytes, headerBytes); @@ -113,12 +115,12 @@ function testAESEAX() { // testing without additional data ct = await eax.encrypt(msgBytes, nonceBytes, new Uint8Array()); pt = await eax.decrypt(ct, nonceBytes, new Uint8Array()); - expect(openpgp.util.uint8ArrayToHex(pt)).to.equal(vec.msg.toLowerCase()); + expect(util.uint8ArrayToHex(pt)).to.equal(vec.msg.toLowerCase()); // testing with multiple additional data - ct = await eax.encrypt(msgBytes, nonceBytes, openpgp.util.concatUint8Array([headerBytes, headerBytes, headerBytes])); - pt = await eax.decrypt(ct, nonceBytes, openpgp.util.concatUint8Array([headerBytes, headerBytes, headerBytes])); - expect(openpgp.util.uint8ArrayToHex(pt)).to.equal(vec.msg.toLowerCase()); + ct = await eax.encrypt(msgBytes, nonceBytes, util.concatUint8Array([headerBytes, headerBytes, headerBytes])); + pt = await eax.decrypt(ct, nonceBytes, util.concatUint8Array([headerBytes, headerBytes, headerBytes])); + expect(util.uint8ArrayToHex(pt)).to.equal(vec.msg.toLowerCase()); })); }); } diff --git a/test/crypto/ecdh.js b/test/crypto/ecdh.js index e7578cc7..ca2e6ede 100644 --- a/test/crypto/ecdh.js +++ b/test/crypto/ecdh.js @@ -1,4 +1,9 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const OID = require('../../src/type/oid'); +const KDFParams = require('../../src/type/kdf_params'); +const elliptic_curves = require('../../src/crypto/public_key/elliptic'); +const util = require('../../src/util'); + const chai = require('chai'); const elliptic_data = require('./elliptic_data'); @@ -8,18 +13,17 @@ const expect = chai.expect; const key_data = elliptic_data.key_data; /* eslint-disable no-invalid-this */ module.exports = () => describe('ECDH key exchange @lightweight', function () { - const elliptic_curves = openpgp.crypto.publicKey.elliptic; const decrypt_message = function (oid, hash, cipher, priv, pub, ephemeral, data, fingerprint) { - if (openpgp.util.isString(data)) { - data = openpgp.util.strToUint8Array(data); + if (util.isString(data)) { + data = util.strToUint8Array(data); } else { data = new Uint8Array(data); } return Promise.resolve().then(() => { const curve = new elliptic_curves.Curve(oid); return elliptic_curves.ecdh.decrypt( - new openpgp.OID(curve.oid), - new openpgp.KDFParams({ cipher, hash }), + new OID(curve.oid), + new KDFParams({ cipher, hash }), new Uint8Array(ephemeral), data, new Uint8Array(pub), @@ -67,7 +71,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { )).to.be.rejectedWith(Error, /Not valid curve/).notify(done); }); it('Invalid ephemeral key', function (done) { - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!openpgp.config.useIndutnyElliptic && !util.getNodeCrypto()) { this.skip(); } expect(decrypt_message( @@ -75,7 +79,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { )).to.be.rejectedWith(Error, /Private key is not valid for specified curve|Unknown point format/).notify(done); }); it('Invalid elliptic public key', function (done) { - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!openpgp.config.useIndutnyElliptic && !util.getNodeCrypto()) { this.skip(); } expect(decrypt_message( @@ -83,7 +87,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { )).to.be.rejectedWith(Error, /Public key is not valid for specified curve|Failed to translate Buffer to a EC_POINT|Invalid elliptic public key/).notify(done); }); it('Invalid key data integrity', function (done) { - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!openpgp.config.useIndutnyElliptic && !util.getNodeCrypto()) { this.skip(); } expect(decrypt_message( @@ -130,7 +134,7 @@ module.exports = () => describe('ECDH key exchange @lightweight', function () { describe('ECDHE key generation', function () { it('Invalid curve', async function () { - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!openpgp.config.useIndutnyElliptic && !util.getNodeCrypto()) { this.skip(); } const { key: publicKey } = await openpgp.generateKey({ curve: "secp256k1", userIds: [{ name: 'Test' }] }); diff --git a/test/crypto/elliptic.js b/test/crypto/elliptic.js index bffb7dd9..54d23632 100644 --- a/test/crypto/elliptic.js +++ b/test/crypto/elliptic.js @@ -1,4 +1,9 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const elliptic_curves = require('../../src/crypto/public_key/elliptic'); +const hashMod = require('../../src/crypto/hash'); +const config = require('../../src/config'); +const util = require('../../src/util'); + const chai = require('chai'); const elliptic_data = require('./elliptic_data'); @@ -9,8 +14,6 @@ const expect = chai.expect; const key_data = elliptic_data.key_data; /* eslint-disable no-invalid-this */ module.exports = () => describe('Elliptic Curve Cryptography @lightweight', function () { - const elliptic_curves = openpgp.crypto.publicKey.elliptic; - const signature_data = { priv: new Uint8Array([ 0x14, 0x2B, 0xE2, 0xB7, 0x4D, 0xBD, 0x1B, 0x22, @@ -65,10 +68,10 @@ module.exports = () => describe('Elliptic Curve Cryptography @lightweight', func done(); }); it('Creating KeyPair', function () { - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!config.useIndutnyElliptic && !util.getNodeCrypto()) { this.skip(); } - const names = openpgp.config.useIndutnyElliptic ? ['p256', 'p384', 'p521', 'secp256k1', 'curve25519', 'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1'] : + const names = config.useIndutnyElliptic ? ['p256', 'p384', 'p521', 'secp256k1', 'curve25519', 'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1'] : ['p256', 'p384', 'p521', 'curve25519']; return Promise.all(names.map(function (name) { const curve = new elliptic_curves.Curve(name); @@ -97,14 +100,14 @@ module.exports = () => describe('Elliptic Curve Cryptography @lightweight', func }); describe('ECDSA signature', function () { const verify_signature = async function (oid, hash, r, s, message, pub) { - if (openpgp.util.isString(message)) { - message = openpgp.util.strToUint8Array(message); - } else if (!openpgp.util.isUint8Array(message)) { + if (util.isString(message)) { + message = util.strToUint8Array(message); + } else if (!util.isUint8Array(message)) { message = new Uint8Array(message); } const ecdsa = elliptic_curves.ecdsa; return ecdsa.verify( - oid, hash, { r: new Uint8Array(r), s: new Uint8Array(s) }, message, new Uint8Array(pub), await openpgp.crypto.hash.digest(hash, message) + oid, hash, { r: new Uint8Array(r), s: new Uint8Array(s) }, message, new Uint8Array(pub), await hashMod.digest(hash, message) ); }; const secp256k1_point = new Uint8Array([ @@ -147,10 +150,10 @@ module.exports = () => describe('Elliptic Curve Cryptography @lightweight', func ]); }); it('Invalid public key', async function () { - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!config.useIndutnyElliptic && !util.getNodeCrypto()) { this.skip(); } - if (openpgp.util.getNodeCrypto()) { + if (util.getNodeCrypto()) { await expect(verify_signature( 'secp256k1', 8, [], [], [], [] )).to.eventually.be.false; @@ -158,9 +161,9 @@ module.exports = () => describe('Elliptic Curve Cryptography @lightweight', func 'secp256k1', 8, [], [], [], secp256k1_invalid_point_format )).to.eventually.be.false; } - if (openpgp.config.useIndutnyElliptic) { - const useNative = openpgp.config.useNative; - openpgp.config.useNative = false; + if (config.useIndutnyElliptic) { + const useNative = config.useNative; + config.useNative = false; try { await Promise.all([ expect(verify_signature( @@ -171,33 +174,33 @@ module.exports = () => describe('Elliptic Curve Cryptography @lightweight', func )).to.be.rejectedWith(Error, /Unknown point format/) ]); } finally { - openpgp.config.useNative = useNative; + config.useNative = useNative; } } }); it('Invalid point', async function () { - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!config.useIndutnyElliptic && !util.getNodeCrypto()) { this.skip(); } - if (openpgp.util.getNodeCrypto()) { + if (util.getNodeCrypto()) { await expect(verify_signature( 'secp256k1', 8, [], [], [], secp256k1_invalid_point )).to.eventually.be.false; } - if (openpgp.config.useIndutnyElliptic) { - const useNative = openpgp.config.useNative; - openpgp.config.useNative = false; + if (config.useIndutnyElliptic) { + const useNative = config.useNative; + config.useNative = false; try { await expect(verify_signature( 'secp256k1', 8, [], [], [], secp256k1_invalid_point )).to.be.rejectedWith(Error, /Invalid elliptic public key/); } finally { - openpgp.config.useNative = useNative; + config.useNative = useNative; } } }); it('Invalid signature', function (done) { - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!config.useIndutnyElliptic && !util.getNodeCrypto()) { this.skip(); } expect(verify_signature( @@ -236,8 +239,8 @@ module.exports = () => describe('Elliptic Curve Cryptography @lightweight', func const keyPrivate = new Uint8Array(keyPair.privateKey); const oid = curve.oid; const message = p384_message; - return elliptic_curves.ecdsa.sign(oid, 10, message, keyPublic, keyPrivate, await openpgp.crypto.hash.digest(10, message)).then(async signature => { - await expect(elliptic_curves.ecdsa.verify(oid, 10, signature, message, keyPublic, await openpgp.crypto.hash.digest(10, message))) + return elliptic_curves.ecdsa.sign(oid, 10, message, keyPublic, keyPrivate, await hashMod.digest(10, message)).then(async signature => { + await expect(elliptic_curves.ecdsa.verify(oid, 10, signature, message, keyPublic, await hashMod.digest(10, message))) .to.eventually.be.true; }); }); diff --git a/test/crypto/hash/md5.js b/test/crypto/hash/md5.js index 7838d5da..e75a7e43 100644 --- a/test/crypto/hash/md5.js +++ b/test/crypto/hash/md5.js @@ -1,9 +1,8 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../..'); +const md5 = require('../../../src/crypto/hash/md5'); +const util = require('../../../src/util'); const chai = require('chai'); -const { util } = openpgp; -const md5 = openpgp.crypto.hash.md5; const { expect } = chai; module.exports = () => it('MD5 with test vectors from RFC 1321', async function() { diff --git a/test/crypto/hash/ripemd.js b/test/crypto/hash/ripemd.js index 5c66f147..6f56367d 100644 --- a/test/crypto/hash/ripemd.js +++ b/test/crypto/hash/ripemd.js @@ -1,9 +1,8 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../..'); +const { ripemd: rmdString } = require('../../../src/crypto/hash'); +const util = require('../../../src/util'); const chai = require('chai'); -const { util } = openpgp; -const rmdString = openpgp.crypto.hash.ripemd; const { expect } = chai; module.exports = () => it("RIPE-MD 160 bits with test vectors from https://homes.esat.kuleuven.be/~bosselae/ripemd160.html", async function() { diff --git a/test/crypto/hash/sha.js b/test/crypto/hash/sha.js index 5849948b..597f917b 100644 --- a/test/crypto/hash/sha.js +++ b/test/crypto/hash/sha.js @@ -1,9 +1,8 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../../..'); +const hash = require('../../../src/crypto/hash'); +const util = require('../../../src/util'); const chai = require('chai'); -const { util } = openpgp; -const { hash } = openpgp.crypto; const { expect } = chai; module.exports = () => it('SHA* with test vectors from NIST FIPS 180-2', async function() { diff --git a/test/crypto/ocb.js b/test/crypto/ocb.js index 7a18404c..15e609b5 100644 --- a/test/crypto/ocb.js +++ b/test/crypto/ocb.js @@ -3,6 +3,8 @@ // Adapted from https://github.com/artjomb/cryptojs-extension/blob/8c61d159/test/eax.js const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const OCB = require('../../src/crypto/ocb'); +const util = require('../../src/util'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -12,7 +14,7 @@ const expect = chai.expect; module.exports = () => describe('Symmetric AES-OCB', function() { it('Passes all test vectors', async function() { const K = '000102030405060708090A0B0C0D0E0F'; - const keyBytes = openpgp.util.hexToUint8Array(K); + const keyBytes = util.hexToUint8Array(K); const vectors = [ // From https://tools.ietf.org/html/rfc7253#appendix-A @@ -117,20 +119,20 @@ module.exports = () => describe('Symmetric AES-OCB', function() { const cipher = 'aes128'; await Promise.all(vectors.map(async vec => { - const msgBytes = openpgp.util.hexToUint8Array(vec.P); - const nonceBytes = openpgp.util.hexToUint8Array(vec.N); - const headerBytes = openpgp.util.hexToUint8Array(vec.A); - const ctBytes = openpgp.util.hexToUint8Array(vec.C); + const msgBytes = util.hexToUint8Array(vec.P); + const nonceBytes = util.hexToUint8Array(vec.N); + const headerBytes = util.hexToUint8Array(vec.A); + const ctBytes = util.hexToUint8Array(vec.C); - const ocb = await openpgp.crypto.ocb(cipher, keyBytes); + const ocb = await OCB(cipher, keyBytes); // encryption test let ct = await ocb.encrypt(msgBytes, nonceBytes, headerBytes); - expect(openpgp.util.uint8ArrayToHex(ct)).to.equal(vec.C.toLowerCase()); + expect(util.uint8ArrayToHex(ct)).to.equal(vec.C.toLowerCase()); // decryption test with verification let pt = await ocb.decrypt(ctBytes, nonceBytes, headerBytes); - expect(openpgp.util.uint8ArrayToHex(pt)).to.equal(vec.P.toLowerCase()); + expect(util.uint8ArrayToHex(pt)).to.equal(vec.P.toLowerCase()); // tampering detection test ct = await ocb.encrypt(msgBytes, nonceBytes, headerBytes); @@ -141,12 +143,12 @@ module.exports = () => describe('Symmetric AES-OCB', function() { // testing without additional data ct = await ocb.encrypt(msgBytes, nonceBytes, new Uint8Array()); pt = await ocb.decrypt(ct, nonceBytes, new Uint8Array()); - expect(openpgp.util.uint8ArrayToHex(pt)).to.equal(vec.P.toLowerCase()); + expect(util.uint8ArrayToHex(pt)).to.equal(vec.P.toLowerCase()); // testing with multiple additional data - ct = await ocb.encrypt(msgBytes, nonceBytes, openpgp.util.concatUint8Array([headerBytes, headerBytes, headerBytes])); - pt = await ocb.decrypt(ct, nonceBytes, openpgp.util.concatUint8Array([headerBytes, headerBytes, headerBytes])); - expect(openpgp.util.uint8ArrayToHex(pt)).to.equal(vec.P.toLowerCase()); + ct = await ocb.encrypt(msgBytes, nonceBytes, util.concatUint8Array([headerBytes, headerBytes, headerBytes])); + pt = await ocb.decrypt(ct, nonceBytes, util.concatUint8Array([headerBytes, headerBytes, headerBytes])); + expect(util.uint8ArrayToHex(pt)).to.equal(vec.P.toLowerCase()); })); }); @@ -162,22 +164,22 @@ module.exports = () => describe('Symmetric AES-OCB', function() { const k = new Uint8Array(keylen / 8); k[k.length - 1] = taglen; - const ocb = await openpgp.crypto.ocb('aes' + keylen, k); + const ocb = await OCB('aes' + keylen, k); const c = []; let n; for (let i = 0; i < 128; i++) { const s = new Uint8Array(i); - n = openpgp.util.concatUint8Array([new Uint8Array(8), openpgp.util.writeNumber(3 * i + 1, 4)]); + n = util.concatUint8Array([new Uint8Array(8), util.writeNumber(3 * i + 1, 4)]); c.push(await ocb.encrypt(s, n, s)); - n = openpgp.util.concatUint8Array([new Uint8Array(8), openpgp.util.writeNumber(3 * i + 2, 4)]); + n = util.concatUint8Array([new Uint8Array(8), util.writeNumber(3 * i + 2, 4)]); c.push(await ocb.encrypt(s, n, new Uint8Array())); - n = openpgp.util.concatUint8Array([new Uint8Array(8), openpgp.util.writeNumber(3 * i + 3, 4)]); + n = util.concatUint8Array([new Uint8Array(8), util.writeNumber(3 * i + 3, 4)]); c.push(await ocb.encrypt(new Uint8Array(), n, s)); } - n = openpgp.util.concatUint8Array([new Uint8Array(8), openpgp.util.writeNumber(385, 4)]); - const output = await ocb.encrypt(new Uint8Array(), n, openpgp.util.concatUint8Array(c)); - expect(openpgp.util.uint8ArrayToHex(output)).to.equal(outputs[keylen].toLowerCase()); + n = util.concatUint8Array([new Uint8Array(8), util.writeNumber(385, 4)]); + const output = await ocb.encrypt(new Uint8Array(), n, util.concatUint8Array(c)); + expect(util.uint8ArrayToHex(output)).to.equal(outputs[keylen].toLowerCase()); })); }); }); diff --git a/test/crypto/pkcs5.js b/test/crypto/pkcs5.js index 3d4c68cb..ea649554 100644 --- a/test/crypto/pkcs5.js +++ b/test/crypto/pkcs5.js @@ -1,9 +1,8 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const pkcs5 = require('../../src/crypto/pkcs5'); const expect = require('chai').expect; module.exports = () => describe('PKCS5 padding', function() { - const pkcs5 = openpgp.crypto.pkcs5; it('Add and remove padding', function () { const m = new Uint8Array([0,1,2,3,4,5,6,7,8]); const padded = pkcs5.encode(m); diff --git a/test/crypto/random.js b/test/crypto/random.js index 68184c39..2b76ce45 100644 --- a/test/crypto/random.js +++ b/test/crypto/random.js @@ -1,4 +1,4 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const random = require('../../src/crypto/random'); const chai = require('chai'); @@ -8,7 +8,7 @@ module.exports = () => describe('Random Buffer', function() { let randomBuffer; before(function() { - randomBuffer = new openpgp.crypto.random.randomBuffer.constructor(); + randomBuffer = new random.randomBuffer.constructor(); expect(randomBuffer).to.exist; }); diff --git a/test/crypto/rsa.js b/test/crypto/rsa.js index 67558f2a..893cf3a1 100644 --- a/test/crypto/rsa.js +++ b/test/crypto/rsa.js @@ -1,4 +1,8 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const crypto = require('../../src/crypto'); +const random = require('../../src/crypto/random'); +const util = require('../../src/util'); + const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -7,11 +11,11 @@ const expect = chai.expect; /* eslint-disable no-unused-expressions */ /* eslint-disable no-invalid-this */ -const native = openpgp.util.getWebCrypto() || openpgp.util.getNodeCrypto(); +const native = util.getWebCrypto() || util.getNodeCrypto(); module.exports = () => (!native ? describe.skip : describe)('basic RSA cryptography with native crypto', function () { it('generate rsa key', async function() { - const bits = openpgp.util.getWebCryptoAll() ? 2048 : 1024; - const keyObject = await openpgp.crypto.publicKey.rsa.generate(bits, 65537); + const bits = util.getWebCryptoAll() ? 2048 : 1024; + const keyObject = await crypto.publicKey.rsa.generate(bits, 65537); expect(keyObject.n).to.exist; expect(keyObject.e).to.exist; expect(keyObject.d).to.exist; @@ -21,46 +25,46 @@ module.exports = () => (!native ? describe.skip : describe)('basic RSA cryptogra }); it('sign and verify using generated key params', async function() { - const bits = openpgp.util.getWebCryptoAll() ? 2048 : 1024; - const { publicParams, privateParams } = await openpgp.crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); - const message = await openpgp.crypto.random.getRandomBytes(64); + const bits = util.getWebCryptoAll() ? 2048 : 1024; + const { publicParams, privateParams } = await crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); + const message = await random.getRandomBytes(64); const hash_algo = openpgp.enums.write(openpgp.enums.hash, 'sha256'); - const hashed = await openpgp.crypto.hash.digest(hash_algo, message); + const hashed = await crypto.hash.digest(hash_algo, message); const { n, e, d, p, q, u } = { ...publicParams, ...privateParams }; - const signature = await openpgp.crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); + const signature = await crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); expect(signature).to.exist; - const verify = await openpgp.crypto.publicKey.rsa.verify(hash_algo, message, signature, n, e, hashed); + const verify = await crypto.publicKey.rsa.verify(hash_algo, message, signature, n, e, hashed); expect(verify).to.be.true; }); it('encrypt and decrypt using generated key params', async function() { - const bits = openpgp.util.getWebCryptoAll() ? 2048 : 1024; - const { publicParams, privateParams } = await openpgp.crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); + const bits = util.getWebCryptoAll() ? 2048 : 1024; + const { publicParams, privateParams } = await crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); const { n, e, d, p, q, u } = { ...publicParams, ...privateParams }; - const message = await openpgp.crypto.generateSessionKey('aes256'); - const encrypted = await openpgp.crypto.publicKey.rsa.encrypt(message, n, e); - const decrypted = await openpgp.crypto.publicKey.rsa.decrypt(encrypted, n, e, d, p, q, u); + const message = await crypto.generateSessionKey('aes256'); + const encrypted = await crypto.publicKey.rsa.encrypt(message, n, e); + const decrypted = await crypto.publicKey.rsa.decrypt(encrypted, n, e, d, p, q, u); expect(decrypted).to.deep.equal(message); }); it('decrypt nodeCrypto by bnCrypto and vice versa', async function() { - if (!openpgp.util.getNodeCrypto()) { + if (!util.getNodeCrypto()) { this.skip(); } const bits = 1024; - const { publicParams, privateParams } = await openpgp.crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); + const { publicParams, privateParams } = await crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); const { n, e, d, p, q, u } = { ...publicParams, ...privateParams }; - const message = await openpgp.crypto.generateSessionKey('aes256'); + const message = await crypto.generateSessionKey('aes256'); const useNative = openpgp.config.useNative; try { openpgp.config.useNative = false; - const encryptedBn = await openpgp.crypto.publicKey.rsa.encrypt(message, n, e); + const encryptedBn = await crypto.publicKey.rsa.encrypt(message, n, e); openpgp.config.useNative = true; - const decrypted1 = await openpgp.crypto.publicKey.rsa.decrypt(encryptedBn, n, e, d, p, q, u); + const decrypted1 = await crypto.publicKey.rsa.decrypt(encryptedBn, n, e, d, p, q, u); expect(decrypted1).to.deep.equal(message); - const encryptedNode = await openpgp.crypto.publicKey.rsa.encrypt(message, n, e); + const encryptedNode = await crypto.publicKey.rsa.encrypt(message, n, e); openpgp.config.useNative = false; - const decrypted2 = await openpgp.crypto.publicKey.rsa.decrypt(encryptedNode, n, e, d, p, q, u); + const decrypted2 = await crypto.publicKey.rsa.decrypt(encryptedNode, n, e, d, p, q, u); expect(decrypted2).to.deep.equal(message); } finally { openpgp.config.useNative = useNative; @@ -68,53 +72,53 @@ module.exports = () => (!native ? describe.skip : describe)('basic RSA cryptogra }); it('compare native crypto and bn math sign', async function() { - const bits = openpgp.util.getWebCrypto() ? 2048 : 1024; - const { publicParams, privateParams } = await openpgp.crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); + const bits = util.getWebCrypto() ? 2048 : 1024; + const { publicParams, privateParams } = await crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); const { n, e, d, p, q, u } = { ...publicParams, ...privateParams }; - const message = await openpgp.crypto.random.getRandomBytes(64); + const message = await random.getRandomBytes(64); const hashName = 'sha256'; const hash_algo = openpgp.enums.write(openpgp.enums.hash, hashName); - const hashed = await openpgp.crypto.hash.digest(hash_algo, message); + const hashed = await crypto.hash.digest(hash_algo, message); const useNative = openpgp.config.useNative; try { openpgp.config.useNative = true; let signatureWeb; try { - signatureWeb = await openpgp.crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); + signatureWeb = await crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); } catch (error) { - openpgp.util.printDebugError('web crypto error'); + util.printDebugError('web crypto error'); this.skip(); } openpgp.config.useNative = false; - const signatureBN = await openpgp.crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); - expect(openpgp.util.uint8ArrayToHex(signatureWeb)).to.be.equal(openpgp.util.uint8ArrayToHex(signatureBN)); + const signatureBN = await crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); + expect(util.uint8ArrayToHex(signatureWeb)).to.be.equal(util.uint8ArrayToHex(signatureBN)); } finally { openpgp.config.useNative = useNative; } }); it('compare native crypto and bn math verify', async function() { - const bits = openpgp.util.getWebCrypto() ? 2048 : 1024; - const { publicParams, privateParams } = await openpgp.crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); + const bits = util.getWebCrypto() ? 2048 : 1024; + const { publicParams, privateParams } = await crypto.generateParams(openpgp.enums.publicKey.rsaSign, bits); const { n, e, d, p, q, u } = { ...publicParams, ...privateParams }; - const message = await openpgp.crypto.random.getRandomBytes(64); + const message = await random.getRandomBytes(64); const hashName = 'sha256'; const hash_algo = openpgp.enums.write(openpgp.enums.hash, hashName); - const hashed = await openpgp.crypto.hash.digest(hash_algo, message); + const hashed = await crypto.hash.digest(hash_algo, message); let verifyWeb; let signature; const useNative = openpgp.config.useNative; try { openpgp.config.useNative = true; try { - signature = await openpgp.crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); - verifyWeb = await openpgp.crypto.publicKey.rsa.verify(hash_algo, message, signature, n, e); + signature = await crypto.publicKey.rsa.sign(hash_algo, message, n, e, d, p, q, u, hashed); + verifyWeb = await crypto.publicKey.rsa.verify(hash_algo, message, signature, n, e); } catch (error) { - openpgp.util.printDebugError('web crypto error'); + util.printDebugError('web crypto error'); this.skip(); } openpgp.config.useNative = false; - const verifyBN = await openpgp.crypto.publicKey.rsa.verify(hash_algo, message, signature, n, e, hashed); + const verifyBN = await crypto.publicKey.rsa.verify(hash_algo, message, signature, n, e, hashed); expect(verifyWeb).to.be.true; expect(verifyBN).to.be.true; } finally { diff --git a/test/general/biginteger.js b/test/general/biginteger.js index befa6347..b317c27d 100644 --- a/test/general/biginteger.js +++ b/test/general/biginteger.js @@ -1,4 +1,7 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const random = require('../../src/crypto/random'); +const util = require('../../src/util'); + const BN = require('bn.js'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -13,13 +16,13 @@ async function getRandomBN(min, max) { const modulus = max.sub(min); const bytes = modulus.byteLength(); - const r = new BN(await openpgp.crypto.random.getRandomBytes(bytes + 8)); + const r = new BN(await random.getRandomBytes(bytes + 8)); return r.mod(modulus).add(min); } module.exports = () => describe('BigInteger interface', function() { before(async () => { - BigInteger = await openpgp.util.getBigInteger(); + BigInteger = await util.getBigInteger(); }); it('constructor throws on undefined input', function() { diff --git a/test/general/brainpool.js b/test/general/brainpool.js index fd555fea..5f7e0856 100644 --- a/test/general/brainpool.js +++ b/test/general/brainpool.js @@ -1,6 +1,7 @@ /* globals tryTests: true */ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const util = require('../../src/util'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -10,7 +11,7 @@ const expect = chai.expect; module.exports = () => (openpgp.config.ci ? describe.skip : describe)('Brainpool Cryptography @lightweight', function () { //only x25519 crypto is fully functional in lightbuild - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!openpgp.config.useIndutnyElliptic && !util.getNodeCrypto()) { before(function() { this.skip(); }); @@ -273,7 +274,7 @@ EJ4QcD/oQ6x1M/8X/iKQCtxZP8RnlrbH7ExkNON5s5g= }); tryTests('Brainpool Omnibus Tests @lightweight', omnibus, { - if: openpgp.config.useIndutnyElliptic || openpgp.util.getNodeCrypto() + if: openpgp.config.useIndutnyElliptic || util.getNodeCrypto() }); }); diff --git a/test/general/ecc_secp256k1.js b/test/general/ecc_secp256k1.js index caff2710..a314fa86 100644 --- a/test/general/ecc_secp256k1.js +++ b/test/general/ecc_secp256k1.js @@ -1,6 +1,7 @@ /* globals tryTests: true */ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const util = require('../../src/util'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -8,7 +9,7 @@ chai.use(require('chai-as-promised')); const expect = chai.expect; module.exports = () => describe('Elliptic Curve Cryptography for secp256k1 curve @lightweight', function () { - if (!openpgp.config.useIndutnyElliptic && !openpgp.util.getNodeCrypto()) { + if (!openpgp.config.useIndutnyElliptic && !util.getNodeCrypto()) { before(function() { this.skip(); }); diff --git a/test/general/key.js b/test/general/key.js index 03fb4593..244c138a 100644 --- a/test/general/key.js +++ b/test/general/key.js @@ -1,8 +1,8 @@ /* globals tryTests: true */ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const util = require('../../src/util'); -const stub = require('sinon/lib/sinon/stub'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -2235,7 +2235,7 @@ function versionSpecificTests() { it('Generate RSA key - two subkeys with default values', function() { const userId = 'test '; const opt = { rsaBits: 512, userIds: [userId], passphrase: '123', subkeys:[{},{}] }; - if (openpgp.util.getWebCryptoAll()) { opt.rsaBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys + if (util.getWebCryptoAll()) { opt.rsaBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { key = key.key; @@ -2286,7 +2286,7 @@ function versionSpecificTests() { it('Generate key - override main RSA key options for subkey', function() { const userId = 'test '; const opt = { rsaBits: 512, userIds: [userId], passphrase: '123', subkeys:[{ curve: 'curve25519' }] }; - if (openpgp.util.getWebCryptoAll()) { opt.rsaBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys + if (util.getWebCryptoAll()) { opt.rsaBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys return openpgp.generateKey(opt).then(function(key) { key = key.key; expect(key.users.length).to.equal(1); @@ -2452,8 +2452,8 @@ function versionSpecificTests() { it('Reformat key with two subkeys with passphrase', function() { const userId1 = 'test '; const userId2 = 'test '; - const now = openpgp.util.normalizeDate(new Date()); - const before = openpgp.util.normalizeDate(new Date(0)); + const now = util.normalizeDate(new Date()); + const before = util.normalizeDate(new Date(0)); const opt1 = { userIds: [userId1], date: now }; return openpgp.generateKey(opt1).then(function(newKey) { newKey = newKey.key; @@ -2640,7 +2640,7 @@ module.exports = () => describe('Key', function() { it('Parsing V5 public key packet', async function() { // Manually modified from https://gitlab.com/openpgp-wg/rfc4880bis/blob/00b2092/back.mkd#sample-eddsa-key - const packetBytes = openpgp.util.hexToUint8Array(` + const packetBytes = util.hexToUint8Array(` 98 37 05 53 f3 5f 0b 16 00 00 00 2d 09 2b 06 01 04 01 da 47 0f 01 01 07 40 3f 09 89 94 bd d9 16 ed 40 53 19 79 34 e4 a8 7c 80 73 3a 12 80 d6 2f 80 10 99 2e @@ -3371,7 +3371,7 @@ VYGdb3eNlV8CfoEC describe('addSubkey functionality testing', function() { let rsaBits; let rsaOpt = {}; - if (openpgp.util.getWebCryptoAll()) { + if (util.getWebCryptoAll()) { rsaBits = 2048; rsaOpt = { rsaBits: rsaBits }; } diff --git a/test/general/oid.js b/test/general/oid.js index 89c98325..22c812d2 100644 --- a/test/general/oid.js +++ b/test/general/oid.js @@ -1,10 +1,9 @@ -const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const OID = require('../../src/type/oid'); +const util = require('../../src/util'); const expect = require('chai').expect; module.exports = () => describe('Oid tests', function() { - const OID = openpgp.OID; - const util = openpgp.util; 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]); @@ -21,7 +20,7 @@ module.exports = () => describe('Oid tests', function() { it('Reading and writing', function() { const oids = [p256_oid, p384_oid, p521_oid]; oids.forEach(function (data) { - data = openpgp.util.concatUint8Array([new Uint8Array([data.length]), data]); + data = util.concatUint8Array([new Uint8Array([data.length]), data]); const oid = new OID(); expect(oid.read(data)).to.equal(data.length); expect(oid.oid).to.exist; diff --git a/test/general/openpgp.js b/test/general/openpgp.js index 24dc3a0f..23c6d81c 100644 --- a/test/general/openpgp.js +++ b/test/general/openpgp.js @@ -1,9 +1,11 @@ /* globals tryTests: true */ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const crypto = require('../../src/crypto'); +const random = require('../../src/crypto/random'); +const util = require('../../src/util'); const spy = require('sinon/lib/sinon/spy'); -const stub = require('sinon/lib/sinon/stub'); const input = require('./testInputs.js'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -636,7 +638,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { describe('generateKey - unit tests', function() { it('should have default params set', function() { - const now = openpgp.util.normalizeDate(new Date()); + const now = util.normalizeDate(new Date()); const opt = { userIds: { name: 'Test User', email: 'text@example.com' }, passphrase: 'secret', @@ -1150,7 +1152,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should encrypt using custom session key and decrypt using session key', async function () { const sessionKey = { - data: await openpgp.crypto.generateSessionKey('aes256'), + data: await crypto.generateSessionKey('aes256'), algorithm: 'aes256' }; const encOpt = { @@ -1173,7 +1175,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should encrypt using custom session key and decrypt using private key', async function () { const sessionKey = { - data: await openpgp.crypto.generateSessionKey('aes128'), + data: await crypto.generateSessionKey('aes128'), algorithm: 'aes128' }; const encOpt = { @@ -1590,7 +1592,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { expect(e.message).to.match(/Ascii armor integrity check on message failed/); expect(stepReached).to.equal( j === 0 ? 0 : - (openpgp.config.aeadChunkSizeByte === 0 && (j === 2 || openpgp.util.detectNode() || openpgp.util.getHardwareConcurrency() < 8)) || (!openpgp.config.aeadProtect && openpgp.config.allowUnauthenticatedStream) ? 2 : + (openpgp.config.aeadChunkSizeByte === 0 && (j === 2 || util.detectNode() || util.getHardwareConcurrency() < 8)) || (!openpgp.config.aeadProtect && openpgp.config.allowUnauthenticatedStream) ? 2 : 1 ); return; @@ -1604,7 +1606,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { it('should fail to decrypt unarmored message with garbage data appended', async function() { const { key } = await openpgp.generateKey({ userIds: {} }); const message = await openpgp.encrypt({ message: openpgp.Message.fromText('test'), publicKeys: key, privateKeys: key, armor: false }); - const encrypted = openpgp.util.concat([message, new Uint8Array([11])]); + const encrypted = util.concat([message, new Uint8Array([11])]); await expect( openpgp.decrypt({ message: await openpgp.readMessage(encrypted), privateKeys: key, publicKeys: key }) ).to.be.rejectedWith('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); @@ -1805,7 +1807,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { const data = new ReadableStream({ async pull(controller) { if (i++ < 4) { - let randomBytes = await openpgp.crypto.random.getRandomBytes(10); + let randomBytes = await random.getRandomBytes(10); controller.enqueue(randomBytes); plaintext.push(randomBytes.slice()); } else { @@ -1817,7 +1819,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { message: openpgp.Message.fromBinary(data), passwords: ['test'] })); - expect(openpgp.util.isStream(encrypted)).to.equal(useNativeStream ? 'web' : 'ponyfill'); + expect(openpgp.stream.isStream(encrypted)).to.equal(useNativeStream ? 'web' : 'ponyfill'); const message = await openpgp.readArmoredMessage(encrypted); const decrypted = await openpgp.decrypt({ @@ -1825,8 +1827,8 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { message, format: 'binary' }); - expect(openpgp.util.isStream(decrypted.data)).to.equal(useNativeStream ? 'web' : 'ponyfill'); - expect(await openpgp.stream.readToEnd(decrypted.data)).to.deep.equal(openpgp.util.concatUint8Array(plaintext)); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(useNativeStream ? 'web' : 'ponyfill'); + expect(await openpgp.stream.readToEnd(decrypted.data)).to.deep.equal(util.concatUint8Array(plaintext)); }); }); }); @@ -1997,7 +1999,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }); it('should sign and verify data and not armor with detached signatures', function () { - const start = openpgp.util.normalizeDate(); + const start = util.normalizeDate(); const message = openpgp.Message.fromText(plaintext); const signOpt = { message, @@ -2014,7 +2016,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { return openpgp.verify(verifyOpt); }).then(async function (verified) { expect(verified.data).to.equal(plaintext); - expect(+verified.signatures[0].signature.packets[0].created).to.be.lte(+openpgp.util.normalizeDate()); + expect(+verified.signatures[0].signature.packets[0].created).to.be.lte(+util.normalizeDate()); expect(+verified.signatures[0].signature.packets[0].created).to.be.gte(+start); expect(verified.signatures[0].valid).to.be.true; const signingKey = await privateKey.getSigningKey(); @@ -2133,7 +2135,7 @@ module.exports = () => describe('OpenPGP.js public api tests', function() { }; const useNativeStream = (() => { try { new global.ReadableStream(); return true; } catch (e) { return false; } })(); return openpgp.sign(signOpt).then(async function (signed) { - expect(openpgp.util.isStream(signed)).to.equal(useNativeStream ? 'web' : 'ponyfill'); + expect(openpgp.stream.isStream(signed)).to.equal(useNativeStream ? 'web' : 'ponyfill'); const message = await openpgp.readMessage(signed); message.packets.concat(await openpgp.stream.readToEnd(message.packets.stream, _ => _)); const packets = new openpgp.PacketList(); @@ -2403,7 +2405,7 @@ J9I8AcH94nE77JUtCm7s1kOlo0EIshZsAqJwGveDGdAuabfViVwVxG4I24M6 }); it('should decrypt with three passwords', async function() { - const messageBinary = openpgp.util.b64ToUint8Array('wy4ECQMIElIx/jiwJV9gp/MZ/ElZwUfHrzOBfOtM8VmgDy76F7eSGWH26tAlx3WI0kMBZv6Tlc1Y6baaZ6MEcOLTG/C7uzHH7KMfuQFd3fcMaVcDawk9EEy/CybiGBE+acT6id2pemHQy6Nk76d9UUTFubcB'); + const messageBinary = util.hexToUint8Array('c32e04090308125231fe38b0255f60a7f319fc4959c147c7af33817ceb4cf159a00f2efa17b7921961f6ead025c77588d2430166fe9395cd58e9b69a67a30470e2d31bf0bbbb31c7eca31fb9015dddf70c6957036b093d104cbf0b26e218113e69c4fa89dda97a61d0cba364efa77d5144c5b9b701'); const message = await openpgp.readMessage(messageBinary); const passwords = ['Test', 'Pinata', 'a']; const decrypted = await openpgp.decrypt({ message, passwords }); @@ -2426,33 +2428,7 @@ J9I8AcH94nE77JUtCm7s1kOlo0EIshZsAqJwGveDGdAuabfViVwVxG4I24M6 expect(decrypted.data).to.equal('Tesssst


Sent from ProtonMail mobile


'); }); - it('should decrypt broken Blowfish message from old OpenPGP.js', async function() { - openpgp.crypto.cipher.blowfish.blockSize = 16; - openpgp.crypto.cipher.blowfish.prototype.blockSize = 16; - const useNativeVal = openpgp.config.useNative; - openpgp.config.useNative = false; - try { - const { data } = await openpgp.decrypt({ - passwords: 'test', - message: await openpgp.readArmoredMessage(`-----BEGIN PGP MESSAGE----- -Version: OpenPGP.js v4.8.1 -Comment: https://openpgpjs.org - -wx4EBAMI0eHVbTnl2iLg6pIJ4sWw2K7OwfxFP8bmaUvSRAGiSDGJSFNUuB4v -SU69Z1XyXiuTpD3780FnLnR4dF41nhbrTXaDG+X1b3JsZCHTFMGF7Eb+YVhh -YCXOZwd3z5lxcj/M -=oXcN ------END PGP MESSAGE-----`) - }); - expect(data).to.equal('Hello World!'); - } finally { - openpgp.crypto.cipher.blowfish.blockSize = 8; - openpgp.crypto.cipher.blowfish.prototype.blockSize = 8; - openpgp.config.useNative = useNativeVal; - } - }); - - it('should decrypt correct Blowfish message from new OpenPGP.js', async function() { + it('should decrypt Blowfish message', async function() { const { data } = await openpgp.decrypt({ passwords: 'test', message: await openpgp.readArmoredMessage(`-----BEGIN PGP MESSAGE----- @@ -2479,7 +2455,7 @@ amnR6g== message: await openpgp.readArmoredMessage(encrypted), format: 'binary' }); - expect(openpgp.util.decodeUtf8(decrypted.data)).to.equal('"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:123\r\nDTSTART:20191211T121212Z\r\nDTEND:20191212T121212Z\r\nEND:VEVENT\r\nEND:VCALENDAR"'); + expect(util.decodeUtf8(decrypted.data)).to.equal('"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:123\r\nDTSTART:20191211T121212Z\r\nDTEND:20191212T121212Z\r\nEND:VEVENT\r\nEND:VCALENDAR"'); }); }); diff --git a/test/general/packet.js b/test/general/packet.js index 0547a14b..e63aea02 100644 --- a/test/general/packet.js +++ b/test/general/packet.js @@ -1,4 +1,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const crypto = require('../../src/crypto'); +const util = require('../../src/util'); const stub = require('sinon/lib/sinon/stub'); const chai = require('chai'); @@ -9,11 +11,11 @@ const input = require('./testInputs.js'); const { PacketList } = require('../../dist/node/openpgp.min'); function stringify(array) { - if (openpgp.util.isStream(array)) { + if (openpgp.stream.isStream(array)) { return openpgp.stream.readToEnd(array).then(stringify); } - if (!openpgp.util.isUint8Array(array)) { + if (!util.isUint8Array(array)) { throw new Error('Data must be in the form of a Uint8Array'); } @@ -200,7 +202,7 @@ module.exports = () => describe("Packet", function() { } it('Sym. encrypted AEAD protected packet is encrypted in parallel (AEAD, GCM)', async function() { - const webCrypto = openpgp.util.getWebCrypto(); + const webCrypto = util.getWebCrypto(); if (!webCrypto) return; const encryptStub = cryptStub(webCrypto, 'encrypt'); const decryptStub = cryptStub(webCrypto, 'decrypt'); @@ -243,10 +245,10 @@ module.exports = () => describe("Packet", function() { it('Sym. encrypted AEAD protected packet test vector (AEAD)', async function() { // From https://gitlab.com/openpgp-wg/rfc4880bis/commit/00b20923e6233fb6ff1666ecd5acfefceb32907d - const nodeCrypto = openpgp.util.getNodeCrypto(); + const nodeCrypto = util.getNodeCrypto(); if (!nodeCrypto) return; - let packetBytes = openpgp.util.hexToUint8Array(` + let packetBytes = util.hexToUint8Array(` d4 4a 01 07 01 0e b7 32 37 9f 73 c4 92 8d e2 5f ac fe 65 17 ec 10 5d c1 1a 81 dc 0c b8 a2 f6 f3 d9 00 16 38 4a 56 fc 82 1a e1 1a e8 db cb 49 86 @@ -259,8 +261,8 @@ module.exports = () => describe("Packet", function() { openpgp.config.aeadProtect = true; openpgp.config.aeadChunkSizeByte = 14; - const iv = openpgp.util.hexToUint8Array('b7 32 37 9f 73 c4 92 8d e2 5f ac fe 65 17 ec 10'.replace(/\s+/g, '')); - const key = openpgp.util.hexToUint8Array('86 f1 ef b8 69 52 32 9f 24 ac d3 bf d0 e5 34 6d'.replace(/\s+/g, '')); + const iv = util.hexToUint8Array('b7 32 37 9f 73 c4 92 8d e2 5f ac fe 65 17 ec 10'.replace(/\s+/g, '')); + const key = util.hexToUint8Array('86 f1 ef b8 69 52 32 9f 24 ac d3 bf d0 e5 34 6d'.replace(/\s+/g, '')); const algo = 'aes128'; const literal = new openpgp.LiteralDataPacket(0); @@ -268,7 +270,7 @@ module.exports = () => describe("Packet", function() { const msg = new openpgp.PacketList(); msg.push(enc); - literal.setBytes(openpgp.util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); + literal.setBytes(util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); literal.filename = ''; enc.packets.push(literal); @@ -320,9 +322,9 @@ module.exports = () => describe("Packet", function() { it('Public key encrypted symmetric key packet', function() { const rsa = openpgp.enums.publicKey.rsaEncryptSign; - const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys + const keySize = util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys - return openpgp.crypto.generateParams(rsa, keySize, 65537).then(function({ publicParams, privateParams }) { + return crypto.generateParams(rsa, keySize, 65537).then(function({ publicParams, privateParams }) { const enc = new openpgp.PublicKeyEncryptedSessionKeyPacket(); const msg = new openpgp.PacketList(); const msg2 = new openpgp.PacketList(); @@ -524,7 +526,7 @@ module.exports = () => describe("Packet", function() { it('Sym. encrypted session key reading/writing test vector (EAX, AEAD)', async function() { // From https://gitlab.com/openpgp-wg/rfc4880bis/blob/00b20923/back.mkd#sample-aead-eax-encryption-and-decryption - const nodeCrypto = openpgp.util.getNodeCrypto(); + const nodeCrypto = util.getNodeCrypto(); if (!nodeCrypto) return; let aeadProtectVal = openpgp.config.aeadProtect; @@ -534,10 +536,10 @@ module.exports = () => describe("Packet", function() { openpgp.config.aeadChunkSizeByte = 14; openpgp.config.s2kIterationCountByte = 0x90; - let salt = openpgp.util.hexToUint8Array(`cd5a9f70fbe0bc65`); - let sessionKey = openpgp.util.hexToUint8Array(`86 f1 ef b8 69 52 32 9f 24 ac d3 bf d0 e5 34 6d`.replace(/\s+/g, '')); - let sessionIV = openpgp.util.hexToUint8Array(`bc 66 9e 34 e5 00 dc ae dc 5b 32 aa 2d ab 02 35`.replace(/\s+/g, '')); - let dataIV = openpgp.util.hexToUint8Array(`b7 32 37 9f 73 c4 92 8d e2 5f ac fe 65 17 ec 10`.replace(/\s+/g, '')); + let salt = util.hexToUint8Array(`cd5a9f70fbe0bc65`); + let sessionKey = util.hexToUint8Array(`86 f1 ef b8 69 52 32 9f 24 ac d3 bf d0 e5 34 6d`.replace(/\s+/g, '')); + let sessionIV = util.hexToUint8Array(`bc 66 9e 34 e5 00 dc ae dc 5b 32 aa 2d ab 02 35`.replace(/\s+/g, '')); + let dataIV = util.hexToUint8Array(`b7 32 37 9f 73 c4 92 8d e2 5f ac fe 65 17 ec 10`.replace(/\s+/g, '')); let randomBytesStub = stub(nodeCrypto, 'randomBytes'); randomBytesStub.onCall(0).returns(salt); @@ -545,7 +547,7 @@ module.exports = () => describe("Packet", function() { randomBytesStub.onCall(2).returns(sessionIV); randomBytesStub.onCall(3).returns(dataIV); - let packetBytes = openpgp.util.hexToUint8Array(` + let packetBytes = util.hexToUint8Array(` c3 3e 05 07 01 03 08 cd 5a 9f 70 fb e0 bc 65 90 bc 66 9e 34 e5 00 dc ae dc 5b 32 aa 2d ab 02 35 9d ee 19 d0 7c 34 46 c4 31 2a 34 ae 19 67 a2 fb @@ -575,7 +577,7 @@ module.exports = () => describe("Packet", function() { const key = key_enc.sessionKey; - literal.setBytes(openpgp.util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); + literal.setBytes(util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); literal.filename = ''; enc.packets.push(literal); await enc.encrypt(algo, key); @@ -602,7 +604,7 @@ module.exports = () => describe("Packet", function() { it('Sym. encrypted session key reading/writing test vector (AEAD, OCB)', async function() { // From https://gitlab.com/openpgp-wg/rfc4880bis/blob/00b20923/back.mkd#sample-aead-ocb-encryption-and-decryption - const nodeCrypto = openpgp.util.getNodeCrypto(); + const nodeCrypto = util.getNodeCrypto(); if (!nodeCrypto) return; let aeadProtectVal = openpgp.config.aeadProtect; @@ -612,10 +614,10 @@ module.exports = () => describe("Packet", function() { openpgp.config.aeadChunkSizeByte = 14; openpgp.config.s2kIterationCountByte = 0x90; - let salt = openpgp.util.hexToUint8Array(`9f0b7da3e5ea6477`); - let sessionKey = openpgp.util.hexToUint8Array(`d1 f0 1b a3 0e 13 0a a7 d2 58 2c 16 e0 50 ae 44`.replace(/\s+/g, '')); - let sessionIV = openpgp.util.hexToUint8Array(`99 e3 26 e5 40 0a 90 93 6c ef b4 e8 eb a0 8c`.replace(/\s+/g, '')); - let dataIV = openpgp.util.hexToUint8Array(`5e d2 bc 1e 47 0a be 8f 1d 64 4c 7a 6c 8a 56`.replace(/\s+/g, '')); + let salt = util.hexToUint8Array(`9f0b7da3e5ea6477`); + let sessionKey = util.hexToUint8Array(`d1 f0 1b a3 0e 13 0a a7 d2 58 2c 16 e0 50 ae 44`.replace(/\s+/g, '')); + let sessionIV = util.hexToUint8Array(`99 e3 26 e5 40 0a 90 93 6c ef b4 e8 eb a0 8c`.replace(/\s+/g, '')); + let dataIV = util.hexToUint8Array(`5e d2 bc 1e 47 0a be 8f 1d 64 4c 7a 6c 8a 56`.replace(/\s+/g, '')); let randomBytesStub = stub(nodeCrypto, 'randomBytes'); randomBytesStub.onCall(0).returns(salt); @@ -623,7 +625,7 @@ module.exports = () => describe("Packet", function() { randomBytesStub.onCall(2).returns(sessionIV); randomBytesStub.onCall(3).returns(dataIV); - let packetBytes = openpgp.util.hexToUint8Array(` + let packetBytes = util.hexToUint8Array(` c3 3d 05 07 02 03 08 9f 0b 7d a3 e5 ea 64 77 90 99 e3 26 e5 40 0a 90 93 6c ef b4 e8 eb a0 8c 67 73 71 6d 1f 27 14 54 0a 38 fc ac 52 99 49 da c5 @@ -654,7 +656,7 @@ module.exports = () => describe("Packet", function() { const key = key_enc.sessionKey; - literal.setBytes(openpgp.util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); + literal.setBytes(util.strToUint8Array('Hello, world!\n'), openpgp.enums.literal.binary); literal.filename = ''; enc.packets.push(literal); await enc.encrypt(algo, key); @@ -845,8 +847,8 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ it('Writing and encryption of a secret key packet (AEAD)', async function() { const rsa = openpgp.enums.publicKey.rsaEncryptSign; - const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys - const { privateParams, publicParams } = await openpgp.crypto.generateParams(rsa, keySize, 65537); + const keySize = util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys + const { privateParams, publicParams } = await crypto.generateParams(rsa, keySize, 65537); const secretKeyPacket = new openpgp.SecretKeyPacket(); secretKeyPacket.privateParams = privateParams; @@ -871,10 +873,10 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ openpgp.config.aeadProtect = false; const rsa = openpgp.enums.publicKey.rsaEncryptSign; - const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys + const keySize = util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys try { - const { privateParams, publicParams } = await openpgp.crypto.generateParams(rsa, keySize, 65537); + const { privateParams, publicParams } = await crypto.generateParams(rsa, keySize, 65537); const secretKeyPacket = new openpgp.SecretKeyPacket(); secretKeyPacket.privateParams = privateParams; secretKeyPacket.publicParams = publicParams; @@ -897,9 +899,9 @@ V+HOQJQxXJkVRYa3QrFUehiMzTeqqMdgC6ZqJy7+ const key = new openpgp.SecretKeyPacket(); const rsa = openpgp.enums.publicKey.rsaEncryptSign; - const keySize = openpgp.util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys + const keySize = util.getWebCryptoAll() ? 2048 : 512; // webkit webcrypto accepts minimum 2048 bit keys - return openpgp.crypto.generateParams(rsa, keySize, 65537).then(function({ privateParams, publicParams }) { + return crypto.generateParams(rsa, keySize, 65537).then(function({ privateParams, publicParams }) { const testText = input.createSomeMessage(); key.publicParams = publicParams; diff --git a/test/general/signature.js b/test/general/signature.js index 010ad1a2..7edf0ad3 100644 --- a/test/general/signature.js +++ b/test/general/signature.js @@ -1,4 +1,5 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const util = require('../../src/util'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -1118,7 +1119,7 @@ bwM= }); it('Verify latin-1 signed message', async function() { - const latin1Binary = openpgp.util.hexToUint8Array('48e46c6cf62057e86c74'); + const latin1Binary = util.hexToUint8Array('48e46c6cf62057e86c74'); const message = openpgp.Message.fromBinary(latin1Binary); message.appendSignature(`-----BEGIN PGP SIGNATURE----- @@ -1404,7 +1405,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA }); it('Sign text with openpgp.sign and verify with openpgp.verify leads to same bytes cleartext and valid signatures - armored', async function() { - const plaintext = openpgp.util.strToUint8Array('short message\nnext line \n한국어/조선말'); + const plaintext = util.strToUint8Array('short message\nnext line \n한국어/조선말'); const pubKey = await openpgp.readArmoredKey(pub_key_arm2); const privKey = await openpgp.readArmoredKey(priv_key_arm2); await privKey.decrypt('hello world'); @@ -1424,7 +1425,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA }); it('Sign text with openpgp.sign and verify with openpgp.verify leads to same bytes cleartext and valid signatures - not armored', async function() { - const plaintext = openpgp.util.strToUint8Array('short message\nnext line \n한국어/조선말'); + const plaintext = util.strToUint8Array('short message\nnext line \n한국어/조선말'); const pubKey = await openpgp.readArmoredKey(pub_key_arm2); const privKey = await openpgp.readArmoredKey(priv_key_arm2); await privKey.decrypt('hello world'); @@ -1450,7 +1451,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA await privKey.decrypt('hello world'); return openpgp.sign({ privateKeys:[privKey], message: openpgp.Message.fromText(plaintext), detached: true}).then(async function(signed) { const signature = await openpgp.readArmoredSignature(signed); - return openpgp.verify({ publicKeys:[pubKey], message: openpgp.Message.fromBinary(openpgp.util.encodeUtf8(plaintext)), signature: signature }); + return openpgp.verify({ publicKeys:[pubKey], message: openpgp.Message.fromBinary(util.encodeUtf8(plaintext)), signature: signature }); }).then(function(cleartextSig) { expect(cleartextSig).to.exist; expect(cleartextSig.signatures).to.have.length(1); @@ -1461,7 +1462,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA it('Should verify cleartext message correctly when using a detached binary signature and text literal data', async function () { const plaintext = 'short message\nnext line \n한국어/조선말'; - const plaintextArray = openpgp.util.encodeUtf8(plaintext); + const plaintextArray = util.encodeUtf8(plaintext); const pubKey = await openpgp.readArmoredKey(pub_key_arm2); const privKey = await openpgp.readArmoredKey(priv_key_arm2); await privKey.decrypt('hello world'); @@ -1483,7 +1484,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA await Promise.all([privKey.primaryKey.decrypt('hello world'), privKey.subKeys[0].keyPacket.decrypt('hello world')]); return openpgp.sign({ privateKeys:[privKey], message: openpgp.Message.fromText(plaintext), detached: true}).then(async function(signed) { const signature = await openpgp.readArmoredSignature(signed); - return openpgp.encrypt({ message: openpgp.Message.fromBinary(openpgp.util.encodeUtf8(plaintext)), publicKeys: [pubKey], signature }) + return openpgp.encrypt({ message: openpgp.Message.fromBinary(util.encodeUtf8(plaintext)), publicKeys: [pubKey], signature }) }).then(async data => { const csMsg = await openpgp.readArmoredMessage(data); return openpgp.decrypt({ message: csMsg, privateKeys: [ privKey ], publicKeys: [ pubKey ] }); @@ -1610,7 +1611,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA await privKey2.decrypt('hello world'); const opt = { rsaBits: 512, userIds: { name:'test', email:'a@b.com' }, passphrase: null }; - if (openpgp.util.getWebCryptoAll()) { opt.rsaBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys + if (util.getWebCryptoAll()) { opt.rsaBits = 2048; } // webkit webcrypto accepts minimum 2048 bit keys const { key: generatedKey } = await openpgp.generateKey(opt); const detachedSig = await msg.signDetached([generatedKey, privKey2]); const result = await msg.verifyDetached(detachedSig, [generatedKey.toPublic(), pubKey2]); diff --git a/test/general/streaming.js b/test/general/streaming.js index 4814d2fe..a2002f79 100644 --- a/test/general/streaming.js +++ b/test/general/streaming.js @@ -1,4 +1,6 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const random = require('../../src/crypto/random'); +const util = require('../../src/util'); const stub = require('sinon/lib/sinon/stub'); const chai = require('chai'); @@ -7,7 +9,7 @@ const input = require('./testInputs.js'); const { expect } = chai; -const { stream, util } = openpgp; +const { stream } = openpgp; const useNativeStream = (() => { try { new global.ReadableStream(); return true; } catch (e) { return false; } })(); const ReadableStream = useNativeStream ? global.ReadableStream : openpgp.stream.ReadableStream; @@ -241,7 +243,7 @@ function tests() { passwords: ['test'], armor: false }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readMessage(encrypted); setTimeout(dataArrived, 3000); // Do not wait until data arrived, but wait a bit to check that it doesn't arrive early. @@ -250,7 +252,7 @@ function tests() { message, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.peekBytes(1024)).to.deep.equal(plaintext[0]); if (i <= 10) throw new Error('Data arrived early.'); @@ -269,7 +271,7 @@ function tests() { passwords: ['test'], armor: false }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readMessage(encrypted); const decrypted = await openpgp.decrypt({ @@ -277,8 +279,8 @@ function tests() { message, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); - expect(util.isStream(decrypted.signatures)).to.be.false; + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.signatures)).to.be.false; const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.peekBytes(1024)).to.deep.equal(plaintext[0]); dataArrived(); @@ -300,7 +302,7 @@ function tests() { privateKeys: privKey, armor: false }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readMessage(encrypted); const decrypted = await openpgp.decrypt({ @@ -309,7 +311,7 @@ function tests() { message, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.peekBytes(1024)).to.deep.equal(plaintext[0]); dataArrived(); @@ -332,7 +334,7 @@ function tests() { privateKeys: priv, armor: false }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readMessage(encrypted); const decrypted = await openpgp.decrypt({ @@ -341,7 +343,7 @@ function tests() { message, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.peekBytes(1024)).to.deep.equal(plaintext[0]); dataArrived(); @@ -364,7 +366,7 @@ function tests() { privateKeys: priv, armor: false }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readMessage(encrypted); const decrypted = await openpgp.decrypt({ @@ -373,7 +375,7 @@ function tests() { message, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.peekBytes(1024)).to.deep.equal(plaintext[0]); dataArrived(); @@ -393,7 +395,7 @@ function tests() { message: openpgp.Message.fromBinary(data), passwords: ['test'] }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readArmoredMessage(openpgp.stream.transform(encrypted, value => { value += ''; @@ -408,7 +410,7 @@ function tests() { streaming: expectedType, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.peekBytes(1024)).not.to.deep.equal(plaintext[0]); dataArrived(); @@ -429,7 +431,7 @@ function tests() { publicKeys: pubKey, privateKeys: privKey }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readArmoredMessage(openpgp.stream.transform(encrypted, value => { value += ''; @@ -444,7 +446,7 @@ function tests() { streaming: expectedType, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.peekBytes(1024)).not.to.deep.equal(plaintext[0]); dataArrived(); @@ -464,7 +466,7 @@ function tests() { publicKeys: pubKey, privateKeys: privKey }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readArmoredMessage(openpgp.stream.transform(encrypted, value => { value += ''; @@ -478,7 +480,7 @@ function tests() { streaming: expectedType, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.peekBytes(1024)).not.to.deep.equal(plaintext[0]); dataArrived(); @@ -495,7 +497,7 @@ function tests() { message: openpgp.Message.fromBinary(data), privateKeys: privKey }); - expect(util.isStream(signed)).to.equal(expectedType); + expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const message = await openpgp.readArmoredMessage(openpgp.stream.transform(signed, value => { value += ''; @@ -509,7 +511,7 @@ function tests() { streaming: expectedType, format: 'binary' }); - expect(util.isStream(verified.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(verified.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(verified.data); expect(await reader.peekBytes(1024)).not.to.deep.equal(plaintext[0]); dataArrived(); @@ -523,7 +525,7 @@ function tests() { passwords: ['test'], armor: false }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readMessage(encrypted); const decrypted = await openpgp.decrypt({ @@ -531,7 +533,7 @@ function tests() { message, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.peekBytes(1024)).to.deep.equal(plaintext[0]); dataArrived(); @@ -561,14 +563,14 @@ function tests() { streaming: expectedType, passwords: ['test'] }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readArmoredMessage(encrypted); const decrypted = await openpgp.decrypt({ passwords: ['test'], message }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect((await reader.peekBytes(plaintext[0].length * 4)).toString('utf8').substr(0, plaintext[0].length)).to.equal(plaintext[0]); dataArrived(); @@ -615,7 +617,7 @@ function tests() { message, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.readBytes(1024)).to.deep.equal(plaintext[0]); dataArrived(); @@ -629,7 +631,7 @@ function tests() { message: openpgp.Message.fromBinary(data), privateKeys: privKey }); - expect(util.isStream(signed)).to.equal(expectedType); + expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const message = await openpgp.readArmoredMessage(signed); const verified = await openpgp.verify({ @@ -637,7 +639,7 @@ function tests() { message, format: 'binary' }); - expect(util.isStream(verified.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(verified.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(verified.data); expect(await reader.readBytes(1024)).to.deep.equal(plaintext[0]); dataArrived(); @@ -653,7 +655,7 @@ function tests() { message: openpgp.Message.fromBinary(data), passwords: ['test'] }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const reader = openpgp.stream.getReader(encrypted); expect(await reader.readBytes(1024)).to.match(/^-----BEGIN PGP MESSAGE-----\r\n/); @@ -667,7 +669,7 @@ function tests() { message: openpgp.Message.fromBinary(data), privateKeys: privKey }); - expect(util.isStream(signed)).to.equal(expectedType); + expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const reader = openpgp.stream.getReader(signed); expect(await reader.readBytes(1024)).to.match(/^-----BEGIN PGP MESSAGE-----\r\n/); @@ -677,28 +679,38 @@ function tests() { }); it("Don't pull entire input stream when we're not pulling decrypted stream (AEAD)", async function() { - let coresStub = stub(openpgp.util, 'getHardwareConcurrency'); - coresStub.returns(1); + let coresStub; + if (util.detectNode()) { + coresStub = stub(require('os'), 'cpus'); + coresStub.returns([,]); + // Object.defineProperty(require('os'), 'cpus', { value: () => [,], configurable: true }); + } else { + Object.defineProperty(navigator, 'hardwareConcurrency', { value: 1, configurable: true }); + } try { const encrypted = await openpgp.encrypt({ message: openpgp.Message.fromBinary(data), passwords: ['test'] }); - expect(util.isStream(encrypted)).to.equal(expectedType); + expect(openpgp.stream.isStream(encrypted)).to.equal(expectedType); const message = await openpgp.readArmoredMessage(encrypted); const decrypted = await openpgp.decrypt({ passwords: ['test'], message, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(decrypted.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(decrypted.data); expect(await reader.readBytes(1024)).to.deep.equal(plaintext[0]); dataArrived(); await new Promise(resolve => setTimeout(resolve, 3000)); expect(i).to.be.lessThan(expectedType === 'web' ? 50 : 100); } finally { - coresStub.restore(); + if (util.detectNode()) { + coresStub.restore(); + } else { + delete navigator.hardwareConcurrency; + } } }); @@ -707,14 +719,14 @@ function tests() { message: openpgp.Message.fromBinary(data), privateKeys: privKey }); - expect(util.isStream(signed)).to.equal(expectedType); + expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const message = await openpgp.readArmoredMessage(signed); const verified = await openpgp.verify({ publicKeys: pubKey, message, format: 'binary' }); - expect(util.isStream(verified.data)).to.equal(expectedType); + expect(openpgp.stream.isStream(verified.data)).to.equal(expectedType); const reader = openpgp.stream.getReader(verified.data); expect(await reader.readBytes(1024)).to.deep.equal(plaintext[0]); dataArrived(); @@ -737,7 +749,7 @@ function tests() { detached: true, streaming: expectedType }); - expect(util.isStream(signed)).to.equal(expectedType); + expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const sigArmored = await openpgp.stream.readToEnd(signed); const signature = await openpgp.readArmoredMessage(sigArmored); const verified = await openpgp.verify({ @@ -766,7 +778,7 @@ function tests() { streaming: false, armor: false }); - expect(util.isStream(signed)).to.be.false; + expect(openpgp.stream.isStream(signed)).to.be.false; const signature = await openpgp.readMessage(signed); const verified = await openpgp.verify({ signature, @@ -796,7 +808,7 @@ function tests() { detached: true, streaming: expectedType }); - expect(util.isStream(signed)).to.equal(expectedType); + expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const sigArmored = await openpgp.stream.readToEnd(signed); const signature = await openpgp.readArmoredMessage(sigArmored); const verified = await openpgp.verify({ @@ -827,7 +839,7 @@ function tests() { detached: true, streaming: expectedType }); - expect(util.isStream(signed)).to.equal(expectedType); + expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const sigArmored = await openpgp.stream.readToEnd(signed); const signature = await openpgp.readArmoredMessage(sigArmored); const verified = await openpgp.verify({ @@ -846,7 +858,7 @@ function tests() { privateKeys: privKey, detached: true }); - expect(util.isStream(signed)).to.equal(expectedType); + expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const reader = openpgp.stream.getReader(signed); expect((await reader.readBytes(31)).toString('utf8')).to.equal('-----BEGIN PGP SIGNATURE-----\r\n'); dataArrived(); @@ -860,7 +872,7 @@ function tests() { privateKeys: privKey, detached: true }); - expect(util.isStream(signed)).to.equal(expectedType); + expect(openpgp.stream.isStream(signed)).to.equal(expectedType); const reader = openpgp.stream.getReader(signed); expect((await reader.readBytes(31)).toString('utf8')).to.equal('-----BEGIN PGP SIGNATURE-----\r\n'); dataArrived(); @@ -896,7 +908,7 @@ module.exports = () => describe('Streaming', function() { await new Promise(setTimeout); if (test === currentTest && i++ < 100) { if (i === 4) await dataArrivedPromise; - let randomBytes = await openpgp.crypto.random.getRandomBytes(1024); + let randomBytes = await random.getRandomBytes(1024); controller.enqueue(randomBytes); plaintext.push(randomBytes); } else { @@ -921,14 +933,14 @@ module.exports = () => describe('Streaming', function() { }); tryTests('Node Streams', tests, { - if: openpgp.util.detectNode(), + if: util.detectNode(), beforeEach: function() { data = openpgp.stream.webToNode(data); expectedType = 'node'; } }); - if (openpgp.util.detectNode()) { + if (util.detectNode()) { const fs = require('fs'); it('Node: Encrypt and decrypt text message roundtrip', async function() { @@ -939,14 +951,14 @@ module.exports = () => describe('Streaming', function() { message: openpgp.Message.fromText(data), passwords: ['test'] }); - expect(util.isStream(encrypted)).to.equal('node'); + expect(openpgp.stream.isStream(encrypted)).to.equal('node'); const message = await openpgp.readArmoredMessage(encrypted); const decrypted = await openpgp.decrypt({ passwords: ['test'], message }); - expect(util.isStream(decrypted.data)).to.equal('node'); + expect(openpgp.stream.isStream(decrypted.data)).to.equal('node'); expect(await openpgp.stream.readToEnd(decrypted.data)).to.equal(plaintext); }); @@ -959,7 +971,7 @@ module.exports = () => describe('Streaming', function() { passwords: ['test'], armor: false }); - expect(util.isStream(encrypted)).to.equal('node'); + expect(openpgp.stream.isStream(encrypted)).to.equal('node'); const message = await openpgp.readMessage(encrypted); const decrypted = await openpgp.decrypt({ @@ -967,7 +979,7 @@ module.exports = () => describe('Streaming', function() { message, format: 'binary' }); - expect(util.isStream(decrypted.data)).to.equal('node'); + expect(openpgp.stream.isStream(decrypted.data)).to.equal('node'); expect(await openpgp.stream.readToEnd(decrypted.data)).to.deep.equal(plaintext); }); } diff --git a/test/general/util.js b/test/general/util.js index ee7e9985..305486f8 100644 --- a/test/general/util.js +++ b/test/general/util.js @@ -1,4 +1,5 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const util = require('../../src/util'); const chai = require('chai'); @@ -9,123 +10,123 @@ module.exports = () => describe('Util unit tests', function() { describe('isString', function() { it('should return true for type "string"', function() { const data = 'foo'; - expect(openpgp.util.isString(data)).to.be.true; + expect(util.isString(data)).to.be.true; }); it('should return true for type String', function() { const data = String('foo'); - expect(openpgp.util.isString(data)).to.be.true; + expect(util.isString(data)).to.be.true; }); it('should return true for inherited type of String', function() { function MyString() {} MyString.prototype = Object.create(String.prototype); const data = new MyString(); - expect(openpgp.util.isString(data)).to.be.true; + expect(util.isString(data)).to.be.true; }); it('should return true for empty string', function() { const data = ''; - expect(openpgp.util.isString(data)).to.be.true; + expect(util.isString(data)).to.be.true; }); it('should return false for undefined', function() { let data; - expect(openpgp.util.isString(data)).to.be.false; + expect(util.isString(data)).to.be.false; }); it('should return false for Object', function() { const data = {}; - expect(openpgp.util.isString(data)).to.be.false; + expect(util.isString(data)).to.be.false; }); }); describe('isArray', function() { it('should return true for []', function() { const data = []; - expect(openpgp.util.isArray(data)).to.be.true; + expect(util.isArray(data)).to.be.true; }); it('should return true for type Array', function() { const data = Array(); - expect(openpgp.util.isArray(data)).to.be.true; + expect(util.isArray(data)).to.be.true; }); it('should return true for inherited type of Array', function() { function MyArray() {} MyArray.prototype = Object.create(Array.prototype); const data = new MyArray(); - expect(openpgp.util.isArray(data)).to.be.true; + expect(util.isArray(data)).to.be.true; }); it('should return false for undefined', function() { let data; - expect(openpgp.util.isArray(data)).to.be.false; + expect(util.isArray(data)).to.be.false; }); it('should return false for Object', function() { const data = {}; - expect(openpgp.util.isArray(data)).to.be.false; + expect(util.isArray(data)).to.be.false; }); }); describe('isUint8Array', function() { it('should return true for type Uint8Array', function() { const data = new Uint8Array(); - expect(openpgp.util.isUint8Array(data)).to.be.true; + expect(util.isUint8Array(data)).to.be.true; }); it('should return true for inherited type of Uint8Array', function() { function MyUint8Array() {} MyUint8Array.prototype = new Uint8Array(); const data = new MyUint8Array(); - expect(openpgp.util.isUint8Array(data)).to.be.true; + expect(util.isUint8Array(data)).to.be.true; }); it('should return false for undefined', function() { let data; - expect(openpgp.util.isUint8Array(data)).to.be.false; + expect(util.isUint8Array(data)).to.be.false; }); it('should return false for Object', function() { const data = {}; - expect(openpgp.util.isUint8Array(data)).to.be.false; + expect(util.isUint8Array(data)).to.be.false; }); }); describe('isEmailAddress', function() { it('should return true for valid email address', function() { const data = 'test@example.com'; - expect(openpgp.util.isEmailAddress(data)).to.be.true; + expect(util.isEmailAddress(data)).to.be.true; }); it('should return true for valid email address', function() { const data = 'test@xn--wgv.xn--q9jyb4c'; - expect(openpgp.util.isEmailAddress(data)).to.be.true; + expect(util.isEmailAddress(data)).to.be.true; }); it('should return false for invalid email address', function() { const data = 'Test User '; - expect(openpgp.util.isEmailAddress(data)).to.be.false; + expect(util.isEmailAddress(data)).to.be.false; }); it('should return false for invalid email address', function() { const data = 'test@examplecom'; - expect(openpgp.util.isEmailAddress(data)).to.be.false; + expect(util.isEmailAddress(data)).to.be.false; }); it('should return false for invalid email address', function() { const data = 'testexamplecom'; - expect(openpgp.util.isEmailAddress(data)).to.be.false; + expect(util.isEmailAddress(data)).to.be.false; }); it('should return false for empty string', function() { const data = ''; - expect(openpgp.util.isEmailAddress(data)).to.be.false; + expect(util.isEmailAddress(data)).to.be.false; }); it('should return false for undefined', function() { let data; - expect(openpgp.util.isEmailAddress(data)).to.be.false; + expect(util.isEmailAddress(data)).to.be.false; }); it('should return false for Object', function() { const data = {}; - expect(openpgp.util.isEmailAddress(data)).to.be.false; + expect(util.isEmailAddress(data)).to.be.false; }); }); describe('parseUserID', function() { it('should parse email address', function() { const email = "TestName Test "; - const result = openpgp.util.parseUserId(email); + const result = util.parseUserId(email); expect(result.name).to.equal('TestName Test'); expect(result.email).to.equal('test@example.com'); }); it('should parse email address with @ in display name and comment', function() { const email = "Test@Name Test (a comment) "; - const result = openpgp.util.parseUserId(email); + const result = util.parseUserId(email); expect(result.name).to.equal('Test@Name Test'); expect(result.email).to.equal('test@example.com'); expect(result.comment).to.equal('a comment'); @@ -136,14 +137,14 @@ module.exports = () => describe('Util unit tests', function() { it('util.readNumber should not overflow until full range of uint32', function () { const ints = [Math.pow(2, 20), Math.pow(2, 25), Math.pow(2, 30), Math.pow(2, 32) - 1]; for(let i = 0; i < ints.length; i++) { - expect(openpgp.util.readNumber(openpgp.util.writeNumber(ints[i], 4))).to.equal(ints[i]); + expect(util.readNumber(util.writeNumber(ints[i], 4))).to.equal(ints[i]); } }); }); describe("Zbase32", function() { it('util.encodeZBase32 encodes correctly', function() { - const encoded = openpgp.util.encodeZBase32(openpgp.util.strToUint8Array('test-wkd')); + const encoded = util.encodeZBase32(util.strToUint8Array('test-wkd')); expect(encoded).to.equal('qt1zg7bpq7ise'); }) }) diff --git a/test/general/x25519.js b/test/general/x25519.js index 2c1016e7..7910b4ae 100644 --- a/test/general/x25519.js +++ b/test/general/x25519.js @@ -1,6 +1,10 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const elliptic = require('../../src/crypto/public_key/elliptic'); +const signature = require('../../src/crypto/signature'); +const OID = require('../../src/type/oid'); +const util = require('../../src/util'); -const elliptic = openpgp.crypto.publicKey.elliptic; +const nacl = require('tweetnacl'); const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -212,18 +216,16 @@ module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cr describe('Ed25519 Test Vectors from RFC8032', function () { // https://tools.ietf.org/html/rfc8032#section-7.1 - const signature = openpgp.crypto.signature; - const util = openpgp.util; function testVector(vector) { const curve = new elliptic.Curve('ed25519'); - const { publicKey } = openpgp.crypto.publicKey.nacl.sign.keyPair.fromSeed(util.hexToUint8Array(vector.SECRET_KEY)); + const { publicKey } = nacl.sign.keyPair.fromSeed(util.hexToUint8Array(vector.SECRET_KEY)); expect(publicKey).to.deep.equal(util.hexToUint8Array(vector.PUBLIC_KEY)); const data = util.strToUint8Array(vector.MESSAGE); const privateParams = { seed: util.hexToUint8Array(vector.SECRET_KEY) }; const publicParams = { - oid: new openpgp.OID(curve.oid), + oid: new OID(curve.oid), Q: util.hexToUint8Array('40' + vector.PUBLIC_KEY) }; const R = util.hexToUint8Array(vector.SIGNATURE.R); diff --git a/test/security/message_signature_bypass.js b/test/security/message_signature_bypass.js index e9d04df3..85034757 100644 --- a/test/security/message_signature_bypass.js +++ b/test/security/message_signature_bypass.js @@ -1,6 +1,7 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const util = require('../../src/util'); -const { readArmoredKey, readArmoredCleartextMessage, util, SignaturePacket } = openpgp; +const { readArmoredKey, readArmoredCleartextMessage, SignaturePacket } = openpgp; const chai = require('chai'); chai.use(require('chai-as-promised')); @@ -73,14 +74,7 @@ async function getOtherPubKey() { /** * The "standalone" signature signed by the victim. */ -const STANDALONE_PKT = util.b64ToUint8Array(` -BAIBCAAQBQJbq3MKCRBVIIstGKzjzgAAWdoIALgj7OuhuuAWr6WEvGfvkx3e -Fn/mg76lh2Hawxq6ryI6+kzUH+YJsG94CfLgGuh5LghZFBnlkdZS11gK87fN -+ifmPdSDj8fsKqSFdX1sHGwzvzBcuPt+qhtHrACCWwiiBgajIOmIczKUlX4D -ASBkthx0o9Qb/r3dT91zmrniIK5I0yqe34/1rsHhOAf8ds2EubupFJJqFOb1 -qssMWE+jBrTREoD/EH5q7un2jEGccITcVQSZCqfjHT4EL6dF/bmuggf7wV/E -QLXfFIJS6cZczK86XW1pGaXBKRLvQXYa/eRWHKcGlrujdFKzJYRoT6LVDk8T -jhAfE9q2ElqlaAvZZYw=`); +const STANDALONE_PKT = util.hexToUint8Array(`04020108001005025bab730a091055208b2d18ace3ce000059da0800b823eceba1bae016afa584bc67ef931dde167fe683bea58761dac31abaaf223afa4cd41fe609b06f7809f2e01ae8792e08591419e591d652d7580af3b7cdfa27e63dd4838fc7ec2aa485757d6c1c6c33bf305cb8fb7eaa1b47ac00825b08a20606a320e988733294957e03012064b61c74a3d41bfebddd4fdd739ab9e220ae48d32a9edf8ff5aec1e13807fc76cd84b9bba914926a14e6f5aacb0c584fa306b4d11280ff107e6aeee9f68c419c7084dc5504990aa7e31d3e042fa745fdb9ae8207fbc15fc440b5df148252e9c65cccaf3a5d6d6919a5c12912ef41761afde4561ca70696bba37452b32584684fa2d50e4f138e101f13dab6125aa5680bd9658c`); async function fakeSignature() { // read the template and modify the text to // invalidate the signature. diff --git a/test/security/subkey_trust.js b/test/security/subkey_trust.js index 24de1cda..95d9dc44 100644 --- a/test/security/subkey_trust.js +++ b/test/security/subkey_trust.js @@ -1,4 +1,5 @@ const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); +const util = require('../../src/util'); const { readArmoredKey, generate, Key, readArmoredCleartextMessage, CleartextMessage, enums, PacketList, SignaturePacket } = openpgp; @@ -10,7 +11,7 @@ const expect = chai.expect; async function generateTestData() { const victimPrivKey = await generate({ userIds: ['Victim '], - rsaBits: openpgp.util.getWebCryptoAll() ? 2048 : 1024, + rsaBits: util.getWebCryptoAll() ? 2048 : 1024, subkeys: [{ sign: true }] @@ -19,7 +20,7 @@ async function generateTestData() { const attackerPrivKey = await generate({ userIds: ['Attacker '], - rsaBits: openpgp.util.getWebCryptoAll() ? 2048 : 1024, + rsaBits: util.getWebCryptoAll() ? 2048 : 1024, subkeys: [], sign: false });