Compare commits

..

No commits in common. "main" and "v4.10.4" have entirely different histories.

314 changed files with 172801 additions and 157740 deletions

14
.codeclimate.yml Normal file
View File

@ -0,0 +1,14 @@
---
engines:
duplication:
enabled: true
config:
languages:
- javascript
eslint:
enabled: true
fixme:
enabled: true
ratings:
paths:
- "lib/**/*"

View File

@ -1,4 +1 @@
dist
test/lib/
test/typescript/
docs
src/compression

View File

@ -1,142 +0,0 @@
module.exports = {
'extends': [
'airbnb-base',
'airbnb-typescript/base'
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaVersion': 11,
'sourceType': 'module',
'project': 'tsconfig.json'
},
'env': {
'browser': true,
'es6': true,
'node': true
},
'plugins': [
'@typescript-eslint',
'chai-friendly',
'import',
'unicorn'
],
'settings': {
'import/resolver': {
'typescript': {}
}
},
'globals': { // TODO are all these necessary?
'globalThis': true,
'console': true,
'Promise': true,
'importScripts': true,
'process': true,
'Event': true,
'describe': true,
'it': true,
'mocha': true,
'before': true,
'beforeEach': true,
'after': true,
'afterEach': true,
'escape': true,
'unescape': true,
'resolves': true,
'rejects': true,
'TransformStream': true,
'BigInt': true
},
'rules': {
'arrow-body-style': 'off',
'arrow-parens': ['error','as-needed'],
'class-methods-use-this': 'off',
'@typescript-eslint/comma-dangle': ['error', 'never'],
'@typescript-eslint/comma-spacing': 'off',
'consistent-return': 'off',
'default-case': 'off',
'@typescript-eslint/default-param-last': 'off',
'eol-last': ['error', 'always'],
'function-call-argument-newline': 'off',
'func-names': ['error', 'never'],
'function-paren-newline': 'off',
'global-require': 'off',
'key-spacing': 'off',
'keyword-spacing': 'error',
'max-classes-per-file': 'off',
'max-len': 'off',
'newline-per-chained-call': 'off',
'no-bitwise': 'off',
'no-continue': 'off',
'no-else-return': 'off',
'no-empty': ['error', { 'allowEmptyCatch': true }],
'no-multiple-empty-lines': ['error', { 'max': 2, 'maxEOF': 1, 'maxBOF':0 }],
'no-nested-ternary': 'off',
'no-param-reassign': 'off', // TODO get rid of this
'no-plusplus': 'off',
'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
'object-curly-newline': 'off',
'@typescript-eslint/no-shadow': 'off', // TODO get rid of this
'object-property-newline': [
'error',
{
'allowMultiplePropertiesPerLine': true
}
],
'object-shorthand': 'off',
'operator-assignment': 'off',
'operator-linebreak': [
'error',
'after'
],
'padded-blocks': 'off',
'prefer-arrow-callback': 'off',
'prefer-destructuring': 'off',
'prefer-rest-params': 'off', // TODO get rid of this
'prefer-spread': 'off', // TODO get rid of this
'prefer-template': 'off',
'quote-props': 'off',
'quotes': ['error', 'single', { 'avoidEscape': true }],
'@typescript-eslint/space-before-function-paren': ['error', { 'anonymous': 'ignore', 'named': 'never', 'asyncArrow': 'always' }],
'spaced-comment': 'off',
'indent': 'off',
'@typescript-eslint/indent': ['error', 2, { 'SwitchCase': 1 }],
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
// eslint-plugin-import rules:
'import/named': '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-unassigned-import': 'error',
'import/no-unresolved': 'error',
'import/prefer-default-export': 'off',
// Custom silencers:
'no-multi-assign': 'off',
'no-underscore-dangle': '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:
'@typescript-eslint/no-use-before-define': ['error', { 'functions': false, 'classes': true, 'variables': false, 'allowNamedExports': true }],
'no-constant-condition': [2, { 'checkLoops': false }],
'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 }],
'@typescript-eslint/no-unused-expressions': 0,
'chai-friendly/no-unused-expressions': [2, { 'allowShortCircuit': true }],
'unicorn/switch-case-braces': ['error', 'avoid'],
// Custom warnings:
'no-console': 1
}
};

350
.eslintrc.js Normal file
View File

@ -0,0 +1,350 @@
module.exports = {
"extends": "airbnb-base",
"parserOptions": { "sourceType": "module" },
"env": {
"browser": true,
"es6": true,
"node": true
},
"plugins": [
"chai-friendly"
],
"globals": { // TODO are all these necessary?
"console": true,
"Promise": true,
"importScripts": true,
"process": true,
"Event": true,
"describe": true,
"it": true,
"sinon": true,
"mocha": true,
"before": true,
"beforeEach": true,
"after": true,
"afterEach": true,
"escape": true,
"unescape": true,
"postMessage": true,
"resolves": true,
"rejects": true,
"TransformStream": true
},
"rules": {
// Auto generated rules:
"accessor-pairs": "error",
"array-bracket-newline": "error",
"array-bracket-spacing": [
"error",
"never"
],
"array-callback-return": "error",
"array-element-newline": "off",
"arrow-body-style": "off",
"arrow-parens": [
"error",
"as-needed"
],
"arrow-spacing": [
"error",
{
"after": true,
"before": true
}
],
"block-spacing": [
"error",
"always"
],
"brace-style": "off",
"callback-return": "error",
"camelcase": [
"error",
{
"properties": "never"
}
],
"capitalized-comments": "off",
"class-methods-use-this": "error",
"comma-dangle": [ "error", "never" ],
"comma-spacing": "off",
"comma-style": [
"error",
"last"
],
"complexity": "off",
"computed-property-spacing": [
"error",
"never"
],
"consistent-return": "off",
"consistent-this": "error",
"curly": "error",
"default-case": "off",
"dot-location": "error",
"dot-notation": [
"error",
{
"allowKeywords": true
}
],
"eol-last": ["error", "always"],
"eqeqeq": "error",
"for-direction": "error",
"func-call-spacing": "error",
"func-name-matching": "error",
"func-names": [
"error",
"never"
],
"func-style": "off",
"function-paren-newline": "off",
"generator-star-spacing": "error",
"getter-return": "error",
"global-require": "off",
"guard-for-in": "off",
"handle-callback-err": "error",
"id-blacklist": "error",
"id-length": "off",
"id-match": "error",
"implicit-arrow-linebreak": [
"error",
"beside"
],
"init-declarations": "off",
"jsx-quotes": "error",
"key-spacing": "off",
"keyword-spacing": "error",
"line-comment-position": "off",
"linebreak-style": [
"error",
"unix"
],
"lines-around-comment": "off",
"lines-around-directive": "error",
"lines-between-class-members": "error",
"max-depth": "off",
"max-len": "off",
"max-lines": "off",
"max-nested-callbacks": "error",
"max-params": "off",
"max-statements": "off",
"max-statements-per-line": "off",
"multiline-comment-style": "off",
"multiline-ternary": "off",
"new-parens": "error",
"newline-after-var": "off",
"newline-before-return": "off",
"newline-per-chained-call": "off",
"no-alert": "error",
"no-array-constructor": "error",
"no-bitwise": "off",
"no-buffer-constructor": "error",
"no-caller": "error",
"no-catch-shadow": "error",
"no-confusing-arrow": "error",
"no-continue": "off",
"no-div-regex": "error",
"no-duplicate-imports": "error",
"no-else-return": "off",
"no-empty": [
"error",
{
"allowEmptyCatch": true
}
],
"no-empty-function": "off",
"no-eq-null": "error",
"no-eval": "error",
"no-extend-native": "error",
"no-extra-bind": "error",
"no-extra-label": "error",
"no-extra-parens": "off",
"no-floating-decimal": "error",
"no-implicit-globals": "error",
"no-implied-eval": "error",
"no-inline-comments": "off",
"no-inner-declarations": [
"error",
"functions"
],
"no-invalid-this": "error",
"no-iterator": "error",
"no-label-var": "error",
"no-labels": "error",
"no-lone-blocks": "error",
"no-lonely-if": "error",
"no-loop-func": "error",
"no-magic-numbers": "off",
"no-mixed-operators": "off",
"no-mixed-requires": "error",
"no-multi-assign": "error",
"no-multi-spaces": [
"error",
{
"ignoreEOLComments": true
}
],
"no-multi-str": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF":0 }],
"no-native-reassign": "error",
"no-negated-condition": "off",
"no-negated-in-lhs": "error",
"no-nested-ternary": "off",
"no-new": "error",
"no-new-func": "error",
"no-new-object": "error",
"no-new-require": "error",
"no-new-wrappers": "error",
"no-octal-escape": "error",
"no-param-reassign": "off",
"no-path-concat": "error",
"no-plusplus": "off",
"no-process-env": "error",
"no-process-exit": "error",
"no-proto": "error",
"no-prototype-builtins": "off",
"no-restricted-globals": "error",
"no-restricted-imports": "error",
"no-restricted-modules": "error",
"no-restricted-properties": "error",
"no-restricted-syntax": "error",
"no-return-assign": "error",
"no-return-await": "error",
"no-script-url": "error",
"no-self-compare": "error",
"no-shadow": "off",
"no-shadow-restricted-names": "error",
"no-spaced-func": "error",
"no-sync": "error",
"no-tabs": "error",
"no-template-curly-in-string": "error",
"no-ternary": "off",
"no-throw-literal": "error",
"no-undef-init": "error",
"no-undefined": "off",
"no-unmodified-loop-condition": "error",
"no-unneeded-ternary": [
"error",
{
"defaultAssignment": true
}
],
"no-use-before-define": "off",
"no-useless-call": "error",
"no-useless-computed-key": "error",
"no-useless-concat": "error",
"no-useless-constructor": "error",
"no-useless-rename": "error",
"no-useless-return": "error",
"no-void": "error",
"no-warning-comments": "off",
"no-whitespace-before-property": "error",
"no-with": "error",
"nonblock-statement-body-position": "error",
"object-curly-newline": "off",
"object-curly-spacing": "error",
"object-property-newline": [
"error",
{
"allowMultiplePropertiesPerLine": true
}
],
"object-shorthand": "off",
"one-var-declaration-per-line": [
"error",
"initializations"
],
"operator-assignment": "off",
"operator-linebreak": [
"error",
"after"
],
"padded-blocks": "off",
"padding-line-between-statements": "error",
"prefer-arrow-callback": "off",
"prefer-destructuring": "off",
"prefer-numeric-literals": "error",
"prefer-promise-reject-errors": "error",
"prefer-reflect": "off",
"prefer-rest-params": "off",
"prefer-spread": "off",
"prefer-template": "off",
"quote-props": "off",
"quotes": "off",
"require-await": "error",
"require-jsdoc": "off",
"semi-spacing": [
"error",
{
"after": true,
"before": false
}
],
"semi-style": [
"error",
"last"
],
"sort-imports": "off",
"sort-keys": "off",
"sort-vars": "off",
"space-before-blocks": "off",
"space-before-function-paren": "off",
"space-in-parens": [
"error",
"never"
],
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "off",
"strict": "off",
"switch-colon-spacing": "error",
"symbol-description": "error",
"template-curly-spacing": "error",
"template-tag-spacing": "error",
"unicode-bom": [
"error",
"never"
],
"wrap-iife": "error",
"wrap-regex": "off",
"yield-star-spacing": "error",
"yoda": [
"error",
"never"
],
"indent": [ "error", 2, { "SwitchCase": 1 } ],
"no-buffer-constructor": "error",
"no-lonely-if": "error",
"no-unused-vars": "error",
// eslint-plugin-import rules:
"import/extensions": "never",
"import/no-extraneous-dependencies": ["error", {"devDependencies": true, "optionalDependencies": false, "peerDependencies": false}],
// Custom silencers:
"camelcase": 0,
"require-await": 0,
"no-multi-assign": 0,
"no-underscore-dangle": 0,
"no-await-in-loop": 0,
// Custom errors:
"no-undef": 2,
"no-trailing-spaces": 2,
"no-mixed-operators": [ 2, {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}],
"no-use-before-define": [ 2, { "functions": false, "classes": true, "variables": false }],
"no-constant-condition": [ 2, { "checkLoops": false } ],
"new-cap": [ 2, { "properties": false, "capIsNewExceptionPattern": "CMAC|CBC|OMAC|CTR", "newIsCapExceptionPattern": "type|hash*"}],
"max-lines": [ 2, { "max": 550, "skipBlankLines": true, "skipComments": true } ],
"no-unused-expressions": 0,
"chai-friendly/no-unused-expressions": [ 2, { "allowShortCircuit": true } ],
// Custom warnings:
"no-console": 1,
}
};

