Merge pull request #1629 from openpgpjs/v6

V6
This commit is contained in:
Daniel Huigens 2024-11-04 12:11:19 +01:00 committed by GitHub
commit 31a7e2616b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
229 changed files with 54114 additions and 17826 deletions

View File

@ -1,8 +1,15 @@
module.exports = { module.exports = {
'extends': 'airbnb-base', 'extends': [
'airbnb-base',
'airbnb-typescript/base'
],
'parser': '@typescript-eslint/parser',
'parserOptions': { 'parserOptions': {
'ecmaVersion': 11, 'ecmaVersion': 11,
'sourceType': 'module' 'sourceType': 'module',
'project': 'tsconfig.json'
}, },
'env': { 'env': {
@ -12,10 +19,18 @@ module.exports = {
}, },
'plugins': [ 'plugins': [
'@typescript-eslint',
'chai-friendly', 'chai-friendly',
'import' 'import',
'unicorn'
], ],
'settings': {
'import/resolver': {
'typescript': {}
}
},
'globals': { // TODO are all these necessary? 'globals': { // TODO are all these necessary?
'globalThis': true, 'globalThis': true,
'console': true, 'console': true,
@ -42,11 +57,11 @@ module.exports = {
'arrow-body-style': 'off', 'arrow-body-style': 'off',
'arrow-parens': ['error','as-needed'], 'arrow-parens': ['error','as-needed'],
'class-methods-use-this': 'off', 'class-methods-use-this': 'off',
'comma-dangle': ['error', 'never'], '@typescript-eslint/comma-dangle': ['error', 'never'],
'comma-spacing': 'off', '@typescript-eslint/comma-spacing': 'off',
'consistent-return': 'off', 'consistent-return': 'off',
'default-case': 'off', 'default-case': 'off',
'default-param-last': 'off', '@typescript-eslint/default-param-last': 'off',
'eol-last': ['error', 'always'], 'eol-last': ['error', 'always'],
'function-call-argument-newline': 'off', 'function-call-argument-newline': 'off',
'func-names': ['error', 'never'], 'func-names': ['error', 'never'],
@ -67,7 +82,7 @@ module.exports = {
'no-plusplus': 'off', 'no-plusplus': 'off',
'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'], 'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
'object-curly-newline': 'off', 'object-curly-newline': 'off',
'no-shadow': 'off', // TODO get rid of this '@typescript-eslint/no-shadow': 'off', // TODO get rid of this
'object-property-newline': [ 'object-property-newline': [
'error', 'error',
{ {
@ -88,31 +103,38 @@ module.exports = {
'prefer-template': 'off', 'prefer-template': 'off',
'quote-props': 'off', 'quote-props': 'off',
'quotes': ['error', 'single', { 'avoidEscape': true }], 'quotes': ['error', 'single', { 'avoidEscape': true }],
'space-before-function-paren': 'off', '@typescript-eslint/space-before-function-paren': ['error', { 'anonymous': 'ignore', 'named': 'never', 'asyncArrow': 'always' }],
'spaced-comment': 'off', 'spaced-comment': 'off',
'indent': ['error', 2, { 'SwitchCase': 1 }], 'indent': 'off',
'no-unused-vars': 'error', '@typescript-eslint/indent': ['error', 2, { 'SwitchCase': 1 }],
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
// eslint-plugin-import rules: // eslint-plugin-import rules:
'import/named': 'error', 'import/named': 'error',
'import/extensions': 'error', 'import/extensions': 'off', // temporary: we use them in tests (ESM compliant), but not in the lib (to limit diff)
'import/first': 'off',
'import/no-extraneous-dependencies': ['error', { 'devDependencies': true, 'optionalDependencies': false, 'peerDependencies': false }], 'import/no-extraneous-dependencies': ['error', { 'devDependencies': true, 'optionalDependencies': false, 'peerDependencies': false }],
'import/no-unassigned-import': 'error', 'import/no-unassigned-import': 'error',
'import/no-unresolved': 'error',
'import/prefer-default-export': 'off', 'import/prefer-default-export': 'off',
// Custom silencers: // Custom silencers:
'camelcase': 'off', // used in tests, need to fix separately
'no-multi-assign': 'off', 'no-multi-assign': 'off',
'no-underscore-dangle': 'off', 'no-underscore-dangle': 'off',
'no-await-in-loop': 'off', 'no-await-in-loop': 'off',
'camelcase': 'off', // snake_case used in tests, need to fix separately
'@typescript-eslint/naming-convention': 'off', // supersedes 'camelcase' rule
'@typescript-eslint/lines-between-class-members': 'off',
// Custom errors: // Custom errors:
'no-use-before-define': [2, { 'functions': false, 'classes': true, 'variables': false }], '@typescript-eslint/no-use-before-define': ['error', { 'functions': false, 'classes': true, 'variables': false, 'allowNamedExports': true }],
'no-constant-condition': [2, { 'checkLoops': false }], 'no-constant-condition': [2, { 'checkLoops': false }],
'new-cap': [2, { 'properties': false, 'capIsNewExceptionPattern': 'EAX|OCB|GCM|CMAC|CBC|OMAC|CTR', 'newIsCapExceptionPattern': 'type|hash*' }], 'new-cap': [2, { 'properties': false, 'capIsNewExceptionPattern': 'EAX|OCB|GCM|CMAC|CBC|OMAC|CTR', 'newIsCapExceptionPattern': 'type|hash*' }],
'max-lines': [2, { 'max': 620, 'skipBlankLines': true, 'skipComments': true }], 'max-lines': [2, { 'max': 620, 'skipBlankLines': true, 'skipComments': true }],
'no-unused-expressions': 0, '@typescript-eslint/no-unused-expressions': 0,
'chai-friendly/no-unused-expressions': [2, { 'allowShortCircuit': true }], 'chai-friendly/no-unused-expressions': [2, { 'allowShortCircuit': true }],
'unicorn/switch-case-braces': ['error', 'avoid'],
// Custom warnings: // Custom warnings:
'no-console': 1 'no-console': 1

29
.github/.dependabot.yml vendored Normal file
View File

@ -0,0 +1,29 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "daily"
allow:
- dependency-name: "playwright"
versioning-strategy: increase
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
allow:
- dependency-name: "@noble*"
- dependency-name: "fflate"
versioning-strategy: increase
groups:
# Any packages matching the pattern @noble* where the highest resolvable
# version is minor or patch will be grouped together.
# Grouping rules apply to version updates only.
noble:
applies-to: version-updates
patterns:
- "@noble*"
update-types:
- "minor"
- "patch"

View File

@ -11,7 +11,8 @@
"id": "sop-openpgpjs-main", "id": "sop-openpgpjs-main",
"path": "__SOP_OPENPGPJS__", "path": "__SOP_OPENPGPJS__",
"env": { "env": {
"OPENPGPJS_PATH": "__OPENPGPJS_MAIN__" "OPENPGPJS_PATH": "__OPENPGPJS_MAIN__",
"DISABLE_PROFILES": "true"
} }
}, },
{ {
@ -21,10 +22,14 @@
"path": "__GPGME_SOP__" "path": "__GPGME_SOP__"
}, },
{ {
"path": "__GOSOP__" "id": "gosop-v2",
"path": "__GOSOP_V2__"
}, },
{ {
"path": "__RNP_SOP__" "path": "__RNP_SOP__"
},
{
"path": "__RSOP__"
} }
], ],
"rlimits": { "rlimits": {

View File

@ -7,7 +7,8 @@ cat $CONFIG_TEMPLATE \
| sed "s@__OPENPGPJS_MAIN__@${OPENPGPJS_MAIN}@g" \ | sed "s@__OPENPGPJS_MAIN__@${OPENPGPJS_MAIN}@g" \
| sed "s@__SQOP__@${SQOP}@g" \ | sed "s@__SQOP__@${SQOP}@g" \
| sed "s@__GPGME_SOP__@${GPGME_SOP}@g" \ | sed "s@__GPGME_SOP__@${GPGME_SOP}@g" \
| sed "s@__GOSOP__@${GOSOP}@g" \ | sed "s@__GOSOP_V2__@${GOSOP_V2}@g" \
| sed "s@__SOP_OPENPGPJS__@${SOP_OPENPGPJS}@g" \ | sed "s@__SOP_OPENPGPJS__@${SOP_OPENPGPJS_V2}@g" \
| sed "s@__RNP_SOP__@${RNP_SOP}@g" \ | sed "s@__RNP_SOP__@${RNP_SOP}@g" \
| sed "s@__RSOP__@${RSOP}@g" \
> $CONFIG_OUTPUT > $CONFIG_OUTPUT

View File

@ -2,7 +2,7 @@ name: Performance Regression Test
on: on:
pull_request: pull_request:
branches: [main] branches: [main, v6]
jobs: jobs:
benchmark: benchmark:
@ -11,15 +11,17 @@ jobs:
steps: steps:
# check out pull request branch # check out pull request branch
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
path: pr path: pr
# check out main branch (to compare performance) # check out main branch (to compare performance)
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
ref: main ref: main
path: main path: main
- uses: actions/setup-node@v3 - uses: actions/setup-node@v4
with:
node-version: '>=20.6.0'
- name: Run pull request time benchmark - name: Run pull request time benchmark
run: cd pr && npm install && npm run --silent benchmark-time > benchmarks.txt && cat benchmarks.txt run: cd pr && npm install && npm run --silent benchmark-time > benchmarks.txt && cat benchmarks.txt

View File

@ -4,7 +4,7 @@ on:
push: push:
branches: [main] branches: [main]
pull_request: pull_request:
branches: [main] branches: [main, v6]
jobs: jobs:
lint: lint:
@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: actions/setup-node@v3 - uses: actions/setup-node@v4
- run: npm ci --ignore-scripts - run: npm ci --ignore-scripts
- run: npm run docs - run: npm run docs

View File

@ -2,7 +2,7 @@ name: SOP interoperability test suite
on: on:
pull_request: pull_request:
branches: [ main ] branches: [ main, v6 ]
jobs: jobs:
@ -10,34 +10,34 @@ jobs:
name: Run interoperability test suite name: Run interoperability test suite
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: ghcr.io/protonmail/openpgp-interop-test-docker:v1.1.1 image: ghcr.io/protonmail/openpgp-interop-test-docker:v1.1.12
credentials: credentials:
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.github_token }} password: ${{ secrets.github_token }}
steps: steps:
# check out repo for scripts # check out repo for scripts
- uses: actions/checkout@v3 - uses: actions/checkout@v4
# check out pull request branch # check out pull request branch
- name: Checkout openpgpjs-branch - name: Checkout openpgpjs-branch
uses: actions/checkout@v3 uses: actions/checkout@v4
with: with:
path: openpgpjs-branch path: openpgpjs-branch
- name: Install openpgpjs-branch - name: Install openpgpjs-branch
run: cd openpgpjs-branch && npm install run: cd openpgpjs-branch && npm install
- name: Print openpgpjs-branch version - name: Print openpgpjs-branch version
run: $SOP_OPENPGPJS version --extended run: $SOP_OPENPGPJS_V2 version --extended
env: env:
OPENPGPJS_PATH: ${{ github.workspace }}/openpgpjs-branch OPENPGPJS_PATH: ${{ github.workspace }}/openpgpjs-branch
# check out main branch # check out main branch
- name: Checkout openpgpjs-main - name: Checkout openpgpjs-main
uses: actions/checkout@v3 uses: actions/checkout@v4
with: with:
ref: main ref: main
path: openpgpjs-main path: openpgpjs-main
- name: Install openpgpjs-main - name: Install openpgpjs-main
run: cd openpgpjs-main && npm install run: cd openpgpjs-main && npm install
- name: Print openpgpjs-main version - name: Print openpgpjs-main version
run: $SOP_OPENPGPJS version --extended run: $SOP_OPENPGPJS_V2 version --extended
env: env:
OPENPGPJS_PATH: ${{ github.workspace }}/openpgpjs-main OPENPGPJS_PATH: ${{ github.workspace }}/openpgpjs-main
# Run test suite # Run test suite
@ -56,12 +56,12 @@ jobs:
RESULTS_HTML: .github/test-suite/test-suite-results.html RESULTS_HTML: .github/test-suite/test-suite-results.html
# Upload results # Upload results
- name: Upload test results json artifact - name: Upload test results json artifact
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v4
with: with:
name: test-suite-results.json name: test-suite-results.json
path: .github/test-suite/test-suite-results.json path: .github/test-suite/test-suite-results.json
- name: Upload test results html artifact - name: Upload test results html artifact
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v4
with: with:
name: test-suite-results.html name: test-suite-results.html
path: .github/test-suite/test-suite-results.html path: .github/test-suite/test-suite-results.html
@ -72,16 +72,16 @@ jobs:
needs: test-suite needs: test-suite
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download test results json artifact - name: Download test results json artifact
id: download-test-results id: download-test-results
uses: actions/download-artifact@v3 uses: actions/download-artifact@v4
with: with:
name: test-suite-results.json name: test-suite-results.json
- name: Compare with baseline - name: Compare with baseline
uses: ProtonMail/openpgp-interop-test-analyzer@v1 uses: ProtonMail/openpgp-interop-test-analyzer@v2
with: with:
results: ${{ steps.download-test-results.outputs.download-path }}/test-suite-results.json results: ${{ steps.download-test-results.outputs.download-path }}/test-suite-results.json
output: baseline-comparison.json output: baseline-comparison.json
baseline: sop-openpgpjs-main baseline: sop-openpgpjs-main
target: sop-openpgpjs-main target: sop-openpgpjs-branch

View File

@ -4,18 +4,18 @@ on:
push: push:
branches: [main] branches: [main]
pull_request: pull_request:
branches: [main] branches: [main, v6]
jobs: jobs:
build: # cache both dist and tests (non-lightweight only), based on commit hash build: # cache both dist and tests (non-lightweight only), based on commit hash
name: Build name: Build
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: actions/setup-node@v3 - uses: actions/setup-node@v4
- name: Check for cached folders - name: Check for cached folders
id: cache-full id: cache-full
uses: actions/cache@v3 uses: actions/cache@v4
with: with:
path: | path: |
dist dist
@ -29,21 +29,22 @@ jobs:
node: node:
strategy: strategy:
fail-fast: false # if tests for one version fail, continue with the rest
matrix: matrix:
node-version: [14.x, 16.x, 18.x, 20.x] node-version: [18.x, 20.x, 22.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
name: Node ${{ matrix.node-version }} name: Node ${{ matrix.node-version }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: build needs: build
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: actions/setup-node@v3 - uses: actions/setup-node@v4
with: with:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
- run: npm ci --ignore-scripts # for mocha - run: npm ci --ignore-scripts # for mocha
- name: Retrieve cached folders - name: Retrieve cached folders
uses: actions/cache/restore@v3 uses: actions/cache/restore@v4
id: cache-full id: cache-full
with: with:
# test/lib is not needed, but the path must be specified fully for a cache-hit # test/lib is not needed, but the path must be specified fully for a cache-hit
@ -56,15 +57,22 @@ jobs:
test-browsers-latest: test-browsers-latest:
name: Browsers (latest) name: Browsers (latest)
runs-on: ubuntu-latest
needs: build needs: build
strategy:
fail-fast: false # if tests for one version fail, continue with the rest
matrix:
# run on all main platforms to test platform-specific code, if present
# (e.g. webkit's WebCrypto API implementation is different in macOS vs Linux)
# TODO: windows-latest fails to fetch resources from the wtr server; investigate if the problem is with path declaration or permissions
runner: ['ubuntu-latest', 'macos-latest']
runs-on: ${{ matrix.runner }}
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: actions/setup-node@v3 - uses: actions/setup-node@v4
- name: Retrieve cached built folders - name: Retrieve cached built folders
uses: actions/cache/restore@v3 uses: actions/cache/restore@v4
id: cache-full id: cache-full
with: with:
path: | path: |
@ -78,33 +86,35 @@ jobs:
npm pkg delete scripts.prepare npm pkg delete scripts.prepare
npm ci npm ci
- name: Get Playwright version - name: Get Playwright version and cache location
id: playwright-version id: playwright-version
run: | run: |
PLAYWRIGHT_VERSION=$(npm ls playwright | grep playwright | sed 's/.*@//') PLAYWRIGHT_VERSION=$(npm ls playwright --depth=0 | grep playwright | sed 's/.*@//')
echo "version=$PLAYWRIGHT_VERSION" >> $GITHUB_OUTPUT echo "version=$PLAYWRIGHT_VERSION" >> $GITHUB_OUTPUT
PLAYWRIGHT_CACHE=${{ fromJSON('{"ubuntu-latest": "~/.cache/ms-playwright", "macos-latest": "~/Library/Caches/ms-playwright"}')[matrix.runner] }}
echo "playwright_cache=$PLAYWRIGHT_CACHE" >> $GITHUB_OUTPUT
- name: Check for cached browsers - name: Check for cached browsers
id: cache-playwright-browsers id: cache-playwright-browsers
uses: actions/cache@v3 uses: actions/cache@v4
with: with:
path: ~/.cache/ms-playwright path: ${{ steps.playwright-version.outputs.playwright_cache }}
key: playwright-browsers-${{ steps.playwright-version.outputs.version }} key: playwright-browsers-${{ matrix.runner }}-${{ steps.playwright-version.outputs.version }}
- name: Install browsers - name: Install browsers
if: steps.cache-playwright-browsers.outputs.cache-hit != 'true' if: steps.cache-playwright-browsers.outputs.cache-hit != 'true'
run: | run: |
npx playwright install-deps chrome npx playwright install --with-deps chromium
npx playwright install-deps firefox npx playwright install --with-deps firefox
- name: Install WebKit # caching not possible, external shared libraries required - name: Install WebKit # caching not possible, external shared libraries required
run: npx playwright install-deps webkit run: npx playwright install --with-deps webkit
- name: Run browser tests - name: Run browser tests
run: npm run test-browser run: npm run test-browser:ci -- --static-logging
- name: Run browser tests (lightweight) # overwrite test/lib - name: Run browser tests (lightweight) # overwrite test/lib
run: | run: |
npm run build-test --lightweight npm run build-test --lightweight
npm run test-browser npm run test-browser:ci -- --static-logging
test-browsers-compatibility: test-browsers-compatibility:
name: Browsers (older, on Browserstack) name: Browsers (older, on Browserstack)
@ -115,14 +125,23 @@ jobs:
BROWSERSTACK_ACCESS_KEY: VjgBVRMxNVBj7SjJFiau BROWSERSTACK_ACCESS_KEY: VjgBVRMxNVBj7SjJFiau
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: actions/setup-node@v3 - uses: actions/setup-node@v4
- name: Generate self-signed HTTPS certificates for web-test-runner server
uses: kofemann/action-create-certificate@v0.0.4
with:
hostcert: '127.0.0.1.pem'
hostkey: '127.0.0.1-key.pem'
cachain: 'ca-chain.pem'
- name: Adjust HTTPS certificates permissions
run: sudo chown runner:docker *.pem
- name: Install dependencies - name: Install dependencies
run: npm ci --ignore-scripts run: npm ci --ignore-scripts
- name: Retrieve cached dist folder - name: Retrieve cached dist folder
uses: actions/cache/restore@v3 uses: actions/cache/restore@v4
id: cache-full id: cache-full
with: with:
path: | path: |
@ -138,12 +157,12 @@ jobs:
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Run browserstack tests - name: Run browserstack tests
run: npm run test-browserstack run: npm run test-browserstack -- --static-logging
- name: Run browserstack tests (lightweight) # overwrite test/lib - name: Run browserstack tests (lightweight) # overwrite test/lib
run: | run: |
npm run build-test --lightweight npm run build-test --lightweight
npm run test-browserstack npm run test-browserstack -- --static-logging
env: env:
LIGHTWEIGHT: true LIGHTWEIGHT: true
@ -153,11 +172,11 @@ jobs:
needs: build needs: build
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: actions/setup-node@v3 - uses: actions/setup-node@v4
- run: npm ci --ignore-scripts # TS - run: npm ci --ignore-scripts # TS
- name: Retrieve cached folders - name: Retrieve cached folders
uses: actions/cache/restore@v3 uses: actions/cache/restore@v4
id: cache-full id: cache-full
with: with:
path: | path: |
@ -172,11 +191,11 @@ jobs:
needs: build needs: build
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: actions/setup-node@v3 - uses: actions/setup-node@v4
- run: npm ci --ignore-scripts # linter - run: npm ci --ignore-scripts # linter
- name: Retrieve cached folders - name: Retrieve cached folders
uses: actions/cache/restore@v3 uses: actions/cache/restore@v4
id: cache-full id: cache-full
with: with:
path: | path: |

2
.gitignore vendored
View File

@ -5,4 +5,4 @@ test/lib/
test/typescript/definitions.js test/typescript/definitions.js
dist/ dist/
openpgp.store/ openpgp.store/
.nyc_output/ coverage

6
.mocharc.json Normal file
View File

@ -0,0 +1,6 @@
{
"node-option": [
"experimental-specifier-resolution=node",
"loader=ts-node/esm"
]
}

101
README.md
View File

@ -1,7 +1,7 @@
OpenPGP.js [![BrowserStack Status](https://automate.browserstack.com/badge.svg?badge_key=N1l2eHFOanVBMU9wYWxJM3ZnWERnc1lidkt5UkRqa3BralV3SWVhOGpGTT0tLVljSjE4Z3dzVmdiQjl6RWgxb2c3T2c9PQ==--5864052cd523f751b6b907d547ac9c4c5f88c8a3)](https://automate.browserstack.com/public-build/N1l2eHFOanVBMU9wYWxJM3ZnWERnc1lidkt5UkRqa3BralV3SWVhOGpGTT0tLVljSjE4Z3dzVmdiQjl6RWgxb2c3T2c9PQ==--5864052cd523f751b6b907d547ac9c4c5f88c8a3) [![Join the chat on Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/openpgpjs/openpgpjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) OpenPGP.js [![Join the chat on Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/openpgpjs/openpgpjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
========== ==========
[OpenPGP.js](https://openpgpjs.org/) is a JavaScript implementation of the OpenPGP protocol. It implements [RFC4880](https://tools.ietf.org/html/rfc4880) and parts of [RFC4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10). [OpenPGP.js](https://openpgpjs.org/) is a JavaScript implementation of the OpenPGP protocol. It implements [RFC9580](https://datatracker.ietf.org/doc/rfc9580/) (superseding [RFC4880](https://tools.ietf.org/html/rfc4880) and [RFC4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10)).
**Table of Contents** **Table of Contents**
@ -33,61 +33,59 @@ OpenPGP.js [![BrowserStack Status](https://automate.browserstack.com/badge.svg?b
### Platform Support ### Platform Support
* The `dist/openpgp.min.js` bundle works well with recent versions of Chrome, Firefox, Safari and Edge. * The `dist/openpgp.min.js` (or `.mjs`) bundle works with recent versions of Chrome, Firefox, Edge and Safari 14+.
* The `dist/node/openpgp.min.js` bundle works well in Node.js. It is used by default when you `require('openpgp')` in Node.js. * The `dist/node/openpgp.min.mjs` (or `.cjs`) bundle works in Node.js v18+: it is used by default when you `import ... from 'openpgp'` (resp. `require('openpgp')`).
* Currently, Chrome, Safari and Edge have partial implementations of the * Streaming support:
[Streams specification](https://streams.spec.whatwg.org/), and Firefox * in browsers: the latest versions of Chrome, Firefox, Edge and Safari implement the
has a partial implementation behind feature flags. Chrome is the only [Streams specification](https://streams.spec.whatwg.org/), including `TransformStream`s.
browser that implements `TransformStream`s, which we need, so we include These are needed if you use the library with streamed inputs.
a [polyfill](https://github.com/MattiasBuelens/web-streams-polyfill) for In previous versions of OpenPGP.js, WebStreams were automatically polyfilled by the library,
all other browsers. Please note that in those browsers, the global but from v6 this task is left up to the library user, due to the more extensive browser support, and the
`ReadableStream` property gets overwritten with the polyfill version if polyfilling side-effects. If you're working with [older browsers versions which do not implement e.g. TransformStreams](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream), you can manually
it exists. In some edge cases, you might need to use the native load [WebStream polyfill](https://github.com/MattiasBuelens/web-streams-polyfills).
Please note that when you load the polyfills, the global `ReadableStream` property (if it exists) gets overwritten with the polyfill version.
In some edge cases, you might need to use the native
`ReadableStream` (for example when using it to create a `Response` `ReadableStream` (for example when using it to create a `Response`
object), in which case you should store a reference to it before loading object), in which case you should store a reference to it before loading
OpenPGP.js. There is also the the polyfills. There is also the [web-streams-adapter](https://github.com/MattiasBuelens/web-streams-adapter)
[web-streams-adapter](https://github.com/MattiasBuelens/web-streams-adapter)
library to convert back and forth between them. library to convert back and forth between them.
* in Node.js: OpenPGP.js v6 no longer supports native Node `Readable` streams in input, and instead expects (and outputs) [Node's WebStreams](https://nodejs.org/api/webstreams.html#class-readablestream). [Node v17+ includes utilities to convert from and to Web Streams](https://nodejs.org/api/stream.html#streamreadabletowebstreamreadable-options).
### Performance ### Performance
* Version 3.0.0 of the library introduces support for public-key cryptography using [elliptic curves](https://wiki.gnupg.org/ECC). We use native implementations on browsers and Node.js when available. Elliptic curve cryptography provides stronger security per bits of key, which allows for much faster operations. Currently the following curves are supported: * Version 3.0.0 of the library introduced support for public-key cryptography using [elliptic curves](https://wiki.gnupg.org/ECC). We use native implementations on browsers and Node.js when available. Compared to RSA, elliptic curve cryptography provides stronger security per bits of key, which allows for much faster operations. Currently the following curves are supported:
| Curve | Encryption | Signature | NodeCrypto | WebCrypto | Constant-Time | | Curve | Encryption | Signature | NodeCrypto | WebCrypto | Constant-Time |
|:---------------:|:----------:|:---------:|:----------:|:---------:|:-----------------:| |:---------------:|:----------:|:---------:|:----------:|:---------:|:-----------------:|
| curve25519 | ECDH | N/A | No | No | Algorithmically** | | curve25519 | ECDH | N/A | No | No | Algorithmically |
| ed25519 | N/A | EdDSA | No | No | Algorithmically** | | ed25519 | N/A | EdDSA | No | Yes* | If native** |
| p256 | ECDH | ECDSA | Yes* | Yes* | If native*** | | nistP256 | ECDH | ECDSA | Yes* | Yes* | If native** |
| p384 | ECDH | ECDSA | Yes* | Yes* | If native*** | | nistP384 | ECDH | ECDSA | Yes* | Yes* | If native** |
| p521 | ECDH | ECDSA | Yes* | Yes* | If native*** | | nistP521 | ECDH | ECDSA | Yes* | Yes* | If native** |
| brainpoolP256r1 | ECDH | ECDSA | Yes* | No | If native*** | | brainpoolP256r1 | ECDH | ECDSA | Yes* | No | If native** |
| brainpoolP384r1 | ECDH | ECDSA | Yes* | No | If native*** | | brainpoolP384r1 | ECDH | ECDSA | Yes* | No | If native** |
| brainpoolP512r1 | ECDH | ECDSA | Yes* | No | If native*** | | brainpoolP512r1 | ECDH | ECDSA | Yes* | No | If native** |
| secp256k1 | ECDH | ECDSA | Yes* | No | If native*** | | secp256k1 | ECDH | ECDSA | Yes* | No | If native** |
\* when available \* when available
\** the curve25519 and ed25519 implementations are algorithmically constant-time, but may not be constant-time after optimizations of the JavaScript compiler \** these curves are only constant-time if the underlying native implementation is available and constant-time
\*** these curves are only constant-time if the underlying native implementation is available and constant-time
* Version 2.x of the library has been built from the ground up with Uint8Arrays. This allows for much better performance and memory usage than strings.
* If the user's browser supports [native WebCrypto](https://caniuse.com/#feat=cryptography) via the `window.crypto.subtle` API, this will be used. Under Node.js the native [crypto module](https://nodejs.org/api/crypto.html#crypto_crypto) is used. * If the user's browser supports [native WebCrypto](https://caniuse.com/#feat=cryptography) via the `window.crypto.subtle` API, this will be used. Under Node.js the native [crypto module](https://nodejs.org/api/crypto.html#crypto_crypto) is used.
* The library implements the [RFC4880bis proposal](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10) for authenticated encryption using native AES-EAX, OCB, or GCM. This makes symmetric encryption up to 30x faster on supported platforms. Since the specification has not been finalized and other OpenPGP implementations haven't adopted it yet, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations, and also with future versions of OpenPGP.js. Don't use it with messages you want to store on disk or in a database.** You can enable it by setting `openpgp.config.aeadProtect = true`. * The library implements authenticated encryption (AEAD) as per [RFC9580](https://datatracker.ietf.org/doc/rfc9580/) using AES-GCM, OCB, or EAX. This makes symmetric encryption faster on platforms with native implementations. However, since the specification is very recent and other OpenPGP implementations are in the process of adopting it, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations which have yet to implement the feature.** You can enable it by setting `openpgp.config.aeadProtect = true`.
Note that this setting has a different effect from the one in OpenPGP.js v5, which implemented support for a provisional version of AEAD from [RFC4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10), which was modified in RFC9580.
You can change the AEAD mode by setting one of the following options: You can change the AEAD mode by setting one of the following options:
``` ```
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax // Default, native openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.gcm; // Default, native in WebCrypto and Node.js
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb // Non-native openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb; // Non-native, but supported across RFC9580 implementations
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGCM // **Non-standard**, fastest openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax; // Native in Node.js
``` ```
* For environments that don't provide native crypto, the library falls back to [asm.js](https://caniuse.com/#feat=asmjs) implementations of AES, SHA-1, and SHA-256.
### Getting started ### Getting started
#### Node.js #### Node.js
@ -98,18 +96,17 @@ Install OpenPGP.js using npm and save it in your dependencies:
npm install --save openpgp npm install --save openpgp
``` ```
And import it as a CommonJS module: And import it as an ES module, from a .mjs file:
```js
import * as openpgp from 'openpgp';
```
Or as a CommonJS module:
```js ```js
const openpgp = require('openpgp'); const openpgp = require('openpgp');
``` ```
Or as an ES6 module, from an .mjs file:
```js
import * as openpgp from 'openpgp';
```
#### Deno (experimental) #### Deno (experimental)
Import as an ES6 module, using /dist/openpgp.mjs. Import as an ES6 module, using /dist/openpgp.mjs.
@ -174,17 +171,17 @@ To offload cryptographic operations off the main thread, you can implement a Web
#### TypeScript #### TypeScript
Since TS is not fully integrated in the library, TS-only dependencies are currently listed as `devDependencies`, so to compile the project youll need to add `@openpgp/web-stream-tools` manually (NB: only versions below v0.12 are compatible with OpenPGP.js v5): Since TS is not fully integrated in the library, TS-only dependencies are currently listed as `devDependencies`, so to compile the project youll need to add `@openpgp/web-stream-tools` manually:
```sh ```sh
npm install --save-dev @openpgp/web-stream-tools@0.0.11-patch-0 npm install --save-dev @openpgp/web-stream-tools
``` ```
If you notice missing or incorrect type definitions, feel free to open a PR. If you notice missing or incorrect type definitions, feel free to open a PR.
### Examples ### Examples
Here are some examples of how to use OpenPGP.js v5. For more elaborate examples and working code, please check out the [public API unit tests](https://github.com/openpgpjs/openpgpjs/blob/main/test/general/openpgp.js). If you're upgrading from v4 it might help to check out the [changelog](https://github.com/openpgpjs/openpgpjs/wiki/V5-Changelog) and [documentation](https://github.com/openpgpjs/openpgpjs#documentation). Here are some examples of how to use OpenPGP.js v6. For more elaborate examples and working code, please check out the [public API unit tests](https://github.com/openpgpjs/openpgpjs/blob/main/test/general/openpgp.js). If you're upgrading from v4 it might help to check out the [changelog](https://github.com/openpgpjs/openpgpjs/wiki/v6-Changelog) and [documentation](https://github.com/openpgpjs/openpgpjs#documentation).
#### Encrypt and decrypt *Uint8Array* data with a password #### Encrypt and decrypt *Uint8Array* data with a password
@ -389,14 +386,8 @@ Where the value can be any of:
})(); })();
``` ```
For more information on using ReadableStreams, see [the MDN Documentation on the For more information on using ReadableStreams (both in browsers and Node.js), see [the MDN Documentation on the
Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API). Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) .
You can also pass a [Node.js `Readable`
stream](https://nodejs.org/api/stream.html#stream_class_stream_readable), in
which case OpenPGP.js will return a Node.js `Readable` stream as well, which you
can `.pipe()` to a `Writable` stream, for example.
#### Streaming encrypt and decrypt *String* data with PGP keys #### Streaming encrypt and decrypt *String* data with PGP keys
@ -453,7 +444,7 @@ can `.pipe()` to a `Writable` stream, for example.
ECC keys (smaller and faster to generate): ECC keys (smaller and faster to generate):
Possible values for `curve` are: `curve25519`, `ed25519`, `p256`, `p384`, `p521`, Possible values for `curve` are: `curve25519`, `ed25519`, `nistP256`, `nistP384`, `nistP521`,
`brainpoolP256r1`, `brainpoolP384r1`, `brainpoolP512r1`, and `secp256k1`. `brainpoolP256r1`, `brainpoolP384r1`, `brainpoolP512r1`, and `secp256k1`.
Note that both the `curve25519` and `ed25519` options generate a primary key for signing using Ed25519 Note that both the `curve25519` and `ed25519` options generate a primary key for signing using Ed25519
and a subkey for encryption using Curve25519. and a subkey for encryption using Curve25519.
@ -670,7 +661,7 @@ To create your own build of the library, just run the following command after cl
npm install && npm test npm install && npm test
For debugging browser errors, you can run `npm start` and open [`http://localhost:8080/test/unittests.html`](http://localhost:8080/test/unittests.html) in a browser, or run the following command: For debugging browser errors, run the following command:
npm run browsertest npm run browsertest

File diff suppressed because one or more lines are too long

986
docs/Argon2S2K.html Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

600
docs/PaddingPacket.html Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

184
docs/module-crypto.html Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

92
docs/module-key_User.html Normal file

File diff suppressed because one or more lines are too long

2891
docs/module-key_helper.html Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

178
docs/module-type_oid.html Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,968 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Class: S2K</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Class: S2K</h1>
<section>
<header>
<h2><span class="attribs"><span class="type-signature"></span></span>S2K<span class="signature">(config<span class="signature-attributes">opt</span>)</span><span class="type-signature"></span></h2>
</header>
<article>
<div class="container-overview">
<h4 class="name" id="S2K"><span class="type-signature"></span>new S2K<span class="signature">(config<span class="signature-attributes">opt</span>)</span><span class="type-signature"></span></h4>
<h5>Parameters:</h5>
<table class="params">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Attributes</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>config</code></td>
<td class="type">
<span class="param-type">Object</span>
</td>
<td class="attributes">
&lt;optional><br>
</td>
<td class="description last"><p>Full configuration, defaults to openpgp.config</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js">type/s2k.js</a>, <a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js#L41">line 41</a>
</li></ul></dd>
</dl>
</div>
<h3 class="subsection-title">Members</h3>
<h4 class="name" id="algorithm"><span class="type-signature"></span>algorithm<span class="type-signature"> :<a href="module-enums.html#.hash">module:enums.hash</a>|0</span></h4>
<div class="description">
<p>Hash function identifier, or 0 for gnu-dummy keys</p>
</div>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type"><a href="module-enums.html#.hash">module:enums.hash</a></span>
|
<span class="param-type">0</span>
</li>
</ul>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js">type/s2k.js</a>, <a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js#L46">line 46</a>
</li></ul></dd>
</dl>
<h4 class="name" id="c"><span class="type-signature"></span>c<span class="type-signature"> :Integer</span></h4>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type">Integer</span>
</li>
</ul>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js">type/s2k.js</a>, <a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js#L53">line 53</a>
</li></ul></dd>
</dl>
<h4 class="name" id="salt"><span class="type-signature"></span>salt<span class="type-signature"> :Uint8Array</span></h4>
<div class="description">
<p>Eight bytes of salt in a binary string.</p>
</div>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type">Uint8Array</span>
</li>
</ul>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js">type/s2k.js</a>, <a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js#L57">line 57</a>
</li></ul></dd>
</dl>
<h4 class="name" id="type"><span class="type-signature"></span>type<span class="type-signature"> :String</span></h4>
<div class="description">
<p>enums.s2k identifier or 'gnu-dummy'</p>
</div>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type">String</span>
</li>
</ul>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js">type/s2k.js</a>, <a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js#L51">line 51</a>
</li></ul></dd>
</dl>
<h3 class="subsection-title">Methods</h3>
<h4 class="name" id="produceKey"><span class="type-signature">(async) </span>produceKey<span class="signature">(passphrase)</span><span class="type-signature"> &rarr; {Promise.&lt;Uint8Array>}</span></h4>
<div class="description">
<p>Produces a key using the specified passphrase and the defined
hashAlgorithm</p>
</div>
<h5>Parameters:</h5>
<table class="params">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>passphrase</code></td>
<td class="type">
<span class="param-type">String</span>
</td>
<td class="description last"><p>Passphrase containing user input</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js">type/s2k.js</a>, <a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js#L157">line 157</a>
</li></ul></dd>
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Produced key with a length corresponding to.
hashAlgorithm hash length</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Promise.&lt;Uint8Array></span>
</dd>
</dl>
<h4 class="name" id="read"><span class="type-signature"></span>read<span class="signature">(bytes)</span><span class="type-signature"> &rarr; {Integer}</span></h4>
<div class="description">
<p>Parsing function for a string-to-key specifier (<a href="https://tools.ietf.org/html/rfc4880#section-3.7">RFC 4880 3.7</a>).</p>
</div>
<h5>Parameters:</h5>
<table class="params">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>bytes</code></td>
<td class="type">
<span class="param-type">Uint8Array</span>
</td>
<td class="description last"><p>Payload of string-to-key specifier</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js">type/s2k.js</a>, <a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js#L72">line 72</a>
</li></ul></dd>
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Actual length of the object.</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Integer</span>
</dd>
</dl>
<h4 class="name" id="write"><span class="type-signature"></span>write<span class="signature">()</span><span class="type-signature"> &rarr; {Uint8Array}</span></h4>
<div class="description">
<p>Serializes s2k information</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js">type/s2k.js</a>, <a href="https://github.com/openpgpjs/openpgpjs/blob/v5.11.2/src/type/s2k.js#L124">line 124</a>
</li></ul></dd>
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>Binary representation of s2k.</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Uint8Array</span>
</dd>
</dl>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Functions</h3><ul><li><a href="global.html#aes">aes</a></li><li><a href="global.html#armor">armor</a></li><li><a href="global.html#createCleartextMessage">createCleartextMessage</a></li><li><a href="global.html#createKey">createKey</a></li><li><a href="global.html#createMessage">createMessage</a></li><li><a href="global.html#decrypt">decrypt</a></li><li><a href="global.html#decryptKey">decryptKey</a></li><li><a href="global.html#decryptSessionKeys">decryptSessionKeys</a></li><li><a href="global.html#encrypt">encrypt</a></li><li><a href="global.html#encryptKey">encryptKey</a></li><li><a href="global.html#encryptSessionKey">encryptSessionKey</a></li><li><a href="global.html#formatObject">formatObject</a></li><li><a href="global.html#generateKey">generateKey</a></li><li><a href="global.html#generateSessionKey">generateSessionKey</a></li><li><a href="global.html#newPacketFromTag">newPacketFromTag</a></li><li><a href="global.html#readCleartextMessage">readCleartextMessage</a></li><li><a href="global.html#readKey">readKey</a></li><li><a href="global.html#readKeys">readKeys</a></li><li><a href="global.html#readMessage">readMessage</a></li><li><a href="global.html#readPrivateKey">readPrivateKey</a></li><li><a href="global.html#readPrivateKeys">readPrivateKeys</a></li><li><a href="global.html#readSignature">readSignature</a></li><li><a href="global.html#reformatKey">reformatKey</a></li><li><a href="global.html#revokeKey">revokeKey</a></li><li><a href="global.html#sign">sign</a></li><li><a href="global.html#unarmor">unarmor</a></li><li><a href="global.html#verify">verify</a></li><li><a href="global.html#wrapKeyObject">wrapKeyObject</a></li></ul><h3>Modules</h3><ul><li><a href="module-config.html">config</a></li><li><a href="module-enums.html">enums</a></li><li><a href="module-type_x25519x448_symkey.html">type/x25519x448_symkey</a></li></ul><h3>Classes</h3><ul><li><a href="AEADEncryptedDataPacket.html">AEADEncryptedDataPacket</a></li><li><a href="CleartextMessage.html">CleartextMessage</a></li><li><a href="CompressedDataPacket.html">CompressedDataPacket</a></li><li><a href="Key.html">Key</a></li><li><a href="LiteralDataPacket.html">LiteralDataPacket</a></li><li><a href="MarkerPacket.html">MarkerPacket</a></li><li><a href="Message.html">Message</a></li><li><a href="module-key_Subkey-Subkey.html">Subkey</a></li><li><a href="module-key_User-User.html">User</a></li><li><a href="module-type_kdf_params-KDFParams.html">KDFParams</a></li><li><a href="module-type_keyid-KeyID.html">KeyID</a></li><li><a href="module-type_s2k-S2K.html">S2K</a></li><li><a href="OnePassSignaturePacket.html">OnePassSignaturePacket</a></li><li><a href="PacketList.html">PacketList</a></li><li><a href="PrivateKey.html">PrivateKey</a></li><li><a href="PublicKey.html">PublicKey</a></li><li><a href="PublicKeyEncryptedSessionKeyPacket.html">PublicKeyEncryptedSessionKeyPacket</a></li><li><a href="PublicKeyPacket.html">PublicKeyPacket</a></li><li><a href="PublicSubkeyPacket.html">PublicSubkeyPacket</a></li><li><a href="SecretKeyPacket.html">SecretKeyPacket</a></li><li><a href="SecretSubkeyPacket.html">SecretSubkeyPacket</a></li><li><a href="Signature.html">Signature</a></li><li><a href="SignaturePacket.html">SignaturePacket</a></li><li><a href="SymEncryptedIntegrityProtectedDataPacket.html">SymEncryptedIntegrityProtectedDataPacket</a></li><li><a href="SymEncryptedSessionKeyPacket.html">SymEncryptedSessionKeyPacket</a></li><li><a href="SymmetricallyEncryptedDataPacket.html">SymmetricallyEncryptedDataPacket</a></li><li><a href="TrustPacket.html">TrustPacket</a></li><li><a href="UserAttributePacket.html">UserAttributePacket</a></li><li><a href="UserIDPacket.html">UserIDPacket</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.11</a>
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>

180
docs/module-type_s2k.html Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

167
docs/module-util.html Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,5 @@
{ {
"name": "openpgp-lightweight", "name": "openpgp-lightweight",
"main": "../dist/lightweight/openpgp.min.mjs", "browser": "../dist/lightweight/openpgp.min.mjs",
"types": "../openpgp.d.ts" "types": "../openpgp.d.ts"
} }

251
openpgp.d.ts vendored
View File

@ -1,3 +1,5 @@
/* eslint-disable max-lines, @typescript-eslint/indent */
/** /**
* Type definitions for OpenPGP.js http://openpgpjs.org/ * Type definitions for OpenPGP.js http://openpgpjs.org/
* *
@ -7,9 +9,19 @@
* - Errietta Kostala <https://github.com/errietta> * - Errietta Kostala <https://github.com/errietta>
*/ */
import type { WebStream as GenericWebStream, NodeStream as GenericNodeStream } from '@openpgp/web-stream-tools'; import type { WebStream as GenericWebStream, NodeWebStream as GenericNodeWebStream } from '@openpgp/web-stream-tools';
/* ############## v5 KEY #################### */ /* ############## STREAM #################### */
type Data = Uint8Array | string;
// web-stream-tools might end up supporting additional data types, so we re-declare the types
// to enforce the type contraint that we need.
export type WebStream<T extends Data> = GenericWebStream<T>;
export type NodeWebStream<T extends Data> = GenericNodeWebStream<T>;
export type Stream<T extends Data> = WebStream<T> | NodeWebStream<T>;
export type MaybeStream<T extends Data> = T | Stream<T>;
type MaybeArray<T> = T | Array<T>;
/* ############## KEY #################### */
// The Key and PublicKey types can be used interchangably since TS cannot detect the difference, as they have the same class properties. // The Key and PublicKey types can be used interchangably since TS cannot detect the difference, as they have the same class properties.
// The declared readKey(s) return type is Key instead of a PublicKey since it seems more obvious that a Key can be cast to a PrivateKey. // The declared readKey(s) return type is Key instead of a PublicKey since it seems more obvious that a Key can be cast to a PrivateKey.
export function readKey(options: { armoredKey: string, config?: PartialConfig }): Promise<Key>; export function readKey(options: { armoredKey: string, config?: PartialConfig }): Promise<Key>;
@ -54,8 +66,8 @@ export abstract class Key {
// NB: the order of the `update` declarations matters, since PublicKey includes PrivateKey // NB: the order of the `update` declarations matters, since PublicKey includes PrivateKey
public update(sourceKey: PrivateKey, date?: Date, config?: Config): Promise<PrivateKey>; public update(sourceKey: PrivateKey, date?: Date, config?: Config): Promise<PrivateKey>;
public update(sourceKey: PublicKey, date?: Date, config?: Config): Promise<PublicKey>; public update(sourceKey: PublicKey, date?: Date, config?: Config): Promise<PublicKey>;
public signPrimaryUser(privateKeys: PrivateKey[], date?: Date, userID?: UserID, config?: Config): Promise<this> public signPrimaryUser(privateKeys: PrivateKey[], date?: Date, userID?: UserID, config?: Config): Promise<this>;
public signAllUsers(privateKeys: PrivateKey[], date?: Date, config?: Config): Promise<this> public signAllUsers(privateKeys: PrivateKey[], date?: Date, config?: Config): Promise<this>;
public verifyPrimaryKey(date?: Date, userID?: UserID, config?: Config): Promise<void>; // throws on error public verifyPrimaryKey(date?: Date, userID?: UserID, config?: Config): Promise<void>; // throws on error
public verifyPrimaryUser(publicKeys: PublicKey[], date?: Date, userIDs?: UserID, config?: Config): Promise<{ keyID: KeyID, valid: boolean | null }[]>; public verifyPrimaryUser(publicKeys: PublicKey[], date?: Date, userIDs?: UserID, config?: Config): Promise<{ keyID: KeyID, valid: boolean | null }[]>;
public verifyAllUsers(publicKeys?: PublicKey[], date?: Date, config?: Config): Promise<{ userID: string, keyID: KeyID, valid: boolean | null }[]>; public verifyAllUsers(publicKeys?: PublicKey[], date?: Date, config?: Config): Promise<{ userID: string, keyID: KeyID, valid: boolean | null }[]>;
@ -82,7 +94,7 @@ export class PrivateKey extends PublicKey {
public revoke(reason?: ReasonForRevocation, date?: Date, config?: Config): Promise<PrivateKey>; public revoke(reason?: ReasonForRevocation, date?: Date, config?: Config): Promise<PrivateKey>;
public isDecrypted(): boolean; public isDecrypted(): boolean;
public addSubkey(options: SubkeyOptions): Promise<PrivateKey>; public addSubkey(options: SubkeyOptions): Promise<PrivateKey>;
public getDecryptionKeys(keyID?: KeyID, date?: Date | null, userID?: UserID, config?: Config): Promise<PrivateKey | Subkey> public getDecryptionKeys(keyID?: KeyID, date?: Date | null, userID?: UserID, config?: Config): Promise<PrivateKey | Subkey>;
public update(sourceKey: PublicKey, date?: Date, config?: Config): Promise<PrivateKey>; public update(sourceKey: PublicKey, date?: Date, config?: Config): Promise<PrivateKey>;
} }
@ -98,9 +110,9 @@ export class Subkey {
public getCreationTime(): Date; public getCreationTime(): Date;
public getAlgorithmInfo(): AlgorithmInfo; public getAlgorithmInfo(): AlgorithmInfo;
public getKeyID(): KeyID; public getKeyID(): KeyID;
public getExpirationTime(date?: Date, config?: Config): Promise<Date | typeof Infinity | null> public getExpirationTime(date?: Date, config?: Config): Promise<Date | typeof Infinity | null>;
public isRevoked(signature: SignaturePacket, key: AnyKeyPacket, date?: Date, config?: Config): Promise<boolean>; public isRevoked(signature: SignaturePacket, key: AnyKeyPacket, date?: Date, config?: Config): Promise<boolean>;
public update(subKey: Subkey, date?: Date, config?: Config): Promise<void> public update(subKey: Subkey, date?: Date, config?: Config): Promise<void>;
public revoke(primaryKey: SecretKeyPacket, reasonForRevocation?: ReasonForRevocation, date?: Date, config?: Config): Promise<Subkey>; public revoke(primaryKey: SecretKeyPacket, reasonForRevocation?: ReasonForRevocation, date?: Date, config?: Config): Promise<Subkey>;
} }
@ -118,13 +130,13 @@ export interface PrimaryUser {
selfCertification: SignaturePacket; selfCertification: SignaturePacket;
} }
type AlgorithmInfo = { export type AlgorithmInfo = {
algorithm: enums.publicKeyNames; algorithm: enums.publicKeyNames;
bits?: number; bits?: number;
curve?: EllipticCurveName; curve?: EllipticCurveName;
}; };
/* ############## v5 SIG #################### */ /* ############## SIG #################### */
export function readSignature(options: { armoredSignature: string, config?: PartialConfig }): Promise<Signature>; export function readSignature(options: { armoredSignature: string, config?: PartialConfig }): Promise<Signature>;
export function readSignature(options: { binarySignature: Uint8Array, config?: PartialConfig }): Promise<Signature>; export function readSignature(options: { binarySignature: Uint8Array, config?: PartialConfig }): Promise<Signature>;
@ -143,7 +155,7 @@ interface VerificationResult {
signature: Promise<Signature>; signature: Promise<Signature>;
} }
/* ############## v5 CLEARTEXT #################### */ /* ############## CLEARTEXT #################### */
export function readCleartextMessage(options: { cleartextMessage: string, config?: PartialConfig }): Promise<CleartextMessage>; export function readCleartextMessage(options: { cleartextMessage: string, config?: PartialConfig }): Promise<CleartextMessage>;
@ -176,12 +188,12 @@ export class CleartextMessage {
verify(keys: PublicKey[], date?: Date, config?: Config): Promise<VerificationResult[]>; verify(keys: PublicKey[], date?: Date, config?: Config): Promise<VerificationResult[]>;
} }
/* ############## v5 MSG #################### */ /* ############## MSG #################### */
export function generateSessionKey(options: { encryptionKeys: MaybeArray<PublicKey>, date?: Date, encryptionUserIDs?: MaybeArray<UserID>, config?: PartialConfig }): Promise<SessionKey>; export function generateSessionKey(options: { encryptionKeys: MaybeArray<PublicKey>, date?: Date, encryptionUserIDs?: MaybeArray<UserID>, config?: PartialConfig }): Promise<SessionKey>;
export function encryptSessionKey(options: EncryptSessionKeyOptions & { format?: 'armored' }): Promise<string>; export function encryptSessionKey(options: EncryptSessionKeyOptions & { format?: 'armored' }): Promise<string>;
export function encryptSessionKey(options: EncryptSessionKeyOptions & { format: 'binary' }): Promise<Uint8Array>; export function encryptSessionKey(options: EncryptSessionKeyOptions & { format: 'binary' }): Promise<Uint8Array>;
export function encryptSessionKey(options: EncryptSessionKeyOptions & { format: 'object' }): Promise<Message<Data>>; export function encryptSessionKey(options: EncryptSessionKeyOptions & { format: 'object' }): Promise<Message<Data>>;
export function decryptSessionKeys<T extends MaybeStream<Data>>(options: { message: Message<T>, decryptionKeys?: MaybeArray<PrivateKey>, passwords?: MaybeArray<string>, date?: Date, config?: PartialConfig }): Promise<SessionKey[]>; export function decryptSessionKeys<T extends MaybeStream<Data>>(options: { message: Message<T>, decryptionKeys?: MaybeArray<PrivateKey>, passwords?: MaybeArray<string>, date?: Date, config?: PartialConfig }): Promise<DecryptedSessionKey[]>;
export function readMessage<T extends MaybeStream<string>>(options: { armoredMessage: T, config?: PartialConfig }): Promise<Message<T>>; export function readMessage<T extends MaybeStream<string>>(options: { armoredMessage: T, config?: PartialConfig }): Promise<Message<T>>;
export function readMessage<T extends MaybeStream<Uint8Array>>(options: { binaryMessage: T, config?: PartialConfig }): Promise<Message<T>>; export function readMessage<T extends MaybeStream<Uint8Array>>(options: { binaryMessage: T, config?: PartialConfig }): Promise<Message<T>>;
@ -190,25 +202,25 @@ export function createMessage<T extends MaybeStream<string>>(options: { text: T,
export function createMessage<T extends MaybeStream<Uint8Array>>(options: { binary: T, filename?: string, date?: Date, format?: enums.literalFormatNames }): Promise<Message<T>>; export function createMessage<T extends MaybeStream<Uint8Array>>(options: { binary: T, filename?: string, date?: Date, format?: enums.literalFormatNames }): Promise<Message<T>>;
export function encrypt<T extends MaybeStream<Data>>(options: EncryptOptions & { message: Message<T>, format?: 'armored' }): Promise< export function encrypt<T extends MaybeStream<Data>>(options: EncryptOptions & { message: Message<T>, format?: 'armored' }): Promise<
T extends WebStream<infer X> ? WebStream<string> : T extends WebStream<Data> ? WebStream<string> :
T extends NodeStream<infer X> ? NodeStream<string> : T extends NodeWebStream<Data> ? NodeWebStream<string> :
string string
>; >;
export function encrypt<T extends MaybeStream<Data>>(options: EncryptOptions & { message: Message<T>, format: 'binary' }): Promise< export function encrypt<T extends MaybeStream<Data>>(options: EncryptOptions & { message: Message<T>, format: 'binary' }): Promise<
T extends WebStream<infer X> ? WebStream<Uint8Array> : T extends WebStream<Data> ? WebStream<Uint8Array> :
T extends NodeStream<infer X> ? NodeStream<Uint8Array> : T extends NodeWebStream<Data> ? NodeWebStream<Uint8Array> :
Uint8Array Uint8Array
>; >;
export function encrypt<T extends MaybeStream<Data>>(options: EncryptOptions & { message: Message<T>, format: 'object' }): Promise<Message<T>>; export function encrypt<T extends MaybeStream<Data>>(options: EncryptOptions & { message: Message<T>, format: 'object' }): Promise<Message<T>>;
export function sign<T extends MaybeStream<Data>>(options: SignOptions & { message: Message<T>, format?: 'armored' }): Promise< export function sign<T extends MaybeStream<Data>>(options: SignOptions & { message: Message<T>, format?: 'armored' }): Promise<
T extends WebStream<infer X> ? WebStream<string> : T extends WebStream<Data> ? WebStream<string> :
T extends NodeStream<infer X> ? NodeStream<string> : T extends NodeWebStream<Data> ? NodeWebStream<string> :
string string
>; >;
export function sign<T extends MaybeStream<Data>>(options: SignOptions & { message: Message<T>, format: 'binary' }): Promise< export function sign<T extends MaybeStream<Data>>(options: SignOptions & { message: Message<T>, format: 'binary' }): Promise<
T extends WebStream<infer X> ? WebStream<Uint8Array> : T extends WebStream<Data> ? WebStream<Uint8Array> :
T extends NodeStream<infer X> ? NodeStream<Uint8Array> : T extends NodeWebStream<Data> ? NodeWebStream<Uint8Array> :
Uint8Array Uint8Array
>; >;
export function sign<T extends MaybeStream<Data>>(options: SignOptions & { message: Message<T>, format: 'object' }): Promise<Message<T>>; export function sign<T extends MaybeStream<Data>>(options: SignOptions & { message: Message<T>, format: 'object' }): Promise<Message<T>>;
@ -217,26 +229,26 @@ export function sign(options: SignOptions & { message: CleartextMessage, format:
export function decrypt<T extends MaybeStream<Data>>(options: DecryptOptions & { message: Message<T>, format: 'binary' }): Promise<DecryptMessageResult & { export function decrypt<T extends MaybeStream<Data>>(options: DecryptOptions & { message: Message<T>, format: 'binary' }): Promise<DecryptMessageResult & {
data: data:
T extends WebStream<infer X> ? WebStream<Uint8Array> : T extends WebStream<Data> ? WebStream<Uint8Array> :
T extends NodeStream<infer X> ? NodeStream<Uint8Array> : T extends NodeWebStream<Data> ? NodeWebStream<Uint8Array> :
Uint8Array Uint8Array
}>; }>;
export function decrypt<T extends MaybeStream<Data>>(options: DecryptOptions & { message: Message<T> }): Promise<DecryptMessageResult & { export function decrypt<T extends MaybeStream<Data>>(options: DecryptOptions & { message: Message<T> }): Promise<DecryptMessageResult & {
data: data:
T extends WebStream<infer X> ? WebStream<string> : T extends WebStream<Data> ? WebStream<string> :
T extends NodeStream<infer X> ? NodeStream<string> : T extends NodeWebStream<Data> ? NodeWebStream<string> :
string string
}>; }>;
export function verify(options: VerifyOptions & { message: CleartextMessage, format?: 'utf8' }): Promise<VerifyMessageResult<string>>; export function verify(options: VerifyOptions & { message: CleartextMessage, format?: 'utf8' }): Promise<VerifyMessageResult<string>>;
export function verify<T extends MaybeStream<Data>>(options: VerifyOptions & { message: Message<T>, format: 'binary' }): Promise<VerifyMessageResult< export function verify<T extends MaybeStream<Data>>(options: VerifyOptions & { message: Message<T>, format: 'binary' }): Promise<VerifyMessageResult<
T extends WebStream<infer X> ? WebStream<Uint8Array> : T extends WebStream<Data> ? WebStream<Uint8Array> :
T extends NodeStream<infer X> ? NodeStream<Uint8Array> : T extends NodeWebStream<Data> ? NodeWebStream<Uint8Array> :
Uint8Array Uint8Array
>>; >>;
export function verify<T extends MaybeStream<Data>>(options: VerifyOptions & { message: Message<T> }): Promise<VerifyMessageResult< export function verify<T extends MaybeStream<Data>>(options: VerifyOptions & { message: Message<T> }): Promise<VerifyMessageResult<
T extends WebStream<infer X> ? WebStream<string> : T extends WebStream<Data> ? WebStream<string> :
T extends NodeStream<infer X> ? NodeStream<string> : T extends NodeWebStream<Data> ? NodeWebStream<string> :
string string
>>; >>;
@ -305,7 +317,7 @@ export class Message<T extends MaybeStream<Data>> {
} }
/* ############## v5 CONFIG #################### */ /* ############## CONFIG #################### */
interface Config { interface Config {
preferredHashAlgorithm: enums.hash; preferredHashAlgorithm: enums.hash;
@ -313,44 +325,44 @@ interface Config {
preferredCompressionAlgorithm: enums.compression; preferredCompressionAlgorithm: enums.compression;
showVersion: boolean; showVersion: boolean;
showComment: boolean; showComment: boolean;
deflateLevel: number;
aeadProtect: boolean; aeadProtect: boolean;
allowUnauthenticatedMessages: boolean; allowUnauthenticatedMessages: boolean;
allowUnauthenticatedStream: boolean; allowUnauthenticatedStream: boolean;
checksumRequired: boolean;
minRSABits: number; minRSABits: number;
passwordCollisionCheck: boolean; passwordCollisionCheck: boolean;
revocationsExpire: boolean;
ignoreUnsupportedPackets: boolean; ignoreUnsupportedPackets: boolean;
ignoreMalformedPackets: boolean; ignoreMalformedPackets: boolean;
versionString: string; versionString: string;
commentString: string; commentString: string;
allowInsecureDecryptionWithSigningKeys: boolean; allowInsecureDecryptionWithSigningKeys: boolean;
allowInsecureVerificationWithReformattedKeys: boolean; allowInsecureVerificationWithReformattedKeys: boolean;
allowMissingKeyFlags: boolean;
constantTimePKCS1Decryption: boolean; constantTimePKCS1Decryption: boolean;
constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: Set<enums.symmetric>; constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: Set<enums.symmetric>;
v5Keys: boolean; v6Keys: boolean;
enableParsingV5Entities: boolean;
preferredAEADAlgorithm: enums.aead; preferredAEADAlgorithm: enums.aead;
aeadChunkSizeByte: number; aeadChunkSizeByte: number;
s2kType: enums.s2k.iterated | enums.s2k.argon2;
s2kIterationCountByte: number; s2kIterationCountByte: number;
minBytesForWebCrypto: number; s2kArgon2Params: { passes: number, parallelism: number; memoryExponent: number; };
maxUserIDLength: number; maxUserIDLength: number;
knownNotations: string[]; knownNotations: string[];
useIndutnyElliptic: boolean; useEllipticFallback: boolean;
rejectHashAlgorithms: Set<enums.hash>; rejectHashAlgorithms: Set<enums.hash>;
rejectMessageHashAlgorithms: Set<enums.hash>; rejectMessageHashAlgorithms: Set<enums.hash>;
rejectPublicKeyAlgorithms: Set<enums.publicKey>; rejectPublicKeyAlgorithms: Set<enums.publicKey>;
rejectCurves: Set<enums.curve>; rejectCurves: Set<enums.curve>;
} }
export var config: Config; export const config: Config;
// PartialConfig has the same properties as Config, but declared as optional. // PartialConfig has the same properties as Config, but declared as optional.
// This interface is relevant for top-level functions, which accept a subset of configuration options // This interface is relevant for top-level functions, which accept a subset of configuration options
interface PartialConfig extends Partial<Config> {} export interface PartialConfig extends Partial<Config> {}
/* ############## v5 PACKET #################### */ /* ############## PACKET #################### */
declare abstract class BasePacket { export declare abstract class BasePacket {
static readonly tag: enums.packet; static readonly tag: enums.packet;
public read(bytes: Uint8Array): void; public read(bytes: Uint8Array): void;
public write(): Uint8Array; public write(): Uint8Array;
@ -423,7 +435,7 @@ export class AEADEncryptedDataPacket extends BasePacket {
static readonly tag: enums.packet.aeadEncryptedData; static readonly tag: enums.packet.aeadEncryptedData;
private decrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void; private decrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void;
private encrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void; private encrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void;
private crypt(fn: Function, sessionKey: Uint8Array, data: MaybeStream<Uint8Array>): MaybeStream<Uint8Array> private crypt(fn: Function, sessionKey: Uint8Array, data: MaybeStream<Uint8Array>): MaybeStream<Uint8Array>;
} }
export class PublicKeyEncryptedSessionKeyPacket extends BasePacket { export class PublicKeyEncryptedSessionKeyPacket extends BasePacket {
@ -486,7 +498,8 @@ export class SignaturePacket extends BasePacket {
public hashAlgorithm: enums.hash | null; public hashAlgorithm: enums.hash | null;
public publicKeyAlgorithm: enums.publicKey | null; public publicKeyAlgorithm: enums.publicKey | null;
public signatureData: null | Uint8Array; public signatureData: null | Uint8Array;
public unhashedSubpackets: null | Uint8Array; public unhashedSubpackets: RawSubpacket[];
public unknownSubpackets: RawSubpacket[];
public signedHashValue: null | Uint8Array; public signedHashValue: null | Uint8Array;
public created: Date | null; public created: Date | null;
public signatureExpirationTime: null | number; public signatureExpirationTime: null | number;
@ -530,6 +543,12 @@ export class SignaturePacket extends BasePacket {
public getExpirationTime(): Date | typeof Infinity; public getExpirationTime(): Date | typeof Infinity;
} }
export interface RawSubpacket {
type: number;
critical: boolean;
body: Uint8Array;
}
export interface RawNotation { export interface RawNotation {
name: string; name: string;
value: Uint8Array; value: Uint8Array;
@ -560,16 +579,7 @@ export class PacketList<T extends AnyPacket> extends Array<T> {
public findPacket(tag: enums.packet): T | undefined; public findPacket(tag: enums.packet): T | undefined;
} }
/* ############## v5 STREAM #################### */ /* ############## GENERAL #################### */
type Data = Uint8Array | string;
export interface WebStream<T extends Data> extends GenericWebStream<T> {}
export interface NodeStream<T extends Data> extends GenericNodeStream<T> {}
export type Stream<T extends Data> = WebStream<T> | NodeStream<T>;
export type MaybeStream<T extends Data> = T | Stream<T>;
/* ############## v5 GENERAL #################### */
type MaybeArray<T> = T | Array<T>;
export interface UserID { name?: string; email?: string; comment?: string; } export interface UserID { name?: string; email?: string; comment?: string; }
export interface SessionKey { export interface SessionKey {
@ -578,9 +588,14 @@ export interface SessionKey {
aeadAlgorithm?: enums.aeadNames; aeadAlgorithm?: enums.aeadNames;
} }
export interface DecryptedSessionKey {
data: Uint8Array;
algorithm: enums.symmetricNames | null; // `null` if the session key is associated with a SEIPDv2 packet
}
export interface ReasonForRevocation { flag?: enums.reasonForRevocation, string?: string } export interface ReasonForRevocation { flag?: enums.reasonForRevocation, string?: string }
interface EncryptOptions { export interface EncryptOptions {
/** message to be encrypted as created by createMessage */ /** message to be encrypted as created by createMessage */
message: Message<MaybeStream<Data>>; message: Message<MaybeStream<Data>>;
/** (optional) array of keys or single key, used to encrypt the message */ /** (optional) array of keys or single key, used to encrypt the message */
@ -612,7 +627,7 @@ interface EncryptOptions {
config?: PartialConfig; config?: PartialConfig;
} }
interface DecryptOptions { export interface DecryptOptions {
/** the message object with the encrypted data */ /** the message object with the encrypted data */
message: Message<MaybeStream<Data>>; message: Message<MaybeStream<Data>>;
/** (optional) private keys with decrypted secret key data or session key */ /** (optional) private keys with decrypted secret key data or session key */
@ -634,7 +649,7 @@ interface DecryptOptions {
config?: PartialConfig; config?: PartialConfig;
} }
interface SignOptions { export interface SignOptions {
message: CleartextMessage | Message<MaybeStream<Data>>; message: CleartextMessage | Message<MaybeStream<Data>>;
signingKeys: MaybeArray<PrivateKey>; signingKeys: MaybeArray<PrivateKey>;
format?: 'armored' | 'binary' | 'object'; format?: 'armored' | 'binary' | 'object';
@ -646,7 +661,7 @@ interface SignOptions {
config?: PartialConfig; config?: PartialConfig;
} }
interface VerifyOptions { export interface VerifyOptions {
/** (cleartext) message object with signatures */ /** (cleartext) message object with signatures */
message: CleartextMessage | Message<MaybeStream<Data>>; message: CleartextMessage | Message<MaybeStream<Data>>;
/** array of publicKeys or single key, to verify signatures */ /** array of publicKeys or single key, to verify signatures */
@ -662,7 +677,7 @@ interface VerifyOptions {
config?: PartialConfig; config?: PartialConfig;
} }
interface EncryptSessionKeyOptions extends SessionKey { export interface EncryptSessionKeyOptions extends SessionKey {
encryptionKeys?: MaybeArray<PublicKey>, encryptionKeys?: MaybeArray<PublicKey>,
passwords?: MaybeArray<string>, passwords?: MaybeArray<string>,
format?: 'armored' | 'binary' | 'object', format?: 'armored' | 'binary' | 'object',
@ -673,7 +688,7 @@ interface EncryptSessionKeyOptions extends SessionKey {
config?: PartialConfig config?: PartialConfig
} }
interface SerializedKeyPair<T extends string|Uint8Array> { interface SerializedKeyPair<T extends string | Uint8Array> {
privateKey: T; privateKey: T;
publicKey: T; publicKey: T;
} }
@ -682,7 +697,7 @@ interface KeyPair {
publicKey: PublicKey; publicKey: PublicKey;
} }
export type EllipticCurveName = 'ed25519' | 'curve25519' | 'p256' | 'p384' | 'p521' | 'secp256k1' | 'brainpoolP256r1' | 'brainpoolP384r1' | 'brainpoolP512r1'; export type EllipticCurveName = 'ed25519Legacy' | 'curve25519Legacy' | 'nistP256' | 'nistP384' | 'nistP521' | 'secp256k1' | 'brainpoolP256r1' | 'brainpoolP384r1' | 'brainpoolP512r1';
interface GenerateKeyOptions { interface GenerateKeyOptions {
userIDs: MaybeArray<UserID>; userIDs: MaybeArray<UserID>;
@ -698,7 +713,7 @@ interface GenerateKeyOptions {
} }
export type KeyOptions = GenerateKeyOptions; export type KeyOptions = GenerateKeyOptions;
interface SubkeyOptions { export interface SubkeyOptions {
type?: 'ecc' | 'rsa'; type?: 'ecc' | 'rsa';
curve?: EllipticCurveName; curve?: EllipticCurveName;
rsaBits?: number; rsaBits?: number;
@ -708,20 +723,20 @@ interface SubkeyOptions {
config?: PartialConfig; config?: PartialConfig;
} }
declare class KeyID { export declare class KeyID {
bytes: string; bytes: string;
equals(keyID: KeyID, matchWildcard?: boolean): boolean; equals(keyID: KeyID, matchWildcard?: boolean): boolean;
toHex(): string; toHex(): string;
static fromID(hex: string): KeyID; static fromID(hex: string): KeyID;
} }
interface DecryptMessageResult { export interface DecryptMessageResult {
data: MaybeStream<Data>; data: MaybeStream<Data>;
signatures: VerificationResult[]; signatures: VerificationResult[];
filename: string; filename: string;
} }
interface VerifyMessageResult<T extends MaybeStream<Data> = MaybeStream<Data>> { export interface VerifyMessageResult<T extends MaybeStream<Data> = MaybeStream<Data>> {
data: T; data: T;
signatures: VerificationResult[]; signatures: VerificationResult[];
} }
@ -730,7 +745,7 @@ interface VerifyMessageResult<T extends MaybeStream<Data> = MaybeStream<Data>> {
/** /**
* Armor an OpenPGP binary packet block * Armor an OpenPGP binary packet block
*/ */
export function armor(messagetype: enums.armor, body: object, partindex?: number, parttotal?: number, customComment?: string, config?: Config): string; export function armor(messagetype: enums.armor, body: object, partindex?: number, parttotal?: number, customComment?: string, emitChecksum?: boolean, config?: Config): string;
/** /**
* DeArmor an OpenPGP armored message; verify the checksum and return the encoded bytes * DeArmor an OpenPGP armored message; verify the checksum and return the encoded bytes
@ -740,44 +755,44 @@ export function unarmor(input: string, config?: Config): Promise<{ text: string,
/* ############## v5 ENUMS #################### */ /* ############## v5 ENUMS #################### */
export namespace enums { export namespace enums {
function read(type: typeof armor, e: armor): armorNames; export function read(type: typeof armor, e: armor): armorNames;
function read(type: typeof compression, e: compression): compressionNames; export function read(type: typeof compression, e: compression): compressionNames;
function read(type: typeof hash, e: hash): hashNames; export function read(type: typeof hash, e: hash): hashNames;
function read(type: typeof packet, e: packet): packetNames; export function read(type: typeof packet, e: packet): packetNames;
function read(type: typeof publicKey, e: publicKey): publicKeyNames; export function read(type: typeof publicKey, e: publicKey): publicKeyNames;
function read(type: typeof symmetric, e: symmetric): symmetricNames; export function read(type: typeof symmetric, e: symmetric): symmetricNames;
function read(type: typeof keyStatus, e: keyStatus): keyStatusNames; export function read(type: typeof keyStatus, e: keyStatus): keyStatusNames;
function read(type: typeof keyFlags, e: keyFlags): keyFlagsNames; export function read(type: typeof keyFlags, e: keyFlags): keyFlagsNames;
export type armorNames = 'multipartSection' | 'multipartLast' | 'signed' | 'message' | 'publicKey' | 'privateKey'; export type armorNames = 'multipartSection' | 'multipartLast' | 'signed' | 'message' | 'publicKey' | 'privateKey';
enum armor { export enum armor {
multipartSection = 0, multipartSection = 0,
multipartLast = 1, multipartLast = 1,
signed = 2, signed = 2,
message = 3, message = 3,
publicKey = 4, publicKey = 4,
privateKey = 5, privateKey = 5,
signature = 6, signature = 6
} }
enum reasonForRevocation { export enum reasonForRevocation {
noReason = 0, // No reason specified (key revocations or cert revocations) noReason = 0, // No reason specified (key revocations or cert revocations)
keySuperseded = 1, // Key is superseded (key revocations) keySuperseded = 1, // Key is superseded (key revocations)
keyCompromised = 2, // Key material has been compromised (key revocations) keyCompromised = 2, // Key material has been compromised (key revocations)
keyRetired = 3, // Key is retired and no longer used (key revocations) keyRetired = 3, // Key is retired and no longer used (key revocations)
userIDInvalid = 32, // User ID information is no longer valid (cert revocations) userIDInvalid = 32 // User ID information is no longer valid (cert revocations)
} }
export type compressionNames = 'uncompressed' | 'zip' | 'zlib' | 'bzip2'; export type compressionNames = 'uncompressed' | 'zip' | 'zlib' | 'bzip2';
enum compression { export enum compression {
uncompressed = 0, uncompressed = 0,
zip = 1, zip = 1,
zlib = 2, zlib = 2,
bzip2 = 3, bzip2 = 3
} }
export type hashNames = 'md5' | 'sha1' | 'ripemd' | 'sha256' | 'sha384' | 'sha512' | 'sha224'; export type hashNames = 'md5' | 'sha1' | 'ripemd' | 'sha256' | 'sha384' | 'sha512' | 'sha224' | 'sha3_256' | 'sha3_512';
enum hash { export enum hash {
md5 = 1, md5 = 1,
sha1 = 2, sha1 = 2,
ripemd = 3, ripemd = 3,
@ -785,12 +800,14 @@ export namespace enums {
sha384 = 9, sha384 = 9,
sha512 = 10, sha512 = 10,
sha224 = 11, sha224 = 11,
sha3_256 = 12,
sha3_512 = 14
} }
export type packetNames = 'publicKeyEncryptedSessionKey' | 'signature' | 'symEncryptedSessionKey' | 'onePassSignature' | 'secretKey' | 'publicKey' export type packetNames = 'publicKeyEncryptedSessionKey' | 'signature' | 'symEncryptedSessionKey' | 'onePassSignature' | 'secretKey' | 'publicKey' |
| 'secretSubkey' | 'compressed' | 'symmetricallyEncrypted' | 'marker' | 'literal' | 'trust' | 'userID' | 'publicSubkey' | 'userAttribute' 'secretSubkey' | 'compressed' | 'symmetricallyEncrypted' | 'marker' | 'literal' | 'trust' | 'userID' | 'publicSubkey' | 'userAttribute' |
| 'symEncryptedIntegrityProtected' | 'modificationDetectionCode' | 'AEADEncryptedDataPacket'; 'symEncryptedIntegrityProtected' | 'modificationDetectionCode' | 'AEADEncryptedDataPacket';
enum packet { export enum packet {
publicKeyEncryptedSessionKey = 1, publicKeyEncryptedSessionKey = 1,
signature = 2, signature = 2,
symEncryptedSessionKey = 3, symEncryptedSessionKey = 3,
@ -808,11 +825,11 @@ export namespace enums {
userAttribute = 17, userAttribute = 17,
symEncryptedIntegrityProtectedData = 18, symEncryptedIntegrityProtectedData = 18,
modificationDetectionCode = 19, modificationDetectionCode = 19,
aeadEncryptedData = 20, aeadEncryptedData = 20
} }
export type publicKeyNames = 'rsaEncryptSign' | 'rsaEncrypt' | 'rsaSign' | 'elgamal' | 'dsa' | 'ecdh' | 'ecdsa' | 'eddsa' | 'aedh' | 'aedsa'; export type publicKeyNames = 'rsaEncryptSign' | 'rsaEncrypt' | 'rsaSign' | 'elgamal' | 'dsa' | 'ecdh' | 'ecdsa' | 'eddsaLegacy' | 'aedh' | 'aedsa' | 'ed25519' | 'x25519' | 'ed448' | 'x448';
enum publicKey { export enum publicKey {
rsaEncryptSign = 1, rsaEncryptSign = 1,
rsaEncrypt = 2, rsaEncrypt = 2,
rsaSign = 3, rsaSign = 3,
@ -820,32 +837,39 @@ export namespace enums {
dsa = 17, dsa = 17,
ecdh = 18, ecdh = 18,
ecdsa = 19, ecdsa = 19,
/** @deprecated use `eddsaLegacy` instead */
eddsa = 22,
eddsaLegacy = 22, eddsaLegacy = 22,
aedh = 23, aedh = 23,
aedsa = 24, aedsa = 24,
x25519 = 25,
x448 = 26,
ed25519 = 27,
ed448 = 28
} }
enum curve { export enum curve {
p256 = 'p256', /** @deprecated use `nistP256` instead */
p384 = 'p384', p256 = 'nistP256',
p521 = 'p521', nistP256 = 'nistP256',
/** @deprecated use `nistP384` instead */
p384 = 'nistP384',
nistP384 = 'nistP384',
/** @deprecated use `nistP521` instead */
p521 = 'nistP521',
nistP521 = 'nistP521',
/** @deprecated use `ed25519Legacy` instead */ /** @deprecated use `ed25519Legacy` instead */
ed25519 = 'ed25519', ed25519 = 'ed25519Legacy',
ed25519Legacy = 'ed25519', ed25519Legacy = 'ed25519Legacy',
/** @deprecated use `curve25519Legacy` instead */ /** @deprecated use `curve25519Legacy` instead */
curve25519 = 'curve25519', curve25519 = 'curve25519Legacy',
curve25519Legacy = 'curve25519', curve25519Legacy = 'curve25519Legacy',
secp256k1 = 'secp256k1', secp256k1 = 'secp256k1',
brainpoolP256r1 = 'brainpoolP256r1', brainpoolP256r1 = 'brainpoolP256r1',
brainpoolP384r1 = 'brainpoolP384r1', brainpoolP384r1 = 'brainpoolP384r1',
brainpoolP512r1 = 'brainpoolP512r1' brainpoolP512r1 = 'brainpoolP512r1'
} }
export type symmetricNames = 'plaintext' | 'idea' | 'tripledes' | 'cast5' | 'blowfish' | 'aes128' | 'aes192' | 'aes256' | 'twofish'; export type symmetricNames = 'idea' | 'tripledes' | 'cast5' | 'blowfish' | 'aes128' | 'aes192' | 'aes256' | 'twofish';
enum symmetric { export enum symmetric {
plaintext = 0,
idea = 1, idea = 1,
tripledes = 2, tripledes = 2,
cast5 = 3, cast5 = 3,
@ -853,31 +877,30 @@ export namespace enums {
aes128 = 7, aes128 = 7,
aes192 = 8, aes192 = 8,
aes256 = 9, aes256 = 9,
twofish = 10, twofish = 10
} }
export type keyStatusNames = 'invalid' | 'expired' | 'revoked' | 'valid' | 'noSelfCert'; export type keyStatusNames = 'invalid' | 'expired' | 'revoked' | 'valid' | 'noSelfCert';
enum keyStatus { export enum keyStatus {
invalid = 0, invalid = 0,
expired = 1, expired = 1,
revoked = 2, revoked = 2,
valid = 3, valid = 3,
noSelfCert = 4, noSelfCert = 4
} }
export type keyFlagsNames = 'certifyKeys' | 'signData' | 'encryptCommunication' | 'encryptStorage' | 'splitPrivateKey' | 'authentication' export type keyFlagsNames = 'certifyKeys' | 'signData' | 'encryptCommunication' | 'encryptStorage' | 'splitPrivateKey' | 'authentication' | 'sharedPrivateKey';
| 'sharedPrivateKey'; export enum keyFlags {
enum keyFlags {
certifyKeys = 1, certifyKeys = 1,
signData = 2, signData = 2,
encryptCommunication = 4, encryptCommunication = 4,
encryptStorage = 8, encryptStorage = 8,
splitPrivateKey = 16, splitPrivateKey = 16,
authentication = 32, authentication = 32,
sharedPrivateKey = 128, sharedPrivateKey = 128
} }
enum signature { export enum signature {
binary = 0, binary = 0,
text = 1, text = 1,
standalone = 2, standalone = 2,
@ -896,17 +919,25 @@ export namespace enums {
} }
export type aeadNames = 'eax' | 'ocb' | 'gcm'; export type aeadNames = 'eax' | 'ocb' | 'gcm';
enum aead { export enum aead {
eax = 1, eax = 1,
ocb = 2, ocb = 2,
experimentalGCM = 100 // Private algorithm experimentalGCM = 100 // Private algorithm
} }
export type literalFormatNames = 'utf8' | 'binary' | 'text' | 'mime' export type literalFormatNames = 'utf8' | 'binary' | 'text' | 'mime';
enum literal { export enum literal {
binary = 98, binary = 98,
text = 116, text = 116,
utf8 = 117, utf8 = 117,
mime = 109 mime = 109
} }
export enum s2k {
simple = 0,
salted = 1,
iterated = 3,
argon2 = 4,
gnu = 101
}
} }

18340
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,11 @@
{ {
"name": "openpgp", "name": "openpgp",
"description": "OpenPGP.js is a Javascript implementation of the OpenPGP protocol. This is defined in RFC 4880.", "description": "OpenPGP.js is a Javascript implementation of the OpenPGP protocol. This is defined in RFC 4880.",
"version": "5.11.2", "version": "6.0.0-beta.3.patch.1",
"license": "LGPL-3.0+", "license": "LGPL-3.0+",
"homepage": "https://openpgpjs.org/", "homepage": "https://openpgpjs.org/",
"engines": { "engines": {
"node": ">= 8.0.0" "node": ">= 18.0.0"
}, },
"keywords": [ "keywords": [
"crypto", "crypto",
@ -13,13 +13,26 @@
"gpg", "gpg",
"openpgp" "openpgp"
], ],
"main": "dist/node/openpgp.min.js", "main": "dist/node/openpgp.min.cjs",
"module": "dist/node/openpgp.min.mjs", "module": "dist/node/openpgp.min.mjs",
"browser": { "browser": {
"./dist/node/openpgp.min.js": "./dist/openpgp.min.js", "./dist/node/openpgp.min.cjs": "./dist/openpgp.min.js",
"./dist/node/openpgp.min.mjs": "./dist/openpgp.min.mjs" "./dist/node/openpgp.min.mjs": "./dist/openpgp.min.mjs"
}, },
"exports": {
".": {
"types": "./openpgp.d.ts",
"import": "./dist/node/openpgp.mjs",
"require": "./dist/node/openpgp.min.cjs",
"browser": "./dist/openpgp.min.mjs"
},
"./lightweight": {
"types": "./openpgp.d.ts",
"browser": "./dist/lightweight/openpgp.min.mjs"
}
},
"types": "openpgp.d.ts", "types": "openpgp.d.ts",
"type": "module",
"directories": { "directories": {
"lib": "src" "lib": "src"
}, },
@ -28,74 +41,76 @@
"lightweight/", "lightweight/",
"openpgp.d.ts" "openpgp.d.ts"
], ],
"esm": {
"cjs": {
"dedefault": true
}
},
"scripts": { "scripts": {
"build": "rollup --config", "build": "rollup --config",
"build-test": "npm run build --build-only=test", "build-test": "npm run build --build-only=test",
"prepare": "npm run build", "prepare": "npm run build",
"test": "mocha --require esm --timeout 120000 test/unittests.js", "test": "mocha --timeout 120000 test/unittests.js",
"test-type-definitions": "tsc test/typescript/definitions.ts && node test/typescript/definitions.js", "test-type-definitions": "tsx test/typescript/definitions.ts",
"benchmark-time": "node test/benchmarks/time.js", "benchmark-time": "node test/benchmarks/time.js",
"benchmark-memory-usage": "node --require esm test/benchmarks/memory_usage.js", "benchmark-memory-usage": "node test/benchmarks/memory_usage.js",
"start": "http-server",
"prebrowsertest": "npm run build-test", "prebrowsertest": "npm run build-test",
"browsertest": "npm start -- -o test/unittests.html", "browsertest": "web-test-runner --config test/web-test-runner.config.js --group local --manual --open",
"test-browser": "karma start test/karma.conf.js", "test-browser": "web-test-runner --config test/web-test-runner.config.js --group local --playwright --browsers chromium firefox webkit",
"test-browserstack": "karma start test/karma.conf.js --browsers bs_safari_latest,bs_ios_14,bs_safari_13_1", "test-browser:ci": "web-test-runner --config test/web-test-runner.config.js --group headless:ci",
"coverage": "nyc npm test", "test-browserstack": "web-test-runner --config test/web-test-runner.browserstack.config.js",
"coverage": "c8 npm test",
"lint": "eslint .", "lint": "eslint .",
"docs": "jsdoc --configure .jsdocrc.js --destination docs --recurse README.md src && printf '%s' 'docs.openpgpjs.org' > docs/CNAME", "docs": "jsdoc --configure .jsdocrc.cjs --destination docs --recurse README.md src && printf '%s' 'docs.openpgpjs.org' > docs/CNAME",
"preversion": "rm -rf dist docs node_modules && npm ci && npm test", "preversion": "rm -rf dist docs node_modules && npm ci && npm test",
"version": "npm run docs && git add -A docs", "version": "npm run docs && git add -A docs",
"postversion": "git push && git push --tags && npm publish" "postversion": "git push && git push --tags && npm publish"
}, },
"devDependencies": { "devDependencies": {
"@openpgp/asmcrypto.js": "^2.3.2", "@noble/ciphers": "^1.0.0",
"@openpgp/elliptic": "^6.5.1", "@noble/curves": "^1.6.0",
"@openpgp/jsdoc": "^3.6.4", "@noble/hashes": "^1.5.0",
"@openpgp/pako": "^1.0.12", "@openpgp/jsdoc": "^3.6.11",
"@openpgp/seek-bzip": "^1.0.5-git", "@openpgp/seek-bzip": "^1.0.5-git",
"@openpgp/tweetnacl": "^1.0.3", "@openpgp/tweetnacl": "^1.0.4-1",
"@openpgp/web-stream-tools": "0.0.11-patch-1", "@openpgp/web-stream-tools": "~0.1.3",
"@rollup/plugin-commonjs": "^11.1.0", "@rollup/plugin-alias": "^5.1.1",
"@rollup/plugin-node-resolve": "^7.1.3", "@rollup/plugin-commonjs": "^25.0.8",
"@rollup/plugin-replace": "^2.3.2", "@rollup/plugin-node-resolve": "^15.3.0",
"@types/chai": "^4.2.14", "@rollup/plugin-replace": "^5.0.7",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.6",
"@rollup/plugin-wasm": "^6.2.2",
"@types/chai": "^4.3.19",
"@types/sinon": "^17.0.3",
"@typescript-eslint/parser": "^7.18.0",
"@web/test-runner": "^0.19.0",
"@web/test-runner-browserstack": "^0.7.2",
"@web/test-runner-mocha": "^0.9.0",
"@web/test-runner-playwright": "^0.11.0",
"argon2id": "^1.0.1",
"benchmark": "^2.1.4", "benchmark": "^2.1.4",
"bn.js": "^4.11.8", "bn.js": "^5.2.1",
"chai": "^4.3.6", "c8": "^8.0.1",
"chai-as-promised": "^7.1.1", "chai": "^4.4.1",
"email-addresses": "3.1.0", "chai-as-promised": "^7.1.2",
"eslint": "^8.34.0", "eckey-utils": "^0.7.14",
"eslint": "^8.57.1",
"eslint-config-airbnb": "^19.0.4", "eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-base": "^15.0.0", "eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-chai-friendly": "^0.7.2", "eslint-config-airbnb-typescript": "^18.0.0",
"eslint-plugin-import": "^2.27.5", "eslint-import-resolver-typescript": "^3.6.3",
"esm": "^3.2.25", "eslint-plugin-chai-friendly": "^0.7.4",
"hash.js": "^1.1.3", "eslint-plugin-import": "^2.31.0",
"http-server": "^14.1.1", "eslint-plugin-unicorn": "^48.0.1",
"karma": "^6.4.0", "fflate": "^0.7.4",
"karma-browserstack-launcher": "^1.6.0", "mocha": "^10.7.3",
"karma-chrome-launcher": "^3.1.1", "playwright": "^1.48.2",
"karma-firefox-launcher": "^2.1.2", "rollup": "^4.24.2",
"karma-mocha": "^2.0.1", "sinon": "^18.0.1",
"karma-mocha-reporter": "^2.2.5", "ts-node": "^10.9.2",
"karma-webkit-launcher": "^2.1.0", "tslib": "^2.8.0",
"mocha": "^8.4.0", "tsx": "^4.19.2",
"nyc": "^14.1.1", "typescript": "^5.6.3",
"playwright": "^1.30.0", "web-streams-polyfill": "^4.0.0"
"rollup": "^2.38.5",
"rollup-plugin-terser": "^7.0.2",
"sinon": "^4.3.0",
"typescript": "^4.1.2",
"web-streams-polyfill": "^3.2.0"
}, },
"dependencies": { "overrides": {
"asn1.js": "^5.0.0" "@web/dev-server-core": "npm:@openpgp/wtr-dev-server-core@0.7.3-patch.1"
}, },
"repository": { "repository": {
"type": "git", "type": "git",

View File

@ -1,15 +1,43 @@
/* eslint-disable no-process-env */ /* eslint-disable no-process-env */
import { builtinModules } from 'module'; import { builtinModules } from 'module';
import { readFileSync } from 'fs';
import alias from '@rollup/plugin-alias';
import resolve from '@rollup/plugin-node-resolve'; import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs'; import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace'; import replace from '@rollup/plugin-replace';
import { terser } from 'rollup-plugin-terser'; import terser from '@rollup/plugin-terser';
import { wasm } from '@rollup/plugin-wasm';
import typescript from '@rollup/plugin-typescript';
import pkg from './package.json'; // ESlint does not support JSON module imports yet, see https://github.com/eslint/eslint/discussions/15305
// import pkg from './package.json' assert { type: 'json' };
const pkg = JSON.parse(readFileSync('./package.json'));
const nodeDependencies = Object.keys(pkg.dependencies); const nodeDependencies = Object.keys(pkg.dependencies || {});
const nodeBuiltinModules = builtinModules.concat(['module']);
const wasmOptions = {
node: { targetEnv: 'node' },
browser: { targetEnv: 'browser', maxFileSize: undefined } // always inlline (our wasm files are small)
};
const getChunkFileName = (chunkInfo, extension) => `[name].${extension}`;
/**
* Dynamically imported modules which expose an index file as entrypoint end up with a chunk named `index`
* by default. We want to preserve the module name instead.
*/
const setManualChunkName = chunkId => {
if (chunkId.includes('seek-bzip')) {
return 'seek-bzip';
} else if (chunkId.includes('argon2id')) {
return 'argon2id';
} else {
return undefined;
}
};
const banner = const banner =
`/*! OpenPGP.js v${pkg.version} - ` + `/*! OpenPGP.js v${pkg.version} - ` +
@ -29,90 +57,120 @@ const terserOptions = {
} }
}; };
export default Object.assign([ const nodeBuild = {
{
input: 'src/index.js', input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [
{ file: 'dist/node/openpgp.cjs', format: 'cjs', name: pkg.name, banner, intro },
{ file: 'dist/node/openpgp.min.cjs', format: 'cjs', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true },
{ file: 'dist/node/openpgp.mjs', format: 'es', banner, intro },
{ file: 'dist/node/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
].map(options => ({ ...options, inlineDynamicImports: true })),
plugins: [
resolve({
exportConditions: ['node'] // needed for resolution of noble-curves import of '@noble/crypto' in Node 18
}),
typescript({
compilerOptions: { outDir: './dist/tmp-ts' }
}),
commonjs(),
replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`
}),
wasm(wasmOptions.node)
]
};
const fullBrowserBuild = {
input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [ output: [
{ file: 'dist/openpgp.js', format: 'iife', name: pkg.name, banner, intro }, { file: 'dist/openpgp.js', format: 'iife', name: pkg.name, banner, intro },
{ file: 'dist/openpgp.min.js', format: 'iife', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true }, { file: 'dist/openpgp.min.js', format: 'iife', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true },
{ file: 'dist/openpgp.mjs', format: 'es', banner, intro }, { file: 'dist/openpgp.mjs', format: 'es', banner, intro },
{ file: 'dist/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true } { file: 'dist/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
], ].map(options => ({ ...options, inlineDynamicImports: true })),
inlineDynamicImports: true,
plugins: [ plugins: [
resolve({ resolve({
browser: true browser: true
}), }),
typescript({
compilerOptions: { outDir: './dist/tmp-ts' } // to avoid js files being overwritten
}),
commonjs({ commonjs({
ignore: builtinModules.concat(nodeDependencies) ignore: nodeBuiltinModules.concat(nodeDependencies)
}), }),
replace({ replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`, 'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`,
'require(': 'void(', "import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', ''] delimiters: ['', '']
}) }),
wasm(wasmOptions.browser)
] ]
}, };
{
const lightweightBrowserBuild = {
input: 'src/index.js', input: 'src/index.js',
inlineDynamicImports: true, external: nodeBuiltinModules.concat(nodeDependencies),
external: builtinModules.concat(nodeDependencies),
output: [ output: [
{ file: 'dist/node/openpgp.js', format: 'cjs', name: pkg.name, banner, intro }, { entryFileNames: 'openpgp.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'mjs') },
{ file: 'dist/node/openpgp.min.js', format: 'cjs', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true }, { entryFileNames: 'openpgp.min.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'min.mjs'), plugins: [terser(terserOptions)], sourcemap: true }
{ file: 'dist/node/openpgp.mjs', format: 'es', banner, intro }, ].map(options => ({ ...options, dir: 'dist/lightweight', manualChunks: setManualChunkName, format: 'es', banner, intro })),
{ file: 'dist/node/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true } preserveEntrySignatures: 'exports-only',
],
plugins: [
resolve(),
commonjs(),
replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`
})
]
},
{
input: 'src/index.js',
output: [
{ dir: 'dist/lightweight', entryFileNames: 'openpgp.mjs', chunkFileNames: '[name].mjs', format: 'es', banner, intro },
{ dir: 'dist/lightweight', entryFileNames: 'openpgp.min.mjs', chunkFileNames: '[name].min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
],
preserveEntrySignatures: 'allow-extension',
plugins: [ plugins: [
resolve({ resolve({
browser: true browser: true
}), }),
typescript({
compilerOptions: { outDir: './dist/lightweight/tmp-ts' }
}),
commonjs({ commonjs({
ignore: builtinModules.concat(nodeDependencies) ignore: nodeBuiltinModules.concat(nodeDependencies)
}), }),
replace({ replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`, 'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`,
'require(': 'void(', "import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', ''] delimiters: ['', '']
}) }),
wasm(wasmOptions.browser)
] ]
}, };
{
const testBuild = {
input: 'test/unittests.js', input: 'test/unittests.js',
output: [ output: [
{ file: 'test/lib/unittests-bundle.js', format: 'es', intro, sourcemap: true } { file: 'test/lib/unittests-bundle.js', format: 'es', intro, sourcemap: true, inlineDynamicImports: true }
], ],
inlineDynamicImports: true, external: nodeBuiltinModules.concat(nodeDependencies),
external: ['../..', '../../..'],
plugins: [ plugins: [
alias({
entries: {
openpgp: `./dist/${process.env.npm_config_lightweight ? 'lightweight/' : ''}openpgp.mjs`
}
}),
resolve({ resolve({
browser: true browser: true
}), }),
typescript({
compilerOptions: { outDir: './test/lib/tmp-ts' }
}),
commonjs({ commonjs({
ignore: builtinModules.concat(nodeDependencies) ignore: nodeBuiltinModules.concat(nodeDependencies),
requireReturnsDefault: 'preferred'
}), }),
replace({ replace({
"import openpgpjs from '../../..';": `import * as openpgpjs from '/dist/${process.env.npm_config_lightweight ? 'lightweight/' : ''}openpgp.mjs'; window.openpgp = openpgpjs;`, "import { createRequire } from 'module';": 'const createRequire = () => () => {}',
'require(': 'void(',
delimiters: ['', ''] delimiters: ['', '']
}) }),
wasm(wasmOptions.browser)
] ]
} };
export default Object.assign([
nodeBuild,
fullBrowserBuild,
lightweightBrowserBuild,
testBuild
].filter(config => { ].filter(config => {
config.output = config.output.filter(output => { config.output = config.output.filter(output => {
return (output.file || output.dir + '/' + output.entryFileNames).includes( return (output.file || output.dir + '/' + output.entryFileNames).includes(

View File

@ -1,334 +0,0 @@
import BN from 'bn.js';
/**
* @fileoverview
* BigInteger implementation of basic operations
* Wrapper of bn.js library (wwww.github.com/indutny/bn.js)
* @module biginteger/bn
* @private
*/
/**
* @private
*/
export default class BigInteger {
/**
* Get a BigInteger (input must be big endian for strings and arrays)
* @param {Number|String|Uint8Array} n - Value to convert
* @throws {Error} on undefined input
*/
constructor(n) {
if (n === undefined) {
throw new Error('Invalid BigInteger input');
}
this.value = new BN(n);
}
clone() {
const clone = new BigInteger(null);
this.value.copy(clone.value);
return clone;
}
/**
* BigInteger increment in place
*/
iinc() {
this.value.iadd(new BN(1));
return this;
}
/**
* BigInteger increment
* @returns {BigInteger} this + 1.
*/
inc() {
return this.clone().iinc();
}
/**
* BigInteger decrement in place
*/
idec() {
this.value.isub(new BN(1));
return this;
}
/**
* BigInteger decrement
* @returns {BigInteger} this - 1.
*/
dec() {
return this.clone().idec();
}
/**
* BigInteger addition in place
* @param {BigInteger} x - Value to add
*/
iadd(x) {
this.value.iadd(x.value);
return this;
}
/**
* BigInteger addition
* @param {BigInteger} x - Value to add
* @returns {BigInteger} this + x.
*/
add(x) {
return this.clone().iadd(x);
}
/**
* BigInteger subtraction in place
* @param {BigInteger} x - Value to subtract
*/
isub(x) {
this.value.isub(x.value);
return this;
}
/**
* BigInteger subtraction
* @param {BigInteger} x - Value to subtract
* @returns {BigInteger} this - x.
*/
sub(x) {
return this.clone().isub(x);
}
/**
* BigInteger multiplication in place
* @param {BigInteger} x - Value to multiply
*/
imul(x) {
this.value.imul(x.value);
return this;
}
/**
* BigInteger multiplication
* @param {BigInteger} x - Value to multiply
* @returns {BigInteger} this * x.
*/
mul(x) {
return this.clone().imul(x);
}
/**
* Compute value modulo m, in place
* @param {BigInteger} m - Modulo
*/
imod(m) {
this.value = this.value.umod(m.value);
return this;
}
/**
* Compute value modulo m
* @param {BigInteger} m - Modulo
* @returns {BigInteger} this mod m.
*/
mod(m) {
return this.clone().imod(m);
}
/**
* Compute modular exponentiation
* Much faster than this.exp(e).mod(n)
* @param {BigInteger} e - Exponent
* @param {BigInteger} n - Modulo
* @returns {BigInteger} this ** e mod n.
*/
modExp(e, n) {
// We use either Montgomery or normal reduction context
// Montgomery requires coprime n and R (montogmery multiplier)
// bn.js picks R as power of 2, so n must be odd
const nred = n.isEven() ? BN.red(n.value) : BN.mont(n.value);
const x = this.clone();
x.value = x.value.toRed(nred).redPow(e.value).fromRed();
return x;
}
/**
* Compute the inverse of this value modulo n
* Note: this and and n must be relatively prime
* @param {BigInteger} n - Modulo
* @returns {BigInteger} x such that this*x = 1 mod n
* @throws {Error} if the inverse does not exist
*/
modInv(n) {
// invm returns a wrong result if the inverse does not exist
if (!this.gcd(n).isOne()) {
throw new Error('Inverse does not exist');
}
return new BigInteger(this.value.invm(n.value));
}
/**
* Compute greatest common divisor between this and n
* @param {BigInteger} n - Operand
* @returns {BigInteger} gcd
*/
gcd(n) {
return new BigInteger(this.value.gcd(n.value));
}
/**
* Shift this to the left by x, in place
* @param {BigInteger} x - Shift value
*/
ileftShift(x) {
this.value.ishln(x.value.toNumber());
return this;
}
/**
* Shift this to the left by x
* @param {BigInteger} x - Shift value
* @returns {BigInteger} this << x.
*/
leftShift(x) {
return this.clone().ileftShift(x);
}
/**
* Shift this to the right by x, in place
* @param {BigInteger} x - Shift value
*/
irightShift(x) {
this.value.ishrn(x.value.toNumber());
return this;
}
/**
* Shift this to the right by x
* @param {BigInteger} x - Shift value
* @returns {BigInteger} this >> x.
*/
rightShift(x) {
return this.clone().irightShift(x);
}
/**
* Whether this value is equal to x
* @param {BigInteger} x
* @returns {Boolean}
*/
equal(x) {
return this.value.eq(x.value);
}
/**
* Whether this value is less than x
* @param {BigInteger} x
* @returns {Boolean}
*/
lt(x) {
return this.value.lt(x.value);
}
/**
* Whether this value is less than or equal to x
* @param {BigInteger} x
* @returns {Boolean}
*/
lte(x) {
return this.value.lte(x.value);
}
/**
* Whether this value is greater than x
* @param {BigInteger} x
* @returns {Boolean}
*/
gt(x) {
return this.value.gt(x.value);
}
/**
* Whether this value is greater than or equal to x
* @param {BigInteger} x
* @returns {Boolean}
*/
gte(x) {
return this.value.gte(x.value);
}
isZero() {
return this.value.isZero();
}
isOne() {
return this.value.eq(new BN(1));
}
isNegative() {
return this.value.isNeg();
}
isEven() {
return this.value.isEven();
}
abs() {
const res = this.clone();
res.value = res.value.abs();
return res;
}
/**
* Get this value as a string
* @returns {String} this value.
*/
toString() {
return this.value.toString();
}
/**
* Get this value as an exact Number (max 53 bits)
* Fails if this value is too large
* @returns {Number}
*/
toNumber() {
return this.value.toNumber();
}
/**
* Get value of i-th bit
* @param {Number} i - Bit index
* @returns {Number} Bit value.
*/
getBit(i) {
return this.value.testn(i) ? 1 : 0;
}
/**
* Compute bit length
* @returns {Number} Bit length.
*/
bitLength() {
return this.value.bitLength();
}
/**
* Compute byte length
* @returns {Number} Byte length.
*/
byteLength() {
return this.value.byteLength();
}
/**
* Get Uint8Array representation of this number
* @param {String} endian - Endianess of output array (defaults to 'be')
* @param {Number} length - Of output array
* @returns {Uint8Array}
*/
toUint8Array(endian = 'be', length) {
return this.value.toArrayLike(Uint8Array, endian, length);
}
}

View File

@ -1,14 +0,0 @@
import BigInteger from './native.interface';
const detectBigInt = () => typeof BigInt !== 'undefined';
async function getBigInteger() {
if (detectBigInt()) {
return BigInteger;
} else {
const { default: BigInteger } = await import('./bn.interface');
return BigInteger;
}
}
export { getBigInteger };

View File

@ -1,453 +0,0 @@
/* eslint-disable new-cap */
/**
* @fileoverview
* BigInteger implementation of basic operations
* that wraps the native BigInt library.
* Operations are not constant time,
* but we try and limit timing leakage where we can
* @module biginteger/native
* @private
*/
/**
* @private
*/
export default class BigInteger {
/**
* Get a BigInteger (input must be big endian for strings and arrays)
* @param {Number|String|Uint8Array} n - Value to convert
* @throws {Error} on null or undefined input
*/
constructor(n) {
if (n === undefined) {
throw new Error('Invalid BigInteger input');
}
if (n instanceof Uint8Array) {
const bytes = n;
const hex = new Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
const hexByte = bytes[i].toString(16);
hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;
}
this.value = BigInt('0x0' + hex.join(''));
} else {
this.value = BigInt(n);
}
}
clone() {
return new BigInteger(this.value);
}
/**
* BigInteger increment in place
*/
iinc() {
this.value++;
return this;
}
/**
* BigInteger increment
* @returns {BigInteger} this + 1.
*/
inc() {
return this.clone().iinc();
}
/**
* BigInteger decrement in place
*/
idec() {
this.value--;
return this;
}
/**
* BigInteger decrement
* @returns {BigInteger} this - 1.
*/
dec() {
return this.clone().idec();
}
/**
* BigInteger addition in place
* @param {BigInteger} x - Value to add
*/
iadd(x) {
this.value += x.value;
return this;
}
/**
* BigInteger addition
* @param {BigInteger} x - Value to add
* @returns {BigInteger} this + x.
*/
add(x) {
return this.clone().iadd(x);
}
/**
* BigInteger subtraction in place
* @param {BigInteger} x - Value to subtract
*/
isub(x) {
this.value -= x.value;
return this;
}
/**
* BigInteger subtraction
* @param {BigInteger} x - Value to subtract
* @returns {BigInteger} this - x.
*/
sub(x) {
return this.clone().isub(x);
}
/**
* BigInteger multiplication in place
* @param {BigInteger} x - Value to multiply
*/
imul(x) {
this.value *= x.value;
return this;
}
/**
* BigInteger multiplication
* @param {BigInteger} x - Value to multiply
* @returns {BigInteger} this * x.
*/
mul(x) {
return this.clone().imul(x);
}
/**
* Compute value modulo m, in place
* @param {BigInteger} m - Modulo
*/
imod(m) {
this.value %= m.value;
if (this.isNegative()) {
this.iadd(m);
}
return this;
}
/**
* Compute value modulo m
* @param {BigInteger} m - Modulo
* @returns {BigInteger} this mod m.
*/
mod(m) {
return this.clone().imod(m);
}
/**
* Compute modular exponentiation using square and multiply
* @param {BigInteger} e - Exponent
* @param {BigInteger} n - Modulo
* @returns {BigInteger} this ** e mod n.
*/
modExp(e, n) {
if (n.isZero()) throw Error('Modulo cannot be zero');
if (n.isOne()) return new BigInteger(0);
if (e.isNegative()) throw Error('Unsopported negative exponent');
let exp = e.value;
let x = this.value;
x %= n.value;
let r = BigInt(1);
while (exp > BigInt(0)) {
const lsb = exp & BigInt(1);
exp >>= BigInt(1); // e / 2
// Always compute multiplication step, to reduce timing leakage
const rx = (r * x) % n.value;
// Update r only if lsb is 1 (odd exponent)
r = lsb ? rx : r;
x = (x * x) % n.value; // Square
}
return new BigInteger(r);
}
/**
* Compute the inverse of this value modulo n
* Note: this and and n must be relatively prime
* @param {BigInteger} n - Modulo
* @returns {BigInteger} x such that this*x = 1 mod n
* @throws {Error} if the inverse does not exist
*/
modInv(n) {
const { gcd, x } = this._egcd(n);
if (!gcd.isOne()) {
throw new Error('Inverse does not exist');
}
return x.add(n).mod(n);
}
/**
* Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)
* Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)
* @param {BigInteger} b - Second operand
* @returns {{ gcd, x, y: BigInteger }}
*/
_egcd(b) {
let x = BigInt(0);
let y = BigInt(1);
let xPrev = BigInt(1);
let yPrev = BigInt(0);
let a = this.value;
b = b.value;
while (b !== BigInt(0)) {
const q = a / b;
let tmp = x;
x = xPrev - q * x;
xPrev = tmp;
tmp = y;
y = yPrev - q * y;
yPrev = tmp;
tmp = b;
b = a % b;
a = tmp;
}
return {
x: new BigInteger(xPrev),
y: new BigInteger(yPrev),
gcd: new BigInteger(a)
};
}
/**
* Compute greatest common divisor between this and n
* @param {BigInteger} b - Operand
* @returns {BigInteger} gcd
*/
gcd(b) {
let a = this.value;
b = b.value;
while (b !== BigInt(0)) {
const tmp = b;
b = a % b;
a = tmp;
}
return new BigInteger(a);
}
/**
* Shift this to the left by x, in place
* @param {BigInteger} x - Shift value
*/
ileftShift(x) {
this.value <<= x.value;
return this;
}
/**
* Shift this to the left by x
* @param {BigInteger} x - Shift value
* @returns {BigInteger} this << x.
*/
leftShift(x) {
return this.clone().ileftShift(x);
}
/**
* Shift this to the right by x, in place
* @param {BigInteger} x - Shift value
*/
irightShift(x) {
this.value >>= x.value;
return this;
}
/**
* Shift this to the right by x
* @param {BigInteger} x - Shift value
* @returns {BigInteger} this >> x.
*/
rightShift(x) {
return this.clone().irightShift(x);
}
/**
* Whether this value is equal to x
* @param {BigInteger} x
* @returns {Boolean}
*/
equal(x) {
return this.value === x.value;
}
/**
* Whether this value is less than x
* @param {BigInteger} x
* @returns {Boolean}
*/
lt(x) {
return this.value < x.value;
}
/**
* Whether this value is less than or equal to x
* @param {BigInteger} x
* @returns {Boolean}
*/
lte(x) {
return this.value <= x.value;
}
/**
* Whether this value is greater than x
* @param {BigInteger} x
* @returns {Boolean}
*/
gt(x) {
return this.value > x.value;
}
/**
* Whether this value is greater than or equal to x
* @param {BigInteger} x
* @returns {Boolean}
*/
gte(x) {
return this.value >= x.value;
}
isZero() {
return this.value === BigInt(0);
}
isOne() {
return this.value === BigInt(1);
}
isNegative() {
return this.value < BigInt(0);
}
isEven() {
return !(this.value & BigInt(1));
}
abs() {
const res = this.clone();
if (this.isNegative()) {
res.value = -res.value;
}
return res;
}
/**
* Get this value as a string
* @returns {String} this value.
*/
toString() {
return this.value.toString();
}
/**
* Get this value as an exact Number (max 53 bits)
* Fails if this value is too large
* @returns {Number}
*/
toNumber() {
const number = Number(this.value);
if (number > Number.MAX_SAFE_INTEGER) {
// We throw and error to conform with the bn.js implementation
throw new Error('Number can only safely store up to 53 bits');
}
return number;
}
/**
* Get value of i-th bit
* @param {Number} i - Bit index
* @returns {Number} Bit value.
*/
getBit(i) {
const bit = (this.value >> BigInt(i)) & BigInt(1);
return (bit === BigInt(0)) ? 0 : 1;
}
/**
* Compute bit length
* @returns {Number} Bit length.
*/
bitLength() {
const zero = new BigInteger(0);
const one = new BigInteger(1);
const negOne = new BigInteger(-1);
// -1n >> -1n is -1n
// 1n >> 1n is 0n
const target = this.isNegative() ? negOne : zero;
let bitlen = 1;
const tmp = this.clone();
while (!tmp.irightShift(one).equal(target)) {
bitlen++;
}
return bitlen;
}
/**
* Compute byte length
* @returns {Number} Byte length.
*/
byteLength() {
const zero = new BigInteger(0);
const negOne = new BigInteger(-1);
const target = this.isNegative() ? negOne : zero;
const eight = new BigInteger(8);
let len = 1;
const tmp = this.clone();
while (!tmp.irightShift(eight).equal(target)) {
len++;
}
return len;
}
/**
* Get Uint8Array representation of this number
* @param {String} endian - Endianess of output array (defaults to 'be')
* @param {Number} length - Of output array
* @returns {Uint8Array}
*/
toUint8Array(endian = 'be', length) {
// we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)
// this is faster than shift+mod iterations
let hex = this.value.toString(16);
if (hex.length % 2 === 1) {
hex = '0' + hex;
}
const rawLength = hex.length / 2;
const bytes = new Uint8Array(length || rawLength);
// parse hex
const offset = length ? (length - rawLength) : 0;
let i = 0;
while (i < rawLength) {
bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
i++;
}
if (endian !== 'be') {
bytes.reverse();
}
return bytes;
}
}

View File

@ -59,20 +59,22 @@ export class CleartextMessage {
/** /**
* Sign the cleartext message * Sign the cleartext message
* @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing * @param {Array<Key>} signingKeys - private keys with decrypted secret key data for signing
* @param {Array<Key>} recipientKeys - recipient keys to get the signing preferences from
* @param {Signature} [signature] - Any existing detached signature * @param {Signature} [signature] - Any existing detached signature
* @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]
* @param {Date} [date] - The creation time of the signature that should be created * @param {Date} [date] - The creation time of the signature that should be created
* @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
* @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from
* @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]
* @param {Object} [config] - Full configuration, defaults to openpgp.config * @param {Object} [config] - Full configuration, defaults to openpgp.config
* @returns {Promise<CleartextMessage>} New cleartext message with signed content. * @returns {Promise<CleartextMessage>} New cleartext message with signed content.
* @async * @async
*/ */
async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) { async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {
const literalDataPacket = new LiteralDataPacket(); const literalDataPacket = new LiteralDataPacket();
literalDataPacket.setText(this.text); literalDataPacket.setText(this.text);
const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config)); const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config));
return new CleartextMessage(this.text, newSignature); return new CleartextMessage(this.text, newSignature);
} }
@ -111,16 +113,22 @@ export class CleartextMessage {
* @returns {String | ReadableStream<String>} ASCII armor. * @returns {String | ReadableStream<String>} ASCII armor.
*/ */
armor(config = defaultConfig) { armor(config = defaultConfig) {
let hashes = this.signature.packets.map(function(packet) { // emit header and checksum if one of the signatures has a version not 6
return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase(); const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6);
}); const hash = emitHeaderAndChecksum ?
hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; }); Array.from(new Set(this.signature.packets.map(
packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase()
))).join() :
null;
const body = { const body = {
hash: hashes.join(), hash,
text: this.text, text: this.text,
data: this.signature.packets.write() data: this.signature.packets.write()
}; };
return armor(enums.armor.signed, body, undefined, undefined, undefined, config);
// An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.
return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config);
} }
} }
@ -171,30 +179,27 @@ function verifyHeaders(headers, packetlist) {
return true; return true;
}; };
let oneHeader = null; const hashAlgos = [];
let hashAlgos = []; headers.forEach(header => {
headers.forEach(function(header) { const hashHeader = header.match(/^Hash: (.+)$/); // get header value
oneHeader = header.match(/^Hash: (.+)$/); // get header value if (hashHeader) {
if (oneHeader) { const parsedHashIDs = hashHeader[1]
oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace .replace(/\s/g, '') // remove whitespace
oneHeader = oneHeader.split(','); .split(',')
oneHeader = oneHeader.map(function(hash) { .map(hashName => {
hash = hash.toLowerCase();
try { try {
return enums.write(enums.hash, hash); return enums.write(enums.hash, hashName.toLowerCase());
} catch (e) { } catch (e) {
throw new Error('Unknown hash algorithm in armor header: ' + hash); throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase());
} }
}); });
hashAlgos = hashAlgos.concat(oneHeader); hashAlgos.push(...parsedHashIDs);
} else { } else {
throw new Error('Only "Hash" header allowed in cleartext signed message'); throw new Error('Only "Hash" header allowed in cleartext signed message');
} }
}); });
if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) { if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
} else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
throw new Error('Hash algorithm mismatch in armor header and signature'); throw new Error('Hash algorithm mismatch in armor header and signature');
} }
} }

View File

@ -26,7 +26,7 @@ export default {
* @memberof module:config * @memberof module:config
* @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}
*/ */
preferredHashAlgorithm: enums.hash.sha256, preferredHashAlgorithm: enums.hash.sha512,
/** /**
* @memberof module:config * @memberof module:config
* @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}
@ -37,28 +37,34 @@ export default {
* @property {Integer} compression Default compression algorithm {@link module:enums.compression} * @property {Integer} compression Default compression algorithm {@link module:enums.compression}
*/ */
preferredCompressionAlgorithm: enums.compression.uncompressed, preferredCompressionAlgorithm: enums.compression.uncompressed,
/**
* @memberof module:config
* @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9
*/
deflateLevel: 6,
/** /**
* Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
* This option is applicable to:
* - key generation (encryption key preferences),
* - password-based message encryption, and
* - private key encryption.
* In the case of message encryption using public keys, the encryption key preferences are respected instead.
* Note: not all OpenPGP implementations are compatible with this option. * Note: not all OpenPGP implementations are compatible with this option.
* **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10}
* @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}
* @memberof module:config * @memberof module:config
* @property {Boolean} aeadProtect * @property {Boolean} aeadProtect
*/ */
aeadProtect: false, aeadProtect: false,
/**
* When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`)
* which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`,
* this option must be set, otherwise key parsing and/or key decryption will fail.
* Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys
* will be processed incorrectly.
*/
parseAEADEncryptedV4KeysAsLegacy: false,
/** /**
* Default Authenticated Encryption with Additional Data (AEAD) encryption mode * Default Authenticated Encryption with Additional Data (AEAD) encryption mode
* Only has an effect when aeadProtect is set to true. * Only has an effect when aeadProtect is set to true.
* @memberof module:config * @memberof module:config
* @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}
*/ */
preferredAEADAlgorithm: enums.aead.eax, preferredAEADAlgorithm: enums.aead.gcm,
/** /**
* Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode
* Only has an effect when aeadProtect is set to true. * Only has an effect when aeadProtect is set to true.
@ -68,20 +74,57 @@ export default {
*/ */
aeadChunkSizeByte: 12, aeadChunkSizeByte: 12,
/** /**
* Use V5 keys. * Use v6 keys.
* Note: not all OpenPGP implementations are compatible with this option. * Note: not all OpenPGP implementations are compatible with this option.
* **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
* @memberof module:config * @memberof module:config
* @property {Boolean} v5Keys * @property {Boolean} v6Keys
*/ */
v5Keys: false, v6Keys: false,
/** /**
* {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet).
* Iteration Count Byte for S2K (String to Key) * These are non-standard entities, which in the crypto-refresh have been superseded
* by v6 keys and v6 signatures, respectively.
* However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries,
* hence parsing them might be necessary in some cases.
*/
enableParsingV5Entities: false,
/**
* S2K (String to Key) type, used for key derivation in the context of secret key encryption
* and password-encrypted data. Weaker s2k options are not allowed.
* Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it
* (pending standardisation).
* @memberof module:config
* @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k}
*/
s2kType: enums.s2k.iterated,
/**
* {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}:
* Iteration Count Byte for Iterated and Salted S2K (String to Key).
* Only relevant if `config.s2kType` is set to `enums.s2k.iterated`.
* Note: this is the exponent value, not the final number of iterations (refer to specs for more details).
* @memberof module:config * @memberof module:config
* @property {Integer} s2kIterationCountByte * @property {Integer} s2kIterationCountByte
*/ */
s2kIterationCountByte: 224, s2kIterationCountByte: 224,
/**
* {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}:
* Argon2 parameters for S2K (String to Key).
* Only relevant if `config.s2kType` is set to `enums.s2k.argon2`.
* Default settings correspond to the second recommendation from RFC9106 ("uniformly safe option"),
* to ensure compatibility with memory-constrained environments.
* For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4.
* @memberof module:config
* @property {Object} params
* @property {Integer} params.passes - number of iterations t
* @property {Integer} params.parallelism - degree of parallelism p
* @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes.
*/
s2kArgon2Params: {
passes: 3,
parallelism: 4, // lanes
memoryExponent: 16 // 64 MiB of RAM
},
/** /**
* Allow decryption of messages without integrity protection. * Allow decryption of messages without integrity protection.
* This is an **insecure** setting: * This is an **insecure** setting:
@ -96,16 +139,16 @@ export default {
* process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible
* and deferring checking their integrity until the decrypted stream has been read in full. * and deferring checking their integrity until the decrypted stream has been read in full.
* *
* This setting is **insecure** if the partially decrypted message is processed further or displayed to the user. * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity:
* - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL
* (see https://efail.de/).
* - an attacker with access to traces or timing info of internal processing errors could learn some info about the data.
*
* NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed.
* @memberof module:config * @memberof module:config
* @property {Boolean} allowUnauthenticatedStream * @property {Boolean} allowUnauthenticatedStream
*/ */
allowUnauthenticatedStream: false, allowUnauthenticatedStream: false,
/**
* @memberof module:config
* @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum
*/
checksumRequired: false,
/** /**
* Minimum RSA key size allowed for key generation and message signing, verification and encryption. * Minimum RSA key size allowed for key generation and message signing, verification and encryption.
* The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.
@ -120,11 +163,6 @@ export default {
* @property {Boolean} passwordCollisionCheck * @property {Boolean} passwordCollisionCheck
*/ */
passwordCollisionCheck: false, passwordCollisionCheck: false,
/**
* @memberof module:config
* @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored
*/
revocationsExpire: false,
/** /**
* Allow decryption using RSA keys without `encrypt` flag. * Allow decryption using RSA keys without `encrypt` flag.
* This setting is potentially insecure, but it is needed to get around an old openpgpjs bug * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug
@ -142,7 +180,14 @@ export default {
* @property {Boolean} allowInsecureDecryptionWithSigningKeys * @property {Boolean} allowInsecureDecryptionWithSigningKeys
*/ */
allowInsecureVerificationWithReformattedKeys: false, allowInsecureVerificationWithReformattedKeys: false,
/**
* Allow using keys that do not have any key flags set.
* Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages
* (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29).
* Some older keys do not declare any key flags, which means they are not allowed to be used for any operation.
* This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm.
*/
allowMissingKeyFlags: false,
/** /**
* Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).
* This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:
@ -161,12 +206,6 @@ export default {
* @property {Set<Integer>} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} * @property {Set<Integer>} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}
*/ */
constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),
/**
* @memberof module:config
* @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available
*/
minBytesForWebCrypto: 1000,
/** /**
* @memberof module:config * @memberof module:config
* @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error
@ -220,13 +259,20 @@ export default {
*/ */
knownNotations: [], knownNotations: [],
/** /**
* Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API. * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design).
* When false, certain standard curves will not be supported (depending on the platform). * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur
* Note: the indutny/elliptic curve library is not designed to be constant time. * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of
* @memberof module:config * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks.
* @property {Boolean} useIndutnyElliptic * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases.
*/ */
useIndutnyElliptic: true, nonDeterministicSignaturesViaNotation: true,
/**
* Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API.
* When false, certain standard curves will not be supported (depending on the platform).
* @memberof module:config
* @property {Boolean} useEllipticFallback
*/
useEllipticFallback: true,
/** /**
* Reject insecure hash algorithms * Reject insecure hash algorithms
* @memberof module:config * @memberof module:config

View File

@ -19,129 +19,79 @@
* @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions
* @see module:crypto/public_key/elliptic/ecdh * @see module:crypto/public_key/elliptic/ecdh
* @module crypto/aes_kw * @module crypto/aes_kw
* @private
*/ */
import * as cipher from './cipher'; import { aeskw as nobleAesKW } from '@noble/ciphers/aes';
import { getCipherParams } from './cipher';
import util from '../util'; import util from '../util';
const webCrypto = util.getWebCrypto();
/** /**
* AES key wrap * AES key wrap
* @function * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo
* @param {Uint8Array} key * @param {Uint8Array} key - wrapping key
* @param {Uint8Array} data * @param {Uint8Array} dataToWrap
* @returns {Uint8Array} * @returns {Uint8Array} wrapped key
*/ */
export function wrap(key, data) { export async function wrap(algo, key, dataToWrap) {
const aes = new cipher['aes' + (key.length * 8)](key); const { keySize } = getCipherParams(algo);
const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); // sanity checks, since WebCrypto does not use the `algo` input
const P = unpack(data); if (!util.isAES(algo) || key.length !== keySize) {
let A = IV; throw new Error('Unexpected algorithm or key size');
const R = P;
const n = P.length / 2;
const t = new Uint32Array([0, 0]);
let B = new Uint32Array(4);
for (let j = 0; j <= 5; ++j) {
for (let i = 0; i < n; ++i) {
t[1] = n * j + (1 + i);
// B = A
B[0] = A[0];
B[1] = A[1];
// B = A || R[i]
B[2] = R[2 * i];
B[3] = R[2 * i + 1];
// B = AES(K, B)
B = unpack(aes.encrypt(pack(B)));
// A = MSB(64, B) ^ t
A = B.subarray(0, 2);
A[0] ^= t[0];
A[1] ^= t[1];
// R[i] = LSB(64, B)
R[2 * i] = B[2];
R[2 * i + 1] = B[3];
} }
try {
const wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']);
// Import data as HMAC key, as it has no key length requirements
const keyToWrap = await webCrypto.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);
const wrapped = await webCrypto.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' });
return new Uint8Array(wrapped);
} catch (err) {
// no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
if (err.name !== 'NotSupportedError' &&
!(key.length === 24 && err.name === 'OperationError')) {
throw err;
} }
return pack(A, R); util.printDebugError('Browser did not support operation: ' + err.message);
}
return nobleAesKW(key).encrypt(dataToWrap);
} }
/** /**
* AES key unwrap * AES key unwrap
* @function * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo
* @param {String} key * @param {Uint8Array} key - wrapping key
* @param {String} data * @param {Uint8Array} wrappedData
* @returns {Uint8Array} * @returns {Uint8Array} unwrapped data
* @throws {Error}
*/ */
export function unwrap(key, data) { export async function unwrap(algo, key, wrappedData) {
const aes = new cipher['aes' + (key.length * 8)](key); const { keySize } = getCipherParams(algo);
const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); // sanity checks, since WebCrypto does not use the `algo` input
const C = unpack(data); if (!util.isAES(algo) || key.length !== keySize) {
let A = C.subarray(0, 2); throw new Error('Unexpected algorithm or key size');
const R = C.subarray(2);
const n = C.length / 2 - 1;
const t = new Uint32Array([0, 0]);
let B = new Uint32Array(4);
for (let j = 5; j >= 0; --j) {
for (let i = n - 1; i >= 0; --i) {
t[1] = n * j + (i + 1);
// B = A ^ t
B[0] = A[0] ^ t[0];
B[1] = A[1] ^ t[1];
// B = (A ^ t) || R[i]
B[2] = R[2 * i];
B[3] = R[2 * i + 1];
// B = AES-1(B)
B = unpack(aes.decrypt(pack(B)));
// A = MSB(64, B)
A = B.subarray(0, 2);
// R[i] = LSB(64, B)
R[2 * i] = B[2];
R[2 * i + 1] = B[3];
} }
let wrappingKey;
try {
wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']);
} catch (err) {
// no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
if (err.name !== 'NotSupportedError' &&
!(key.length === 24 && err.name === 'OperationError')) {
throw err;
} }
if (A[0] === IV[0] && A[1] === IV[1]) { util.printDebugError('Browser did not support operation: ' + err.message);
return pack(R); return nobleAesKW(key).decrypt(wrappedData);
} }
try {
const unwrapped = await webCrypto.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);
return new Uint8Array(await webCrypto.exportKey('raw', unwrapped));
} catch (err) {
if (err.name === 'OperationError') {
throw new Error('Key Data Integrity failed'); throw new Error('Key Data Integrity failed');
} }
throw err;
function createArrayBuffer(data) { }
if (util.isString(data)) {
const { length } = data;
const buffer = new ArrayBuffer(length);
const view = new Uint8Array(buffer);
for (let j = 0; j < length; ++j) {
view[j] = data.charCodeAt(j);
}
return buffer;
}
return new Uint8Array(data).buffer;
}
function unpack(data) {
const { length } = data;
const buffer = createArrayBuffer(data);
const view = new DataView(buffer);
const arr = new Uint32Array(length / 4);
for (let i = 0; i < length / 4; ++i) {
arr[i] = view.getUint32(4 * i);
}
return arr;
}
function pack() {
let length = 0;
for (let k = 0; k < arguments.length; ++k) {
length += 4 * arguments[k].length;
}
const buffer = new ArrayBuffer(length);
const view = new DataView(buffer);
let offset = 0;
for (let i = 0; i < arguments.length; ++i) {
for (let j = 0; j < arguments[i].length; ++j) {
view.setUint32(offset + 4 * j, arguments[i][j]);
}
offset += 4 * arguments[i].length;
}
return new Uint8Array(buffer);
} }

216
src/crypto/biginteger.ts Normal file
View File

@ -0,0 +1,216 @@
// Operations are not constant time, but we try and limit timing leakage where we can
const _0n = BigInt(0);
const _1n = BigInt(1);
export function uint8ArrayToBigInt(bytes: Uint8Array) {
const hexAlphabet = '0123456789ABCDEF';
let s = '';
bytes.forEach(v => {
s += hexAlphabet[v >> 4] + hexAlphabet[v & 15];
});
return BigInt('0x0' + s);
}
export function mod(a: bigint, m: bigint) {
const reduced = a % m;
return reduced < _0n ? reduced + m : reduced;
}
/**
* Compute modular exponentiation using square and multiply
* @param {BigInt} a - Base
* @param {BigInt} e - Exponent
* @param {BigInt} n - Modulo
* @returns {BigInt} b ** e mod n.
*/
export function modExp(b: bigint, e: bigint, n: bigint) {
if (n === _0n) throw Error('Modulo cannot be zero');
if (n === _1n) return BigInt(0);
if (e < _0n) throw Error('Unsopported negative exponent');
let exp = e;
let x = b;
x %= n;
let r = BigInt(1);
while (exp > _0n) {
const lsb = exp & _1n;
exp >>= _1n; // e / 2
// Always compute multiplication step, to reduce timing leakage
const rx = (r * x) % n;
// Update r only if lsb is 1 (odd exponent)
r = lsb ? rx : r;
x = (x * x) % n; // Square
}
return r;
}
function abs(x: bigint) {
return x >= _0n ? x : -x;
}
/**
* Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)
* Given a and b, compute (x, y) such that ax + by = gdc(a, b).
* Negative numbers are also supported.
* @param {BigInt} a - First operand
* @param {BigInt} b - Second operand
* @returns {{ gcd, x, y: bigint }}
*/
function _egcd(aInput: bigint, bInput: bigint) {
let x = BigInt(0);
let y = BigInt(1);
let xPrev = BigInt(1);
let yPrev = BigInt(0);
// Deal with negative numbers: run algo over absolute values,
// and "move" the sign to the returned x and/or y.
// See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers
let a = abs(aInput);
let b = abs(bInput);
const aNegated = aInput < _0n;
const bNegated = bInput < _0n;
while (b !== _0n) {
const q = a / b;
let tmp = x;
x = xPrev - q * x;
xPrev = tmp;
tmp = y;
y = yPrev - q * y;
yPrev = tmp;
tmp = b;
b = a % b;
a = tmp;
}
return {
x: aNegated ? -xPrev : xPrev,
y: bNegated ? -yPrev : yPrev,
gcd: a
};
}
/**
* Compute the inverse of `a` modulo `n`
* Note: `a` and and `n` must be relatively prime
* @param {BigInt} a
* @param {BigInt} n - Modulo
* @returns {BigInt} x such that a*x = 1 mod n
* @throws {Error} if the inverse does not exist
*/
export function modInv(a: bigint, n: bigint) {
const { gcd, x } = _egcd(a, n);
if (gcd !== _1n) {
throw new Error('Inverse does not exist');
}
return mod(x + n, n);
}
/**
* Compute greatest common divisor between this and n
* @param {BigInt} aInput - Operand
* @param {BigInt} bInput - Operand
* @returns {BigInt} gcd
*/
export function gcd(aInput: bigint, bInput: bigint) {
let a = aInput;
let b = bInput;
while (b !== _0n) {
const tmp = b;
b = a % b;
a = tmp;
}
return a;
}
/**
* Get this value as an exact Number (max 53 bits)
* Fails if this value is too large
* @returns {Number}
*/
export function bigIntToNumber(x: bigint) {
const number = Number(x);
if (number > Number.MAX_SAFE_INTEGER) {
// We throw and error to conform with the bn.js implementation
throw new Error('Number can only safely store up to 53 bits');
}
return number;
}
/**
* Get value of i-th bit
* @param {BigInt} x
* @param {Number} i - Bit index
* @returns {Number} Bit value.
*/
export function getBit(x:bigint, i: number) {
const bit = (x >> BigInt(i)) & _1n;
return bit === _0n ? 0 : 1;
}
/**
* Compute bit length
*/
export function bitLength(x: bigint) {
// -1n >> -1n is -1n
// 1n >> 1n is 0n
const target = x < _0n ? BigInt(-1) : _0n;
let bitlen = 1;
let tmp = x;
// eslint-disable-next-line no-cond-assign
while ((tmp >>= _1n) !== target) {
bitlen++;
}
return bitlen;
}
/**
* Compute byte length
*/
export function byteLength(x: bigint) {
const target = x < _0n ? BigInt(-1) : _0n;
const _8n = BigInt(8);
let len = 1;
let tmp = x;
// eslint-disable-next-line no-cond-assign
while ((tmp >>= _8n) !== target) {
len++;
}
return len;
}
/**
* Get Uint8Array representation of this number
* @param {String} endian - Endianess of output array (defaults to 'be')
* @param {Number} length - Of output array
* @returns {Uint8Array}
*/
export function bigIntToUint8Array(x: bigint, endian = 'be', length: number) {
// we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)
// this is faster than shift+mod iterations
let hex = x.toString(16);
if (hex.length % 2 === 1) {
hex = '0' + hex;
}
const rawLength = hex.length / 2;
const bytes = new Uint8Array(length || rawLength);
// parse hex
const offset = length ? length - rawLength : 0;
let i = 0;
while (i < rawLength) {
bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
i++;
}
if (endian !== 'be') {
bytes.reverse();
}
return bytes;
}

View File

@ -1,26 +0,0 @@
import { AES_ECB } from '@openpgp/asmcrypto.js/dist_es8/aes/ecb';
/**
* Javascript AES implementation.
* This is used as fallback if the native Crypto APIs are not available.
*/
function aes(length) {
const C = function(key) {
const aesECB = new AES_ECB(key);
this.encrypt = function(block) {
return aesECB.encrypt(block);
};
this.decrypt = function(block) {
return aesECB.decrypt(block);
};
};
C.blockSize = C.prototype.blockSize = 16;
C.keySize = C.prototype.keySize = length / 8;
return C;
}
export default aes;

View File

@ -1,13 +0,0 @@
import * as cipher from '.';
import enums from '../../enums';
/**
* Get implementation of the given cipher
* @param {enums.symmetric} algo
* @returns {Object}
* @throws {Error} on invalid algo
*/
export default function getCipher(algo) {
const algoName = enums.read(enums.symmetric, algo);
return cipher[algoName];
}

View File

@ -1,81 +1,72 @@
/** import enums from '../../enums';
* @fileoverview Symmetric cryptography functions
* @module crypto/cipher
* @private
*/
import aes from './aes'; export async function getLegacyCipher(algo) {
import { DES, TripleDES } from './des'; switch (algo) {
import CAST5 from './cast5'; case enums.symmetric.aes128:
import TF from './twofish'; case enums.symmetric.aes192:
import BF from './blowfish'; case enums.symmetric.aes256:
throw new Error('Not a legacy cipher');
case enums.symmetric.cast5:
case enums.symmetric.blowfish:
case enums.symmetric.twofish:
case enums.symmetric.tripledes: {
const { legacyCiphers } = await import('./legacy_ciphers');
const cipher = legacyCiphers.get(algo);
if (!cipher) {
throw new Error('Unsupported cipher algorithm');
}
return cipher;
}
default:
throw new Error('Unsupported cipher algorithm');
}
}
/** /**
* AES-128 encryption and decryption (ID 7) * Get block size for given cipher algo
* @function * @param {module:enums.symmetric} algo - alrogithm identifier
* @param {String} key - 128-bit key
* @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
* @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
* @returns {Object}
*/ */
export const aes128 = aes(128); function getCipherBlockSize(algo) {
switch (algo) {
case enums.symmetric.aes128:
case enums.symmetric.aes192:
case enums.symmetric.aes256:
case enums.symmetric.twofish:
return 16;
case enums.symmetric.blowfish:
case enums.symmetric.cast5:
case enums.symmetric.tripledes:
return 8;
default:
throw new Error('Unsupported cipher');
}
}
/** /**
* AES-128 Block Cipher (ID 8) * Get key size for given cipher algo
* @function * @param {module:enums.symmetric} algo - alrogithm identifier
* @param {String} key - 192-bit key
* @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
* @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
* @returns {Object}
*/ */
export const aes192 = aes(192); function getCipherKeySize(algo) {
switch (algo) {
case enums.symmetric.aes128:
case enums.symmetric.blowfish:
case enums.symmetric.cast5:
return 16;
case enums.symmetric.aes192:
case enums.symmetric.tripledes:
return 24;
case enums.symmetric.aes256:
case enums.symmetric.twofish:
return 32;
default:
throw new Error('Unsupported cipher');
}
}
/** /**
* AES-128 Block Cipher (ID 9) * Get block and key size for given cipher algo
* @function * @param {module:enums.symmetric} algo - alrogithm identifier
* @param {String} key - 256-bit key
* @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
* @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
* @returns {Object}
*/ */
export const aes256 = aes(256); export function getCipherParams(algo) {
// Not in OpenPGP specifications return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) };
export const des = DES; }
/**
* Triple DES Block Cipher (ID 2)
* @function
* @param {String} key - 192-bit key
* @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}
* @returns {Object}
*/
export const tripledes = TripleDES;
/**
* CAST-128 Block Cipher (ID 3)
* @function
* @param {String} key - 128-bit key
* @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}
* @returns {Object}
*/
export const cast5 = CAST5;
/**
* Twofish Block Cipher (ID 10)
* @function
* @param {String} key - 256-bit key
* @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}
* @returns {Object}
*/
export const twofish = TF;
/**
* Blowfish Block Cipher (ID 4)
* @function
* @param {String} key - 128-bit key
* @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}
* @returns {Object}
*/
export const blowfish = BF;
/**
* Not implemented
* @function
* @throws {Error}
*/
export const idea = function() {
throw new Error('IDEA symmetric-key algorithm not implemented');
};

View File

@ -0,0 +1,17 @@
/**
* This file is needed to dynamic import the legacy ciphers.
* Separate dynamic imports are not convenient as they result in multiple chunks.
*/
import { TripleDES } from './des';
import CAST5 from './cast5';
import TwoFish from './twofish';
import BlowFish from './blowfish';
import enums from '../../enums';
export const legacyCiphers = new Map([
[enums.symmetric.tripledes, TripleDES],
[enums.symmetric.cast5, CAST5],
[enums.symmetric.blowfish, BlowFish],
[enums.symmetric.twofish, TwoFish]
]);

View File

@ -2,10 +2,9 @@
* @fileoverview This module implements AES-CMAC on top of * @fileoverview This module implements AES-CMAC on top of
* native AES-CBC using either the WebCrypto API or Node.js' crypto API. * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
* @module crypto/cmac * @module crypto/cmac
* @private
*/ */
import { AES_CBC } from '@openpgp/asmcrypto.js/dist_es8/aes/cbc'; import { cbc as nobleAesCbc } from '@noble/ciphers/aes';
import util from '../util'; import util from '../util';
const webCrypto = util.getWebCrypto(); const webCrypto = util.getWebCrypto();
@ -73,13 +72,6 @@ export default async function CMAC(key) {
} }
async function CBC(key) { async function CBC(key) {
if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
return async function(pt) {
const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);
return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);
};
}
if (util.getNodeCrypto()) { // Node crypto library if (util.getNodeCrypto()) { // Node crypto library
return async function(pt) { return async function(pt) {
const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock); const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);
@ -87,8 +79,25 @@ async function CBC(key) {
return new Uint8Array(ct); return new Uint8Array(ct);
}; };
} }
// asm.js fallback
if (util.getWebCrypto()) {
try {
key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
return async function(pt) { return async function(pt) {
return AES_CBC.encrypt(pt, key, false, zeroBlock); const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);
return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);
};
} catch (err) {
// no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
if (err.name !== 'NotSupportedError' &&
!(key.length === 24 && err.name === 'OperationError')) {
throw err;
}
util.printDebugError('Browser did not support operation: ' + err.message);
}
}
return async function(pt) {
return nobleAesCbc(key, zeroBlock, { disablePadding: true }).encrypt(pt);
}; };
} }

Some files were not shown because too many files have changed in this diff Show More