View File

@ -1,10 +0,0 @@
---
name: Bug report
about: Report an issue with this library
---
<!-- Please search existing issues and discussions to avoid creating duplicates. -->
- OpenPGP.js version:
- Affected platform (Browser or Node.js version):
<!-- Describe the bug you have encountered -->

View File

@ -1,8 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Feature request
url: https://github.com/openpgpjs/openpgpjs/discussions/categories/ideas
about: Suggest an idea for this project
- name: Question
url: https://github.com/openpgpjs/openpgpjs/discussions/categories/q-a
about: Please ask any questions here

View File

@ -1,33 +0,0 @@
version: 2
updates:
- package-ecosystem: "npm"
# The redundant target-branch directive is needed to set two different update schedules for npm,
# working around a dependabot limitation:
# see https://github.com/dependabot/dependabot-core/issues/1778#issuecomment-1988140219 .
target-branch: main
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

@ -1,39 +0,0 @@
{
"drivers": [
{
"id": "sop-openpgpjs-branch",
"path": "__SOP_OPENPGPJS__",
"env": {
"OPENPGPJS_PATH": "__OPENPGPJS_BRANCH__"
}
},
{
"id": "sop-openpgpjs-main",
"path": "__SOP_OPENPGPJS__",
"env": {
"OPENPGPJS_PATH": "__OPENPGPJS_MAIN__",
"DISABLE_PROFILES": "true"
}
},
{
"path": "__SQOP__"
},
{
"path": "__GPGME_SOP__"
},
{
"id": "gosop-v2",
"path": "__GOSOP_V2__"
},
{
"path": "__RNP_SOP__"
},
{
"path": "__RSOP__"
}
],
"rlimits": {
"DATA": 1073741824
}
}

View File

@ -1,14 +0,0 @@
CONFIG_TEMPLATE=$1
CONFIG_OUTPUT=$2
OPENPGPJS_BRANCH=$3
OPENPGPJS_MAIN=$4
cat $CONFIG_TEMPLATE \
| sed "s@__OPENPGPJS_BRANCH__@${OPENPGPJS_BRANCH}@g" \
| sed "s@__OPENPGPJS_MAIN__@${OPENPGPJS_MAIN}@g" \
| sed "s@__SQOP__@${SQOP}@g" \
| sed "s@__GPGME_SOP__@${GPGME_SOP}@g" \
| sed "s@__GOSOP_V2__@${GOSOP_V2}@g" \
| sed "s@__SOP_OPENPGPJS__@${SOP_OPENPGPJS_V2}@g" \
| sed "s@__RNP_SOP__@${RNP_SOP}@g" \
| sed "s@__RSOP__@${RSOP}@g" \
> $CONFIG_OUTPUT

View File

@ -1,67 +0,0 @@
name: Performance Regression Test
on:
pull_request:
branches: [main]
jobs:
benchmark:
name: Time and memory usage benchmark
runs-on: ubuntu-latest
steps:
# check out pull request branch
- uses: actions/checkout@v4
with:
path: pr
# check out main branch (to compare performance)
- uses: actions/checkout@v4
with:
ref: main
path: main
- uses: actions/setup-node@v4
with:
node-version: '>=20.6.0'
- name: Run pull request time benchmark
run: cd pr && npm install && npm run --silent benchmark-time > benchmarks.txt && cat benchmarks.txt
- name: Run pull request memory usage benchmark
run: cd pr && npm run --silent benchmark-memory-usage > memory_usage.txt && cat memory_usage.txt
- name: Run time benchmark on main (baseline)
run: cd main && npm install && npm run --silent benchmark-time > benchmarks.txt && cat benchmarks.txt
- name: Run memory usage benchmark on main (baseline)
run: cd main && npm run --silent benchmark-memory-usage > memory_usage.txt && cat memory_usage.txt
- name: Compare time benchmark result
uses: openpgpjs/github-action-pull-request-benchmark@v1
with:
tool: 'benchmarkjs'
name: 'Time benchmark'
pr-benchmark-file-path: pr/benchmarks.txt
base-benchmark-file-path: main/benchmarks.txt
github-token: ${{ secrets.GITHUB_TOKEN }}
# trigger alert comment if 1.3 times slower
alert-threshold: '130%'
comment-on-alert: false
# fail workdlow if 1.5 times slower
fail-threshold: '150%'
fail-on-alert: true
file-to-annotate: ${{ github.workspace }}/test/benchmarks/time.js
- name: Compare memory usage benchmark result
uses: openpgpjs/github-action-pull-request-benchmark@v1
with:
tool: 'raw'
name: 'Memory usage benchmark'
pr-benchmark-file-path: pr/memory_usage.txt
base-benchmark-file-path: main/memory_usage.txt
github-token: ${{ secrets.GITHUB_TOKEN }}
alert-threshold: '102%'
comment-on-alert: false
fail-threshold: '110%'
fail-on-alert: true
file-to-annotate: ${{ github.workspace }}/test/benchmarks/memory_usage.js

View File

@ -1,19 +0,0 @@
name: Documentation
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
lint:
name: JSDoc
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci --ignore-scripts
- run: npm run docs

View File

@ -1,87 +0,0 @@
name: SOP interoperability test suite
on:
pull_request:
branches: [ main ]
jobs:
test-suite:
name: Run interoperability test suite
runs-on: ubuntu-latest
container:
image: ghcr.io/protonmail/openpgp-interop-test-docker:v1.1.12
credentials:
username: ${{ github.actor }}
password: ${{ secrets.github_token }}
steps:
# check out repo for scripts
- uses: actions/checkout@v4
# check out pull request branch
- name: Checkout openpgpjs-branch
uses: actions/checkout@v4
with:
path: openpgpjs-branch
- name: Install openpgpjs-branch
run: cd openpgpjs-branch && npm install
- name: Print openpgpjs-branch version
run: $SOP_OPENPGPJS_V2 version --extended
env:
OPENPGPJS_PATH: ${{ github.workspace }}/openpgpjs-branch
# check out main branch
- name: Checkout openpgpjs-main
uses: actions/checkout@v4
with:
ref: main
path: openpgpjs-main
- name: Install openpgpjs-main
run: cd openpgpjs-main && npm install
- name: Print openpgpjs-main version
run: $SOP_OPENPGPJS_V2 version --extended
env:
OPENPGPJS_PATH: ${{ github.workspace }}/openpgpjs-main
# Run test suite
- name: Prepare test configuration
run: ./.github/test-suite/prepare_config.sh $CONFIG_TEMPLATE $CONFIG_OUTPUT $GITHUB_WORKSPACE/openpgpjs-branch $GITHUB_WORKSPACE/openpgpjs-main
env:
CONFIG_TEMPLATE: .github/test-suite/config.json.template
CONFIG_OUTPUT: .github/test-suite/config.json
- name: Display configuration
run: cat .github/test-suite/config.json
- name: Run interoperability test suite
run: cd $TEST_SUITE_DIR && $TEST_SUITE --config $GITHUB_WORKSPACE/$CONFIG --json-out $GITHUB_WORKSPACE/$RESULTS_JSON --html-out $GITHUB_WORKSPACE/$RESULTS_HTML
env:
CONFIG: .github/test-suite/config.json
RESULTS_JSON: .github/test-suite/test-suite-results.json
RESULTS_HTML: .github/test-suite/test-suite-results.html
# Upload results
- name: Upload test results json artifact
uses: actions/upload-artifact@v4
with:
name: test-suite-results.json
path: .github/test-suite/test-suite-results.json
- name: Upload test results html artifact
uses: actions/upload-artifact@v4
with:
name: test-suite-results.html
path: .github/test-suite/test-suite-results.html
compare-with-main:
name: Compare with main
runs-on: ubuntu-latest
needs: test-suite
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Download test results json artifact
id: download-test-results
uses: actions/download-artifact@v4
with:
name: test-suite-results.json
- name: Compare with baseline
uses: ProtonMail/openpgp-interop-test-analyzer@v2
with:
results: ${{ steps.download-test-results.outputs.download-path }}/test-suite-results.json
output: baseline-comparison.json
baseline: sop-openpgpjs-main
target: sop-openpgpjs-branch

View File

@ -1,206 +0,0 @@
name: Code Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build: # cache both dist and tests (non-lightweight only), based on commit hash
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- name: Check for cached folders
id: cache-full
uses: actions/cache@v4
with:
path: |
dist
test/lib
key: cache-${{ github.sha }}
- name: Build dist and tests
if: steps.cache-full.outputs.cache-hit != 'true'
run: |
npm ci
npm run build-test
node:
strategy:
fail-fast: false # if tests for one version fail, continue with the rest
matrix:
node-version: [18.x, 20.x, 22.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
name: Node ${{ matrix.node-version }}
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm ci --ignore-scripts # for mocha
- name: Retrieve cached folders
uses: actions/cache/restore@v4
id: cache-full
with:
# test/lib is not needed, but the path must be specified fully for a cache-hit
path: |
dist
test/lib
key: cache-${{ github.sha }}
# ignore cache miss, since it was taken care of the `build` step and it should never occur here
- run: npm test
test-browsers-latest:
name: Browsers (latest)
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:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- name: Retrieve cached built folders
uses: actions/cache/restore@v4
id: cache-full
with:
path: |
dist
test/lib
key: cache-${{ github.sha }}
- name: Install dependencies
# cannot use `--ignore-scripts` since playwright seems to use it to set ENV vars
run: |
npm pkg delete scripts.prepare
npm ci
- name: Get Playwright version and cache location
id: playwright-version
run: |
PLAYWRIGHT_VERSION=$(npm ls playwright --depth=0 | grep playwright | sed 's/.*@//')
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
id: cache-playwright-browsers
uses: actions/cache@v4
with:
path: ${{ steps.playwright-version.outputs.playwright_cache }}
key: playwright-browsers-${{ matrix.runner }}-${{ steps.playwright-version.outputs.version }}
- name: Install browsers
if: steps.cache-playwright-browsers.outputs.cache-hit != 'true'
run: |
npx playwright install --with-deps chromium
npx playwright install --with-deps firefox
- name: Install WebKit # caching not possible, external shared libraries required
if: ${{ matrix.runner == 'macos-latest' }} # do not install on ubuntu, since the X25519 WebCrypto implementation has issues
run: npx playwright install --with-deps webkit
- name: Run browser tests
run: npm run test-browser:ci -- --static-logging
- name: Run browser tests (lightweight) # overwrite test/lib
run: |
npm run build-test --lightweight
npm run test-browser:ci -- --static-logging
test-browsers-compatibility:
name: Browsers (older, on Browserstack)
runs-on: ubuntu-latest
needs: test-browsers-latest
env: # credentials need hardcoding for now since Github secrets aren't accessible on pull requests from forks
BROWSERSTACK_USERNAME: openpgpjs_PlY4Uq885CQ
BROWSERSTACK_ACCESS_KEY: VjgBVRMxNVBj7SjJFiau
steps:
- uses: actions/checkout@v4
- 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
run: npm ci --ignore-scripts
- name: Retrieve cached dist folder
uses: actions/cache/restore@v4
id: cache-full
with:
path: |
dist
test/lib
key: cache-${{ github.sha }}
- name: Wait for other Browserstack tests to finish
uses: softprops/turnstyle@v1
with:
poll-interval-seconds: 30
abort-after-seconds: 900
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Run browserstack tests
run: npm run test-browserstack -- --static-logging
- name: Run browserstack tests (lightweight) # overwrite test/lib
run: |
npm run build-test --lightweight
npm run test-browserstack -- --static-logging
env:
LIGHTWEIGHT: true
types:
name: Type definitions
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci --ignore-scripts # TS
- name: Retrieve cached folders
uses: actions/cache/restore@v4
id: cache-full
with:
path: |
dist
test/lib
key: cache-${{ github.sha }}
- run: npm run test-type-definitions
lint:
name: ESLint
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci --ignore-scripts # linter
- name: Retrieve cached folders
uses: actions/cache/restore@v4
id: cache-full
with:
path: |
dist
test/lib
key: cache-${{ github.sha }}
- run: npm run lint

6
.gitignore vendored
View File

@ -1,8 +1,10 @@
.DS_Store
node_modules/
npm*
src/compression/
test/lib/
test/typescript/definitions.js
dist/
openpgp.store/
coverage
doc/
browserify-cache*.json
.nyc_output/

View File

@ -1,17 +0,0 @@
const pkg = require('./package.json');
module.exports = {
plugins: ['plugins/markdown'],
markdown: {
idInHeadings: true
},
templates: {
default: {
includeDate: false,
outputSourceFiles: false,
externalSourceLinks: {
urlPrefix: `${pkg.repository.url}/blob/v${pkg.version}/src/`
}
}
}
};

3
.jsdocrc.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
plugins: ['plugins/markdown']
};

View File

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

55
.travis.yml Normal file
View File

@ -0,0 +1,55 @@
sudo: false
language: node_js
cache:
directories:
- node_modules
addons:
code_climate:
repo_token: $CODECLIMATE_REPO_TOKEN
matrix:
fast_finish: true
include:
- node_js: "8"
env: OPENPGP_NODE_JS='8' OPENPGPJSTEST='unit'
- node_js: "10"
env: OPENPGP_NODE_JS='10' OPENPGPJSTEST='unit'
- node_js: "12"
env: OPENPGP_NODE_JS='12' OPENPGPJSTEST='unit'
- node_js: "10"
env: OPENPGP_NODE_JS='10' OPENPGPJSTEST='unit' LIGHTWEIGHT=1
- node_js: "9"
env: BROWSER='"firefox_26"' OPENPGPJSTEST='browserstack' COMPAT=1
- node_js: "9"
env: BROWSER='"firefox_61"' OPENPGPJSTEST='browserstack'
- node_js: "10"
env: BROWSER='"chrome_68"' OPENPGPJSTEST='browserstack' LIGHTWEIGHT=1
- node_js: "9"
env: BROWSER='"chrome_49"' OPENPGPJSTEST='browserstack' COMPAT=1
- node_js: "10"
env: BROWSER='"chrome_68"' OPENPGPJSTEST='browserstack'
- node_js: "9"
env: BROWSER='"ie_11"' OPENPGPJSTEST='browserstack' COMPAT=1
- node_js: "9"
env: BROWSER='"edge_17"' OPENPGPJSTEST='browserstack'
- node_js: "9"
env: BROWSER='"safari_9_1"' OPENPGPJSTEST='browserstack' COMPAT=1
- node_js: "9"
env: BROWSER='"safari_10_1"' OPENPGPJSTEST='browserstack' COMPAT=1
- node_js: "9"
env: BROWSER='"safari_11_1"' OPENPGPJSTEST='browserstack'
- node_js: "9"
env: BROWSER='{"os":"ios", "os_version":"10.3", "device":"iPhone 7 Plus", "real_mobile":true}' OPENPGPJSTEST='browserstack' COMPAT=1
- node_js: "9"
env: BROWSER='{"os":"ios", "os_version":"11.3", "device":"iPhone 8 Plus", "real_mobile":true}' OPENPGPJSTEST='browserstack'
allow_failures:
- node_js: "9"
before_script:
- npm install -g grunt-cli codeclimate-test-reporter browserstack-runner
script:
- $TRAVIS_BUILD_DIR/travis.sh
install: npm install
env:
global:
- BROWSERSTACK_USERNAME=danielhuigens2
- BROWSERSTACK_KEY=aW2q1ms393QRorwBnfmW

360
Gruntfile.js Normal file
View File

@ -0,0 +1,360 @@
module.exports = function(grunt) {
const version = grunt.option('release');
const fs = require('fs');
// Project configuration.
const dev = !!grunt.option('dev');
const compat = !!grunt.option('compat');
const lightweight = !!grunt.option('lightweight');
const plugins = compat ? [
"transform-async-to-generator",
"syntax-async-functions",
"transform-regenerator",
"transform-runtime"
] : [];
const presets = [[require.resolve('babel-preset-env'), {
targets: {
browsers: compat ? [
'IE >= 11',
'Safari >= 9',
'Last 2 Chrome versions',
'Last 2 Firefox versions',
'Last 2 Edge versions'
] : [
'Last 2 Chrome versions',
'Last 2 Firefox versions',
'Last 2 Safari versions',
'Last 2 Edge versions'
]
}
}]];
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify: {
openpgp: {
files: {
'dist/openpgp.js': ['./src/index.js']
},
options: {
browserifyOptions: {
fullPaths: dev,
debug: dev,
standalone: 'openpgp'
},
cacheFile: 'browserify-cache' + (compat ? '-compat' : '') + (lightweight ? '-lightweight' : '') + '.json',
// Don't bundle these packages with openpgp.js
external: ['crypto', 'zlib', 'node-localstorage', 'node-fetch', 'asn1.js', 'stream', 'buffer'].concat(
compat ? [] : [
'whatwg-fetch',
'core-js/fn/array/fill',
'core-js/fn/array/find',
'core-js/fn/array/includes',
'core-js/fn/array/from',
'core-js/fn/promise',
'core-js/fn/typed/uint8-array',
'core-js/fn/string/repeat',
'core-js/fn/symbol',
'core-js/fn/object/assign'
],
lightweight ? [
'elliptic',
'elliptic.min.js'
] : []
),
transform: [
["babelify", {
global: true,
// Only babelify web-streams-polyfill, web-stream-tools, asmcrypto, email-addresses and seek-bzip in node_modules
only: /^(?:.*\/node_modules\/@mattiasbuelens\/web-streams-polyfill\/|.*\/node_modules\/web-stream-tools\/|.*\/node_modules\/asmcrypto\.js\/|.*\/node_modules\/email-addresses\/|.*\/node_modules\/seek-bzip\/|(?!.*\/node_modules\/)).*$/,
ignore: ['*.min.js'],
plugins,
presets
}]
],
plugin: ['browserify-derequire']
}
},
worker: {
files: {
'dist/openpgp.worker.js': ['./src/worker/worker.js']
},
options: {
cacheFile: 'browserify-cache-worker.json'
}
},
unittests: {
files: {
'test/lib/unittests-bundle.js': ['./test/unittests.js']
},
options: {
cacheFile: 'browserify-cache-unittests.json',
external: ['buffer', 'openpgp', '../../dist/openpgp', '../../../dist/openpgp'],
transform: [
["babelify", {
global: true,
// Only babelify chai-as-promised in node_modules
only: /^(?:.*\/node_modules\/chai-as-promised\/|(?!.*\/node_modules\/)).*$/,
ignore: ['*.min.js'],
plugins,
presets
}]
]
}
}
},
nyc: {
cover: {
options: {
include: ['dist/**'],
reporter: ['text-summary'],
reportDir: 'coverage'
},
cmd: false,
args: ['grunt', 'mochaTest'],
sourceMap: true
},
report: {
options: {
reporter: 'text'
}
}
},
replace: {
openpgp: {
src: ['dist/openpgp.js'],
dest: ['dist/openpgp.js'],
replacements: [{
from: /OpenPGP.js VERSION/g,
to: 'OpenPGP.js v<%= pkg.version %>'
}]
},
openpgp_min: {
src: ['dist/openpgp.min.js'],
dest: ['dist/openpgp.min.js'],
replacements: [{
from: "openpgp.worker.js",
to: "openpgp.worker.min.js"
}]
},
worker_min: {
src: ['dist/openpgp.worker.min.js'],
dest: ['dist/openpgp.worker.min.js'],
replacements: [{
from: "openpgp.js",
to: "openpgp.min.js"
}]
},
lightweight_build: {
src: ['dist/openpgp.js'],
overwrite: true,
replacements: [
{
from: "external_indutny_elliptic: false",
to: "external_indutny_elliptic: true"
}
]
},
indutny_global: {
src: ['dist/elliptic.min.js'],
overwrite: true,
replacements: [
{
from: 'b.elliptic=a()',
to: 'b.openpgp.elliptic=a()'
}
]
}
},
terser: {
openpgp: {
files: {
'dist/openpgp.min.js' : ['dist/openpgp.js'],
'dist/openpgp.worker.min.js' : ['dist/openpgp.worker.js']
},
options: {
output: {
comments: `/^!/`
},
sourceMap: dev ? {
content: 'inline',
url: 'inline'
} : {},
safari10: true
}
}
},
header: {
openpgp: {
options: {
text: '/*! OpenPGP.js v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> - ' +
'this is LGPL licensed code, see LICENSE/our website <%= pkg.homepage %> for more information. */'
},
files: {
'dist/openpgp.js': 'dist/openpgp.js',
'dist/openpgp.worker.js': 'dist/openpgp.worker.js'
}
}
},
jsbeautifier: {
files: ['src/**/*.js'],
options: {
indent_size: 2,
preserve_newlines: true,
keep_array_indentation: false,
keep_function_indentation: false,
wrap_line_length: 120
}
},
eslint: {
target: ['src/**/*.js', './Gruntfile.js', './eslintrc.js', 'test/crypto/**/*.js'],
options: {
configFile: '.eslintrc.js',
fix: !!grunt.option('fix')
}
},
jsdoc: {
dist: {
src: ['README.md', 'src'],
options: {
configure: '.jsdocrc.js',
destination: 'doc',
recurse: true
}
}
},
mochaTest: {
unittests: {
options: {
reporter: 'spec',
timeout: 120000,
grep: lightweight ? 'lightweight' : undefined
},
src: ['test/unittests.js']
}
},
copy: {
browsertest: {
expand: true,
flatten: true,
cwd: 'node_modules/',
src: ['mocha/mocha.css', 'mocha/mocha.js'],
dest: 'test/lib/'
},
openpgp_compat: {
expand: true,
cwd: 'dist/',
src: ['*.js'],
dest: 'dist/compat/'
},
openpgp_lightweight: {
expand: true,
cwd: 'dist/',
src: ['*.js'],
dest: 'dist/lightweight/'
},
indutny_elliptic: {
expand: true,
flatten: true,
src: ['./node_modules/elliptic/dist/elliptic.min.js'],
dest: 'dist/'
}
},
clean: {
dist: ['dist/'],
js: ['dist/*.js']
},
connect: {
dev: {
options: {
port: 3001,
base: '.',
keepalive: true
}
},
test: {
options: {
port: 3000,
base: '.'
}
}
},
watch: {
src: {
files: ['src/**/*.js'],
tasks: lightweight ? ['browserify:openpgp', 'browserify:worker', 'replace:lightweight_build'] : ['browserify:openpgp', 'browserify:worker']
},
test: {
files: ['test/*.js', 'test/crypto/**/*.js', 'test/general/**/*.js', 'test/worker/**/*.js'],
tasks: ['browserify:unittests']
}
}
});
// Load the plugin(s)
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-terser');
grunt.loadNpmTasks('grunt-header');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-jsbeautifier');
grunt.loadNpmTasks('grunt-jsdoc');
grunt.loadNpmTasks('gruntify-eslint');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-simple-nyc');
grunt.registerTask('set_version', function() {
if (!version) {
throw new Error('You must specify the version: "--release=1.0.0"');
}
patchFile({
fileName: 'package.json',
version: version
});
patchFile({
fileName: 'package-lock.json',
version: version
});
patchFile({
fileName: 'bower.json',
version: version
});
});
function patchFile(options) {
const path = './' + options.fileName;
//eslint-disable-next-line
const file = require(path);
if (options.version) {
file.version = options.version;
}
//eslint-disable-next-line
fs.writeFileSync(path, JSON.stringify(file, null, 2) + '\n');
}
// Build tasks
grunt.registerTask('version', ['replace:openpgp']);
grunt.registerTask('replace_min', ['replace:openpgp_min', 'replace:worker_min']);
grunt.registerTask('build', function() {
if (lightweight) {
grunt.task.run(['copy:indutny_elliptic', 'browserify:openpgp', 'browserify:worker', 'replace:lightweight_build', 'replace:indutny_global', 'version', 'header', 'terser', 'replace_min']);
return;
}
grunt.task.run(['browserify:openpgp', 'browserify:worker', 'version', 'header', 'terser', 'replace_min']);
}
);
grunt.registerTask('documentation', ['jsdoc']);
grunt.registerTask('default', ['build']);
// Test/Dev tasks
grunt.registerTask('test', ['eslint', 'mochaTest']);
grunt.registerTask('coverage', ['nyc']);
grunt.registerTask('browsertest', ['build', 'browserify:unittests', 'copy:browsertest', 'connect:test', 'watch']);
};

606
README.md
View File

@ -1,26 +1,28 @@
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 [![Build Status](https://travis-ci.org/openpgpjs/openpgpjs.svg?branch=master)](https://travis-ci.org/openpgpjs/openpgpjs) [![BrowserStack Status](https://automate.browserstack.com/badge.svg?badge_key=eEkxVVM1TytwOGJNWEdnTjk4Y0VNUUNyR3pXcEtJUGRXOVFBRjVNT1JpUT0tLTZYUlZaMWdtQWs4Z0ROS3grRXc2bFE9PQ==--4a9cac0d6ea009d81aff66de0dbb239edd1aef3c)](https://automate.browserstack.com/public-build/eEkxVVM1TytwOGJNWEdnTjk4Y0VNUUNyR3pXcEtJUGRXOVFBRjVNT1JpUT0tLTZYUlZaMWdtQWs4Z0ROS3grRXc2bFE9PQ==--4a9cac0d6ea009d81aff66de0dbb239edd1aef3c) [![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 [RFC 9580](https://datatracker.ietf.org/doc/rfc9580/) (superseding [RFC 4880](https://tools.ietf.org/html/rfc4880) and [RFC 4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10)).
[OpenPGP.js](https://openpgpjs.org/) is a JavaScript implementation of the OpenPGP protocol. This is defined in [RFC 4880](https://tools.ietf.org/html/rfc4880).
<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-generate-toc again -->
**Table of Contents**
- [OpenPGP.js](#openpgpjs)
- [Platform Support](#platform-support)
- [Performance](#performance)
- [Getting started](#getting-started)
- [Node.js](#nodejs)
- [Deno (experimental)](#deno-experimental)
- [Browser (webpack)](#browser-webpack)
- [Browser (plain files)](#browser-plain-files)
- [Npm](#npm)
- [Bower](#bower)
- [Examples](#examples)
- [Set up](#set-up)
- [Encrypt and decrypt *Uint8Array* data with a password](#encrypt-and-decrypt-uint8array-data-with-a-password)
- [Encrypt and decrypt *String* data with PGP keys](#encrypt-and-decrypt-string-data-with-pgp-keys)
- [Encrypt symmetrically with compression](#encrypt-symmetrically-with-compression)
- [Encrypt with compression](#encrypt-with-compression)
- [Streaming encrypt *Uint8Array* data with a password](#streaming-encrypt-uint8array-data-with-a-password)
- [Streaming encrypt and decrypt *String* data with PGP keys](#streaming-encrypt-and-decrypt-string-data-with-pgp-keys)
- [Generate new key pair](#generate-new-key-pair)
- [Revoke a key](#revoke-a-key)
- [Lookup public key on HKP server](#lookup-public-key-on-hkp-server)
- [Upload public key to HKP server](#upload-public-key-to-hkp-server)
- [Sign and verify cleartext messages](#sign-and-verify-cleartext-messages)
- [Create and verify *detached* signatures](#create-and-verify-detached-signatures)
- [Streaming sign and verify *Uint8Array* data](#streaming-sign-and-verify-uint8array-data)
@ -30,183 +32,147 @@ OpenPGP.js [![Join the chat on Gitter](https://badges.gitter.im/Join%20Chat.svg)
- [Development](#development)
- [How do I get involved?](#how-do-i-get-involved)
- [License](#license)
- [Resources](#resources)
<!-- markdown-toc end -->
### Platform Support
* The `dist/openpgp.min.js` (or `.mjs`) bundle works with recent versions of Chrome, Firefox, Edge and Safari 14+.
* The `dist/openpgp.min.js` bundle works well with recent versions of Chrome, Firefox, Safari and Edge. It also works in Node.js 8+.
* The `dist/node/openpgp.min.mjs` (or `.cjs`) bundle works in Node.js v18+: it is used by default when you `import ... from 'openpgp'` (or `require('openpgp')`, respectively).
* The `dist/compat/openpgp.min.js` bundle also works with Internet Explorer 11 and old versions of Safari. Please note that this bundle overwrites the global `Promise` with a polyfill version even in some cases where it already exists, which may cause issues. It also adds some built-in prototype functions if they don't exist, such as `Array.prototype.includes`.
* Support for the [Web Cryptography API](https://w3c.github.io/webcrypto/)'s `SubtleCrypto` is required.
* In browsers, `SubtleCrypto` is only available in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).
* In supported versions of Node.js, `SubtleCrypto` is always available.
* Support for the [Web Streams API](https://streams.spec.whatwg.org/) is required.
* In browsers: the latest versions of Chrome, Firefox, Edge and Safari support Streams, including `TransformStream`s.
These are needed if you use the library with stream inputs.
In previous versions of OpenPGP.js, Web Streams were automatically polyfilled by the library,
but from v6 this task is left up to the library user, due to the more extensive browser support, and the
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#browser_compatibility), you can manually
load the [Web Streams 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`
object), in which case you should store a reference to it before loading
the polyfills. There is also the [web-streams-adapter](https://github.com/MattiasBuelens/web-streams-adapter)
library to convert back and forth between them.
* In Node.js: OpenPGP.js v6 no longer supports native Node `Readable` streams in inputs, and instead expects (and outputs) [Node's Web Streams](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).
* If you wish, you could even load one or the other depending on which browser the user is using. However, if you're using the Web Worker, keep in mind that you also need to pass `{ path: 'compat/openpgp.worker.min.js' }` to `initWorker` whenever you load `compat/openpgp.min.js`.
* Currently, Chrome, Safari and Edge have partial implementations of the
[Streams specification](https://streams.spec.whatwg.org/), and Firefox
has a partial implementation behind feature flags. Chrome is the only
browser that implements `TransformStream`s, which we need, so we include
a [polyfill](https://github.com/MattiasBuelens/web-streams-polyfill) for
all other browsers. Please note that in those browsers, the global
`ReadableStream` property gets overwritten with the polyfill version if
it exists. In some edge cases, you might need to use the native
`ReadableStream` (for example when using it to create a `Response`
object), in which case you should store a reference to it before loading
OpenPGP.js. There is also the
[web-streams-adapter](https://github.com/MattiasBuelens/web-streams-adapter)
library to convert back and forth between them.
### Performance
* 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:
* 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 or [Elliptic](https://github.com/indutny/elliptic) otherwise. Elliptic curve cryptography provides stronger security per bits of key, which allows for much faster operations. Currently the following curves are supported (* = when available):
| Curve | Encryption | Signature | NodeCrypto | WebCrypto | Constant-Time |
|:---------------:|:----------:|:---------:|:----------:|:---------:|:-----------------:|
| curve25519 | ECDH | N/A | No | No | Algorithmically |
| ed25519 | N/A | EdDSA | No | Yes* | If native** |
| nistP256 | ECDH | ECDSA | Yes* | Yes* | If native** |
| nistP384 | ECDH | ECDSA | Yes* | Yes* | If native** |
| nistP521 | ECDH | ECDSA | Yes* | Yes* | If native** |
| brainpoolP256r1 | ECDH | ECDSA | Yes* | No | If native** |
| brainpoolP384r1 | ECDH | ECDSA | Yes* | No | If native** |
| brainpoolP512r1 | ECDH | ECDSA | Yes* | No | If native** |
| secp256k1 | ECDH | ECDSA | Yes* | No | If native** |
\* when available
\** these curves are only constant-time if the underlying native implementation is available and constant-time
| Curve | Encryption | Signature | Elliptic | NodeCrypto | WebCrypto |
|:--------------- |:----------:|:---------:|:--------:|:----------:|:---------:|
| p256 | ECDH | ECDSA | Yes | Yes* | Yes* |
| p384 | ECDH | ECDSA | Yes | Yes* | Yes* |
| p521 | ECDH | ECDSA | Yes | Yes* | Yes* |
| secp256k1 | ECDH | ECDSA | Yes | Yes* | No |
| brainpoolP256r1 | ECDH | ECDSA | Yes | Yes* | No |
| brainpoolP384r1 | ECDH | ECDSA | Yes | Yes* | No |
| brainpoolP512r1 | ECDH | ECDSA | Yes | Yes* | No |
| curve25519 | ECDH | N/A | Yes | No | No |
| ed25519 | N/A | EdDSA | Yes | No | No |
* The platform's [native Web Crypto API](https://w3c.github.io/webcrypto/) is used for performance. On Node.js the native [crypto module](https://nodejs.org/api/crypto.html#crypto_crypto) is also used, in cases where it offers additional functionality.
* 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.
* The library implements authenticated encryption (AEAD) as per [RFC 9580](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 [RFC 4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10), which was modified in RFC 9580.
* 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. This can be deactivated by setting `openpgp.config.use_native = false`.
* The library implements the [IETF proposal](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07) 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.aead_protect = true`.
You can change the AEAD mode by setting one of the following options:
```
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.gcm; // Default, native in WebCrypto and Node.js
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb; // Non-native, but supported across RFC 9580 implementations
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax; // Native in Node.js
openpgp.config.aead_mode = openpgp.enums.aead.eax // Default, native
openpgp.config.aead_mode = openpgp.enums.aead.ocb // Non-native
openpgp.config.aead_mode = openpgp.enums.aead.experimental_gcm // **Non-standard**, fastest
```
* 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. We use [Rusha](https://github.com/srijs/rusha) and [asmCrypto Lite](https://github.com/openpgpjs/asmcrypto-lite) (a minimal subset of asmCrypto.js built specifically for OpenPGP.js).
### Getting started
#### Node.js
#### Npm
Install OpenPGP.js using npm and save it in your dependencies:
npm install --save openpgp
```sh
npm install --save openpgp
```
#### Bower
And import it as an ES module, from a .mjs file:
```js
import * as openpgp from 'openpgp';
```
bower install --save openpgp
Or as a CommonJS module:
Or just fetch a minified build under [dist](https://github.com/openpgpjs/openpgpjs/tree/master/dist).
### Examples
Here are some examples of how to use the v2.x+ API. For more elaborate examples and working code, please check out the [public API unit tests](https://github.com/openpgpjs/openpgpjs/blob/master/test/general/openpgp.js). If you're upgrading from v1.x it might help to check out the [documentation](https://github.com/openpgpjs/openpgpjs#documentation).
#### Set up
##### Node.js
```js
const openpgp = require('openpgp');
```
#### Deno (experimental)
##### Browser
Import as an ES6 module, using /dist/openpgp.mjs.
```js
import * as openpgp from './openpgpjs/dist/openpgp.mjs';
```
#### Browser (webpack)
Install OpenPGP.js using npm and save it in your devDependencies:
```sh
npm install --save-dev openpgp
```
And import it as an ES6 module:
```js
import * as openpgp from 'openpgp';
```
You can also only import the functions you need, as follows:
```js
import { readMessage, decrypt } from 'openpgp';
```
Or, if you want to use the lightweight build (which is smaller, and lazily loads non-default curves on demand):
```js
import * as openpgp from 'openpgp/lightweight';
```
To test whether the lazy loading works, try to generate a key with a non-standard curve:
```js
import { generateKey } from 'openpgp/lightweight';
await generateKey({ curve: 'brainpoolP512r1', userIDs: [{ name: 'Test', email: 'test@test.com' }] });
```
For more examples of how to generate a key, see [Generate new key pair](#generate-new-key-pair). It is recommended to use `curve25519` instead of `brainpoolP512r1` by default.
#### Browser (plain files)
Grab `openpgp.min.js` from [unpkg.com/openpgp/dist](https://unpkg.com/openpgp/dist/), and load it in a script tag:
Copy `dist/openpgp.min.js` or `dist/compat/openpgp.min.js` (depending on the browser support you need, see [Platform Support](#platform-support)) to your project folder, and load it in a script tag:
```html
<script src="openpgp.min.js"></script>
```
Or, to load OpenPGP.js as an ES6 module, grab `openpgp.min.mjs` from [unpkg.com/openpgp/dist](https://unpkg.com/openpgp/dist/), and import it as follows:
If you want to use the built-in Web Worker, to offload cryptographic operations off the main thread:
```js
await openpgp.initWorker({ path: 'openpgp.worker.js' }); // set the relative web worker path
```
On logout, be sure to destroy the worker again, to clear private keys from memory:
```js
await openpgp.destroyWorker();
```
Alternatively, you can also implement a Web Worker in your application and load OpenPGP.js from there. This can be more performant if you store or fetch keys and messages directly inside the Worker, so that they don't have to be `postMessage`d there.
If you want to use the lightweight build (which is smaller, and lazily loads non-default curves on demand), copy `dist/lightweight/openpgp.min.js` and `dist/lightweight/elliptic.min.js`, load the former in a script tag, and point `openpgp.config.indutny_elliptic_path` to the latter:
```html
<script type="module">
import * as openpgp from './openpgp.min.mjs';
<script src="lightweight/openpgp.min.js"></script>
<script>
openpgp.config.indutny_elliptic_path = 'lightweight/elliptic.min.js';
</script>
```
To offload cryptographic operations off the main thread, you can implement a Web Worker in your application and load OpenPGP.js from there. For an example Worker implementation, see `test/worker/worker_example.js`.
To test whether the lazy loading works, try:
#### 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:
```sh
npm install --save-dev @openpgp/web-stream-tools
```js
await openpgp.generateKey({ curve: 'brainpoolP512r1', userIds: [{ name: 'Test', email: 'test@test.com' }] });
```
If you notice missing or incorrect type definitions, feel free to open a PR.
### Examples
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).
For more examples of how to generate a key, see [Generate new key pair](#generate-new-key-pair). It is recommended to use `curve25519` instead of `brainpoolP512r1` by default.
#### Encrypt and decrypt *Uint8Array* data with a password
Encryption will use the algorithm specified in config.preferredSymmetricAlgorithm (defaults to aes256), and decryption will use the algorithm used for encryption.
Encryption will use the algorithm specified in config.encryption_cipher (defaults to aes256), and decryption will use the algorithm used for encryption.
```js
(async () => {
const message = await openpgp.createMessage({ binary: new Uint8Array([0x01, 0x01, 0x01]) });
const encrypted = await openpgp.encrypt({
message, // input as Message object
passwords: ['secret stuff'], // multiple passwords possible
format: 'binary' // don't ASCII armor (for Uint8Array output)
const { message } = await openpgp.encrypt({
message: openpgp.message.fromBinary(new Uint8Array([0x01, 0x01, 0x01])), // input as Message object
passwords: ['secret stuff'], // multiple passwords possible
armor: false // don't ASCII armor (for Uint8Array output)
});
console.log(encrypted); // Uint8Array
const encrypted = message.packets.write(); // get raw encrypted packets as Uint8Array
const encryptedMessage = await openpgp.readMessage({
binaryMessage: encrypted // parse encrypted bytes
});
const { data: decrypted } = await openpgp.decrypt({
message: encryptedMessage,
passwords: ['secret stuff'], // decrypt with password
format: 'binary' // output as Uint8Array
message: await openpgp.message.read(encrypted), // parse encrypted bytes
passwords: ['secret stuff'], // decrypt with password
format: 'binary' // output as Uint8Array
});
console.log(decrypted); // Uint8Array([0x01, 0x01, 0x01])
})();
@ -214,12 +180,14 @@ Encryption will use the algorithm specified in config.preferredSymmetricAlgorith
#### Encrypt and decrypt *String* data with PGP keys
Encryption will use the algorithm preferred by the public (encryption) key (defaults to aes256 for keys generated in OpenPGP.js), and decryption will use the algorithm used for encryption.
Encryption will use the algorithm preferred by the public key (defaults to aes256 for keys generated in OpenPGP.js), and decryption will use the algorithm used for encryption.
```js
const openpgp = require('openpgp'); // use as CommonJS, AMD, ES6 module or via window.openpgp
(async () => {
await openpgp.initWorker({ path: 'openpgp.worker.js' }); // set the relative web worker path
// put keys in backtick (``) to avoid errors caused by spaces or tabs
const publicKeyArmored = `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
@ -229,40 +197,25 @@ const openpgp = require('openpgp'); // use as CommonJS, AMD, ES6 module or via w
-----END PGP PRIVATE KEY BLOCK-----`; // encrypted private key
const passphrase = `yourPassphrase`; // what the private key is encrypted with
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
const { keys: [privateKey] } = await openpgp.key.readArmored(privateKeyArmored);
await privateKey.decrypt(passphrase);
const privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }),
passphrase
});
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ text: 'Hello, World!' }), // input as Message object
encryptionKeys: publicKey,
signingKeys: privateKey // optional
const { data: encrypted } = await openpgp.encrypt({
message: openpgp.message.fromText('Hello, World!'), // input as Message object
publicKeys: (await openpgp.key.readArmored(publicKeyArmored)).keys, // for encryption
privateKeys: [privateKey] // for signing (optional)
});
console.log(encrypted); // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
const message = await openpgp.readMessage({
armoredMessage: encrypted // parse armored message
});
const { data: decrypted, signatures } = await openpgp.decrypt({
message,
verificationKeys: publicKey, // optional
decryptionKeys: privateKey
const { data: decrypted } = await openpgp.decrypt({
message: await openpgp.message.readArmored(encrypted), // parse armored message
publicKeys: (await openpgp.key.readArmored(publicKeyArmored)).keys, // for verification (optional)
privateKeys: [privateKey] // for decryption
});
console.log(decrypted); // 'Hello, World!'
// check signature validity (signed messages only)
try {
await signatures[0].verified; // throws on invalid signature
console.log('Signature is valid');
} catch (e) {
throw new Error('Signature could not be verified: ' + e.message);
}
})();
```
Encrypt to multiple public keys:
Encrypt with multiple public keys:
```js
(async () => {
@ -278,88 +231,49 @@ Encrypt to multiple public keys:
...
-----END PGP PRIVATE KEY BLOCK-----`; // encrypted private key
const passphrase = `yourPassphrase`; // what the private key is encrypted with
const plaintext = 'Hello, World!';
const message = 'Hello, World!';
const publicKeys = await Promise.all(publicKeysArmored.map(armoredKey => openpgp.readKey({ armoredKey })));
const { keys: [privateKey] } = await openpgp.key.readArmored(privateKeyArmored);
await privateKey.decrypt(passphrase)
const privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readKey({ armoredKey: privateKeyArmored }),
passphrase
});
const publicKeys = await Promise.all(publicKeysArmored.map(async (key) => {
return (await openpgp.key.readArmored(key)).keys[0];
}));
const message = await openpgp.createMessage({ text: plaintext });
const encrypted = await openpgp.encrypt({
message, // input as Message object
encryptionKeys: publicKeys,
signingKeys: privateKey // optional
const { data: encrypted } = await openpgp.encrypt({
message: openpgp.message.fromText(message), // input as Message object
publicKeys, // for encryption
privateKeys: [privateKey] // for signing (optional)
});
console.log(encrypted); // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
})();
```
If you expect an encrypted message to be signed with one of the public keys you have, and do not want to trust the decrypted data otherwise, you can pass the decryption option `expectSigned = true`, so that the decryption operation will fail if no valid signature is found:
```js
(async () => {
// put keys in backtick (``) to avoid errors caused by spaces or tabs
const publicKeyArmored = `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`;
const privateKeyArmored = `-----BEGIN PGP PRIVATE KEY BLOCK-----
...
-----END PGP PRIVATE KEY BLOCK-----`; // encrypted private key
const passphrase = `yourPassphrase`; // what the private key is encrypted with
#### Encrypt with compression
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
By default, `encrypt` will not use any compression. It's possible to override that behavior in two ways:
const privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }),
passphrase
});
const encryptedAndSignedMessage = `-----BEGIN PGP MESSAGE-----
...
-----END PGP MESSAGE-----`;
const message = await openpgp.readMessage({
armoredMessage: encryptedAndSignedMessage // parse armored message
});
// decryption will fail if all signatures are invalid or missing
const { data: decrypted, signatures } = await openpgp.decrypt({
message,
decryptionKeys: privateKey,
expectSigned: true,
verificationKeys: publicKey, // mandatory with expectSigned=true
});
console.log(decrypted); // 'Hello, World!'
})();
```
#### Encrypt symmetrically with compression
By default, `encrypt` will not use any compression when encrypting symmetrically only (i.e. when no `encryptionKeys` are given).
It's possible to change that behaviour by enabling compression through the config, either for the single encryption:
Either set the `compression` parameter in the options object when calling `encrypt`.
```js
(async () => {
const message = await openpgp.createMessage({ binary: new Uint8Array([0x01, 0x02, 0x03]) }); // or createMessage({ text: 'string' })
const encrypted = await openpgp.encrypt({
message,
passwords: ['secret stuff'], // multiple passwords possible
config: { preferredCompressionAlgorithm: openpgp.enums.compression.zlib } // compress the data with zlib
message: openpgp.message.fromBinary(new Uint8Array([0x01, 0x02, 0x03])), // or .fromText('string')
passwords: ['secret stuff'], // multiple passwords possible
compression: openpgp.enums.compression.zip // compress the data with zip
});
})();
```
or by changing the default global configuration:
Or, override the config to enable compression:
```js
openpgp.config.preferredCompressionAlgorithm = openpgp.enums.compression.zlib
openpgp.config.compression = openpgp.enums.compression.zlib;
```
Where the value can be any of:
* `openpgp.enums.compression.zip`
* `openpgp.enums.compression.zlib`
* `openpgp.enums.compression.uncompressed` (default)
#### Streaming encrypt *Uint8Array* data with a password
@ -373,24 +287,34 @@ Where the value can be any of:
}
});
const message = await openpgp.createMessage({ binary: readableStream });
const encrypted = await openpgp.encrypt({
message, // input as Message object
passwords: ['secret stuff'], // multiple passwords possible
format: 'binary' // don't ASCII armor (for Uint8Array output)
const { message } = await openpgp.encrypt({
message: openpgp.message.fromBinary(readableStream), // input as Message object
passwords: ['secret stuff'], // multiple passwords possible
armor: false // don't ASCII armor (for Uint8Array output)
});
console.log(encrypted); // raw encrypted packets as ReadableStream<Uint8Array>
const encrypted = message.packets.write(); // get raw encrypted packets as ReadableStream<Uint8Array>
// Either pipe the above stream somewhere, pass it to another function,
// or read it manually as follows:
for await (const chunk of encrypted) {
console.log('new chunk:', chunk); // Uint8Array
const reader = openpgp.stream.getReader(encrypted);
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log('new chunk:', value); // Uint8Array
}
// Or, in Node.js, you can pipe the above stream as follows:
const nodeStream = openpgp.stream.webToNode(encrypted);
nodeStream.pipe(nodeWritableStream);
})();
```
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) .
For more information on creating ReadableStreams, see [the MDN Documentation on `new
ReadableStream()`](https://developer.mozilla.org/docs/Web/API/ReadableStream/ReadableStream).
For more information on reading streams using `openpgp.stream`, see the documentation of
[the web-stream-tools dependency](https://openpgpjs.org/web-stream-tools/), particularly
its [Reader class](https://openpgpjs.org/web-stream-tools/Reader.html).
#### Streaming encrypt and decrypt *String* data with PGP keys
@ -399,17 +323,13 @@ Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) .
const publicKeyArmored = `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`; // Public key
const privateKeyArmored = `-----BEGIN PGP PRIVATE KEY BLOCK-----
const [privateKeyArmored] = `-----BEGIN PGP PRIVATE KEY BLOCK-----
...
-----END PGP PRIVATE KEY BLOCK-----`; // Encrypted private key
const passphrase = `yourPassphrase`; // Password that private key is encrypted with
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
const privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }),
passphrase
});
const privateKey = (await openpgp.key.readArmored([privateKeyArmored])).keys[0];
await privateKey.decrypt(passphrase);
const readableStream = new ReadableStream({
start(controller) {
@ -419,64 +339,53 @@ Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) .
});
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ text: readableStream }), // input as Message object
encryptionKeys: publicKey,
signingKeys: privateKey // optional
message: openpgp.message.fromText(readableStream), // input as Message object
publicKeys: (await openpgp.key.readArmored(publicKeyArmored)).keys, // for encryption
privateKeys: [privateKey] // for signing (optional)
});
console.log(encrypted); // ReadableStream containing '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
const ciphertext = encrypted.data; // ReadableStream containing '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
const message = await openpgp.readMessage({
armoredMessage: encrypted // parse armored message
});
const decrypted = await openpgp.decrypt({
message,
verificationKeys: publicKey, // optional
decryptionKeys: privateKey
message: await openpgp.message.readArmored(ciphertext), // parse armored message
publicKeys: (await openpgp.key.readArmored(publicKeyArmored)).keys, // for verification (optional)
privateKeys: [privateKey] // for decryption
});
const chunks = [];
for await (const chunk of decrypted.data) {
chunks.push(chunk);
}
const plaintext = chunks.join('');
console.log(plaintext); // 'Hello, World!'
const plaintext = await openpgp.stream.readToEnd(decrypted.data); // 'Hello, World!'
})();
```
#### Generate new key pair
ECC keys (smaller and faster to generate):
ECC keys:
Possible values for `curve` are: `curve25519`, `ed25519`, `nistP256`, `nistP384`, `nistP521`,
`brainpoolP256r1`, `brainpoolP384r1`, `brainpoolP512r1`, and `secp256k1`.
Possible values for `curve` are: `curve25519`, `ed25519`, `p256`, `p384`, `p521`, `secp256k1`,
`brainpoolP256r1`, `brainpoolP384r1`, or `brainpoolP512r1`.
Note that both the `curve25519` and `ed25519` options generate a primary key for signing using Ed25519
and a subkey for encryption using Curve25519.
```js
(async () => {
const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({
type: 'ecc', // Type of the key, defaults to ECC
curve: 'curve25519', // ECC curve name, defaults to curve25519
userIDs: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs
passphrase: 'super long and hard to guess secret', // protects the private key
format: 'armored' // output key format, defaults to 'armored' (other options: 'binary' or 'object')
const { privateKeyArmored, publicKeyArmored, revocationCertificate } = await openpgp.generateKey({
userIds: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs
curve: 'ed25519', // ECC curve name
passphrase: 'super long and hard to guess secret' // protects the private key
});
console.log(privateKey); // '-----BEGIN PGP PRIVATE KEY BLOCK ... '
console.log(publicKey); // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
console.log(privateKeyArmored); // '-----BEGIN PGP PRIVATE KEY BLOCK ... '
console.log(publicKeyArmored); // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
console.log(revocationCertificate); // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
})();
```
RSA keys (increased compatibility):
RSA keys:
```js
(async () => {
const { privateKey, publicKey } = await openpgp.generateKey({
type: 'rsa', // Type of the key
rsaBits: 4096, // RSA key size (defaults to 4096 bits)
userIDs: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs
passphrase: 'super long and hard to guess secret' // protects the private key
const key = await openpgp.generateKey({
userIds: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs
rsaBits: 4096, // RSA key size
passphrase: 'super long and hard to guess secret' // protects the private key
});
})();
```
@ -486,10 +395,9 @@ RSA keys (increased compatibility):
Using a revocation certificate:
```js
(async () => {
const { publicKey: revokedKeyArmored } = await openpgp.revokeKey({
key: await openpgp.readKey({ armoredKey: publicKeyArmored }),
revocationCertificate,
format: 'armored' // output armored keys
const { publicKeyArmored: revokedKeyArmored } = await openpgp.revokeKey({
key: (await openpgp.key.readArmored(publicKeyArmored)).keys[0],
revocationCertificate
});
console.log(revokedKeyArmored); // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
})();
@ -498,11 +406,36 @@ Using a revocation certificate:
Using the private key:
```js
(async () => {
const { publicKey: revokedKeyArmored } = await openpgp.revokeKey({
key: await openpgp.readKey({ armoredKey: privateKeyArmored }),
format: 'armored' // output armored keys
const { publicKeyArmored, publicKey } = await openpgp.revokeKey({
key: (await openpgp.key.readArmored(privateKeyArmored)).keys[0]
});
console.log(revokedKeyArmored); // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
})();
```
#### Lookup public key on HKP server
```js
(async () => {
var hkp = new openpgp.HKP(); // Defaults to https://keyserver.ubuntu.com, or pass another keyserver URL as a string
let publicKeyArmored = await hkp.lookup({
query: 'alice@example.com'
});
var { keys: [publicKey] } = await openpgp.key.readArmored(publicKeyArmored);
})();
```
#### Upload public key to HKP server
```js
(async () => {
var hkp = new openpgp.HKP('https://pgp.mit.edu');
var publicKeyArmored = `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`;
await hkp.upload(publicKeyArmored);
})();
```
@ -518,33 +451,24 @@ Using the private key:
-----END PGP PRIVATE KEY BLOCK-----`; // encrypted private key
const passphrase = `yourPassphrase`; // what the private key is encrypted with
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
const { keys: [privateKey] } = await openpgp.key.readArmored(privateKeyArmored);
await privateKey.decrypt(passphrase);
const privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }),
passphrase
const { data: cleartext } = await openpgp.sign({
message: openpgp.cleartext.fromText('Hello, World!'), // CleartextMessage or Message object
privateKeys: [privateKey] // for signing
});
console.log(cleartext); // '-----BEGIN PGP SIGNED MESSAGE ... END PGP SIGNATURE-----'
const unsignedMessage = await openpgp.createCleartextMessage({ text: 'Hello, World!' });
const cleartextMessage = await openpgp.sign({
message: unsignedMessage, // CleartextMessage or Message object
signingKeys: privateKey
const verified = await openpgp.verify({
message: await openpgp.cleartext.readArmored(cleartext), // parse armored message
publicKeys: (await openpgp.key.readArmored(publicKeyArmored)).keys // for verification
});
console.log(cleartextMessage); // '-----BEGIN PGP SIGNED MESSAGE ... END PGP SIGNATURE-----'
const signedMessage = await openpgp.readCleartextMessage({
cleartextMessage // parse armored message
});
const verificationResult = await openpgp.verify({
message: signedMessage,
verificationKeys: publicKey
});
const { verified, keyID } = verificationResult.signatures[0];
try {
await verified; // throws on invalid signature
console.log('Signed by key id ' + keyID.toHex());
} catch (e) {
throw new Error('Signature could not be verified: ' + e.message);
const { valid } = verified.signatures[0];
if (valid) {
console.log('signed by key id ' + verified.signatures[0].keyid.toHex());
} else {
throw new Error('signature could not be verified');
}
})();
```
@ -561,35 +485,26 @@ Using the private key:
-----END PGP PRIVATE KEY BLOCK-----`; // encrypted private key
const passphrase = `yourPassphrase`; // what the private key is encrypted with
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
const { keys: [privateKey] } = await openpgp.key.readArmored(privateKeyArmored);
await privateKey.decrypt(passphrase);
const privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }),
passphrase
});
const message = await openpgp.createMessage({ text: 'Hello, World!' });
const detachedSignature = await openpgp.sign({
message, // Message object
signingKeys: privateKey,
const { signature: detachedSignature } = await openpgp.sign({
message: openpgp.cleartext.fromText('Hello, World!'), // CleartextMessage or Message object
privateKeys: [privateKey], // for signing
detached: true
});
console.log(detachedSignature);
const signature = await openpgp.readSignature({
armoredSignature: detachedSignature // parse detached signature
const verified = await openpgp.verify({
message: openpgp.cleartext.fromText('Hello, World!'), // CleartextMessage or Message object
signature: await openpgp.signature.readArmored(detachedSignature), // parse detached signature
publicKeys: (await openpgp.key.readArmored(publicKeyArmored)).keys // for verification
});
const verificationResult = await openpgp.verify({
message, // Message object
signature,
verificationKeys: publicKey
});
const { verified, keyID } = verificationResult.signatures[0];
try {
await verified; // throws on invalid signature
console.log('Signed by key id ' + keyID.toHex());
} catch (e) {
throw new Error('Signature could not be verified: ' + e.message);
const { valid } = verified.signatures[0];
if (valid) {
console.log('signed by key id ' + verified.signatures[0].keyid.toHex());
} else {
throw new Error('signature could not be verified');
}
})();
```
@ -613,40 +528,39 @@ Using the private key:
-----END PGP PRIVATE KEY BLOCK-----`; // encrypted private key
const passphrase = `yourPassphrase`; // what the private key is encrypted with
const privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }),
passphrase
});
const { keys: [privateKey] } = await openpgp.key.readArmored(privateKeyArmored);
await privateKey.decrypt(passphrase);
const message = await openpgp.createMessage({ binary: readableStream }); // or createMessage({ text: ReadableStream<String> })
const signatureArmored = await openpgp.sign({
message,
signingKeys: privateKey
const { data: signatureArmored } = await openpgp.sign({
message: openpgp.message.fromBinary(readableStream), // or .fromText(readableStream: ReadableStream<String>)
privateKeys: [privateKey] // for signing
});
console.log(signatureArmored); // ReadableStream containing '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
const verificationResult = await openpgp.verify({
message: await openpgp.readMessage({ armoredMessage: signatureArmored }), // parse armored signature
verificationKeys: await openpgp.readKey({ armoredKey: publicKeyArmored })
const verified = await openpgp.verify({
message: await openpgp.message.readArmored(signatureArmored), // parse armored signature
publicKeys: (await openpgp.key.readArmored(publicKeyArmored)).keys // for verification
});
for await (const chunk of verificationResult.data) {}
// Note: you *have* to read `verificationResult.data` in some way or other,
await openpgp.stream.readToEnd(verified.data);
// Note: you *have* to read `verified.data` in some way or other,
// even if you don't need it, as that is what triggers the
// verification of the data.
try {
await verificationResult.signatures[0].verified; // throws on invalid signature
console.log('Signed by key id ' + verificationResult.signatures[0].keyID.toHex());
} catch (e) {
throw new Error('Signature could not be verified: ' + e.message);
const { valid } = verified.signatures[0];
if (valid) {
console.log('signed by key id ' + verified.signatures[0].keyid.toHex());
} else {
throw new Error('signature could not be verified');
}
})();
```
### Documentation
The full documentation is available at [openpgpjs.org](https://docs.openpgpjs.org/).
A jsdoc build of our code comments is available at [doc/index.html](https://openpgpjs.org/openpgpjs/doc/index.html). Public calls should generally be made through the OpenPGP object [doc/openpgp.html](https://openpgpjs.org/openpgpjs/doc/module-openpgp.html).
For the documentation of `openpgp.stream`, see the documentation of [the web-stream-tools dependency](https://openpgpjs.org/web-stream-tools/).
### Security Audit
@ -664,9 +578,9 @@ To create your own build of the library, just run the following command after cl
npm install && npm test
For debugging browser errors, run the following command:
For debugging browser errors, you can open `test/unittests.html` in a browser or, after running the following command, open [`http://localhost:3000/test/unittests.html`](http://localhost:3000/test/unittests.html):
npm run browsertest
grunt browsertest
### How do I get involved?
@ -675,3 +589,13 @@ You want to help, great! It's probably best to send us a message on [Gitter](htt
### License
[GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl-3.0.en.html) (3.0 or any later version). Please take a look at the [LICENSE](LICENSE) file for more information.
### Resources
Below is a collection of resources, many of these were projects that were in someway a precursor to the current OpenPGP.js project. If you'd like to add your link here, please do so in a pull request or email to the list.
* [https://www.hanewin.net/encrypt/](https://www.hanewin.net/encrypt/)
* [https://github.com/seancolyer/gmail-crypt](https://github.com/seancolyer/gmail-crypt)
* [https://github.com/mete0r/jspg](https://github.com/mete0r/jspg)
* [https://github.com/GPGTools/Mobile/wiki/Introduction](https://github.com/GPGTools/Mobile/wiki/Introduction)
* [https://github.com/gmontalvoriv/mailock](https://github.com/gmontalvoriv/mailock)

View File

@ -1,7 +0,0 @@
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
If you believe you have found a security vulnerability in OpenPGP.js, please report it via email to [security@openpgpjs.org](mailto:security@openpgpjs.org). If possible, encrypt your message with our PGP key: it can be downloaded automatically using [WKD](https://wiki.gnupg.org/WKD), or manually on [openpgpjs.org](https://openpgpjs.org/.well-known/openpgpkey/hu/t5s8ztdbon8yzntexy6oz5y48etqsnbb?l=security).
You should receive a response within 2 working days.

37
bower.json Normal file
View File

@ -0,0 +1,37 @@
{
"name": "openpgp",
"version": "4.10.4",
"license": "LGPL-3.0+",
"homepage": "https://openpgpjs.org/",
"authors": [
"OpenPGP Development Team <list@openpgpjs.org> (https://github.com/openpgpjs/openpgpjs/graphs/contributors)"
],
"description": "OpenPGP.js is a Javascript implementation of the OpenPGP protocol. This is defined in RFC 4880.",
"main": [
"dist/openpgp.js",
"dist/openpgp.worker.js"
],
"moduleType": [
"amd",
"es6",
"globals",
"node"
],
"keywords": [
"crypto",
"gpg",
"pgp",
"openpgp",
"encryption"
],
"ignore": [
"**/.*",
"dist/*.tgz",
"dist/*_debug.js",
"node_modules",
"bower_components",
"test",
"tests",
"doc"
]
}

59937
dist/compat/openpgp.js vendored Normal file

File diff suppressed because one or more lines are too long

2
dist/compat/openpgp.min.js vendored Normal file

File diff suppressed because one or more lines are too long

173
dist/compat/openpgp.worker.js vendored Normal file
View File

@ -0,0 +1,173 @@
/*! OpenPGP.js v4.10.4 - 2020-04-22 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function (global){
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
/* eslint-disable no-restricted-globals */
/* eslint-disable no-var */
/* eslint-disable vars-on-top */
/**
* @fileoverview Provides functions for communicating with workers
* @see module:openpgp.initWorker
* @see module:openpgp.getWorker
* @see module:openpgp.destroyWorker
* @see module:worker/async_proxy
* @module worker/worker
*/
importScripts('openpgp.js');
var openpgp = global.openpgp;
var randomQueue = [];
var MAX_SIZE_RANDOM_BUFFER = 60000;
/**
* Handle random buffer exhaustion by requesting more random bytes from the main window
* @returns {Promise<Object>} Empty promise whose resolution indicates that the buffer has been refilled
*/
function randomCallback() {
if (!randomQueue.length) {
self.postMessage({ event: 'request-seed', amount: MAX_SIZE_RANDOM_BUFFER });
}
return new Promise(function(resolve) {
randomQueue.push(resolve);
});
}
openpgp.crypto.random.randomBuffer.init(MAX_SIZE_RANDOM_BUFFER, randomCallback);
/**
* Handle messages from the main window.
* @param {Object} event Contains event type and data
*/
self.onmessage = function(event) {
var msg = event.data || {};
switch (msg.event) {
case 'configure':
configure(msg.config);
break;
case 'seed-random':
seedRandom(msg.buf);
var queueCopy = randomQueue;
randomQueue = [];
for (var i = 0; i < queueCopy.length; i++) {
queueCopy[i]();
}
break;
default:
delegate(msg.id, msg.event, msg.options || {});
}
};
/**
* Set config from main context to worker context.
* @param {Object} config The openpgp configuration
*/
function configure(config) {
Object.keys(config).forEach(function(key) {
openpgp.config[key] = config[key];
});
}
/**
* Seed the library with entropy gathered global.crypto.getRandomValues
* as this api is only avalible in the main window.
* @param {ArrayBuffer} buffer Some random bytes
*/
function seedRandom(buffer) {
if (!(buffer instanceof Uint8Array)) {
buffer = new Uint8Array(buffer);
}
openpgp.crypto.random.randomBuffer.set(buffer);
}
const keyCache = new Map();
function getCachedKey(key) {
const armor = key.armor();
if (keyCache.has(armor)) {
return keyCache.get(armor);
}
keyCache.set(armor, key);
return key;
}
/**
* Generic proxy function that handles all commands from the public api.
* @param {String} method The public api function to be delegated to the worker thread
* @param {Object} options The api function's options
*/
function delegate(id, method, options) {
if (method === 'clear-key-cache') {
Array.from(keyCache.values()).forEach(key => {
if (key.isPrivate()) {
key.clearPrivateParams();
}
});
keyCache.clear();
response({ id, event: 'method-return' });
return;
}
if (typeof openpgp[method] !== 'function') {
response({ id:id, event:'method-return', err:'Unknown Worker Event' });
return;
}
// construct ReadableStreams from MessagePorts
openpgp.util.restoreStreams(options);
// parse cloned packets
options = openpgp.packet.clone.parseClonedPackets(options, method);
// cache keys by armor, so that we don't have to repeatedly verify self-signatures
if (options.publicKeys) {
options.publicKeys = options.publicKeys.map(getCachedKey);
}
if (options.privateKeys) {
options.privateKeys = options.privateKeys.map(getCachedKey);
}
openpgp[method](options).then(function(data) {
// clone packets (for web worker structured cloning algorithm)
response({ id:id, event:'method-return', data:openpgp.packet.clone.clonePackets(data) });
}).catch(function(e) {
openpgp.util.print_debug_error(e);
response({
id:id, event:'method-return', err:e.message, stack:e.stack
});
});
}
/**
* Respond to the main window.
* @param {Object} event Contains event type and data
*/
function response(event) {
self.postMessage(event, openpgp.util.getTransferables(event.data, true));
}
/**
* Let the main window know the worker has loaded.
*/
postMessage({ event: 'loaded' });
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1]);

2
dist/compat/openpgp.worker.min.js vendored Normal file
View File

@ -0,0 +1,2 @@
/*! OpenPGP.js v4.10.4 - 2020-04-22 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
!function(){return function e(n,t,r){function o(i,s){if(!t[i]){if(!n[i]){var u="function"==typeof require&&require;if(!s&&u)return u(i,!0);if(a)return a(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var f=t[i]={exports:{}};n[i][0].call(f.exports,function(e){return o(n[i][1][e]||e)},f,f.exports,e,n,t,r)}return t[i].exports}for(var a="function"==typeof require&&require,i=0;i<r.length;i++)o(r[i]);return o}}()({1:[function(e,n,t){(function(e){importScripts("openpgp.min.js");var n=e.openpgp,t=[],r=6e4;n.crypto.random.randomBuffer.init(r,function(){return t.length||self.postMessage({event:"request-seed",amount:r}),new Promise(function(e){t.push(e)})}),self.onmessage=function(e){var r,s=e.data||{};switch(s.event){case"configure":r=s.config,Object.keys(r).forEach(function(e){n.config[e]=r[e]});break;case"seed-random":!function(e){e instanceof Uint8Array||(e=new Uint8Array(e));n.crypto.random.randomBuffer.set(e)}(s.buf);var u=t;t=[];for(var c=0;c<u.length;c++)u[c]();break;default:!function(e,t,r){if("clear-key-cache"===t)return Array.from(o.values()).forEach(e=>{e.isPrivate()&&e.clearPrivateParams()}),o.clear(),void i({id:e,event:"method-return"});if("function"!=typeof n[t])return void i({id:e,event:"method-return",err:"Unknown Worker Event"});n.util.restoreStreams(r),(r=n.packet.clone.parseClonedPackets(r,t)).publicKeys&&(r.publicKeys=r.publicKeys.map(a));r.privateKeys&&(r.privateKeys=r.privateKeys.map(a));n[t](r).then(function(t){i({id:e,event:"method-return",data:n.packet.clone.clonePackets(t)})}).catch(function(t){n.util.print_debug_error(t),i({id:e,event:"method-return",err:t.message,stack:t.stack})})}(s.id,s.event,s.options||{})}};const o=new Map;function a(e){const n=e.armor();return o.has(n)?o.get(n):(o.set(n,e),e)}function i(e){self.postMessage(e,n.util.getTransferables(e.data,!0))}postMessage({event:"loaded"})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1]);

5
dist/lightweight/elliptic.min.js vendored Normal file

File diff suppressed because one or more lines are too long

39335
dist/lightweight/openpgp.js vendored Normal file

File diff suppressed because one or more lines are too long

2
dist/lightweight/openpgp.min.js vendored Normal file

File diff suppressed because one or more lines are too long

173
dist/lightweight/openpgp.worker.js vendored Normal file
View File

@ -0,0 +1,173 @@
/*! OpenPGP.js v4.10.4 - 2020-04-22 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function (global){
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
/* eslint-disable no-restricted-globals */
/* eslint-disable no-var */
/* eslint-disable vars-on-top */
/**
* @fileoverview Provides functions for communicating with workers
* @see module:openpgp.initWorker
* @see module:openpgp.getWorker
* @see module:openpgp.destroyWorker
* @see module:worker/async_proxy
* @module worker/worker
*/
importScripts('openpgp.js');
var openpgp = global.openpgp;
var randomQueue = [];
var MAX_SIZE_RANDOM_BUFFER = 60000;
/**
* Handle random buffer exhaustion by requesting more random bytes from the main window
* @returns {Promise<Object>} Empty promise whose resolution indicates that the buffer has been refilled
*/
function randomCallback() {
if (!randomQueue.length) {
self.postMessage({ event: 'request-seed', amount: MAX_SIZE_RANDOM_BUFFER });
}
return new Promise(function(resolve) {
randomQueue.push(resolve);
});
}
openpgp.crypto.random.randomBuffer.init(MAX_SIZE_RANDOM_BUFFER, randomCallback);
/**
* Handle messages from the main window.
* @param {Object} event Contains event type and data
*/
self.onmessage = function(event) {
var msg = event.data || {};
switch (msg.event) {
case 'configure':
configure(msg.config);
break;
case 'seed-random':
seedRandom(msg.buf);
var queueCopy = randomQueue;
randomQueue = [];
for (var i = 0; i < queueCopy.length; i++) {
queueCopy[i]();
}
break;
default:
delegate(msg.id, msg.event, msg.options || {});
}
};
/**
* Set config from main context to worker context.
* @param {Object} config The openpgp configuration
*/
function configure(config) {
Object.keys(config).forEach(function(key) {
openpgp.config[key] = config[key];
});
}
/**
* Seed the library with entropy gathered global.crypto.getRandomValues
* as this api is only avalible in the main window.
* @param {ArrayBuffer} buffer Some random bytes
*/
function seedRandom(buffer) {
if (!(buffer instanceof Uint8Array)) {
buffer = new Uint8Array(buffer);
}
openpgp.crypto.random.randomBuffer.set(buffer);
}
const keyCache = new Map();
function getCachedKey(key) {
const armor = key.armor();
if (keyCache.has(armor)) {
return keyCache.get(armor);
}
keyCache.set(armor, key);
return key;
}
/**
* Generic proxy function that handles all commands from the public api.
* @param {String} method The public api function to be delegated to the worker thread
* @param {Object} options The api function's options
*/
function delegate(id, method, options) {
if (method === 'clear-key-cache') {
Array.from(keyCache.values()).forEach(key => {
if (key.isPrivate()) {
key.clearPrivateParams();
}
});
keyCache.clear();
response({ id, event: 'method-return' });
return;
}
if (typeof openpgp[method] !== 'function') {
response({ id:id, event:'method-return', err:'Unknown Worker Event' });
return;
}
// construct ReadableStreams from MessagePorts
openpgp.util.restoreStreams(options);
// parse cloned packets
options = openpgp.packet.clone.parseClonedPackets(options, method);
// cache keys by armor, so that we don't have to repeatedly verify self-signatures
if (options.publicKeys) {
options.publicKeys = options.publicKeys.map(getCachedKey);
}
if (options.privateKeys) {
options.privateKeys = options.privateKeys.map(getCachedKey);
}
openpgp[method](options).then(function(data) {
// clone packets (for web worker structured cloning algorithm)
response({ id:id, event:'method-return', data:openpgp.packet.clone.clonePackets(data) });
}).catch(function(e) {
openpgp.util.print_debug_error(e);
response({
id:id, event:'method-return', err:e.message, stack:e.stack
});
});
}
/**
* Respond to the main window.
* @param {Object} event Contains event type and data
*/
function response(event) {
self.postMessage(event, openpgp.util.getTransferables(event.data, true));
}
/**
* Let the main window know the worker has loaded.
*/
postMessage({ event: 'loaded' });
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1]);

View File

@ -0,0 +1,2 @@
/*! OpenPGP.js v4.10.4 - 2020-04-22 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
!function(){return function e(n,t,r){function o(i,s){if(!t[i]){if(!n[i]){var u="function"==typeof require&&require;if(!s&&u)return u(i,!0);if(a)return a(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var f=t[i]={exports:{}};n[i][0].call(f.exports,function(e){return o(n[i][1][e]||e)},f,f.exports,e,n,t,r)}return t[i].exports}for(var a="function"==typeof require&&require,i=0;i<r.length;i++)o(r[i]);return o}}()({1:[function(e,n,t){(function(e){importScripts("openpgp.min.js");var n=e.openpgp,t=[],r=6e4;n.crypto.random.randomBuffer.init(r,function(){return t.length||self.postMessage({event:"request-seed",amount:r}),new Promise(function(e){t.push(e)})}),self.onmessage=function(e){var r,s=e.data||{};switch(s.event){case"configure":r=s.config,Object.keys(r).forEach(function(e){n.config[e]=r[e]});break;case"seed-random":!function(e){e instanceof Uint8Array||(e=new Uint8Array(e));n.crypto.random.randomBuffer.set(e)}(s.buf);var u=t;t=[];for(var c=0;c<u.length;c++)u[c]();break;default:!function(e,t,r){if("clear-key-cache"===t)return Array.from(o.values()).forEach(e=>{e.isPrivate()&&e.clearPrivateParams()}),o.clear(),void i({id:e,event:"method-return"});if("function"!=typeof n[t])return void i({id:e,event:"method-return",err:"Unknown Worker Event"});n.util.restoreStreams(r),(r=n.packet.clone.parseClonedPackets(r,t)).publicKeys&&(r.publicKeys=r.publicKeys.map(a));r.privateKeys&&(r.privateKeys=r.privateKeys.map(a));n[t](r).then(function(t){i({id:e,event:"method-return",data:n.packet.clone.clonePackets(t)})}).catch(function(t){n.util.print_debug_error(t),i({id:e,event:"method-return",err:t.message,stack:t.stack})})}(s.id,s.event,s.options||{})}};const o=new Map;function a(e){const n=e.armor();return o.has(n)?o.get(n):(o.set(n,e),e)}function i(e){self.postMessage(e,n.util.getTransferables(e.data,!0))}postMessage({event:"loaded"})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1]);

43722
dist/openpgp.js vendored Normal file

File diff suppressed because one or more lines are too long

2
dist/openpgp.min.js vendored Normal file

File diff suppressed because one or more lines are too long

173
dist/openpgp.worker.js vendored Normal file
View File

@ -0,0 +1,173 @@
/*! OpenPGP.js v4.10.4 - 2020-04-22 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function (global){
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
/* eslint-disable no-restricted-globals */
/* eslint-disable no-var */
/* eslint-disable vars-on-top */
/**
* @fileoverview Provides functions for communicating with workers
* @see module:openpgp.initWorker
* @see module:openpgp.getWorker
* @see module:openpgp.destroyWorker
* @see module:worker/async_proxy
* @module worker/worker
*/
importScripts('openpgp.js');
var openpgp = global.openpgp;
var randomQueue = [];
var MAX_SIZE_RANDOM_BUFFER = 60000;
/**
* Handle random buffer exhaustion by requesting more random bytes from the main window
* @returns {Promise<Object>} Empty promise whose resolution indicates that the buffer has been refilled
*/
function randomCallback() {
if (!randomQueue.length) {
self.postMessage({ event: 'request-seed', amount: MAX_SIZE_RANDOM_BUFFER });
}
return new Promise(function(resolve) {
randomQueue.push(resolve);
});
}
openpgp.crypto.random.randomBuffer.init(MAX_SIZE_RANDOM_BUFFER, randomCallback);
/**
* Handle messages from the main window.
* @param {Object} event Contains event type and data
*/
self.onmessage = function(event) {
var msg = event.data || {};
switch (msg.event) {
case 'configure':
configure(msg.config);
break;
case 'seed-random':
seedRandom(msg.buf);
var queueCopy = randomQueue;
randomQueue = [];
for (var i = 0; i < queueCopy.length; i++) {
queueCopy[i]();
}
break;
default:
delegate(msg.id, msg.event, msg.options || {});
}
};
/**
* Set config from main context to worker context.
* @param {Object} config The openpgp configuration
*/
function configure(config) {
Object.keys(config).forEach(function(key) {
openpgp.config[key] = config[key];
});
}
/**
* Seed the library with entropy gathered global.crypto.getRandomValues
* as this api is only avalible in the main window.
* @param {ArrayBuffer} buffer Some random bytes
*/
function seedRandom(buffer) {
if (!(buffer instanceof Uint8Array)) {
buffer = new Uint8Array(buffer);
}
openpgp.crypto.random.randomBuffer.set(buffer);
}
const keyCache = new Map();
function getCachedKey(key) {
const armor = key.armor();
if (keyCache.has(armor)) {
return keyCache.get(armor);
}
keyCache.set(armor, key);
return key;
}
/**
* Generic proxy function that handles all commands from the public api.
* @param {String} method The public api function to be delegated to the worker thread
* @param {Object} options The api function's options
*/
function delegate(id, method, options) {
if (method === 'clear-key-cache') {
Array.from(keyCache.values()).forEach(key => {
if (key.isPrivate()) {
key.clearPrivateParams();
}
});
keyCache.clear();
response({ id, event: 'method-return' });
return;
}
if (typeof openpgp[method] !== 'function') {
response({ id:id, event:'method-return', err:'Unknown Worker Event' });
return;
}
// construct ReadableStreams from MessagePorts
openpgp.util.restoreStreams(options);
// parse cloned packets
options = openpgp.packet.clone.parseClonedPackets(options, method);
// cache keys by armor, so that we don't have to repeatedly verify self-signatures
if (options.publicKeys) {
options.publicKeys = options.publicKeys.map(getCachedKey);
}
if (options.privateKeys) {
options.privateKeys = options.privateKeys.map(getCachedKey);
}
openpgp[method](options).then(function(data) {
// clone packets (for web worker structured cloning algorithm)
response({ id:id, event:'method-return', data:openpgp.packet.clone.clonePackets(data) });
}).catch(function(e) {
openpgp.util.print_debug_error(e);
response({
id:id, event:'method-return', err:e.message, stack:e.stack
});
});
}
/**
* Respond to the main window.
* @param {Object} event Contains event type and data
*/
function response(event) {
self.postMessage(event, openpgp.util.getTransferables(event.data, true));
}
/**
* Let the main window know the worker has loaded.
*/
postMessage({ event: 'loaded' });
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1]);

2
dist/openpgp.worker.min.js vendored Normal file
View File

@ -0,0 +1,2 @@
/*! OpenPGP.js v4.10.4 - 2020-04-22 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
!function(){return function e(n,t,r){function o(i,s){if(!t[i]){if(!n[i]){var u="function"==typeof require&&require;if(!s&&u)return u(i,!0);if(a)return a(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var f=t[i]={exports:{}};n[i][0].call(f.exports,function(e){return o(n[i][1][e]||e)},f,f.exports,e,n,t,r)}return t[i].exports}for(var a="function"==typeof require&&require,i=0;i<r.length;i++)o(r[i]);return o}}()({1:[function(e,n,t){(function(e){importScripts("openpgp.min.js");var n=e.openpgp,t=[],r=6e4;n.crypto.random.randomBuffer.init(r,function(){return t.length||self.postMessage({event:"request-seed",amount:r}),new Promise(function(e){t.push(e)})}),self.onmessage=function(e){var r,s=e.data||{};switch(s.event){case"configure":r=s.config,Object.keys(r).forEach(function(e){n.config[e]=r[e]});break;case"seed-random":!function(e){e instanceof Uint8Array||(e=new Uint8Array(e));n.crypto.random.randomBuffer.set(e)}(s.buf);var u=t;t=[];for(var c=0;c<u.length;c++)u[c]();break;default:!function(e,t,r){if("clear-key-cache"===t)return Array.from(o.values()).forEach(e=>{e.isPrivate()&&e.clearPrivateParams()}),o.clear(),void i({id:e,event:"method-return"});if("function"!=typeof n[t])return void i({id:e,event:"method-return",err:"Unknown Worker Event"});n.util.restoreStreams(r),(r=n.packet.clone.parseClonedPackets(r,t)).publicKeys&&(r.publicKeys=r.publicKeys.map(a));r.privateKeys&&(r.privateKeys=r.privateKeys.map(a));n[t](r).then(function(t){i({id:e,event:"method-return",data:n.packet.clone.clonePackets(t)})}).catch(function(t){n.util.print_debug_error(t),i({id:e,event:"method-return",err:t.message,stack:t.stack})})}(s.id,s.event,s.options||{})}};const o=new Map;function a(e){const n=e.armor();return o.has(n)?o.get(n):(o.set(n,e),e)}function i(e){self.postMessage(e,n.util.getTransferables(e.data,!0))}postMessage({event:"loaded"})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1]);

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 +0,0 @@
docs.openpgpjs.org

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

Binary file not shown.

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 116 KiB

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 118 KiB

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 120 KiB

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 114 KiB

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 120 KiB

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 117 KiB

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

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