From 99c1d9af689e5325f3cf535c4007b3aeb8325229 Mon Sep 17 00:00:00 2001 From: Minteck Date: Tue, 10 Jan 2023 14:54:04 +0100 Subject: Update - This is an automated commit --- alarm/node_modules/node-forge/.jscsrc | 64 - alarm/node_modules/node-forge/.jshintignore | 6 - alarm/node_modules/node-forge/.jshintrc | 3 - alarm/node_modules/node-forge/.npmignore | 23 - alarm/node_modules/node-forge/.travis.yml | 12 - alarm/node_modules/node-forge/HACKING.md | 37 - alarm/node_modules/node-forge/LICENSE | 331 -- alarm/node_modules/node-forge/Makefile.in | 110 - alarm/node_modules/node-forge/README.md | 1796 -------- alarm/node_modules/node-forge/bower.json | 16 - alarm/node_modules/node-forge/build-flash.xml | 7 - alarm/node_modules/node-forge/build-setup | 46 - alarm/node_modules/node-forge/end.frag | 4 - .../node_modules/node-forge/flash/PooledSocket.as | 18 - alarm/node_modules/node-forge/flash/SocketEvent.as | 36 - alarm/node_modules/node-forge/flash/SocketPool.as | 754 ---- alarm/node_modules/node-forge/js/aes.js | 1147 ------ .../node_modules/node-forge/js/aesCipherSuites.js | 338 -- alarm/node_modules/node-forge/js/asn1.js | 1114 ----- alarm/node_modules/node-forge/js/cipher.js | 286 -- alarm/node_modules/node-forge/js/cipherModes.js | 1049 ----- alarm/node_modules/node-forge/js/debug.js | 134 - alarm/node_modules/node-forge/js/des.js | 552 --- alarm/node_modules/node-forge/js/forge.js | 92 - alarm/node_modules/node-forge/js/form.js | 157 - alarm/node_modules/node-forge/js/hmac.js | 200 - alarm/node_modules/node-forge/js/http.js | 1369 ------- alarm/node_modules/node-forge/js/jsbn.js | 1321 ------ alarm/node_modules/node-forge/js/kem.js | 221 - alarm/node_modules/node-forge/js/log.js | 372 -- alarm/node_modules/node-forge/js/md.js | 75 - alarm/node_modules/node-forge/js/md5.js | 322 -- alarm/node_modules/node-forge/js/mgf.js | 67 - alarm/node_modules/node-forge/js/mgf1.js | 112 - alarm/node_modules/node-forge/js/oids.js | 269 -- alarm/node_modules/node-forge/js/pbe.js | 975 ----- alarm/node_modules/node-forge/js/pbkdf2.js | 264 -- alarm/node_modules/node-forge/js/pem.js | 285 -- alarm/node_modules/node-forge/js/pkcs1.js | 329 -- alarm/node_modules/node-forge/js/pkcs12.js | 1133 ----- alarm/node_modules/node-forge/js/pkcs7.js | 842 ---- alarm/node_modules/node-forge/js/pkcs7asn1.js | 399 -- alarm/node_modules/node-forge/js/pki.js | 161 - alarm/node_modules/node-forge/js/prime.js | 337 -- alarm/node_modules/node-forge/js/prime.worker.js | 165 - alarm/node_modules/node-forge/js/prng.js | 458 --- alarm/node_modules/node-forge/js/pss.js | 295 -- alarm/node_modules/node-forge/js/random.js | 237 -- alarm/node_modules/node-forge/js/rc2.js | 470 --- alarm/node_modules/node-forge/js/rsa.js | 1712 -------- alarm/node_modules/node-forge/js/sha1.js | 342 -- alarm/node_modules/node-forge/js/sha256.js | 352 -- alarm/node_modules/node-forge/js/sha512.js | 590 --- alarm/node_modules/node-forge/js/socket.js | 342 -- alarm/node_modules/node-forge/js/ssh.js | 295 -- alarm/node_modules/node-forge/js/task.js | 778 ---- alarm/node_modules/node-forge/js/tls.js | 4316 -------------------- alarm/node_modules/node-forge/js/tlssocket.js | 304 -- alarm/node_modules/node-forge/js/util.js | 2988 -------------- alarm/node_modules/node-forge/js/x509.js | 3178 -------------- alarm/node_modules/node-forge/js/xhr.js | 739 ---- alarm/node_modules/node-forge/minify.js | 10 - alarm/node_modules/node-forge/mod_fsp/README | 135 - alarm/node_modules/node-forge/mod_fsp/mod_fsp.c | 415 -- alarm/node_modules/node-forge/nodejs/.istanbul.yml | 2 - alarm/node_modules/node-forge/nodejs/README.md | 34 - alarm/node_modules/node-forge/nodejs/build.js | 8 - alarm/node_modules/node-forge/nodejs/minify.js | 8 - alarm/node_modules/node-forge/nodejs/package.json | 24 - alarm/node_modules/node-forge/nodejs/server.js | 46 - alarm/node_modules/node-forge/nodejs/test/aes.js | 1498 ------- alarm/node_modules/node-forge/nodejs/test/asn1.js | 262 -- .../node_modules/node-forge/nodejs/test/browser.js | 41 - alarm/node_modules/node-forge/nodejs/test/csr.js | 148 - alarm/node_modules/node-forge/nodejs/test/des.js | 155 - alarm/node_modules/node-forge/nodejs/test/hmac.js | 85 - alarm/node_modules/node-forge/nodejs/test/kem.js | 198 - alarm/node_modules/node-forge/nodejs/test/md5.js | 117 - alarm/node_modules/node-forge/nodejs/test/mgf1.js | 39 - .../node_modules/node-forge/nodejs/test/pbkdf2.js | 140 - alarm/node_modules/node-forge/nodejs/test/pem.js | 104 - alarm/node_modules/node-forge/nodejs/test/pkcs1.js | 1105 ----- .../node_modules/node-forge/nodejs/test/pkcs12.js | 687 ---- alarm/node_modules/node-forge/nodejs/test/pkcs7.js | 350 -- .../node_modules/node-forge/nodejs/test/random.js | 70 - alarm/node_modules/node-forge/nodejs/test/rc2.js | 109 - alarm/node_modules/node-forge/nodejs/test/rsa.js | 602 --- alarm/node_modules/node-forge/nodejs/test/sha1.js | 75 - .../node_modules/node-forge/nodejs/test/sha256.js | 81 - .../node_modules/node-forge/nodejs/test/sha512.js | 174 - alarm/node_modules/node-forge/nodejs/test/ssh.js | 193 - alarm/node_modules/node-forge/nodejs/test/tls.js | 191 - alarm/node_modules/node-forge/nodejs/test/util.js | 406 -- alarm/node_modules/node-forge/nodejs/test/x509.js | 734 ---- alarm/node_modules/node-forge/nodejs/ui/index.html | 12 - alarm/node_modules/node-forge/nodejs/ui/require.js | 35 - alarm/node_modules/node-forge/nodejs/ui/test.js | 36 - .../node_modules/node-forge/nodejs/ui/test.min.js | 1 - alarm/node_modules/node-forge/package.json | 86 - alarm/node_modules/node-forge/setup/configure.ac | 202 - alarm/node_modules/node-forge/setup/install-sh | 269 -- .../node_modules/node-forge/setup/m4/as-python.m4 | 156 - alarm/node_modules/node-forge/start.frag | 7 - alarm/node_modules/node-forge/swf/SocketPool.swf | Bin 18034 -> 0 bytes alarm/node_modules/node-forge/tests/aes-speed.js | 62 - alarm/node_modules/node-forge/tests/common.html | 84 - alarm/node_modules/node-forge/tests/common.js | 2199 ---------- alarm/node_modules/node-forge/tests/favicon.ico | 0 alarm/node_modules/node-forge/tests/flash/Test.as | 96 - .../node-forge/tests/flash/build-flash.xml | 7 - .../node_modules/node-forge/tests/flash/index.html | 27 - .../node-forge/tests/forge_ssl/forge/__init__.py | 0 .../node-forge/tests/forge_ssl/forge/_ssl.c | 1770 -------- .../tests/forge_ssl/forge/socketmodule.h | 268 -- .../node-forge/tests/forge_ssl/forge/ssl.py | 486 --- .../node-forge/tests/forge_ssl/setup.py | 12 - alarm/node_modules/node-forge/tests/form.html | 150 - alarm/node_modules/node-forge/tests/form.js | 40 - alarm/node_modules/node-forge/tests/heartbleed.js | 55 - alarm/node_modules/node-forge/tests/http.html | 229 -- alarm/node_modules/node-forge/tests/index.html | 64 - alarm/node_modules/node-forge/tests/keygen.html | 56 - alarm/node_modules/node-forge/tests/login.css | 26 - alarm/node_modules/node-forge/tests/loginDemo.html | 56 - alarm/node_modules/node-forge/tests/loginDemo.js | 149 - .../node-forge/tests/nodejs-create-cert.js | 110 - .../node-forge/tests/nodejs-create-csr.js | 66 - .../node-forge/tests/nodejs-create-pkcs12.js | 160 - alarm/node_modules/node-forge/tests/nodejs-imap.js | 46 - alarm/node_modules/node-forge/tests/nodejs-tls.js | 189 - .../node-forge/tests/nodejs-ws-webid.js | 491 --- alarm/node_modules/node-forge/tests/nodejs-ws.js | 166 - .../node_modules/node-forge/tests/performance.html | 550 --- .../node_modules/node-forge/tests/policyserver.py | 112 - alarm/node_modules/node-forge/tests/result.txt | 1 - alarm/node_modules/node-forge/tests/screen.css | 61 - alarm/node_modules/node-forge/tests/server.crt | 26 - alarm/node_modules/node-forge/tests/server.key | 27 - alarm/node_modules/node-forge/tests/server.py | 184 - .../node_modules/node-forge/tests/socketPool.html | 299 -- alarm/node_modules/node-forge/tests/tasks.html | 53 - alarm/node_modules/node-forge/tests/tasks.js | 378 -- alarm/node_modules/node-forge/tests/tls.html | 426 -- alarm/node_modules/node-forge/tests/webid.html | 110 - alarm/node_modules/node-forge/tests/webid.js | 313 -- alarm/node_modules/node-forge/tests/ws-webid.js | 132 - alarm/node_modules/node-forge/tests/ws.js | 237 -- alarm/node_modules/node-forge/tests/xhr.html | 87 - alarm/node_modules/node-forge/tests/xhr.js | 590 --- 149 files changed, 54446 deletions(-) delete mode 100644 alarm/node_modules/node-forge/.jscsrc delete mode 100644 alarm/node_modules/node-forge/.jshintignore delete mode 100644 alarm/node_modules/node-forge/.jshintrc delete mode 100644 alarm/node_modules/node-forge/.npmignore delete mode 100644 alarm/node_modules/node-forge/.travis.yml delete mode 100644 alarm/node_modules/node-forge/HACKING.md delete mode 100644 alarm/node_modules/node-forge/LICENSE delete mode 100644 alarm/node_modules/node-forge/Makefile.in delete mode 100644 alarm/node_modules/node-forge/README.md delete mode 100644 alarm/node_modules/node-forge/bower.json delete mode 100644 alarm/node_modules/node-forge/build-flash.xml delete mode 100755 alarm/node_modules/node-forge/build-setup delete mode 100644 alarm/node_modules/node-forge/end.frag delete mode 100644 alarm/node_modules/node-forge/flash/PooledSocket.as delete mode 100644 alarm/node_modules/node-forge/flash/SocketEvent.as delete mode 100644 alarm/node_modules/node-forge/flash/SocketPool.as delete mode 100644 alarm/node_modules/node-forge/js/aes.js delete mode 100644 alarm/node_modules/node-forge/js/aesCipherSuites.js delete mode 100644 alarm/node_modules/node-forge/js/asn1.js delete mode 100644 alarm/node_modules/node-forge/js/cipher.js delete mode 100644 alarm/node_modules/node-forge/js/cipherModes.js delete mode 100644 alarm/node_modules/node-forge/js/debug.js delete mode 100644 alarm/node_modules/node-forge/js/des.js delete mode 100644 alarm/node_modules/node-forge/js/forge.js delete mode 100644 alarm/node_modules/node-forge/js/form.js delete mode 100644 alarm/node_modules/node-forge/js/hmac.js delete mode 100644 alarm/node_modules/node-forge/js/http.js delete mode 100644 alarm/node_modules/node-forge/js/jsbn.js delete mode 100644 alarm/node_modules/node-forge/js/kem.js delete mode 100644 alarm/node_modules/node-forge/js/log.js delete mode 100644 alarm/node_modules/node-forge/js/md.js delete mode 100644 alarm/node_modules/node-forge/js/md5.js delete mode 100644 alarm/node_modules/node-forge/js/mgf.js delete mode 100644 alarm/node_modules/node-forge/js/mgf1.js delete mode 100644 alarm/node_modules/node-forge/js/oids.js delete mode 100644 alarm/node_modules/node-forge/js/pbe.js delete mode 100644 alarm/node_modules/node-forge/js/pbkdf2.js delete mode 100644 alarm/node_modules/node-forge/js/pem.js delete mode 100644 alarm/node_modules/node-forge/js/pkcs1.js delete mode 100644 alarm/node_modules/node-forge/js/pkcs12.js delete mode 100644 alarm/node_modules/node-forge/js/pkcs7.js delete mode 100644 alarm/node_modules/node-forge/js/pkcs7asn1.js delete mode 100644 alarm/node_modules/node-forge/js/pki.js delete mode 100644 alarm/node_modules/node-forge/js/prime.js delete mode 100644 alarm/node_modules/node-forge/js/prime.worker.js delete mode 100644 alarm/node_modules/node-forge/js/prng.js delete mode 100644 alarm/node_modules/node-forge/js/pss.js delete mode 100644 alarm/node_modules/node-forge/js/random.js delete mode 100644 alarm/node_modules/node-forge/js/rc2.js delete mode 100644 alarm/node_modules/node-forge/js/rsa.js delete mode 100644 alarm/node_modules/node-forge/js/sha1.js delete mode 100644 alarm/node_modules/node-forge/js/sha256.js delete mode 100644 alarm/node_modules/node-forge/js/sha512.js delete mode 100644 alarm/node_modules/node-forge/js/socket.js delete mode 100644 alarm/node_modules/node-forge/js/ssh.js delete mode 100644 alarm/node_modules/node-forge/js/task.js delete mode 100644 alarm/node_modules/node-forge/js/tls.js delete mode 100644 alarm/node_modules/node-forge/js/tlssocket.js delete mode 100644 alarm/node_modules/node-forge/js/util.js delete mode 100644 alarm/node_modules/node-forge/js/x509.js delete mode 100644 alarm/node_modules/node-forge/js/xhr.js delete mode 100644 alarm/node_modules/node-forge/minify.js delete mode 100644 alarm/node_modules/node-forge/mod_fsp/README delete mode 100644 alarm/node_modules/node-forge/mod_fsp/mod_fsp.c delete mode 100644 alarm/node_modules/node-forge/nodejs/.istanbul.yml delete mode 100644 alarm/node_modules/node-forge/nodejs/README.md delete mode 100644 alarm/node_modules/node-forge/nodejs/build.js delete mode 100644 alarm/node_modules/node-forge/nodejs/minify.js delete mode 100644 alarm/node_modules/node-forge/nodejs/package.json delete mode 100644 alarm/node_modules/node-forge/nodejs/server.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/aes.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/asn1.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/browser.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/csr.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/des.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/hmac.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/kem.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/md5.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/mgf1.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/pbkdf2.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/pem.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/pkcs1.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/pkcs12.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/pkcs7.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/random.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/rc2.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/rsa.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/sha1.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/sha256.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/sha512.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/ssh.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/tls.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/util.js delete mode 100644 alarm/node_modules/node-forge/nodejs/test/x509.js delete mode 100644 alarm/node_modules/node-forge/nodejs/ui/index.html delete mode 100644 alarm/node_modules/node-forge/nodejs/ui/require.js delete mode 100644 alarm/node_modules/node-forge/nodejs/ui/test.js delete mode 100644 alarm/node_modules/node-forge/nodejs/ui/test.min.js delete mode 100644 alarm/node_modules/node-forge/package.json delete mode 100644 alarm/node_modules/node-forge/setup/configure.ac delete mode 100755 alarm/node_modules/node-forge/setup/install-sh delete mode 100644 alarm/node_modules/node-forge/setup/m4/as-python.m4 delete mode 100644 alarm/node_modules/node-forge/start.frag delete mode 100644 alarm/node_modules/node-forge/swf/SocketPool.swf delete mode 100644 alarm/node_modules/node-forge/tests/aes-speed.js delete mode 100644 alarm/node_modules/node-forge/tests/common.html delete mode 100644 alarm/node_modules/node-forge/tests/common.js delete mode 100644 alarm/node_modules/node-forge/tests/favicon.ico delete mode 100644 alarm/node_modules/node-forge/tests/flash/Test.as delete mode 100644 alarm/node_modules/node-forge/tests/flash/build-flash.xml delete mode 100644 alarm/node_modules/node-forge/tests/flash/index.html delete mode 100644 alarm/node_modules/node-forge/tests/forge_ssl/forge/__init__.py delete mode 100644 alarm/node_modules/node-forge/tests/forge_ssl/forge/_ssl.c delete mode 100644 alarm/node_modules/node-forge/tests/forge_ssl/forge/socketmodule.h delete mode 100644 alarm/node_modules/node-forge/tests/forge_ssl/forge/ssl.py delete mode 100644 alarm/node_modules/node-forge/tests/forge_ssl/setup.py delete mode 100644 alarm/node_modules/node-forge/tests/form.html delete mode 100644 alarm/node_modules/node-forge/tests/form.js delete mode 100644 alarm/node_modules/node-forge/tests/heartbleed.js delete mode 100644 alarm/node_modules/node-forge/tests/http.html delete mode 100644 alarm/node_modules/node-forge/tests/index.html delete mode 100644 alarm/node_modules/node-forge/tests/keygen.html delete mode 100644 alarm/node_modules/node-forge/tests/login.css delete mode 100644 alarm/node_modules/node-forge/tests/loginDemo.html delete mode 100644 alarm/node_modules/node-forge/tests/loginDemo.js delete mode 100644 alarm/node_modules/node-forge/tests/nodejs-create-cert.js delete mode 100644 alarm/node_modules/node-forge/tests/nodejs-create-csr.js delete mode 100644 alarm/node_modules/node-forge/tests/nodejs-create-pkcs12.js delete mode 100644 alarm/node_modules/node-forge/tests/nodejs-imap.js delete mode 100644 alarm/node_modules/node-forge/tests/nodejs-tls.js delete mode 100644 alarm/node_modules/node-forge/tests/nodejs-ws-webid.js delete mode 100644 alarm/node_modules/node-forge/tests/nodejs-ws.js delete mode 100644 alarm/node_modules/node-forge/tests/performance.html delete mode 100755 alarm/node_modules/node-forge/tests/policyserver.py delete mode 100644 alarm/node_modules/node-forge/tests/result.txt delete mode 100644 alarm/node_modules/node-forge/tests/screen.css delete mode 100644 alarm/node_modules/node-forge/tests/server.crt delete mode 100644 alarm/node_modules/node-forge/tests/server.key delete mode 100755 alarm/node_modules/node-forge/tests/server.py delete mode 100644 alarm/node_modules/node-forge/tests/socketPool.html delete mode 100644 alarm/node_modules/node-forge/tests/tasks.html delete mode 100644 alarm/node_modules/node-forge/tests/tasks.js delete mode 100644 alarm/node_modules/node-forge/tests/tls.html delete mode 100644 alarm/node_modules/node-forge/tests/webid.html delete mode 100644 alarm/node_modules/node-forge/tests/webid.js delete mode 100644 alarm/node_modules/node-forge/tests/ws-webid.js delete mode 100644 alarm/node_modules/node-forge/tests/ws.js delete mode 100644 alarm/node_modules/node-forge/tests/xhr.html delete mode 100644 alarm/node_modules/node-forge/tests/xhr.js (limited to 'alarm/node_modules/node-forge') diff --git a/alarm/node_modules/node-forge/.jscsrc b/alarm/node_modules/node-forge/.jscsrc deleted file mode 100644 index 06245e6..0000000 --- a/alarm/node_modules/node-forge/.jscsrc +++ /dev/null @@ -1,64 +0,0 @@ -{ - "excludeFiles": [ - "./js/forge.bundle.js", - "./js/forge.min.js", - "./js/jsbn.js", - "./nodejs/ui/require.js", - "./nodejs/ui/test.min.js" - ], - "disallowKeywords": ["with"], - "disallowKeywordsOnNewLine": ["else", "catch"], - // FIXME: enable this? - //"disallowImplicitTypeConversion": ["string"], - "disallowMixedSpacesAndTabs": true, - "disallowMultipleLineBreaks": true, - // FIXME: enable this or do we prefer to - // use w/angular directive templates? - //"disallowMultipleLineStrings": true, - "disallowNewlineBeforeBlockStatements": true, - "disallowSpaceAfterObjectKeys": true, - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "disallowSpaceBeforeBinaryOperators": [","], - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "disallowSpacesInAnonymousFunctionExpression": { - "beforeOpeningRoundBrace": true - }, - "disallowSpacesInFunctionDeclaration": { - "beforeOpeningRoundBrace": true - }, - "disallowSpacesInNamedFunctionExpression": { - "beforeOpeningRoundBrace": true - }, - "disallowSpacesInsideParentheses": true, - "disallowTrailingComma": true, - "disallowTrailingWhitespace": true, - "requireCommaBeforeLineBreak": true, - "requireCurlyBraces": ["if", "else", "for", "while", "do", "try", "catch"], - "requireLineFeedAtFileEnd": true, - "requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], - "requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], - "requireSpaceAfterKeywords": [ - "else", - "do", - "return", - "try" - ], - "requireSpaceBeforeBlockStatements": true, - "requireSpacesInConditionalExpression": { - "afterTest": true, - "beforeConsequent": true, - "afterConsequent": true, - "beforeAlternate": true - }, - "requireSpacesInFunction": { - "beforeOpeningCurlyBrace": true - }, - "safeContextKeyword": "self", - "validateLineBreaks": "LF", - // FIXME: enable doc checks (update to use newer jscs jsdoc module) - //"validateJSDoc": { - // "checkParamNames": true, - // "requireParamTypes": true - //}, - "validateParameterSeparator": ", " -} diff --git a/alarm/node_modules/node-forge/.jshintignore b/alarm/node_modules/node-forge/.jshintignore deleted file mode 100644 index c50f474..0000000 --- a/alarm/node_modules/node-forge/.jshintignore +++ /dev/null @@ -1,6 +0,0 @@ -js/forge.bundle.js -minify.js -nodejs/build.js -nodejs/minify.js -nodejs/ui/require.js -nodejs/ui/test.min.js diff --git a/alarm/node_modules/node-forge/.jshintrc b/alarm/node_modules/node-forge/.jshintrc deleted file mode 100644 index 26d261c..0000000 --- a/alarm/node_modules/node-forge/.jshintrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "sub": true -} diff --git a/alarm/node_modules/node-forge/.npmignore b/alarm/node_modules/node-forge/.npmignore deleted file mode 100644 index 0cac541..0000000 --- a/alarm/node_modules/node-forge/.npmignore +++ /dev/null @@ -1,23 +0,0 @@ -*.py[co] -*.sw[nop] -*~ -.bower.json -.cdtproject -.classpath -.cproject -.project -.settings -Makefile -TAGS -aclocal.m4 -autom4te.cache -build -config.log -config.status -configure -dist -js/forge.bundle.js -js/forge.min.js -node_modules -nodejs/coverage -tests/forge diff --git a/alarm/node_modules/node-forge/.travis.yml b/alarm/node_modules/node-forge/.travis.yml deleted file mode 100644 index 7124426..0000000 --- a/alarm/node_modules/node-forge/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: node_js -node_js: - - "0.10" - - "0.12" - - iojs -install: (cd nodejs && npm install) -script: - - (cd nodejs && npm test) -notifications: - email: - on_success: change - on_failure: change diff --git a/alarm/node_modules/node-forge/HACKING.md b/alarm/node_modules/node-forge/HACKING.md deleted file mode 100644 index 762dfe1..0000000 --- a/alarm/node_modules/node-forge/HACKING.md +++ /dev/null @@ -1,37 +0,0 @@ -Hacking on forge -================ - -Want to hack on forge? Great! Here are a few notes: - -Code ----- - -* In general, follow a common [Node.js Style Guide][]. -* Use version X.Y.Z-dev in dev mode. -* Use version X.Y.Z for releases. - -Versioning ----------- - -* Follow the [Semantic Versioning][] guidelines. - -Release Process ---------------- - -* commit changes -* `$EDITOR package.json`: update to release version and remove `-dev` suffix. -* `git commit package.json -m "Release {version}."` -* `git tag {version}` -* `$EDITOR package.json`: update to next version and add `-dev` suffix. -* `git commit package.json -m "Start {next-version}."` -* `git push` -* `git push --tags` - -To ensure a clean upload, use a clean updated checkout, and run the following: - -* `git checkout {version}` -* `npm publish` - -[Node.js Style Guide]: http://nodeguide.com/style.html -[jshint]: http://www.jshint.com/install/ -[Semantic Versioning]: http://semver.org/ diff --git a/alarm/node_modules/node-forge/LICENSE b/alarm/node_modules/node-forge/LICENSE deleted file mode 100644 index 1bba5ce..0000000 --- a/alarm/node_modules/node-forge/LICENSE +++ /dev/null @@ -1,331 +0,0 @@ -You may use the Forge project under the terms of either the BSD License or the -GNU General Public License (GPL) Version 2. - -The BSD License is recommended for most projects. It is simple and easy to -understand and it places almost no restrictions on what you can do with the -Forge project. - -If the GPL suits your project better you are also free to use Forge under -that license. - -You don't have to do anything special to choose one license or the other and -you don't have to notify anyone which license you are using. You are free to -use this project in commercial projects as long as the copyright header is -left intact. - -If you are a commercial entity and use this set of libraries in your -commercial software then reasonable payment to Digital Bazaar, if you can -afford it, is not required but is expected and would be appreciated. If this -library saves you time, then it's saving you money. The cost of developing -the Forge software was on the order of several hundred hours and tens of -thousands of dollars. We are attempting to strike a balance between helping -the development community while not being taken advantage of by lucrative -commercial entities for our efforts. - -------------------------------------------------------------------------------- -New BSD License (3-clause) -Copyright (c) 2010, Digital Bazaar, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of Digital Bazaar, Inc. nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL DIGITAL BAZAAR BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -------------------------------------------------------------------------------- - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - diff --git a/alarm/node_modules/node-forge/Makefile.in b/alarm/node_modules/node-forge/Makefile.in deleted file mode 100644 index eb4495e..0000000 --- a/alarm/node_modules/node-forge/Makefile.in +++ /dev/null @@ -1,110 +0,0 @@ -# Makefile for Forge - -# Top-level build and dist dir -BUILD_DIR=@FORGE_DIR@/build -TOP_DIST_DIR=@FORGE_DIR@/dist -DIST_DIR=$(TOP_DIST_DIR)/forge - -_FLASH := $(DIST_DIR)/SocketPool.swf -ifeq (@BUILD_FLASH@,yes) -FLASH := $(_FLASH) -else -ifeq (@USE_PRE_BUILT_FLASH@,yes) -FLASH := $(_FLASH) -endif -endif -JS_SOURCES := $(wildcard js/*.js) -JS_DIST := $(JS_SOURCES:js/%.js=$(DIST_DIR)/%.js) -JS_DIST_MIN := $(JS_DIST:%.js=%.min.js) -TESTS_FORGE_LINK := @FORGE_DIR@/tests/forge - -ifeq (@BUILD_PYTHON_MODULES@,yes) -SSL_SESSIONS_DIR = \ - $(TOP_DIST_DIR)/forge_ssl/lib/python@PYTHON_VERSION@/site-packages -SSL_SESSIONS_FILES = \ - $(SSL_SESSIONS_DIR)/_forge_ssl.so \ - $(SSL_SESSIONS_DIR)/forge/ssl.py -endif - -# Whether or not to print commands as they are being executed, helpful for -# debugging the build system. -ifdef PRINT_COMMANDS -PCMD= -else -PCMD=@ -endif - -.PHONY: all build-all update-all verbose clean verbose-commands - -# debug flags for flash build -ifeq (@MXMLC_DEBUG_MODE@,yes) -FLASH_FLAGS = \ - -debug=true \ - -define=CONFIG::debugging,true \ - -define=CONFIG::release,false -else -FLASH_FLAGS = \ - -debug=false \ - -define=CONFIG::debugging,false \ - -define=CONFIG::release,true -endif - -all: $(BUILD_DIR) $(DIST_DIR) $(FLASH) $(JS_DIST) $(TESTS_FORGE_LINK) $(SSL_SESSIONS_FILES) - @echo "forge build complete." - -build-all: all - -update-all: - @git pull && ./build-setup && make all - -$(BUILD_DIR): - $(PCMD) mkdir -p $@ -$(DIST_DIR): - $(PCMD) mkdir -p $@ - -ifeq (@BUILD_FLASH@,yes) -$(DIST_DIR)/SocketPool.swf: flash/SocketPool.as flash/PooledSocket.as flash/SocketEvent.as - @echo "Building $@..." - $(PCMD) @MXMLC@ $(FLASH_FLAGS) \ - -load-config+=build-flash.xml \ - -output=$@ $< -else -ifeq (@USE_PRE_BUILT_FLASH@,yes) -$(DIST_DIR)/SocketPool.swf: @FORGE_DIR@/swf/SocketPool.swf - @echo "Copying pre-built $(@F)..." - $(PCMD) cp $< $@ -endif -endif - -$(DIST_DIR)/%.js: js/%.js - @echo "Linking $@..." - $(PCMD) ln -sf $(realpath $<) $@ - -$(TESTS_FORGE_LINK): $(DIST_DIR) - @echo "Linking $@..." - $(PCMD) ln -sf $(realpath $<) $@ - -ifeq (@BUILD_PYTHON_MODULES@,yes) -$(SSL_SESSIONS_DIR)/_forge_ssl.so: \ - @FORGE_DIR@/tests/forge_ssl/forge/_ssl.c \ - @FORGE_DIR@/tests/forge_ssl/forge/socketmodule.h \ - @FORGE_DIR@/tests/forge_ssl/setup.py -$(SSL_SESSIONS_DIR)/forge/ssl.py: \ - @FORGE_DIR@/tests/forge_ssl/forge/ssl.py \ - @FORGE_DIR@/tests/forge_ssl/setup.py - (cd @FORGE_DIR@/tests/forge_ssl && \ - @PYTHON@ setup.py \ - build --build-base $(BUILD_DIR) \ - install --prefix=$(TOP_DIST_DIR)/forge_ssl) - @# fix distutils timestamp issue - @# (sub-seconds of source file are truncated on target so rebuild is - @# always triggered) - @touch $@ -endif - -clean: - $(PCMD) rm -rf $(BUILD_DIR) $(TOP_DIST_DIR) - @echo "Removed all generated files." - -verbose-commands: - PRINT_COMMANDS=true $(MAKE) all diff --git a/alarm/node_modules/node-forge/README.md b/alarm/node_modules/node-forge/README.md deleted file mode 100644 index 0130ef4..0000000 --- a/alarm/node_modules/node-forge/README.md +++ /dev/null @@ -1,1796 +0,0 @@ -# Forge - -[![Build Status][travis-ci-png]][travis-ci-site] -[travis-ci-png]: https://travis-ci.org/digitalbazaar/forge.png?branch=master -[travis-ci-site]: https://travis-ci.org/digitalbazaar/forge - -A native implementation of [TLS][] (and various other cryptographic tools) in -[JavaScript][]. - -## Introduction - -The Forge software is a fully native implementation of the [TLS][] protocol in -JavaScript as well as a set of tools for developing Web Apps that utilize many -network resources. - -## Performance - -Forge is fast. Benchmarks against other popular JavaScript cryptography -libraries can be found here: - -http://dominictarr.github.io/crypto-bench/ - -http://cryptojs.altervista.org/test/simulate-threading-speed_test.html - -## Getting Started ------------------- - -### Node.js ### - -If you want to use forge with [node.js][], it is available through `npm`: - -https://npmjs.org/package/node-forge - -Installation: - - npm install node-forge - -You can then use forge as a regular module: - - var forge = require('node-forge'); - -### Requirements ### - -* General - * Optional: GNU autotools for the build infrastructure if using Flash. -* Building a Browser Bundle: - * nodejs - * npm -* Testing - * nodejs - * Optional: Python and OpenSSL development environment to build - * a special SSL module with session cache support for testing with flash. - * http://www.python.org/dev/ - * http://www.openssl.org/ - * Debian users should install python-dev and libssl-dev. -* Optional: Flash - * A pre-built SocketPool.swf is included. - * Adobe Flex 3 SDK to build the Flash socket code. - * http://opensource.adobe.com/wiki/display/flexsdk/ - -### Building a browser bundle ### - -To create a minimized JavaScript bundle, run the following: - -``` -npm install -npm run minify -``` - -This will create a single minimized file that can be included in -the browser: - -``` -js/forge.min.js -``` - -Include the file via: - -```html - -``` - -Note that the minify script depends on the requirejs package, -and that the requirejs binary 'r.js' assumes that the name of -the node binary is 'node' not 'nodejs', as it is on some -systems. You may need to change the hashbang line to use -'nodejs' or run the command manually. - -To create a single non-minimized file that can be included in -the browser: - -``` -npm install -npm run bundle -``` - -This will create: - -``` -js/forge.bundle.js -``` - -Include the file via: - -```html - -``` - -The above bundles will synchronously create a global 'forge' object. - -Keep in mind that these bundles will not include any WebWorker -scripts (eg: prime.worker.js) or their dependencies, so these will -need to be accessible from the browser if any WebWorkers are used. - -### Testing with NodeJS & RequireJS ### - -A test server for [node.js][] can be found at `./nodejs`. The following are included: - - * Example of how to use `forge` within NodeJS in the form of a [mocha](http://mochajs.org/) test. - * Example of how to serve `forge` to the browser using [RequireJS](http://requirejs.org/). - -To run: - - cd nodejs - npm install - npm test - npm start - - -### Old build system that includes flash support ### - -To build the whole project, including Flash, run the following: - - $ ./build-setup - $ make - -This will create the SWF, symlink all the JavaScript files, and build a Python -SSL module for testing. To see configure options, run `./configure --help`. - -### Old test system including flash support ### - -A test server is provided which can be run in TLS mode and non-TLS mode. Use -the --help option to get help for configuring ports. The server will print out -the local URL you can vist to run tests. - -Some of the simplier tests should be run with just the non-TLS server:: - - $ ./tests/server.py - -More advanced tests need TLS enabled:: - - $ ./tests/server.py --tls - -## Contributing ---------------- - -Any contributions (eg: PRs) that are accepted will be brought under the same -license used by the rest of the Forge project. This license allows Forge to -be used under the terms of either the BSD License or the GNU General Public -License (GPL) Version 2. - -See: [LICENSE](https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE) - -If a contribution contains 3rd party source code with its own license, it -may retain it, so long as that license is compatible with the Forge license. - -## Documentation ----------------- - -### Transports - -* [TLS](#tls) -* [HTTP](#http) -* [SSH](#ssh) -* [XHR](#xhr) -* [Sockets](#socket) - -### Ciphers - -* [CIPHER](#cipher) -* [AES](#aes) -* [DES](#des) -* [RC2](#rc2) - -### PKI - -* [RSA](#rsa) -* [RSA-KEM](#rsakem) -* [X.509](#x509) -* [PKCS#5](#pkcs5) -* [PKCS#7](#pkcs7) -* [PKCS#8](#pkcs8) -* [PKCS#10](#pkcs10) -* [PKCS#12](#pkcs12) -* [ASN.1](#asn) - -### Message Digests - -* [SHA1](#sha1) -* [SHA256](#sha256) -* [SHA384](#sha384) -* [SHA512](#sha512) -* [MD5](#md5) -* [HMAC](#hmac) - -### Utilities - -* [Prime](#prime) -* [PRNG](#prng) -* [Tasks](#task) -* [Utilities](#util) -* [Logging](#log) -* [Debugging](#debug) -* [Flash Socket Policy Module](#fsp) - ---------------------------------------- - -If at any time you wish to disable the use of native code, where available, -for particular forge features like its secure random number generator, you -may set the ```disableNativeCode``` flag on ```forge``` to ```true```. It -is not recommended that you set this flag as native code is typically more -performant and may have stronger security properties. It may be useful to -set this flag to test certain features that you plan to run in environments -that are different from your testing environment. - -To disable native code when including forge in the browser: - -```js -forge = {disableNativeCode: true}; -// now include forge script file(s) -// Note: with this approach, script files *must* -// be included after initializing the global forge var - -// alternatively, include script files first and then call -forge = forge({disableNativeCode: true}); - -// Note: forge will be permanently reconfigured now; -// to avoid this but use the same "forge" var name, -// you can wrap your code in a function to shadow the -// global var, eg: -(function(forge) { - // ... -})(forge({disableNativeCode: true})); -``` - -To disable native code when using node.js: - -```js -var forge = require('node-forge')({disableNativeCode: true}); -``` - ---------------------------------------- -## Transports - - -### TLS - -Provides a native javascript client and server-side [TLS][] implementation. - -__Examples__ - -```js -// create TLS client -var client = forge.tls.createConnection({ - server: false, - caStore: /* Array of PEM-formatted certs or a CA store object */, - sessionCache: {}, - // supported cipher suites in order of preference - cipherSuites: [ - forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, - forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], - virtualHost: 'example.com', - verify: function(connection, verified, depth, certs) { - if(depth === 0) { - var cn = certs[0].subject.getField('CN').value; - if(cn !== 'example.com') { - verified = { - alert: forge.tls.Alert.Description.bad_certificate, - message: 'Certificate common name does not match hostname.' - }; - } - } - return verified; - }, - connected: function(connection) { - console.log('connected'); - // send message to server - connection.prepare(forge.util.encodeUtf8('Hi server!')); - /* NOTE: experimental, start heartbeat retransmission timer - myHeartbeatTimer = setInterval(function() { - connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); - }, 5*60*1000);*/ - }, - /* provide a client-side cert if you want - getCertificate: function(connection, hint) { - return myClientCertificate; - }, - /* the private key for the client-side cert if provided */ - getPrivateKey: function(connection, cert) { - return myClientPrivateKey; - }, - tlsDataReady: function(connection) { - // TLS data (encrypted) is ready to be sent to the server - sendToServerSomehow(connection.tlsData.getBytes()); - // if you were communicating with the server below, you'd do: - // server.process(connection.tlsData.getBytes()); - }, - dataReady: function(connection) { - // clear data from the server is ready - console.log('the server sent: ' + - forge.util.decodeUtf8(connection.data.getBytes())); - // close connection - connection.close(); - }, - /* NOTE: experimental - heartbeatReceived: function(connection, payload) { - // restart retransmission timer, look at payload - clearInterval(myHeartbeatTimer); - myHeartbeatTimer = setInterval(function() { - connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); - }, 5*60*1000); - payload.getBytes(); - },*/ - closed: function(connection) { - console.log('disconnected'); - }, - error: function(connection, error) { - console.log('uh oh', error); - } -}); - -// start the handshake process -client.handshake(); - -// when encrypted TLS data is received from the server, process it -client.process(encryptedBytesFromServer); - -// create TLS server -var server = forge.tls.createConnection({ - server: true, - caStore: /* Array of PEM-formatted certs or a CA store object */, - sessionCache: {}, - // supported cipher suites in order of preference - cipherSuites: [ - forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, - forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], - // require a client-side certificate if you want - verifyClient: true, - verify: function(connection, verified, depth, certs) { - if(depth === 0) { - var cn = certs[0].subject.getField('CN').value; - if(cn !== 'the-client') { - verified = { - alert: forge.tls.Alert.Description.bad_certificate, - message: 'Certificate common name does not match expected client.' - }; - } - } - return verified; - }, - connected: function(connection) { - console.log('connected'); - // send message to client - connection.prepare(forge.util.encodeUtf8('Hi client!')); - /* NOTE: experimental, start heartbeat retransmission timer - myHeartbeatTimer = setInterval(function() { - connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); - }, 5*60*1000);*/ - }, - getCertificate: function(connection, hint) { - return myServerCertificate; - }, - getPrivateKey: function(connection, cert) { - return myServerPrivateKey; - }, - tlsDataReady: function(connection) { - // TLS data (encrypted) is ready to be sent to the client - sendToClientSomehow(connection.tlsData.getBytes()); - // if you were communicating with the client above you'd do: - // client.process(connection.tlsData.getBytes()); - }, - dataReady: function(connection) { - // clear data from the client is ready - console.log('the client sent: ' + - forge.util.decodeUtf8(connection.data.getBytes())); - // close connection - connection.close(); - }, - /* NOTE: experimental - heartbeatReceived: function(connection, payload) { - // restart retransmission timer, look at payload - clearInterval(myHeartbeatTimer); - myHeartbeatTimer = setInterval(function() { - connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); - }, 5*60*1000); - payload.getBytes(); - },*/ - closed: function(connection) { - console.log('disconnected'); - }, - error: function(connection, error) { - console.log('uh oh', error); - } -}); - -// when encrypted TLS data is received from the client, process it -server.process(encryptedBytesFromClient); -``` - -Connect to a TLS server using node's net.Socket: - -```js -var socket = new net.Socket(); - -var client = forge.tls.createConnection({ - server: false, - verify: function(connection, verified, depth, certs) { - // skip verification for testing - console.log('[tls] server certificate verified'); - return true; - }, - connected: function(connection) { - console.log('[tls] connected'); - // prepare some data to send (note that the string is interpreted as - // 'binary' encoded, which works for HTTP which only uses ASCII, use - // forge.util.encodeUtf8(str) otherwise - client.prepare('GET / HTTP/1.0\r\n\r\n'); - }, - tlsDataReady: function(connection) { - // encrypted data is ready to be sent to the server - var data = connection.tlsData.getBytes(); - socket.write(data, 'binary'); // encoding should be 'binary' - }, - dataReady: function(connection) { - // clear data from the server is ready - var data = connection.data.getBytes(); - console.log('[tls] data received from the server: ' + data); - }, - closed: function() { - console.log('[tls] disconnected'); - }, - error: function(connection, error) { - console.log('[tls] error', error); - } -}); - -socket.on('connect', function() { - console.log('[socket] connected'); - client.handshake(); -}); -socket.on('data', function(data) { - client.process(data.toString('binary')); // encoding should be 'binary' -}); -socket.on('end', function() { - console.log('[socket] disconnected'); -}); - -// connect to google.com -socket.connect(443, 'google.com'); - -// or connect to gmail's imap server (but don't send the HTTP header above) -//socket.connect(993, 'imap.gmail.com'); -``` - - -### HTTP - -Provides a native [JavaScript][] mini-implementation of an http client that -uses pooled sockets. - -__Examples__ - -```js -// create an HTTP GET request -var request = forge.http.createRequest({method: 'GET', path: url.path}); - -// send the request somewhere -sendSomehow(request.toString()); - -// receive response -var buffer = forge.util.createBuffer(); -var response = forge.http.createResponse(); -var someAsyncDataHandler = function(bytes) { - if(!response.bodyReceived) { - buffer.putBytes(bytes); - if(!response.headerReceived) { - if(response.readHeader(buffer)) { - console.log('HTTP response header: ' + response.toString()); - } - } - if(response.headerReceived && !response.bodyReceived) { - if(response.readBody(buffer)) { - console.log('HTTP response body: ' + response.body); - } - } - } -}; -``` - - -### SSH - -Provides some SSH utility functions. - -__Examples__ - -```js -// encodes (and optionally encrypts) a private RSA key as a Putty PPK file -forge.ssh.privateKeyToPutty(privateKey, passphrase, comment); - -// encodes a public RSA key as an OpenSSH file -forge.ssh.publicKeyToOpenSSH(key, comment); - -// encodes a private RSA key as an OpenSSH file -forge.ssh.privateKeyToOpenSSH(privateKey, passphrase); - -// gets the SSH public key fingerprint in a byte buffer -forge.ssh.getPublicKeyFingerprint(key); - -// gets a hex-encoded, colon-delimited SSH public key fingerprint -forge.ssh.getPublicKeyFingerprint(key, {encoding: 'hex', delimiter: ':'}); -``` - - -### XHR - -Provides an XmlHttpRequest implementation using forge.http as a backend. - -__Examples__ - -```js -``` - - -### Sockets - -Provides an interface to create and use raw sockets provided via Flash. - -__Examples__ - -```js -``` - ---------------------------------------- -## Ciphers - - -### CIPHER - -Provides a basic API for block encryption and decryption. There is built-in -support for the ciphers: [AES][], [3DES][], and [DES][], and for the modes -of operation: [ECB][], [CBC][], [CFB][], [OFB][], [CTR][], and [GCM][]. - -These algorithms are currently supported: - -* AES-ECB -* AES-CBC -* AES-CFB -* AES-OFB -* AES-CTR -* AES-GCM -* 3DES-ECB -* 3DES-CBC -* DES-ECB -* DES-CBC - -When using an [AES][] algorithm, the key size will determine whether -AES-128, AES-192, or AES-256 is used (all are supported). When a [DES][] -algorithm is used, the key size will determine whether [3DES][] or regular -[DES][] is used. Use a [3DES][] algorithm to enforce Triple-DES. - -__Examples__ - -```js -// generate a random key and IV -// Note: a key size of 16 bytes will use AES-128, 24 => AES-192, 32 => AES-256 -var key = forge.random.getBytesSync(16); -var iv = forge.random.getBytesSync(16); - -/* alternatively, generate a password-based 16-byte key -var salt = forge.random.getBytesSync(128); -var key = forge.pkcs5.pbkdf2('password', salt, numIterations, 16); -*/ - -// encrypt some bytes using CBC mode -// (other modes include: ECB, CFB, OFB, CTR, and GCM) -var cipher = forge.cipher.createCipher('AES-CBC', key); -cipher.start({iv: iv}); -cipher.update(forge.util.createBuffer(someBytes)); -cipher.finish(); -var encrypted = cipher.output; -// outputs encrypted hex -console.log(encrypted.toHex()); - -// decrypt some bytes using CBC mode -// (other modes include: CFB, OFB, CTR, and GCM) -var decipher = forge.cipher.createDecipher('AES-CBC', key); -decipher.start({iv: iv}); -decipher.update(encrypted); -decipher.finish(); -// outputs decrypted hex -console.log(decipher.output.toHex()); - -// encrypt some bytes using GCM mode -var cipher = forge.cipher.createCipher('AES-GCM', key); -cipher.start({ - iv: iv, // should be a 12-byte binary-encoded string or byte buffer - additionalData: 'binary-encoded string', // optional - tagLength: 128 // optional, defaults to 128 bits -}); -cipher.update(forge.util.createBuffer(someBytes)); -cipher.finish(); -var encrypted = cipher.output; -var tag = cipher.mode.tag; -// outputs encrypted hex -console.log(encrypted.toHex()); -// outputs authentication tag -console.log(tag.toHex()); - -// decrypt some bytes using GCM mode -var decipher = forge.cipher.createDecipher('AES-GCM', key); -decipher.start({ - iv: iv, - additionalData: 'binary-encoded string', // optional - tagLength: 128, // optional, defaults to 128 bits - tag: tag // authentication tag from encryption -}); -decipher.update(encrypted); -var pass = decipher.finish(); -// pass is false if there was a failure (eg: authentication tag didn't match) -if(pass) { - // outputs decrypted hex - console.log(decipher.output.toHex()); -} -``` - -Using forge in node.js to match openssl's "enc" command line tool (**Note**: OpenSSL "enc" uses a non-standard file format with a custom key derivation function and a fixed iteration count of 1, which some consider less secure than alternatives such as [OpenPGP](https://tools.ietf.org/html/rfc4880)/[GnuPG](https://www.gnupg.org/)): - -```js -var forge = require('node-forge'); -var fs = require('fs'); - -// openssl enc -des3 -in input.txt -out input.enc -function encrypt(password) { - var input = fs.readFileSync('input.txt', {encoding: 'binary'}); - - // 3DES key and IV sizes - var keySize = 24; - var ivSize = 8; - - // get derived bytes - // Notes: - // 1. If using an alternative hash (eg: "-md sha1") pass - // "forge.md.sha1.create()" as the final parameter. - // 2. If using "-nosalt", set salt to null. - var salt = forge.random.getBytesSync(8); - // var md = forge.md.sha1.create(); // "-md sha1" - var derivedBytes = forge.pbe.opensslDeriveBytes( - password, salt, keySize + ivSize/*, md*/); - var buffer = forge.util.createBuffer(derivedBytes); - var key = buffer.getBytes(keySize); - var iv = buffer.getBytes(ivSize); - - var cipher = forge.cipher.createCipher('3DES-CBC', key); - cipher.start({iv: iv}); - cipher.update(forge.util.createBuffer(input, 'binary')); - cipher.finish(); - - var output = forge.util.createBuffer(); - - // if using a salt, prepend this to the output: - if(salt !== null) { - output.putBytes('Salted__'); // (add to match openssl tool output) - output.putBytes(salt); - } - output.putBuffer(cipher.output); - - fs.writeFileSync('input.enc', output.getBytes(), {encoding: 'binary'}); -} - -// openssl enc -d -des3 -in input.enc -out input.dec.txt -function decrypt(password) { - var input = fs.readFileSync('input.enc', {encoding: 'binary'}); - - // parse salt from input - input = forge.util.createBuffer(input, 'binary'); - // skip "Salted__" (if known to be present) - input.getBytes('Salted__'.length); - // read 8-byte salt - var salt = input.getBytes(8); - - // Note: if using "-nosalt", skip above parsing and use - // var salt = null; - - // 3DES key and IV sizes - var keySize = 24; - var ivSize = 8; - - var derivedBytes = forge.pbe.opensslDeriveBytes( - password, salt, keySize + ivSize); - var buffer = forge.util.createBuffer(derivedBytes); - var key = buffer.getBytes(keySize); - var iv = buffer.getBytes(ivSize); - - var decipher = forge.cipher.createDecipher('3DES-CBC', key); - decipher.start({iv: iv}); - decipher.update(input); - var result = decipher.finish(); // check 'result' for true/false - - fs.writeFileSync( - 'input.dec.txt', decipher.output.getBytes(), {encoding: 'binary'}); -} -``` - - -### AES - -Provides [AES][] encryption and decryption in [CBC][], [CFB][], [OFB][], -[CTR][], and [GCM][] modes. See [CIPHER](#cipher) for examples. - - -### DES - -Provides [3DES][] and [DES][] encryption and decryption in [ECB][] and -[CBC][] modes. See [CIPHER](#cipher) for examples. - - -### RC2 - -__Examples__ - -```js -// generate a random key and IV -var key = forge.random.getBytesSync(16); -var iv = forge.random.getBytesSync(8); - -// encrypt some bytes -var cipher = forge.rc2.createEncryptionCipher(key); -cipher.start(iv); -cipher.update(forge.util.createBuffer(someBytes)); -cipher.finish(); -var encrypted = cipher.output; -// outputs encrypted hex -console.log(encrypted.toHex()); - -// decrypt some bytes -var cipher = forge.rc2.createDecryptionCipher(key); -cipher.start(iv); -cipher.update(encrypted); -cipher.finish(); -// outputs decrypted hex -console.log(cipher.output.toHex()); -``` ---------------------------------------- -## PKI - -Provides [X.509][] certificate and RSA public and private key encoding, -decoding, encryption/decryption, and signing/verifying. - - -### RSA - -__Examples__ - -```js -var rsa = forge.pki.rsa; - -// generate an RSA key pair synchronously -var keypair = rsa.generateKeyPair({bits: 2048, e: 0x10001}); - -// generate an RSA key pair asynchronously (uses web workers if available) -// use workers: -1 to run a fast core estimator to optimize # of workers -rsa.generateKeyPair({bits: 2048, workers: 2}, function(err, keypair) { - // keypair.privateKey, keypair.publicKey -}); - -// generate an RSA key pair in steps that attempt to run for a specified period -// of time on the main JS thread -var state = rsa.createKeyPairGenerationState(2048, 0x10001); -var step = function() { - // run for 100 ms - if(!rsa.stepKeyPairGenerationState(state, 100)) { - setTimeout(step, 1); - } - else { - // done, turn off progress indicator, use state.keys - } -}; -// turn on progress indicator, schedule generation to run -setTimeout(step); - -// sign data with a private key and output DigestInfo DER-encoded bytes -// (defaults to RSASSA PKCS#1 v1.5) -var md = forge.md.sha1.create(); -md.update('sign this', 'utf8'); -var signature = privateKey.sign(md); - -// verify data with a public key -// (defaults to RSASSA PKCS#1 v1.5) -var verified = publicKey.verify(md.digest().bytes(), signature); - -// sign data using RSASSA-PSS where PSS uses a SHA-1 hash, a SHA-1 based -// masking function MGF1, and a 20 byte salt -var md = forge.md.sha1.create(); -md.update('sign this', 'utf8'); -var pss = forge.pss.create({ - md: forge.md.sha1.create(), - mgf: forge.mgf.mgf1.create(forge.md.sha1.create()), - saltLength: 20 - // optionally pass 'prng' with a custom PRNG implementation - // optionalls pass 'salt' with a forge.util.ByteBuffer w/custom salt -}); -var signature = privateKey.sign(md, pss); - -// verify RSASSA-PSS signature -var pss = forge.pss.create({ - md: forge.md.sha1.create(), - mgf: forge.mgf.mgf1.create(forge.md.sha1.create()), - saltLength: 20 - // optionally pass 'prng' with a custom PRNG implementation -}); -var md = forge.md.sha1.create(); -md.update('sign this', 'utf8'); -publicKey.verify(md.digest().getBytes(), signature, pss); - -// encrypt data with a public key (defaults to RSAES PKCS#1 v1.5) -var encrypted = publicKey.encrypt(bytes); - -// decrypt data with a private key (defaults to RSAES PKCS#1 v1.5) -var decrypted = privateKey.decrypt(encrypted); - -// encrypt data with a public key using RSAES PKCS#1 v1.5 -var encrypted = publicKey.encrypt(bytes, 'RSAES-PKCS1-V1_5'); - -// decrypt data with a private key using RSAES PKCS#1 v1.5 -var decrypted = privateKey.decrypt(encrypted, 'RSAES-PKCS1-V1_5'); - -// encrypt data with a public key using RSAES-OAEP -var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP'); - -// decrypt data with a private key using RSAES-OAEP -var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP'); - -// encrypt data with a public key using RSAES-OAEP/SHA-256 -var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP', { - md: forge.md.sha256.create() -}); - -// decrypt data with a private key using RSAES-OAEP/SHA-256 -var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP', { - md: forge.md.sha256.create() -}); - -// encrypt data with a public key using RSAES-OAEP/SHA-256/MGF1-SHA-1 -// compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding -var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP', { - md: forge.md.sha256.create(), - mgf1: { - md: forge.md.sha1.create() - } -}); - -// decrypt data with a private key using RSAES-OAEP/SHA-256/MGF1-SHA-1 -// compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding -var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP', { - md: forge.md.sha256.create(), - mgf1: { - md: forge.md.sha1.create() - } -}); - -``` - - -### RSA-KEM - -__Examples__ - -```js -// generate an RSA key pair asynchronously (uses web workers if available) -// use workers: -1 to run a fast core estimator to optimize # of workers -forge.rsa.generateKeyPair({bits: 2048, workers: -1}, function(err, keypair) { - // keypair.privateKey, keypair.publicKey -}); - -// generate and encapsulate a 16-byte secret key -var kdf1 = new forge.kem.kdf1(forge.md.sha1.create()); -var kem = forge.kem.rsa.create(kdf1); -var result = kem.encrypt(keypair.publicKey, 16); -// result has 'encapsulation' and 'key' - -// encrypt some bytes -var iv = forge.random.getBytesSync(12); -var someBytes = 'hello world!'; -var cipher = forge.cipher.createCipher('AES-GCM', result.key); -cipher.start({iv: iv}); -cipher.update(forge.util.createBuffer(someBytes)); -cipher.finish(); -var encrypted = cipher.output.getBytes(); -var tag = cipher.mode.tag.getBytes(); - -// send 'encrypted', 'iv', 'tag', and result.encapsulation to recipient - -// decrypt encapsulated 16-byte secret key -var kdf1 = new forge.kem.kdf1(forge.md.sha1.create()); -var kem = forge.kem.rsa.create(kdf1); -var key = kem.decrypt(keypair.privateKey, result.encapsulation, 16); - -// decrypt some bytes -var decipher = forge.cipher.createDecipher('AES-GCM', key); -decipher.start({iv: iv, tag: tag}); -decipher.update(forge.util.createBuffer(encrypted)); -var pass = decipher.finish(); -// pass is false if there was a failure (eg: authentication tag didn't match) -if(pass) { - // outputs 'hello world!' - console.log(decipher.output.getBytes()); -} - -``` - - -### X.509 - -__Examples__ - -```js -var pki = forge.pki; - -// convert a PEM-formatted public key to a Forge public key -var publicKey = pki.publicKeyFromPem(pem); - -// convert a Forge public key to PEM-format -var pem = pki.publicKeyToPem(publicKey); - -// convert an ASN.1 SubjectPublicKeyInfo to a Forge public key -var publicKey = pki.publicKeyFromAsn1(subjectPublicKeyInfo); - -// convert a Forge public key to an ASN.1 SubjectPublicKeyInfo -var subjectPublicKeyInfo = pki.publicKeyToAsn1(publicKey); - -// gets a SHA-1 RSAPublicKey fingerprint a byte buffer -pki.getPublicKeyFingerprint(key); - -// gets a SHA-1 SubjectPublicKeyInfo fingerprint a byte buffer -pki.getPublicKeyFingerprint(key, {type: 'SubjectPublicKeyInfo'}); - -// gets a hex-encoded, colon-delimited SHA-1 RSAPublicKey public key fingerprint -pki.getPublicKeyFingerprint(key, {encoding: 'hex', delimiter: ':'}); - -// gets a hex-encoded, colon-delimited SHA-1 SubjectPublicKeyInfo public key fingerprint -pki.getPublicKeyFingerprint(key, { - type: 'SubjectPublicKeyInfo', - encoding: 'hex', - delimiter: ':' -}); - -// gets a hex-encoded, colon-delimited MD5 RSAPublicKey public key fingerprint -pki.getPublicKeyFingerprint(key, { - md: forge.md.md5.create(), - encoding: 'hex', - delimiter: ':' -}); - -// creates a CA store -var caStore = pki.createCaStore([/* PEM-encoded cert */, ...]); - -// add a certificate to the CA store -caStore.addCertificate(certObjectOrPemString); - -// gets the issuer (its certificate) for the given certificate -var issuerCert = caStore.getIssuer(subjectCert); - -// verifies a certificate chain against a CA store -pki.verifyCertificateChain(caStore, chain, customVerifyCallback); - -// signs a certificate using the given private key -cert.sign(privateKey); - -// signs a certificate using SHA-256 instead of SHA-1 -cert.sign(privateKey, forge.md.sha256.create()); - -// verifies an issued certificate using the certificates public key -var verified = issuer.verify(issued); - -// generate a keypair and create an X.509v3 certificate -var keys = pki.rsa.generateKeyPair(2048); -var cert = pki.createCertificate(); -cert.publicKey = keys.publicKey; -// alternatively set public key from a csr -//cert.publicKey = csr.publicKey; -cert.serialNumber = '01'; -cert.validity.notBefore = new Date(); -cert.validity.notAfter = new Date(); -cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1); -var attrs = [{ - name: 'commonName', - value: 'example.org' -}, { - name: 'countryName', - value: 'US' -}, { - shortName: 'ST', - value: 'Virginia' -}, { - name: 'localityName', - value: 'Blacksburg' -}, { - name: 'organizationName', - value: 'Test' -}, { - shortName: 'OU', - value: 'Test' -}]; -cert.setSubject(attrs); -// alternatively set subject from a csr -//cert.setSubject(csr.subject.attributes); -cert.setIssuer(attrs); -cert.setExtensions([{ - name: 'basicConstraints', - cA: true -}, { - name: 'keyUsage', - keyCertSign: true, - digitalSignature: true, - nonRepudiation: true, - keyEncipherment: true, - dataEncipherment: true -}, { - name: 'extKeyUsage', - serverAuth: true, - clientAuth: true, - codeSigning: true, - emailProtection: true, - timeStamping: true -}, { - name: 'nsCertType', - client: true, - server: true, - email: true, - objsign: true, - sslCA: true, - emailCA: true, - objCA: true -}, { - name: 'subjectAltName', - altNames: [{ - type: 6, // URI - value: 'http://example.org/webid#me' - }, { - type: 7, // IP - ip: '127.0.0.1' - }] -}, { - name: 'subjectKeyIdentifier' -}]); -/* alternatively set extensions from a csr -var extensions = csr.getAttribute({name: 'extensionRequest'}).extensions; -// optionally add more extensions -extensions.push.apply(extensions, [{ - name: 'basicConstraints', - cA: true -}, { - name: 'keyUsage', - keyCertSign: true, - digitalSignature: true, - nonRepudiation: true, - keyEncipherment: true, - dataEncipherment: true -}]); -cert.setExtensions(extensions); -*/ -// self-sign certificate -cert.sign(keys.privateKey); - -// convert a Forge certificate to PEM -var pem = pki.certificateToPem(cert); - -// convert a Forge certificate from PEM -var cert = pki.certificateFromPem(pem); - -// convert an ASN.1 X.509x3 object to a Forge certificate -var cert = pki.certificateFromAsn1(obj); - -// convert a Forge certificate to an ASN.1 X.509v3 object -var asn1Cert = pki.certificateToAsn1(cert); -``` - - -### PKCS#5 - -Provides the password-based key-derivation function from [PKCS#5][]. - -__Examples__ - -```js -// generate a password-based 16-byte key -// note an optional message digest can be passed as the final parameter -var salt = forge.random.getBytesSync(128); -var derivedKey = forge.pkcs5.pbkdf2('password', salt, numIterations, 16); - -// generate key asynchronously -// note an optional message digest can be passed before the callback -forge.pkcs5.pbkdf2('password', salt, numIterations, 16, function(err, derivedKey) { - // do something w/derivedKey -}); -``` - - -### PKCS#7 - -Provides cryptographically protected messages from [PKCS#7][]. - -__Examples__ - -```js -// convert a message from PEM -var p7 = forge.pkcs7.messageFromPem(pem); -// look at p7.recipients - -// find a recipient by the issuer of a certificate -var recipient = p7.findRecipient(cert); - -// decrypt -p7.decrypt(p7.recipients[0], privateKey); - -// create a p7 enveloped message -var p7 = forge.pkcs7.createEnvelopedData(); - -// add a recipient -var cert = forge.pki.certificateFromPem(certPem); -p7.addRecipient(cert); - -// set content -p7.content = forge.util.createBuffer('Hello'); - -// encrypt -p7.encrypt(); - -// convert message to PEM -var pem = forge.pkcs7.messageToPem(p7); - -// create a degenerate PKCS#7 certificate container -// (CRLs not currently supported, only certificates) -var p7 = forge.pkcs7.createSignedData(); -p7.addCertificate(certOrCertPem1); -p7.addCertificate(certOrCertPem2); -var pem = forge.pkcs7.messageToPem(p7); -``` - - -### PKCS#8 - -__Examples__ - -```js -var pki = forge.pki; - -// convert a PEM-formatted private key to a Forge private key -var privateKey = pki.privateKeyFromPem(pem); - -// convert a Forge private key to PEM-format -var pem = pki.privateKeyToPem(privateKey); - -// convert an ASN.1 PrivateKeyInfo or RSAPrivateKey to a Forge private key -var privateKey = pki.privateKeyFromAsn1(rsaPrivateKey); - -// convert a Forge private key to an ASN.1 RSAPrivateKey -var rsaPrivateKey = pki.privateKeyToAsn1(privateKey); - -// wrap an RSAPrivateKey ASN.1 object in a PKCS#8 ASN.1 PrivateKeyInfo -var privateKeyInfo = pki.wrapRsaPrivateKey(rsaPrivateKey); - -// convert a PKCS#8 ASN.1 PrivateKeyInfo to PEM -var pem = pki.privateKeyInfoToPem(privateKeyInfo); - -// encrypts a PrivateKeyInfo and outputs an EncryptedPrivateKeyInfo -var encryptedPrivateKeyInfo = pki.encryptPrivateKeyInfo( - privateKeyInfo, 'password', { - algorithm: 'aes256', // 'aes128', 'aes192', 'aes256', '3des' - }); - -// decrypts an ASN.1 EncryptedPrivateKeyInfo -var privateKeyInfo = pki.decryptPrivateKeyInfo( - encryptedPrivateKeyInfo, 'password'); - -// converts an EncryptedPrivateKeyInfo to PEM -var pem = pki.encryptedPrivateKeyToPem(encryptedPrivateKeyInfo); - -// converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format -var encryptedPrivateKeyInfo = pki.encryptedPrivateKeyFromPem(pem); - -// wraps and encrypts a Forge private key and outputs it in PEM format -var pem = pki.encryptRsaPrivateKey(privateKey, 'password'); - -// encrypts a Forge private key and outputs it in PEM format using OpenSSL's -// proprietary legacy format + encapsulated PEM headers (DEK-Info) -var pem = pki.encryptRsaPrivateKey(privateKey, 'password', {legacy: true}); - -// decrypts a PEM-formatted, encrypted private key -var privateKey = pki.decryptRsaPrivateKey(pem, 'password'); - -// sets an RSA public key from a private key -var publicKey = pki.setRsaPublicKey(privateKey.n, privateKey.e); -``` - - -### PKCS#10 - -Provides certification requests or certificate signing requests (CSR) from -[PKCS#10][]. - -__Examples__ - -```js -// generate a key pair -var keys = forge.pki.rsa.generateKeyPair(1024); - -// create a certification request (CSR) -var csr = forge.pki.createCertificationRequest(); -csr.publicKey = keys.publicKey; -csr.setSubject([{ - name: 'commonName', - value: 'example.org' -}, { - name: 'countryName', - value: 'US' -}, { - shortName: 'ST', - value: 'Virginia' -}, { - name: 'localityName', - value: 'Blacksburg' -}, { - name: 'organizationName', - value: 'Test' -}, { - shortName: 'OU', - value: 'Test' -}]); -// set (optional) attributes -csr.setAttributes([{ - name: 'challengePassword', - value: 'password' -}, { - name: 'unstructuredName', - value: 'My Company, Inc.' -}, { - name: 'extensionRequest', - extensions: [{ - name: 'subjectAltName', - altNames: [{ - // 2 is DNS type - type: 2, - value: 'test.domain.com' - }, { - type: 2, - value: 'other.domain.com', - }, { - type: 2, - value: 'www.domain.net' - }] - }] -}]); - -// sign certification request -csr.sign(keys.privateKey); - -// verify certification request -var verified = csr.verify(); - -// convert certification request to PEM-format -var pem = forge.pki.certificationRequestToPem(csr); - -// convert a Forge certification request from PEM-format -var csr = forge.pki.certificationRequestFromPem(pem); - -// get an attribute -csr.getAttribute({name: 'challengePassword'}); - -// get extensions array -csr.getAttribute({name: 'extensionRequest'}).extensions; - -``` - - -### PKCS#12 - -Provides the cryptographic archive file format from [PKCS#12][]. - -__Examples__ - -```js -// decode p12 from base64 -var p12Der = forge.util.decode64(p12b64); -// get p12 as ASN.1 object -var p12Asn1 = forge.asn1.fromDer(p12Der); -// decrypt p12 using the password 'password' -var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'password'); -// decrypt p12 using non-strict parsing mode (resolves some ASN.1 parse errors) -var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, false, 'password'); -// decrypt p12 using literally no password (eg: Mac OS X/apple push) -var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1); -// decrypt p12 using an "empty" password (eg: OpenSSL with no password input) -var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, ''); -// p12.safeContents is an array of safe contents, each of -// which contains an array of safeBags - -// get bags by friendlyName -var bags = p12.getBags({friendlyName: 'test'}); -// bags are key'd by attribute type (here "friendlyName") -// and the key values are an array of matching objects -var cert = bags.friendlyName[0]; - -// get bags by localKeyId -var bags = p12.getBags({localKeyId: buffer}); -// bags are key'd by attribute type (here "localKeyId") -// and the key values are an array of matching objects -var cert = bags.localKeyId[0]; - -// get bags by localKeyId (input in hex) -var bags = p12.getBags({localKeyIdHex: '7b59377ff142d0be4565e9ac3d396c01401cd879'}); -// bags are key'd by attribute type (here "localKeyId", *not* "localKeyIdHex") -// and the key values are an array of matching objects -var cert = bags.localKeyId[0]; - -// get bags by type -var bags = p12.getBags({bagType: forge.pki.oids.certBag}); -// bags are key'd by bagType and each bagType key's value -// is an array of matches (in this case, certificate objects) -var cert = bags[forge.pki.oids.certBag][0]; - -// get bags by friendlyName and filter on bag type -var bags = p12.getBags({ - friendlyName: 'test', - bagType: forge.pki.oids.certBag -}); - -// get key bags -var bags = p12.getBags({bagType: forge.pki.oids.keyBag}); -// get key -var bag = bags[forge.pki.oids.keyBag][0]; -var key = bag.key; -// if the key is in a format unrecognized by forge then -// bag.key will be `null`, use bag.asn1 to get the ASN.1 -// representation of the key -if(bag.key === null) { - var keyAsn1 = bag.asn1; - // can now convert back to DER/PEM/etc for export -} - -// generate a p12 using AES (default) -var p12Asn1 = forge.pkcs12.toPkcs12Asn1( - privateKey, certificateChain, 'password'); - -// generate a p12 that can be imported by Chrome/Firefox -// (requires the use of Triple DES instead of AES) -var p12Asn1 = forge.pkcs12.toPkcs12Asn1( - privateKey, certificateChain, 'password', - {algorithm: '3des'}); - -// base64-encode p12 -var p12Der = forge.asn1.toDer(p12Asn1).getBytes(); -var p12b64 = forge.util.encode64(p12Der); - -// create download link for p12 -var a = document.createElement('a'); -a.download = 'example.p12'; -a.setAttribute('href', 'data:application/x-pkcs12;base64,' + p12b64); -a.appendChild(document.createTextNode('Download')); -``` - - -### ASN.1 - -Provides [ASN.1][] DER encoding and decoding. - -__Examples__ - -```js -var asn1 = forge.asn1; - -// create a SubjectPublicKeyInfo -var subjectPublicKeyInfo = - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(pki.oids['rsaEncryption']).getBytes()), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]), - // subjectPublicKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ - // RSAPublicKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // modulus (n) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.n)), - // publicExponent (e) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - _bnToBytes(key.e)) - ]) - ]) - ]); - -// serialize an ASN.1 object to DER format -var derBuffer = asn1.toDer(subjectPublicKeyInfo); - -// deserialize to an ASN.1 object from a byte buffer filled with DER data -var object = asn1.fromDer(derBuffer); - -// convert an OID dot-separated string to a byte buffer -var derOidBuffer = asn1.oidToDer('1.2.840.113549.1.1.5'); - -// convert a byte buffer with a DER-encoded OID to a dot-separated string -console.log(asn1.derToDer(derOidBuffer)); -// output: 1.2.840.113549.1.1.5 - -// validates that an ASN.1 object matches a particular ASN.1 structure and -// captures data of interest from that structure for easy access -var publicKeyValidator = { - name: 'SubjectPublicKeyInfo', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'subjectPublicKeyInfo', - value: [{ - name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: 'publicKeyOid' - }] - }, { - // subjectPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'rsaPublicKey' - }] - }] -}; - -var capture = {}; -var errors = []; -if(!asn1.validate( - publicKeyValidator, subjectPublicKeyInfo, validator, capture, errors)) { - throw 'ASN.1 object is not a SubjectPublicKeyInfo.'; -} -// capture.subjectPublicKeyInfo contains the full ASN.1 object -// capture.rsaPublicKey contains the full ASN.1 object for the RSA public key -// capture.publicKeyOid only contains the value for the OID -var oid = asn1.derToOid(capture.publicKeyOid); -if(oid !== pki.oids['rsaEncryption']) { - throw 'Unsupported OID.'; -} - -// pretty print an ASN.1 object to a string for debugging purposes -asn1.prettyPrint(object); -``` - ---------------------------------------- -## Message Digests - - -### SHA1 - -Provides [SHA-1][] message digests. - -__Examples__ - -```js -var md = forge.md.sha1.create(); -md.update('The quick brown fox jumps over the lazy dog'); -console.log(md.digest().toHex()); -// output: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12 -``` - - -### SHA256 - -Provides [SHA-256][] message digests. - -__Examples__ - -```js -var md = forge.md.sha256.create(); -md.update('The quick brown fox jumps over the lazy dog'); -console.log(md.digest().toHex()); -// output: d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 -``` - - -### SHA384 - -Provides [SHA-384][] message digests. - -__Examples__ - -```js -var md = forge.md.sha384.create(); -md.update('The quick brown fox jumps over the lazy dog'); -console.log(md.digest().toHex()); -// output: ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1 -``` - - -### SHA512 - -Provides [SHA-512][] message digests. - -__Examples__ - -```js -// SHA-512 -var md = forge.md.sha512.create(); -md.update('The quick brown fox jumps over the lazy dog'); -console.log(md.digest().toHex()); -// output: 07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6 - -// SHA-512/224 -var md = forge.md.sha512.sha224.create(); -md.update('The quick brown fox jumps over the lazy dog'); -console.log(md.digest().toHex()); -// output: 944cd2847fb54558d4775db0485a50003111c8e5daa63fe722c6aa37 - -// SHA-512/256 -var md = forge.md.sha512.sha256.create(); -md.update('The quick brown fox jumps over the lazy dog'); -console.log(md.digest().toHex()); -// output: dd9d67b371519c339ed8dbd25af90e976a1eeefd4ad3d889005e532fc5bef04d -``` - - -### MD5 - -Provides [MD5][] message digests. - -__Examples__ - -```js -var md = forge.md.md5.create(); -md.update('The quick brown fox jumps over the lazy dog'); -console.log(md.digest().toHex()); -// output: 9e107d9d372bb6826bd81d3542a419d6 -``` - - -### HMAC - -Provides [HMAC][] w/any supported message digest algorithm. - -__Examples__ - -```js -var hmac = forge.hmac.create(); -hmac.start('sha1', 'Jefe'); -hmac.update('what do ya want for nothing?'); -console.log(hmac.digest().toHex()); -// output: effcdf6ae5eb2fa2d27416d5f184df9c259a7c79 -``` - ---------------------------------------- -## Utilities - - -### Prime - -Provides an API for generating large, random, probable primes. - -__Examples__ - -```js -// generate a random prime on the main JS thread -var bits = 1024; -forge.prime.generateProbablePrime(bits, function(err, num) { - console.log('random prime', num.toString(16)); -}); - -// generate a random prime using Web Workers (if available, otherwise -// falls back to the main thread) -var bits = 1024; -var options = { - algorithm: { - name: 'PRIMEINC', - workers: -1 // auto-optimize # of workers - } -}; -forge.prime.generateProbablePrime(bits, options, function(err, num) { - console.log('random prime', num.toString(16)); -}); -``` - - -### PRNG - -Provides a [Fortuna][]-based cryptographically-secure pseudo-random number -generator, to be used with a cryptographic function backend, e.g. [AES][]. An -implementation using [AES][] as a backend is provided. An API for collecting -entropy is given, though if window.crypto.getRandomValues is available, it will -be used automatically. - -__Examples__ - -```js -// get some random bytes synchronously -var bytes = forge.random.getBytesSync(32); -console.log(forge.util.bytesToHex(bytes)); - -// get some random bytes asynchronously -forge.random.getBytes(32, function(err, bytes) { - console.log(forge.util.bytesToHex(bytes)); -}); - -// collect some entropy if you'd like -forge.random.collect(someRandomBytes); -jQuery().mousemove(function(e) { - forge.random.collectInt(e.clientX, 16); - forge.random.collectInt(e.clientY, 16); -}); - -// specify a seed file for use with the synchronous API if you'd like -forge.random.seedFileSync = function(needed) { - // get 'needed' number of random bytes from somewhere - return fetchedRandomBytes; -}; - -// specify a seed file for use with the asynchronous API if you'd like -forge.random.seedFile = function(needed, callback) { - // get the 'needed' number of random bytes from somewhere - callback(null, fetchedRandomBytes); -}); - -// register the main thread to send entropy or a Web Worker to receive -// entropy on demand from the main thread -forge.random.registerWorker(self); - -// generate a new instance of a PRNG with no collected entropy -var myPrng = forge.random.createInstance(); -``` - - -### Tasks - -Provides queuing and synchronizing tasks in a web application. - -__Examples__ - -```js -``` - - -### Utilities - -Provides utility functions, including byte buffer support, base64, -bytes to/from hex, zlib inflate/deflate, etc. - -__Examples__ - -```js -// encode/decode base64 -var encoded = forge.util.encode64(str); -var str = forge.util.decode64(encoded); - -// encode/decode UTF-8 -var encoded = forge.util.encodeUtf8(str); -var str = forge.util.decodeUtf8(encoded); - -// bytes to/from hex -var bytes = forge.util.hexToBytes(hex); -var hex = forge.util.bytesToHex(bytes); - -// create an empty byte buffer -var buffer = forge.util.createBuffer(); -// create a byte buffer from raw binary bytes -var buffer = forge.util.createBuffer(input, 'raw'); -// create a byte buffer from utf8 bytes -var buffer = forge.util.createBuffer(input, 'utf8'); - -// get the length of the buffer in bytes -buffer.length(); -// put bytes into the buffer -buffer.putBytes(bytes); -// put a 32-bit integer into the buffer -buffer.putInt32(10); -// buffer to hex -buffer.toHex(); -// get a copy of the bytes in the buffer -bytes.bytes(/* count */); -// empty this buffer and get its contents -bytes.getBytes(/* count */); - -// convert a forge buffer into a node.js Buffer -// make sure you specify the encoding as 'binary' -var forgeBuffer = forge.util.createBuffer(); -var nodeBuffer = new Buffer(forgeBuffer.getBytes(), 'binary'); - -// convert a node.js Buffer into a forge buffer -// make sure you specify the encoding as 'binary' -var nodeBuffer = new Buffer(); -var forgeBuffer = forge.util.createBuffer(nodeBuffer.toString('binary')); - -// parse a URL -var parsed = forge.util.parseUrl('http://example.com/foo?bar=baz'); -// parsed.scheme, parsed.host, parsed.port, parsed.path, parsed.fullHost -``` - - -### Logging - -Provides logging to a javascript console using various categories and -levels of verbosity. - -__Examples__ - -```js -``` - - -### Debugging - -Provides storage of debugging information normally inaccessible in -closures for viewing/investigation. - -__Examples__ - -```js -``` - - -### Flash Socket Policy Module - -Provides an [Apache][] module "mod_fsp" that can serve up a Flash Socket -Policy. See `mod_fsp/README` for more details. This module makes it easy to -modify an [Apache][] server to allow cross domain requests to be made to it. - - -Library Details ---------------- - -* http://digitalbazaar.com/2010/07/20/javascript-tls-1/ -* http://digitalbazaar.com/2010/07/20/javascript-tls-2/ - -Contact -------- - -* Code: https://github.com/digitalbazaar/forge -* Bugs: https://github.com/digitalbazaar/forge/issues -* Email: support@digitalbazaar.com - -Donations welcome: - -* Donate: paypal@digitalbazaar.com - -[AES]: http://en.wikipedia.org/wiki/Advanced_Encryption_Standard -[ASN.1]: http://en.wikipedia.org/wiki/ASN.1 -[Apache]: http://httpd.apache.org/ -[CFB]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation -[CBC]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation -[CTR]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation -[3DES]: http://en.wikipedia.org/wiki/Triple_DES -[DES]: http://en.wikipedia.org/wiki/Data_Encryption_Standard -[ECB]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation -[Fortuna]: http://en.wikipedia.org/wiki/Fortuna_(PRNG) -[GCM]: http://en.wikipedia.org/wiki/GCM_mode -[HMAC]: http://en.wikipedia.org/wiki/HMAC -[JavaScript]: http://en.wikipedia.org/wiki/JavaScript -[MD5]: http://en.wikipedia.org/wiki/MD5 -[OFB]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation -[PKCS#5]: http://en.wikipedia.org/wiki/PKCS -[PKCS#7]: http://en.wikipedia.org/wiki/Cryptographic_Message_Syntax -[PKCS#10]: http://en.wikipedia.org/wiki/Certificate_signing_request -[PKCS#12]: http://en.wikipedia.org/wiki/PKCS_%E2%99%AF12 -[RC2]: http://en.wikipedia.org/wiki/RC2 -[SHA-1]: http://en.wikipedia.org/wiki/SHA-1 -[SHA-256]: http://en.wikipedia.org/wiki/SHA-256 -[SHA-384]: http://en.wikipedia.org/wiki/SHA-384 -[SHA-512]: http://en.wikipedia.org/wiki/SHA-512 -[TLS]: http://en.wikipedia.org/wiki/Transport_Layer_Security -[X.509]: http://en.wikipedia.org/wiki/X.509 -[node.js]: http://nodejs.org/ diff --git a/alarm/node_modules/node-forge/bower.json b/alarm/node_modules/node-forge/bower.json deleted file mode 100644 index 10e6210..0000000 --- a/alarm/node_modules/node-forge/bower.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "forge", - "version": "0.6.33", - "description": "JavaScript implementations of network transports, cryptography, ciphers, PKI, message digests, and various utilities.", - "moduleType": ["amd"], - "authors": [ - "Digital Bazaar, Inc." - ], - "license": "BSD", - "main": ["js/forge.js"], - "dependencies": {}, - "ignore": [ - "node_modules", - "bower_components" - ] -} diff --git a/alarm/node_modules/node-forge/build-flash.xml b/alarm/node_modules/node-forge/build-flash.xml deleted file mode 100644 index 8d8829c..0000000 --- a/alarm/node_modules/node-forge/build-flash.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - flash - - - diff --git a/alarm/node_modules/node-forge/build-setup b/alarm/node_modules/node-forge/build-setup deleted file mode 100755 index 5c3866e..0000000 --- a/alarm/node_modules/node-forge/build-setup +++ /dev/null @@ -1,46 +0,0 @@ -#!/bin/sh -# -# This shell script sets up the software to be built using 'make'. In -# order to perform a build from a fresh source tree, do the following: -# -# 1. ./build-setup -# 2. make -# -# If you don't want ./configure to be run automatically, you can do -# the following: ./build-setup -s - -# Process command line options -SKIP_CONFIGURE=0 -for arg in "$*" -do - case $arg in - "-s" | "--setup-only" ) SKIP_CONFIGURE=1 ;; - esac -done - -# Check and add potential aclocal dirs -MAYBE_AC_DIRS=" - /usr/local/share/aclocal - /opt/local/share/aclocal - /sw/share/aclocal - " -ACDIRS="-I m4" -for dir in $MAYBE_AC_DIRS; do - if test -d $dir; then - ACDIRS="$ACDIRS -I $dir" - fi -done - -# Run aclocal on the set of local ac scripts -cd setup -aclocal $ACDIRS -# Generate the configure script -autoconf && mv configure .. -cd .. - -# Run the configure script if "-s" isn't a command line option -if [ $SKIP_CONFIGURE -eq 0 ]; then - # Run the configure script in default development mode - ./configure $* -fi - diff --git a/alarm/node_modules/node-forge/end.frag b/alarm/node_modules/node-forge/end.frag deleted file mode 100644 index cbcf226..0000000 --- a/alarm/node_modules/node-forge/end.frag +++ /dev/null @@ -1,4 +0,0 @@ - -return require('js/forge'); - -}); diff --git a/alarm/node_modules/node-forge/flash/PooledSocket.as b/alarm/node_modules/node-forge/flash/PooledSocket.as deleted file mode 100644 index 15e3ae4..0000000 --- a/alarm/node_modules/node-forge/flash/PooledSocket.as +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved. - * - * @author Dave Longley - */ -package -{ - import flash.net.Socket; - - /** - * A helper class that contains the ID for a Socket. - */ - public class PooledSocket extends Socket - { - // the ID in the related socket pool - public var id:String; - } -} diff --git a/alarm/node_modules/node-forge/flash/SocketEvent.as b/alarm/node_modules/node-forge/flash/SocketEvent.as deleted file mode 100644 index 56f5e7f..0000000 --- a/alarm/node_modules/node-forge/flash/SocketEvent.as +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved. - * - * @author Dave Longley - */ -package -{ - import flash.events.Event; - - /** - * A helper class that contains the ID for a Socket. - */ - public class SocketEvent extends Event - { - // the associated socket - public var socket:PooledSocket; - // an associated message - public var message:String; - - /** - * Creates a new SocketEvent. - * - * @param type the type of event. - * @param socket the associated PooledSocket. - * @param message an associated message. - */ - public function SocketEvent( - type:String, socket:PooledSocket, message:String = null) - { - super(type, false, false); - this.socket = socket; - this.message = message; - } - } -} - diff --git a/alarm/node_modules/node-forge/flash/SocketPool.as b/alarm/node_modules/node-forge/flash/SocketPool.as deleted file mode 100644 index d99b3ec..0000000 --- a/alarm/node_modules/node-forge/flash/SocketPool.as +++ /dev/null @@ -1,754 +0,0 @@ -/* - * Copyright (c) 2009-2010 Digital Bazaar, Inc. All rights reserved. - * - * @author Dave Longley - */ -package -{ - import flash.display.Sprite; - - /** - * A SocketPool is a flash object that can be embedded in a web page to - * allow javascript access to pools of Sockets. - * - * Javascript can create a pool and then as many Sockets as it desires. Each - * Socket will be assigned a unique ID that allows continued javascript - * access to it. There is no limit on the number of persistent socket - * connections. - */ - public class SocketPool extends Sprite - { - import flash.events.Event; - import flash.events.EventDispatcher; - import flash.errors.IOError; - import flash.events.IOErrorEvent; - import flash.events.ProgressEvent; - import flash.events.SecurityErrorEvent; - import flash.events.TextEvent; - import flash.external.ExternalInterface; - import flash.net.SharedObject; - import flash.system.Security; - import flash.utils.ByteArray; - import mx.utils.Base64Decoder; - import mx.utils.Base64Encoder; - - // a map of ID to Socket - private var mSocketMap:Object; - - // a counter for Socket IDs (Note: assumes there will be no overflow) - private var mNextId:uint; - - // an event dispatcher for sending events to javascript - private var mEventDispatcher:EventDispatcher; - - /** - * Creates a new, unitialized SocketPool. - * - * @throws Error - if no external interface is available to provide - * javascript access. - */ - public function SocketPool() - { - if(!ExternalInterface.available) - { - trace("ExternalInterface is not available"); - throw new Error( - "Flash's ExternalInterface is not available. This is a " + - "requirement of SocketPool and therefore, it will be " + - "unavailable."); - } - else - { - try - { - // set up javascript access: - - // initializes/cleans up the SocketPool - ExternalInterface.addCallback("init", init); - ExternalInterface.addCallback("cleanup", cleanup); - - // creates/destroys a socket - ExternalInterface.addCallback("create", create); - ExternalInterface.addCallback("destroy", destroy); - - // connects/closes a socket - ExternalInterface.addCallback("connect", connect); - ExternalInterface.addCallback("close", close); - - // checks for a connection - ExternalInterface.addCallback("isConnected", isConnected); - - // sends/receives data over the socket - ExternalInterface.addCallback("send", send); - ExternalInterface.addCallback("receive", receive); - - // gets the number of bytes available on a socket - ExternalInterface.addCallback( - "getBytesAvailable", getBytesAvailable); - - // add a callback for subscribing to socket events - ExternalInterface.addCallback("subscribe", subscribe); - - // add callbacks for deflate/inflate - ExternalInterface.addCallback("deflate", deflate); - ExternalInterface.addCallback("inflate", inflate); - - // add callbacks for local disk storage - ExternalInterface.addCallback("setItem", setItem); - ExternalInterface.addCallback("getItem", getItem); - ExternalInterface.addCallback("removeItem", removeItem); - ExternalInterface.addCallback("clearItems", clearItems); - - // socket pool is now ready - ExternalInterface.call("window.forge.socketPool.ready"); - } - catch(e:Error) - { - log("error=" + e.errorID + "," + e.name + "," + e.message); - throw e; - } - - log("ready"); - } - } - - /** - * A debug logging function. - * - * @param obj the string or error to log. - */ - CONFIG::debugging - private function log(obj:Object):void - { - if(obj is String) - { - var str:String = obj as String; - ExternalInterface.call("console.log", "SocketPool", str); - } - else if(obj is Error) - { - var e:Error = obj as Error; - log("error=" + e.errorID + "," + e.name + "," + e.message); - } - } - - CONFIG::release - private function log(obj:Object):void - { - // log nothing in release mode - } - - /** - * Called by javascript to initialize this SocketPool. - * - * @param options: - * marshallExceptions: true to pass exceptions to and from - * javascript. - */ - private function init(... args):void - { - log("init()"); - - // get options from first argument - var options:Object = args.length > 0 ? args[0] : null; - - // create socket map, set next ID, and create event dispatcher - mSocketMap = new Object(); - mNextId = 1; - mEventDispatcher = new EventDispatcher(); - - // enable marshalling exceptions if appropriate - if(options != null && - "marshallExceptions" in options && - options.marshallExceptions === true) - { - try - { - // Note: setting marshallExceptions in IE, even inside of a - // try-catch block will terminate flash. Don't set this on IE. - ExternalInterface.marshallExceptions = true; - } - catch(e:Error) - { - log(e); - } - } - - log("init() done"); - } - - /** - * Called by javascript to clean up a SocketPool. - */ - private function cleanup():void - { - log("cleanup()"); - - mSocketMap = null; - mNextId = 1; - mEventDispatcher = null; - - log("cleanup() done"); - } - - /** - * Handles events. - * - * @param e the event to handle. - */ - private function handleEvent(e:Event):void - { - // dispatch socket event - var message:String = (e is TextEvent) ? (e as TextEvent).text : null; - mEventDispatcher.dispatchEvent( - new SocketEvent(e.type, e.target as PooledSocket, message)); - } - - /** - * Called by javascript to create a Socket. - * - * @return the Socket ID. - */ - private function create():String - { - log("create()"); - - // create a Socket - var id:String = "" + mNextId++; - var s:PooledSocket = new PooledSocket(); - s.id = id; - s.addEventListener(Event.CONNECT, handleEvent); - s.addEventListener(Event.CLOSE, handleEvent); - s.addEventListener(ProgressEvent.SOCKET_DATA, handleEvent); - s.addEventListener(IOErrorEvent.IO_ERROR, handleEvent); - s.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleEvent); - mSocketMap[id] = s; - - log("socket " + id + " created"); - log("create() done"); - - return id; - } - - /** - * Called by javascript to clean up a Socket. - * - * @param id the ID of the Socket to clean up. - */ - private function destroy(id:String):void - { - log("destroy(" + id + ")"); - - if(id in mSocketMap) - { - // remove Socket - delete mSocketMap[id]; - log("socket " + id + " destroyed"); - } - - log("destroy(" + id + ") done"); - } - - /** - * Connects the Socket with the given ID to the given host and port, - * using the given socket policy port. - * - * @param id the ID of the Socket. - * @param host the host to connect to. - * @param port the port to connect to. - * @param spPort the security policy port to use, 0 to use a url. - * @param spUrl the http URL to the policy file to use, null for default. - */ - private function connect( - id:String, host:String, port:uint, spPort:uint, - spUrl:String = null):void - { - log("connect(" + - id + "," + host + "," + port + "," + spPort + "," + spUrl + ")"); - - if(id in mSocketMap) - { - // get the Socket - var s:PooledSocket = mSocketMap[id]; - - // load socket policy file - // (permits socket access to backend) - if(spPort !== 0) - { - spUrl = "xmlsocket://" + host + ":" + spPort; - log("using cross-domain url: " + spUrl); - Security.loadPolicyFile(spUrl); - } - else if(spUrl !== null && typeof(spUrl) !== undefined) - { - log("using cross-domain url: " + spUrl); - Security.loadPolicyFile(spUrl); - } - else - { - log("not loading any cross-domain url"); - } - - // connect - s.connect(host, port); - } - else - { - // no such socket - log("socket " + id + " does not exist"); - } - - log("connect(" + id + ") done"); - } - - /** - * Closes the Socket with the given ID. - * - * @param id the ID of the Socket. - */ - private function close(id:String):void - { - log("close(" + id + ")"); - - if(id in mSocketMap) - { - // close the Socket - var s:PooledSocket = mSocketMap[id]; - if(s.connected) - { - s.close(); - } - } - else - { - // no such socket - log("socket " + id + " does not exist"); - } - - log("close(" + id + ") done"); - } - - /** - * Determines if the Socket with the given ID is connected or not. - * - * @param id the ID of the Socket. - * - * @return true if the socket is connected, false if not. - */ - private function isConnected(id:String):Boolean - { - var rval:Boolean = false; - log("isConnected(" + id + ")"); - - if(id in mSocketMap) - { - // check the Socket - var s:PooledSocket = mSocketMap[id]; - rval = s.connected; - } - else - { - // no such socket - log("socket " + id + " does not exist"); - } - - log("isConnected(" + id + ") done"); - return rval; - } - - /** - * Writes bytes to a Socket. - * - * @param id the ID of the Socket. - * @param bytes the string of base64-encoded bytes to write. - * - * @return true on success, false on failure. - */ - private function send(id:String, bytes:String):Boolean - { - var rval:Boolean = false; - log("send(" + id + ")"); - - if(id in mSocketMap) - { - // write bytes to socket - var s:PooledSocket = mSocketMap[id]; - try - { - var b64:Base64Decoder = new Base64Decoder(); - b64.decode(bytes); - var b:ByteArray = b64.toByteArray(); - s.writeBytes(b, 0, b.length); - s.flush(); - rval = true; - } - catch(e:IOError) - { - log(e); - - // dispatch IO error event - mEventDispatcher.dispatchEvent(new SocketEvent( - IOErrorEvent.IO_ERROR, s, e.message)); - if(s.connected) - { - s.close(); - } - } - } - else - { - // no such socket - log("socket " + id + " does not exist"); - } - - log("send(" + id + ") done"); - return rval; - } - - /** - * Receives bytes from a Socket. - * - * @param id the ID of the Socket. - * @param count the maximum number of bytes to receive. - * - * @return an object with 'rval' set to the received bytes, - * base64-encoded, or set to null on error. - */ - private function receive(id:String, count:uint):Object - { - var rval:String = null; - log("receive(" + id + "," + count + ")"); - - if(id in mSocketMap) - { - // only read what is available - var s:PooledSocket = mSocketMap[id]; - if(count > s.bytesAvailable) - { - count = s.bytesAvailable; - } - - try - { - // read bytes from socket - var b:ByteArray = new ByteArray(); - s.readBytes(b, 0, count); - b.position = 0; - var b64:Base64Encoder = new Base64Encoder(); - b64.insertNewLines = false; - b64.encodeBytes(b, 0, b.length); - rval = b64.toString(); - } - catch(e:IOError) - { - log(e); - - // dispatch IO error event - mEventDispatcher.dispatchEvent(new SocketEvent( - IOErrorEvent.IO_ERROR, s, e.message)); - if(s.connected) - { - s.close(); - } - } - } - else - { - // no such socket - log("socket " + id + " does not exist"); - } - - log("receive(" + id + "," + count + ") done"); - return {rval: rval}; - } - - /** - * Gets the number of bytes available from a Socket. - * - * @param id the ID of the Socket. - * - * @return the number of available bytes. - */ - private function getBytesAvailable(id:String):uint - { - var rval:uint = 0; - log("getBytesAvailable(" + id + ")"); - - if(id in mSocketMap) - { - var s:PooledSocket = mSocketMap[id]; - rval = s.bytesAvailable; - } - else - { - // no such socket - log("socket " + id + " does not exist"); - } - - log("getBytesAvailable(" + id +") done"); - return rval; - } - - /** - * Registers a javascript function as a callback for an event. - * - * @param eventType the type of event (socket event types). - * @param callback the name of the callback function. - */ - private function subscribe(eventType:String, callback:String):void - { - log("subscribe(" + eventType + "," + callback + ")"); - - switch(eventType) - { - case Event.CONNECT: - case Event.CLOSE: - case IOErrorEvent.IO_ERROR: - case SecurityErrorEvent.SECURITY_ERROR: - case ProgressEvent.SOCKET_DATA: - { - log(eventType + " => " + callback); - mEventDispatcher.addEventListener( - eventType, function(event:SocketEvent):void - { - log("event dispatched: " + eventType); - - // build event for javascript - var e:Object = new Object(); - e.id = event.socket ? event.socket.id : 0; - e.type = eventType; - if(event.socket && event.socket.connected) - { - e.bytesAvailable = event.socket.bytesAvailable; - } - else - { - e.bytesAvailable = 0; - } - if(event.message) - { - e.message = event.message; - } - - // send event to javascript - ExternalInterface.call(callback, e); - }); - break; - } - default: - throw new ArgumentError( - "Could not subscribe to event. " + - "Invalid event type specified: " + eventType); - } - - log("subscribe(" + eventType + "," + callback + ") done"); - } - - /** - * Deflates the given data. - * - * @param data the base64-encoded data to deflate. - * - * @return an object with 'rval' set to deflated data, base64-encoded. - */ - private function deflate(data:String):Object - { - log("deflate"); - - var b64d:Base64Decoder = new Base64Decoder(); - b64d.decode(data); - var b:ByteArray = b64d.toByteArray(); - b.compress(); - b.position = 0; - var b64e:Base64Encoder = new Base64Encoder(); - b64e.insertNewLines = false; - b64e.encodeBytes(b, 0, b.length); - - log("deflate done"); - return {rval: b64e.toString()}; - } - - /** - * Inflates the given data. - * - * @param data the base64-encoded data to inflate. - * - * @return an object with 'rval' set to the inflated data, - * base64-encoded, null on error. - */ - private function inflate(data:String):Object - { - log("inflate"); - var rval:Object = {rval: null}; - - try - { - var b64d:Base64Decoder = new Base64Decoder(); - b64d.decode(data); - var b:ByteArray = b64d.toByteArray(); - b.uncompress(); - b.position = 0; - var b64e:Base64Encoder = new Base64Encoder(); - b64e.insertNewLines = false; - b64e.encodeBytes(b, 0, b.length); - rval.rval = b64e.toString(); - } - catch(e:Error) - { - log(e); - rval.error = { - id: e.errorID, - name: e.name, - message: e.message - }; - } - - log("inflate done"); - return rval; - } - - /** - * Stores an item with a key and arbitrary base64-encoded data on local - * disk. - * - * @param key the key for the item. - * @param data the base64-encoded item data. - * @param storeId the storage ID to use, defaults to "forge.storage". - * - * @return an object with rval set to true on success, false on failure - * with error included. - */ - private function setItem( - key:String, data:String, storeId:String = "forge.storage"):Object - { - var rval:Object = {rval: false}; - try - { - var store:SharedObject = SharedObject.getLocal(storeId); - if(!('keys' in store.data)) - { - store.data.keys = {}; - } - store.data.keys[key] = data; - store.flush(); - rval.rval = true; - } - catch(e:Error) - { - log(e); - rval.error = { - id: e.errorID, - name: e.name, - message: e.message - }; - } - return rval; - } - - /** - * Gets an item from the local disk. - * - * @param key the key for the item. - * @param storeId the storage ID to use, defaults to "forge.storage". - * - * @return an object with rval set to the item data (which may be null), - * check for error object if null. - */ - private function getItem( - key:String, storeId:String = "forge.storage"):Object - { - var rval:Object = {rval: null}; - try - { - var store:SharedObject = SharedObject.getLocal(storeId); - if('keys' in store.data && key in store.data.keys) - { - rval.rval = store.data.keys[key]; - } - } - catch(e:Error) - { - log(e); - rval.error = { - id: e.errorID, - name: e.name, - message: e.message - }; - } - return rval; - } - - /** - * Removes an item from the local disk. - * - * @param key the key for the item. - * @param storeId the storage ID to use, defaults to "forge.storage". - * - * @return an object with rval set to true if removed, false if not. - */ - private function removeItem( - key:String, storeId:String = "forge.storage"):Object - { - var rval:Object = {rval: false}; - try - { - var store:SharedObject = SharedObject.getLocal(storeId); - if('keys' in store.data && key in store.data.keys) - { - delete store.data.keys[key]; - - // clean up storage entirely if empty - var empty:Boolean = true; - for(var prop:String in store.data.keys) - { - empty = false; - break; - } - if(empty) - { - store.clear(); - } - rval.rval = true; - } - } - catch(e:Error) - { - log(e); - rval.error = { - id: e.errorID, - name: e.name, - message: e.message - }; - } - return rval; - } - - /** - * Clears an entire store of all of its items. - * - * @param storeId the storage ID to use, defaults to "forge.storage". - * - * @return an object with rval set to true if cleared, false if not. - */ - private function clearItems(storeId:String = "forge.storage"):Object - { - var rval:Object = {rval: false}; - try - { - var store:SharedObject = SharedObject.getLocal(storeId); - store.clear(); - rval.rval = true; - } - catch(e:Error) - { - log(e); - rval.error = { - id: e.errorID, - name: e.name, - message: e.message - }; - } - return rval; - } - } -} diff --git a/alarm/node_modules/node-forge/js/aes.js b/alarm/node_modules/node-forge/js/aes.js deleted file mode 100644 index d16fc34..0000000 --- a/alarm/node_modules/node-forge/js/aes.js +++ /dev/null @@ -1,1147 +0,0 @@ -/** - * Advanced Encryption Standard (AES) implementation. - * - * This implementation is based on the public domain library 'jscrypto' which - * was written by: - * - * Emily Stark (estark@stanford.edu) - * Mike Hamburg (mhamburg@stanford.edu) - * Dan Boneh (dabo@cs.stanford.edu) - * - * Parts of this code are based on the OpenSSL implementation of AES: - * http://www.openssl.org - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ -(function() { -/* ########## Begin module implementation ########## */ -function initModule(forge) { - -/* AES API */ -forge.aes = forge.aes || {}; - -/** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('AES-', key); - * cipher.start({iv: iv}); - * - * Creates an AES cipher object to encrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as a string of bytes, an array of bytes, - * a byte buffer, or an array of 32-bit words. - * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge.aes.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key: key, - output: output, - decrypt: false, - mode: mode - }); - cipher.start(iv); - return cipher; -}; - -/** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('AES-', key); - * - * Creates an AES cipher object to encrypt data using the given symmetric key. - * - * The key may be given as a string of bytes, an array of bytes, a - * byte buffer, or an array of 32-bit words. - * - * @param key the symmetric key to use. - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge.aes.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key: key, - output: null, - decrypt: false, - mode: mode - }); -}; - -/** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('AES-', key); - * decipher.start({iv: iv}); - * - * Creates an AES cipher object to decrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as a string of bytes, an array of bytes, - * a byte buffer, or an array of 32-bit words. - * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge.aes.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key: key, - output: output, - decrypt: true, - mode: mode - }); - cipher.start(iv); - return cipher; -}; - -/** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('AES-', key); - * - * Creates an AES cipher object to decrypt data using the given symmetric key. - * - * The key may be given as a string of bytes, an array of bytes, a - * byte buffer, or an array of 32-bit words. - * - * @param key the symmetric key to use. - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge.aes.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key: key, - output: null, - decrypt: true, - mode: mode - }); -}; - -/** - * Creates a new AES cipher algorithm object. - * - * @param name the name of the algorithm. - * @param mode the mode factory function. - * - * @return the AES algorithm object. - */ -forge.aes.Algorithm = function(name, mode) { - if(!init) { - initialize(); - } - var self = this; - self.name = name; - self.mode = new mode({ - blockSize: 16, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self._w, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self._w, inBlock, outBlock, true); - } - } - }); - self._init = false; -}; - -/** - * Initializes this AES algorithm by expanding its key. - * - * @param options the options to use. - * key the key to use with this algorithm. - * decrypt true if the algorithm should be initialized for decryption, - * false for encryption. - */ -forge.aes.Algorithm.prototype.initialize = function(options) { - if(this._init) { - return; - } - - var key = options.key; - var tmp; - - /* Note: The key may be a string of bytes, an array of bytes, a byte - buffer, or an array of 32-bit integers. If the key is in bytes, then - it must be 16, 24, or 32 bytes in length. If it is in 32-bit - integers, it must be 4, 6, or 8 integers long. */ - - if(typeof key === 'string' && - (key.length === 16 || key.length === 24 || key.length === 32)) { - // convert key string into byte buffer - key = forge.util.createBuffer(key); - } else if(forge.util.isArray(key) && - (key.length === 16 || key.length === 24 || key.length === 32)) { - // convert key integer array into byte buffer - tmp = key; - key = forge.util.createBuffer(); - for(var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - - // convert key byte buffer into 32-bit integer array - if(!forge.util.isArray(key)) { - tmp = key; - key = []; - - // key lengths of 16, 24, 32 bytes allowed - var len = tmp.length(); - if(len === 16 || len === 24 || len === 32) { - len = len >>> 2; - for(var i = 0; i < len; ++i) { - key.push(tmp.getInt32()); - } - } - } - - // key must be an array of 32-bit integers by now - if(!forge.util.isArray(key) || - !(key.length === 4 || key.length === 6 || key.length === 8)) { - throw new Error('Invalid key parameter.'); - } - - // encryption operation is always used for these modes - var mode = this.mode.name; - var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1); - - // do key expansion - this._w = _expandKey(key, options.decrypt && !encryptOp); - this._init = true; -}; - -/** - * Expands a key. Typically only used for testing. - * - * @param key the symmetric key to expand, as an array of 32-bit words. - * @param decrypt true to expand for decryption, false for encryption. - * - * @return the expanded key. - */ -forge.aes._expandKey = function(key, decrypt) { - if(!init) { - initialize(); - } - return _expandKey(key, decrypt); -}; - -/** - * Updates a single block. Typically only used for testing. - * - * @param w the expanded key to use. - * @param input an array of block-size 32-bit words. - * @param output an array of block-size 32-bit words. - * @param decrypt true to decrypt, false to encrypt. - */ -forge.aes._updateBlock = _updateBlock; - - -/** Register AES algorithms **/ - -registerAlgorithm('AES-ECB', forge.cipher.modes.ecb); -registerAlgorithm('AES-CBC', forge.cipher.modes.cbc); -registerAlgorithm('AES-CFB', forge.cipher.modes.cfb); -registerAlgorithm('AES-OFB', forge.cipher.modes.ofb); -registerAlgorithm('AES-CTR', forge.cipher.modes.ctr); -registerAlgorithm('AES-GCM', forge.cipher.modes.gcm); - -function registerAlgorithm(name, mode) { - var factory = function() { - return new forge.aes.Algorithm(name, mode); - }; - forge.cipher.registerAlgorithm(name, factory); -} - - -/** AES implementation **/ - -var init = false; // not yet initialized -var Nb = 4; // number of words comprising the state (AES = 4) -var sbox; // non-linear substitution table used in key expansion -var isbox; // inversion of sbox -var rcon; // round constant word array -var mix; // mix-columns table -var imix; // inverse mix-columns table - -/** - * Performs initialization, ie: precomputes tables to optimize for speed. - * - * One way to understand how AES works is to imagine that 'addition' and - * 'multiplication' are interfaces that require certain mathematical - * properties to hold true (ie: they are associative) but they might have - * different implementations and produce different kinds of results ... - * provided that their mathematical properties remain true. AES defines - * its own methods of addition and multiplication but keeps some important - * properties the same, ie: associativity and distributivity. The - * explanation below tries to shed some light on how AES defines addition - * and multiplication of bytes and 32-bit words in order to perform its - * encryption and decryption algorithms. - * - * The basics: - * - * The AES algorithm views bytes as binary representations of polynomials - * that have either 1 or 0 as the coefficients. It defines the addition - * or subtraction of two bytes as the XOR operation. It also defines the - * multiplication of two bytes as a finite field referred to as GF(2^8) - * (Note: 'GF' means "Galois Field" which is a field that contains a finite - * number of elements so GF(2^8) has 256 elements). - * - * This means that any two bytes can be represented as binary polynomials; - * when they multiplied together and modularly reduced by an irreducible - * polynomial of the 8th degree, the results are the field GF(2^8). The - * specific irreducible polynomial that AES uses in hexadecimal is 0x11b. - * This multiplication is associative with 0x01 as the identity: - * - * (b * 0x01 = GF(b, 0x01) = b). - * - * The operation GF(b, 0x02) can be performed at the byte level by left - * shifting b once and then XOR'ing it (to perform the modular reduction) - * with 0x11b if b is >= 128. Repeated application of the multiplication - * of 0x02 can be used to implement the multiplication of any two bytes. - * - * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can - * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these - * factors can each be multiplied by 0x57 and then added together. To do - * the multiplication, values for 0x57 multiplied by each of these 3 factors - * can be precomputed and stored in a table. To add them, the values from - * the table are XOR'd together. - * - * AES also defines addition and multiplication of words, that is 4-byte - * numbers represented as polynomials of 3 degrees where the coefficients - * are the values of the bytes. - * - * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0. - * - * Addition is performed by XOR'ing like powers of x. Multiplication - * is performed in two steps, the first is an algebriac expansion as - * you would do normally (where addition is XOR). But the result is - * a polynomial larger than 3 degrees and thus it cannot fit in a word. So - * next the result is modularly reduced by an AES-specific polynomial of - * degree 4 which will always produce a polynomial of less than 4 degrees - * such that it will fit in a word. In AES, this polynomial is x^4 + 1. - * - * The modular product of two polynomials 'a' and 'b' is thus: - * - * d(x) = d3x^3 + d2x^2 + d1x + d0 - * with - * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3) - * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3) - * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3) - * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3) - * - * As a matrix: - * - * [d0] = [a0 a3 a2 a1][b0] - * [d1] [a1 a0 a3 a2][b1] - * [d2] [a2 a1 a0 a3][b2] - * [d3] [a3 a2 a1 a0][b3] - * - * Special polynomials defined by AES (0x02 == {02}): - * a(x) = {03}x^3 + {01}x^2 + {01}x + {02} - * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}. - * - * These polynomials are used in the MixColumns() and InverseMixColumns() - * operations, respectively, to cause each element in the state to affect - * the output (referred to as diffusing). - * - * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the - * polynomial x3. - * - * The ShiftRows() method modifies the last 3 rows in the state (where - * the state is 4 words with 4 bytes per word) by shifting bytes cyclically. - * The 1st byte in the second row is moved to the end of the row. The 1st - * and 2nd bytes in the third row are moved to the end of the row. The 1st, - * 2nd, and 3rd bytes are moved in the fourth row. - * - * More details on how AES arithmetic works: - * - * In the polynomial representation of binary numbers, XOR performs addition - * and subtraction and multiplication in GF(2^8) denoted as GF(a, b) - * corresponds with the multiplication of polynomials modulo an irreducible - * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply - * polynomial 'a' with polynomial 'b' and then do a modular reduction by - * an AES-specific irreducible polynomial of degree 8. - * - * A polynomial is irreducible if its only divisors are one and itself. For - * the AES algorithm, this irreducible polynomial is: - * - * m(x) = x^8 + x^4 + x^3 + x + 1, - * - * or {01}{1b} in hexadecimal notation, where each coefficient is a bit: - * 100011011 = 283 = 0x11b. - * - * For example, GF(0x57, 0x83) = 0xc1 because - * - * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1 - * 0x85 = 131 = 10000101 = x^7 + x + 1 - * - * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1) - * = x^13 + x^11 + x^9 + x^8 + x^7 + - * x^7 + x^5 + x^3 + x^2 + x + - * x^6 + x^4 + x^2 + x + 1 - * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y - * y modulo (x^8 + x^4 + x^3 + x + 1) - * = x^7 + x^6 + 1. - * - * The modular reduction by m(x) guarantees the result will be a binary - * polynomial of less than degree 8, so that it can fit in a byte. - * - * The operation to multiply a binary polynomial b with x (the polynomial - * x in binary representation is 00000010) is: - * - * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1 - * - * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the - * most significant bit is 0 in b) then the result is already reduced. If - * it is 1, then we can reduce it by subtracting m(x) via an XOR. - * - * It follows that multiplication by x (00000010 or 0x02) can be implemented - * by performing a left shift followed by a conditional bitwise XOR with - * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by - * higher powers of x can be implemented by repeated application of xtime(). - * - * By adding intermediate results, multiplication by any constant can be - * implemented. For instance: - * - * GF(0x57, 0x13) = 0xfe because: - * - * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1) - * - * Note: We XOR with 0x11b instead of 0x1b because in javascript our - * datatype for b can be larger than 1 byte, so a left shift will not - * automatically eliminate bits that overflow a byte ... by XOR'ing the - * overflow bit with 1 (the extra one from 0x11b) we zero it out. - * - * GF(0x57, 0x02) = xtime(0x57) = 0xae - * GF(0x57, 0x04) = xtime(0xae) = 0x47 - * GF(0x57, 0x08) = xtime(0x47) = 0x8e - * GF(0x57, 0x10) = xtime(0x8e) = 0x07 - * - * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10)) - * - * And by the distributive property (since XOR is addition and GF() is - * multiplication): - * - * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10) - * = 0x57 ^ 0xae ^ 0x07 - * = 0xfe. - */ -function initialize() { - init = true; - - /* Populate the Rcon table. These are the values given by - [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02) - in the field of GF(2^8), where i starts at 1. - - rcon[0] = [0x00, 0x00, 0x00, 0x00] - rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1 - rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2 - ... - rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B - rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36 - - We only store the first byte because it is the only one used. - */ - rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]; - - // compute xtime table which maps i onto GF(i, 0x02) - var xtime = new Array(256); - for(var i = 0; i < 128; ++i) { - xtime[i] = i << 1; - xtime[i + 128] = (i + 128) << 1 ^ 0x11B; - } - - // compute all other tables - sbox = new Array(256); - isbox = new Array(256); - mix = new Array(4); - imix = new Array(4); - for(var i = 0; i < 4; ++i) { - mix[i] = new Array(256); - imix[i] = new Array(256); - } - var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; - for(var i = 0; i < 256; ++i) { - /* We need to generate the SubBytes() sbox and isbox tables so that - we can perform byte substitutions. This requires us to traverse - all of the elements in GF, find their multiplicative inverses, - and apply to each the following affine transformation: - - bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^ - b(i + 7) mod 8 ^ ci - for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the - ith bit of a byte c with the value {63} or {01100011}. - - It is possible to traverse every possible value in a Galois field - using what is referred to as a 'generator'. There are many - generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully - traverse GF we iterate 255 times, multiplying by our generator - each time. - - On each iteration we can determine the multiplicative inverse for - the current element. - - Suppose there is an element in GF 'e'. For a given generator 'g', - e = g^x. The multiplicative inverse of e is g^(255 - x). It turns - out that if use the inverse of a generator as another generator - it will produce all of the corresponding multiplicative inverses - at the same time. For this reason, we choose 5 as our inverse - generator because it only requires 2 multiplies and 1 add and its - inverse, 82, requires relatively few operations as well. - - In order to apply the affine transformation, the multiplicative - inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a - bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and - 'x'. Then 's' is left shifted and the high bit of 's' is made the - low bit. The resulting value is stored in 's'. Then 'x' is XOR'd - with 's' and stored in 'x'. On each subsequent iteration the same - operation is performed. When 4 iterations are complete, 'x' is - XOR'd with 'c' (0x63) and the transformed value is stored in 'x'. - For example: - - s = 01000001 - x = 01000001 - - iteration 1: s = 10000010, x ^= s - iteration 2: s = 00000101, x ^= s - iteration 3: s = 00001010, x ^= s - iteration 4: s = 00010100, x ^= s - x ^= 0x63 - - This can be done with a loop where s = (s << 1) | (s >> 7). However, - it can also be done by using a single 16-bit (in this case 32-bit) - number 'sx'. Since XOR is an associative operation, we can set 'sx' - to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times. - The most significant bits will flow into the high 8 bit positions - and be correctly XOR'd with one another. All that remains will be - to cycle the high 8 bits by XOR'ing them all with the lower 8 bits - afterwards. - - At the same time we're populating sbox and isbox we can precompute - the multiplication we'll need to do to do MixColumns() later. - */ - - // apply affine transformation - sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); - sx = (sx >> 8) ^ (sx & 255) ^ 0x63; - - // update tables - sbox[e] = sx; - isbox[sx] = e; - - /* Mixing columns is done using matrix multiplication. The columns - that are to be mixed are each a single word in the current state. - The state has Nb columns (4 columns). Therefore each column is a - 4 byte word. So to mix the columns in a single column 'c' where - its rows are r0, r1, r2, and r3, we use the following matrix - multiplication: - - [2 3 1 1]*[r0,c]=[r'0,c] - [1 2 3 1] [r1,c] [r'1,c] - [1 1 2 3] [r2,c] [r'2,c] - [3 1 1 2] [r3,c] [r'3,c] - - r0, r1, r2, and r3 are each 1 byte of one of the words in the - state (a column). To do matrix multiplication for each mixed - column c' we multiply the corresponding row from the left matrix - with the corresponding column from the right matrix. In total, we - get 4 equations: - - r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c - r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c - r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c - r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c - - As usual, the multiplication is as previously defined and the - addition is XOR. In order to optimize mixing columns we can store - the multiplication results in tables. If you think of the whole - column as a word (it might help to visualize by mentally rotating - the equations above by counterclockwise 90 degrees) then you can - see that it would be useful to map the multiplications performed on - each byte (r0, r1, r2, r3) onto a word as well. For instance, we - could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the - highest 8 bits and 3*r0 in the lowest 8 bits (with the other two - respectively in the middle). This means that a table can be - constructed that uses r0 as an index to the word. We can do the - same with r1, r2, and r3, creating a total of 4 tables. - - To construct a full c', we can just look up each byte of c in - their respective tables and XOR the results together. - - Also, to build each table we only have to calculate the word - for 2,1,1,3 for every byte ... which we can do on each iteration - of this loop since we will iterate over every byte. After we have - calculated 2,1,1,3 we can get the results for the other tables - by cycling the byte at the end to the beginning. For instance - we can take the result of table 2,1,1,3 and produce table 3,2,1,1 - by moving the right most byte to the left most position just like - how you can imagine the 3 moved out of 2,1,1,3 and to the front - to produce 3,2,1,1. - - There is another optimization in that the same multiples of - the current element we need in order to advance our generator - to the next iteration can be reused in performing the 2,1,1,3 - calculation. We also calculate the inverse mix column tables, - with e,9,d,b being the inverse of 2,1,1,3. - - When we're done, and we need to actually mix columns, the first - byte of each state word should be put through mix[0] (2,1,1,3), - the second through mix[1] (3,2,1,1) and so forth. Then they should - be XOR'd together to produce the fully mixed column. - */ - - // calculate mix and imix table values - sx2 = xtime[sx]; - e2 = xtime[e]; - e4 = xtime[e2]; - e8 = xtime[e4]; - me = - (sx2 << 24) ^ // 2 - (sx << 16) ^ // 1 - (sx << 8) ^ // 1 - (sx ^ sx2); // 3 - ime = - (e2 ^ e4 ^ e8) << 24 ^ // E (14) - (e ^ e8) << 16 ^ // 9 - (e ^ e4 ^ e8) << 8 ^ // D (13) - (e ^ e2 ^ e8); // B (11) - // produce each of the mix tables by rotating the 2,1,1,3 value - for(var n = 0; n < 4; ++n) { - mix[n][e] = me; - imix[n][sx] = ime; - // cycle the right most byte to the left most position - // ie: 2,1,1,3 becomes 3,2,1,1 - me = me << 24 | me >>> 8; - ime = ime << 24 | ime >>> 8; - } - - // get next element and inverse - if(e === 0) { - // 1 is the inverse of 1 - e = ei = 1; - } else { - // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator) - // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator) - e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; - ei ^= xtime[xtime[ei]]; - } - } -} - -/** - * Generates a key schedule using the AES key expansion algorithm. - * - * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion - * routine to generate a key schedule. The Key Expansion generates a total - * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words, - * and each of the Nr rounds requires Nb words of key data. The resulting - * key schedule consists of a linear array of 4-byte words, denoted [wi ], - * with i in the range 0 ≤ i < Nb(Nr + 1). - * - * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk) - * AES-128 (Nb=4, Nk=4, Nr=10) - * AES-192 (Nb=4, Nk=6, Nr=12) - * AES-256 (Nb=4, Nk=8, Nr=14) - * Note: Nr=Nk+6. - * - * Nb is the number of columns (32-bit words) comprising the State (or - * number of bytes in a block). For AES, Nb=4. - * - * @param key the key to schedule (as an array of 32-bit words). - * @param decrypt true to modify the key schedule to decrypt, false not to. - * - * @return the generated key schedule. - */ -function _expandKey(key, decrypt) { - // copy the key's words to initialize the key schedule - var w = key.slice(0); - - /* RotWord() will rotate a word, moving the first byte to the last - byte's position (shifting the other bytes left). - - We will be getting the value of Rcon at i / Nk. 'i' will iterate - from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in - a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from - 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will - increase by 1. We use a counter iNk to keep track of this. - */ - - // go through the rounds expanding the key - var temp, iNk = 1; - var Nk = w.length; - var Nr1 = Nk + 6 + 1; - var end = Nb * Nr1; - for(var i = Nk; i < end; ++i) { - temp = w[i - 1]; - if(i % Nk === 0) { - // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] - temp = - sbox[temp >>> 16 & 255] << 24 ^ - sbox[temp >>> 8 & 255] << 16 ^ - sbox[temp & 255] << 8 ^ - sbox[temp >>> 24] ^ (rcon[iNk] << 24); - iNk++; - } else if(Nk > 6 && (i % Nk === 4)) { - // temp = SubWord(temp) - temp = - sbox[temp >>> 24] << 24 ^ - sbox[temp >>> 16 & 255] << 16 ^ - sbox[temp >>> 8 & 255] << 8 ^ - sbox[temp & 255]; - } - w[i] = w[i - Nk] ^ temp; - } - - /* When we are updating a cipher block we always use the code path for - encryption whether we are decrypting or not (to shorten code and - simplify the generation of look up tables). However, because there - are differences in the decryption algorithm, other than just swapping - in different look up tables, we must transform our key schedule to - account for these changes: - - 1. The decryption algorithm gets its key rounds in reverse order. - 2. The decryption algorithm adds the round key before mixing columns - instead of afterwards. - - We don't need to modify our key schedule to handle the first case, - we can just traverse the key schedule in reverse order when decrypting. - - The second case requires a little work. - - The tables we built for performing rounds will take an input and then - perform SubBytes() and MixColumns() or, for the decrypt version, - InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires - us to AddRoundKey() before InvMixColumns(). This means we'll need to - apply some transformations to the round key to inverse-mix its columns - so they'll be correct for moving AddRoundKey() to after the state has - had its columns inverse-mixed. - - To inverse-mix the columns of the state when we're decrypting we use a - lookup table that will apply InvSubBytes() and InvMixColumns() at the - same time. However, the round key's bytes are not inverse-substituted - in the decryption algorithm. To get around this problem, we can first - substitute the bytes in the round key so that when we apply the - transformation via the InvSubBytes()+InvMixColumns() table, it will - undo our substitution leaving us with the original value that we - want -- and then inverse-mix that value. - - This change will correctly alter our key schedule so that we can XOR - each round key with our already transformed decryption state. This - allows us to use the same code path as the encryption algorithm. - - We make one more change to the decryption key. Since the decryption - algorithm runs in reverse from the encryption algorithm, we reverse - the order of the round keys to avoid having to iterate over the key - schedule backwards when running the encryption algorithm later in - decryption mode. In addition to reversing the order of the round keys, - we also swap each round key's 2nd and 4th rows. See the comments - section where rounds are performed for more details about why this is - done. These changes are done inline with the other substitution - described above. - */ - if(decrypt) { - var tmp; - var m0 = imix[0]; - var m1 = imix[1]; - var m2 = imix[2]; - var m3 = imix[3]; - var wnew = w.slice(0); - end = w.length; - for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { - // do not sub the first or last round key (round keys are Nb - // words) as no column mixing is performed before they are added, - // but do change the key order - if(i === 0 || i === (end - Nb)) { - wnew[i] = w[wi]; - wnew[i + 1] = w[wi + 3]; - wnew[i + 2] = w[wi + 2]; - wnew[i + 3] = w[wi + 1]; - } else { - // substitute each round key byte because the inverse-mix - // table will inverse-substitute it (effectively cancel the - // substitution because round key bytes aren't sub'd in - // decryption mode) and swap indexes 3 and 1 - for(var n = 0; n < Nb; ++n) { - tmp = w[wi + n]; - wnew[i + (3&-n)] = - m0[sbox[tmp >>> 24]] ^ - m1[sbox[tmp >>> 16 & 255]] ^ - m2[sbox[tmp >>> 8 & 255]] ^ - m3[sbox[tmp & 255]]; - } - } - } - w = wnew; - } - - return w; -} - -/** - * Updates a single block (16 bytes) using AES. The update will either - * encrypt or decrypt the block. - * - * @param w the key schedule. - * @param input the input block (an array of 32-bit words). - * @param output the updated output block. - * @param decrypt true to decrypt the block, false to encrypt it. - */ -function _updateBlock(w, input, output, decrypt) { - /* - Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) - begin - byte state[4,Nb] - state = in - AddRoundKey(state, w[0, Nb-1]) - for round = 1 step 1 to Nr–1 - SubBytes(state) - ShiftRows(state) - MixColumns(state) - AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) - end for - SubBytes(state) - ShiftRows(state) - AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - out = state - end - - InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) - begin - byte state[4,Nb] - state = in - AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - for round = Nr-1 step -1 downto 1 - InvShiftRows(state) - InvSubBytes(state) - AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) - InvMixColumns(state) - end for - InvShiftRows(state) - InvSubBytes(state) - AddRoundKey(state, w[0, Nb-1]) - out = state - end - */ - - // Encrypt: AddRoundKey(state, w[0, Nb-1]) - // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - var Nr = w.length / 4 - 1; - var m0, m1, m2, m3, sub; - if(decrypt) { - m0 = imix[0]; - m1 = imix[1]; - m2 = imix[2]; - m3 = imix[3]; - sub = isbox; - } else { - m0 = mix[0]; - m1 = mix[1]; - m2 = mix[2]; - m3 = mix[3]; - sub = sbox; - } - var a, b, c, d, a2, b2, c2; - a = input[0] ^ w[0]; - b = input[decrypt ? 3 : 1] ^ w[1]; - c = input[2] ^ w[2]; - d = input[decrypt ? 1 : 3] ^ w[3]; - var i = 3; - - /* In order to share code we follow the encryption algorithm when both - encrypting and decrypting. To account for the changes required in the - decryption algorithm, we use different lookup tables when decrypting - and use a modified key schedule to account for the difference in the - order of transformations applied when performing rounds. We also get - key rounds in reverse order (relative to encryption). */ - for(var round = 1; round < Nr; ++round) { - /* As described above, we'll be using table lookups to perform the - column mixing. Each column is stored as a word in the state (the - array 'input' has one column as a word at each index). In order to - mix a column, we perform these transformations on each row in c, - which is 1 byte in each word. The new column for c0 is c'0: - - m0 m1 m2 m3 - r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0 - r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0 - r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0 - r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0 - - So using mix tables where c0 is a word with r0 being its upper - 8 bits and r3 being its lower 8 bits: - - m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0] - ... - m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3] - - Therefore to mix the columns in each word in the state we - do the following (& 255 omitted for brevity): - c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - - However, before mixing, the algorithm requires us to perform - ShiftRows(). The ShiftRows() transformation cyclically shifts the - last 3 rows of the state over different offsets. The first row - (r = 0) is not shifted. - - s'_r,c = s_r,(c + shift(r, Nb) mod Nb - for 0 < r < 4 and 0 <= c < Nb and - shift(1, 4) = 1 - shift(2, 4) = 2 - shift(3, 4) = 3. - - This causes the first byte in r = 1 to be moved to the end of - the row, the first 2 bytes in r = 2 to be moved to the end of - the row, the first 3 bytes in r = 3 to be moved to the end of - the row: - - r1: [c0 c1 c2 c3] => [c1 c2 c3 c0] - r2: [c0 c1 c2 c3] [c2 c3 c0 c1] - r3: [c0 c1 c2 c3] [c3 c0 c1 c2] - - We can make these substitutions inline with our column mixing to - generate an updated set of equations to produce each word in the - state (note the columns have changed positions): - - c0 c1 c2 c3 => c0 c1 c2 c3 - c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte) - c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes) - c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes) - - Therefore: - - c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3 - c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3 - c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3 - c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3 - - c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0 - c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0 - c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0 - c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0 - - ... and so forth for c'2 and c'3. The important distinction is - that the columns are cycling, with c0 being used with the m0 - map when calculating c0, but c1 being used with the m0 map when - calculating c1 ... and so forth. - - When performing the inverse we transform the mirror image and - skip the bottom row, instead of the top one, and move upwards: - - c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption - c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes) - c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption - c3 c2 c1 c0 c3 c2 c1 c0 - - If you compare the resulting matrices for ShiftRows()+MixColumns() - and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are - different (in encrypt mode vs. decrypt mode). So in order to use - the same code to handle both encryption and decryption, we will - need to do some mapping. - - If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be - a row number in the state, then the resulting matrix in encryption - mode for applying the above transformations would be: - - r1: a b c d - r2: b c d a - r3: c d a b - r4: d a b c - - If we did the same in decryption mode we would get: - - r1: a d c b - r2: b a d c - r3: c b a d - r4: d c b a - - If instead we swap d and b (set b=c3 and d=c1), then we get: - - r1: a b c d - r2: d a b c - r3: c d a b - r4: b c d a - - Now the 1st and 3rd rows are the same as the encryption matrix. All - we need to do then to make the mapping exactly the same is to swap - the 2nd and 4th rows when in decryption mode. To do this without - having to do it on each iteration, we swapped the 2nd and 4th rows - in the decryption key schedule. We also have to do the swap above - when we first pull in the input and when we set the final output. */ - a2 = - m0[a >>> 24] ^ - m1[b >>> 16 & 255] ^ - m2[c >>> 8 & 255] ^ - m3[d & 255] ^ w[++i]; - b2 = - m0[b >>> 24] ^ - m1[c >>> 16 & 255] ^ - m2[d >>> 8 & 255] ^ - m3[a & 255] ^ w[++i]; - c2 = - m0[c >>> 24] ^ - m1[d >>> 16 & 255] ^ - m2[a >>> 8 & 255] ^ - m3[b & 255] ^ w[++i]; - d = - m0[d >>> 24] ^ - m1[a >>> 16 & 255] ^ - m2[b >>> 8 & 255] ^ - m3[c & 255] ^ w[++i]; - a = a2; - b = b2; - c = c2; - } - - /* - Encrypt: - SubBytes(state) - ShiftRows(state) - AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - - Decrypt: - InvShiftRows(state) - InvSubBytes(state) - AddRoundKey(state, w[0, Nb-1]) - */ - // Note: rows are shifted inline - output[0] = - (sub[a >>> 24] << 24) ^ - (sub[b >>> 16 & 255] << 16) ^ - (sub[c >>> 8 & 255] << 8) ^ - (sub[d & 255]) ^ w[++i]; - output[decrypt ? 3 : 1] = - (sub[b >>> 24] << 24) ^ - (sub[c >>> 16 & 255] << 16) ^ - (sub[d >>> 8 & 255] << 8) ^ - (sub[a & 255]) ^ w[++i]; - output[2] = - (sub[c >>> 24] << 24) ^ - (sub[d >>> 16 & 255] << 16) ^ - (sub[a >>> 8 & 255] << 8) ^ - (sub[b & 255]) ^ w[++i]; - output[decrypt ? 1 : 3] = - (sub[d >>> 24] << 24) ^ - (sub[a >>> 16 & 255] << 16) ^ - (sub[b >>> 8 & 255] << 8) ^ - (sub[c & 255]) ^ w[++i]; -} - -/** - * Deprecated. Instead, use: - * - * forge.cipher.createCipher('AES-', key); - * forge.cipher.createDecipher('AES-', key); - * - * Creates a deprecated AES cipher object. This object's mode will default to - * CBC (cipher-block-chaining). - * - * The key and iv may be given as a string of bytes, an array of bytes, a - * byte buffer, or an array of 32-bit words. - * - * @param options the options to use. - * key the symmetric key to use. - * output the buffer to write to. - * decrypt true for decryption, false for encryption. - * mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -function _createCipher(options) { - options = options || {}; - var mode = (options.mode || 'CBC').toUpperCase(); - var algorithm = 'AES-' + mode; - - var cipher; - if(options.decrypt) { - cipher = forge.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge.cipher.createCipher(algorithm, options.key); - } - - // backwards compatible start API - var start = cipher.start; - cipher.start = function(iv, options) { - // backwards compatibility: support second arg as output buffer - var output = null; - if(options instanceof forge.util.ByteBuffer) { - output = options; - options = {}; - } - options = options || {}; - options.output = output; - options.iv = iv; - start.call(cipher, options); - }; - - return cipher; -} - -} // end module implementation - -/* ########## Begin module wrapper ########## */ -var name = 'aes'; -if(typeof define !== 'function') { - // NodeJS -> AMD - if(typeof module === 'object' && module.exports) { - var nodeJS = true; - define = function(ids, factory) { - factory(require, module); - }; - } else { - // - - - - -
- - diff --git a/alarm/node_modules/node-forge/nodejs/ui/require.js b/alarm/node_modules/node-forge/nodejs/ui/require.js deleted file mode 100644 index 7df5d90..0000000 --- a/alarm/node_modules/node-forge/nodejs/ui/require.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - RequireJS 2.1.5 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. - Available via the MIT or new BSD license. - see: http://github.com/jrburke/requirejs for details -*/ -var requirejs,require,define; -(function(aa){function I(b){return"[object Function]"===L.call(b)}function J(b){return"[object Array]"===L.call(b)}function y(b,c){if(b){var d;for(d=0;dthis.depCount&&!this.defined){if(I(n)){if(this.events.error)try{e=i.execCb(c,n,b,e)}catch(d){a=d}else e=i.execCb(c,n,b,e);this.map.isDefine&&((b=this.module)&&void 0!==b.exports&&b.exports!==this.exports?e=b.exports:void 0===e&&this.usingExports&&(e=this.exports));if(a)return a.requireMap=this.map,a.requireModules=[this.map.id],a.requireType="define",v(this.error= -a)}else e=n;this.exports=e;if(this.map.isDefine&&!this.ignore&&(q[c]=e,l.onResourceLoad))l.onResourceLoad(i,this.map,this.depMaps);x(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,d=j(a.prefix);this.depMaps.push(d);t(d,"defined",u(this,function(e){var n,d;d=this.map.name;var g=this.map.parentMap?this.map.parentMap.name:null,h= -i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(e.normalize&&(d=e.normalize(d,function(a){return c(a,g,!0)})||""),e=j(a.prefix+"!"+d,this.map.parentMap),t(e,"defined",u(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),d=m(p,e.id)){this.depMaps.push(e);if(this.events.error)d.on("error",u(this,function(a){this.emit("error",a)}));d.enable()}}else n=u(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),n.error=u(this, -function(a){this.inited=!0;this.error=a;a.requireModules=[b];G(p,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&x(a.map.id)});v(a)}),n.fromText=u(this,function(e,c){var d=a.name,g=j(d),C=O;c&&(e=c);C&&(O=!1);r(g);s(k.config,b)&&(k.config[d]=k.config[b]);try{l.exec(e)}catch(ca){return v(B("fromtexteval","fromText eval for "+b+" failed: "+ca,ca,[b]))}C&&(O=!0);this.depMaps.push(g);i.completeLoad(d);h([d],n)}),e.load(a.name,h,n,k)}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){V[this.map.id]= -this;this.enabling=this.enabled=!0;y(this.depMaps,u(this,function(a,b){var c,e;if("string"===typeof a){a=j(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=m(N,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;t(a,"defined",u(this,function(a){this.defineDep(b,a);this.check()}));this.errback&&t(a,"error",this.errback)}c=a.id;e=p[c];!s(N,c)&&(e&&!e.enabled)&&i.enable(a,this)}));G(this.pluginMaps,u(this,function(a){var b=m(p,a.id);b&&!b.enabled&&i.enable(a, -this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){y(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:k,contextName:b,registry:p,defined:q,urlFetched:U,defQueue:H,Module:Z,makeModuleMap:j,nextTick:l.nextTick,onError:v,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=k.pkgs,c=k.shim,e={paths:!0,config:!0,map:!0};G(a,function(a,b){e[b]? -"map"===b?(k.map||(k.map={}),R(k[b],a,!0,!0)):R(k[b],a,!0):k[b]=a});a.shim&&(G(a.shim,function(a,b){J(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);c[b]=a}),k.shim=c);a.packages&&(y(a.packages,function(a){a="string"===typeof a?{name:a}:a;b[a.name]={name:a.name,location:a.location||a.name,main:(a.main||"main").replace(ja,"").replace(ea,"")}}),k.pkgs=b);G(p,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=j(b))});if(a.deps||a.callback)i.require(a.deps||[], -a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(aa,arguments));return b||a.exports&&ba(a.exports)}},makeRequire:function(a,f){function d(e,c,h){var g,k;f.enableBuildCallback&&(c&&I(c))&&(c.__requireJsBuild=!0);if("string"===typeof e){if(I(c))return v(B("requireargs","Invalid require call"),h);if(a&&s(N,e))return N[e](p[a.id]);if(l.get)return l.get(i,e,a,d);g=j(e,a,!1,!0);g=g.id;return!s(q,g)?v(B("notloaded",'Module name "'+g+'" has not been loaded yet for context: '+ -b+(a?"":". Use require([])"))):q[g]}L();i.nextTick(function(){L();k=r(j(null,a));k.skipMap=f.skipMap;k.init(e,c,h,{enabled:!0});D()});return d}f=f||{};R(d,{isBrowser:A,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==f&&(!("."===g||".."===g)||1h.attachEvent.toString().indexOf("[native code"))&&!Y?(O=!0,h.attachEvent("onreadystatechange",b.onScriptLoad)):(h.addEventListener("load",b.onScriptLoad,!1),h.addEventListener("error",b.onScriptError,!1)),h.src=d,K=h,D?x.insertBefore(h,D):x.appendChild(h),K=null,h;if(da)try{importScripts(d),b.completeLoad(c)}catch(j){b.onError(B("importscripts","importScripts failed for "+c+" at "+d,j,[c]))}};A&&M(document.getElementsByTagName("script"),function(b){x||(x= -b.parentNode);if(t=b.getAttribute("data-main"))return r.baseUrl||(E=t.split("/"),Q=E.pop(),fa=E.length?E.join("/")+"/":"./",r.baseUrl=fa,t=Q),t=t.replace(ea,""),r.deps=r.deps?r.deps.concat(t):[t],!0});define=function(b,c,d){var l,h;"string"!==typeof b&&(d=c,c=b,b=null);J(c)||(d=c,c=[]);!c.length&&I(d)&&d.length&&(d.toString().replace(la,"").replace(ma,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c));if(O){if(!(l=K))P&&"interactive"===P.readyState||M(document.getElementsByTagName("script"), -function(b){if("interactive"===b.readyState)return P=b}),l=P;l&&(b||(b=l.getAttribute("data-requiremodule")),h=F[l.getAttribute("data-requirecontext")])}(h?h.defQueue:T).push([b,c,d])};define.amd={jQuery:!0};l.exec=function(b){return eval(b)};l(r)}})(this); \ No newline at end of file diff --git a/alarm/node_modules/node-forge/nodejs/ui/test.js b/alarm/node_modules/node-forge/nodejs/ui/test.js deleted file mode 100644 index fa51fe2..0000000 --- a/alarm/node_modules/node-forge/nodejs/ui/test.js +++ /dev/null @@ -1,36 +0,0 @@ -var ASSERT = chai.assert; -mocha.setup({ - ui: 'bdd', - timeout: 30000 -}); -requirejs.config({ - paths: { - forge: 'forge', - test: 'test' - } -}); -requirejs([ - 'test/util', - 'test/md5', - 'test/sha1', - 'test/sha256', - 'test/hmac', - 'test/pbkdf2', - 'test/mgf1', - 'test/random', - 'test/asn1', - 'test/pem', - 'test/rsa', - 'test/kem', - 'test/pkcs1', - 'test/x509', - 'test/csr', - 'test/aes', - 'test/rc2', - 'test/des', - 'test/pkcs7', - 'test/pkcs12', - 'test/tls' -], function() { - mocha.run(); -}); diff --git a/alarm/node_modules/node-forge/nodejs/ui/test.min.js b/alarm/node_modules/node-forge/nodejs/ui/test.min.js deleted file mode 100644 index e94e9e0..0000000 --- a/alarm/node_modules/node-forge/nodejs/ui/test.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(){function e(e){var t=e.util=e.util||{};typeof process=="undefined"||!process.nextTick?typeof setImmediate=="function"?(t.setImmediate=setImmediate,t.nextTick=function(e){return setImmediate(e)}):(t.setImmediate=function(e){setTimeout(e,0)},t.nextTick=t.setImmediate):(t.nextTick=process.nextTick,typeof setImmediate=="function"?t.setImmediate=setImmediate:t.setImmediate=t.nextTick),t.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"},t.ByteBuffer=function(e){this.data=e||"",this.read=0},t.ByteBuffer.prototype.length=function(){return this.data.length-this.read},t.ByteBuffer.prototype.isEmpty=function(){return this.length()<=0},t.ByteBuffer.prototype.putByte=function(e){return this.data+=String.fromCharCode(e),this},t.ByteBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);var n=this.data;while(t>0)t&1&&(n+=e),t>>>=1,t>0&&(e+=e);return this.data=n,this},t.ByteBuffer.prototype.putBytes=function(e){return this.data+=e,this},t.ByteBuffer.prototype.putString=function(e){return this.data+=t.encodeUtf8(e),this},t.ByteBuffer.prototype.putInt16=function(e){return this.data+=String.fromCharCode(e>>8&255)+String.fromCharCode(e&255),this},t.ByteBuffer.prototype.putInt24=function(e){return this.data+=String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255),this},t.ByteBuffer.prototype.putInt32=function(e){return this.data+=String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255),this},t.ByteBuffer.prototype.putInt16Le=function(e){return this.data+=String.fromCharCode(e&255)+String.fromCharCode(e>>8&255),this},t.ByteBuffer.prototype.putInt24Le=function(e){return this.data+=String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255),this},t.ByteBuffer.prototype.putInt32Le=function(e){return this.data+=String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255),this},t.ByteBuffer.prototype.putInt=function(e,t){do t-=8,this.data+=String.fromCharCode(e>>t&255);while(t>0);return this},t.ByteBuffer.prototype.putBuffer=function(e){return this.data+=e.getBytes(),this},t.ByteBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},t.ByteBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e},t.ByteBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e},t.ByteBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e},t.ByteBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e},t.ByteBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e},t.ByteBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e},t.ByteBuffer.prototype.getInt=function(e){var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t},t.ByteBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t},t.ByteBuffer.prototype.bytes=function(e){return typeof e=="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},t.ByteBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},t.ByteBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},t.ByteBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},t.ByteBuffer.prototype.copy=function(){var e=t.createBuffer(this.data);return e.read=this.read,e},t.ByteBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},t.ByteBuffer.prototype.clear=function(){return this.data="",this.read=0,this},t.ByteBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},t.ByteBuffer.prototype.toHex=function(){var e="";for(var t=this.read;t0)t&1&&(n+=e),t>>>=1,t>0&&(e+=e);return n},t.xorBytes=function(e,t,n){var r="",i="",s="",o=0,u=0;for(;n>0;--n,++o)i=e.charCodeAt(o)^t.charCodeAt(o),u>=10&&(r+=s,s="",u=0),s+=String.fromCharCode(i),++u;return r+=s,r},t.hexToBytes=function(e){var t="",n=0;e.length&!0&&(n=1,t+=String.fromCharCode(parseInt(e[0],16)));for(;n>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];t.encode64=function(e,t){var r="",i="",s,o,u,a=0;while(a>2),r+=n.charAt((s&3)<<4|o>>4),isNaN(o)?r+="==":(r+=n.charAt((o&15)<<2|u>>6),r+=isNaN(u)?"=":n.charAt(u&63)),t&&r.length>t&&(i+=r.substr(0,t)+"\r\n",r=r.substr(t));return i+=r,i},t.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");var t="",n,i,s,o,u=0;while(u>4),s!==64&&(t+=String.fromCharCode((i&15)<<4|s>>2),o!==64&&(t+=String.fromCharCode((s&3)<<6|o)));return t},t.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},t.decodeUtf8=function(e){return decodeURIComponent(escape(e))},t.deflate=function(e,n,r){n=t.decode64(e.deflate(t.encode64(n)).rval);if(r){var i=2,s=n.charCodeAt(1);s&32&&(i=6),n=n.substring(i,n.length-4)}return n},t.inflate=function(e,n,r){var i=e.inflate(t.encode64(n)).rval;return i===null?null:t.decode64(i)};var i=function(e,n,r){if(!e)throw{message:"WebStorage not available."};var i;r===null?i=e.removeItem(n):(r=t.encode64(JSON.stringify(r)),i=e.setItem(n,r));if(typeof i!="undefined"&&i.rval!==!0)throw i.error},s=function(e,n){if(!e)throw{message:"WebStorage not available."};var r=e.getItem(n);if(e.init)if(r.rval===null){if(r.error)throw r.error;r=null}else r=r.rval;return r!==null&&(r=JSON.parse(t.decode64(r))),r},o=function(e,t,n,r){var o=s(e,t);o===null&&(o={}),o[n]=r,i(e,t,o)},u=function(e,t,n){var r=s(e,t);return r!==null&&(r=n in r?r[n]:null),r},a=function(e,t,n){var r=s(e,t);if(r!==null&&n in r){delete r[n];var o=!0;for(var u in r){o=!1;break}o&&(r=null),i(e,t,r)}},f=function(e,t){i(e,t,null)},l=function(e,t,n){var r=null;typeof n=="undefined"&&(n=["web","flash"]);var i,s=!1,o=null;for(var u in n){i=n[u];try{if(i==="flash"||i==="both"){if(t[0]===null)throw{message:"Flash local storage not available."};r=e.apply(this,t),s=i==="flash"}if(i==="web"||i==="both")t[0]=localStorage,r=e.apply(this,t),s=!0}catch(a){o=a}if(s)break}if(!s)throw o;return r};t.setItem=function(e,t,n,r,i){l(o,arguments,i)},t.getItem=function(e,t,n,r){return l(u,arguments,r)},t.removeItem=function(e,t,n,r){l(a,arguments,r)},t.clearItems=function(e,t,n){l(f,arguments,n)},t.parseUrl=function(e){var t=/^(https?):\/\/([^:&^\/]*):?(\d*)(.*)$/g;t.lastIndex=0;var n=t.exec(e),r=n===null?null:{full:e,scheme:n[1],host:n[2],port:n[3],path:n[4]};return r&&(r.fullHost=r.host,r.port?r.port!==80&&r.scheme==="http"?r.fullHost+=":"+r.port:r.port!==443&&r.scheme==="https"&&(r.fullHost+=":"+r.port):r.scheme==="http"?r.port=80:r.scheme==="https"&&(r.port=443),r.full=r.scheme+"://"+r.fullHost),r};var c=null;t.getQueryVariables=function(e){var t=function(e){var t={},n=e.split("&");for(var r=0;r0?(s=n[r].substring(0,i),o=n[r].substring(i+1)):(s=n[r],o=null),s in t||(t[s]=[]),!(s in Object.prototype)&&o!==null&&t[s].push(unescape(o))}return t},n;return typeof e=="undefined"?(c===null&&(typeof window=="undefined"?c={}:c=t(window.location.search.substring(1))),n=c):n=t(e),n},t.parseFragment=function(e){var n=e,r="",i=e.indexOf("?");i>0&&(n=e.substring(0,i),r=e.substring(i+1));var s=n.split("/");s.length>0&&s[0]===""&&s.shift();var o=r===""?{}:t.getQueryVariables(r);return{pathString:n,queryString:r,path:s,query:o}},t.makeRequest=function(e){var n=t.parseFragment(e),r={path:n.pathString,query:n.queryString,getPath:function(e){return typeof e=="undefined"?n.path:n.path[e]},getQuery:function(e,t){var r;return typeof e=="undefined"?r=n.query:(r=n.query[e],r&&typeof t!="undefined"&&(r=r[t])),r},getQueryLast:function(e,t){var n,i=r.getQuery(e);return i?n=i[i.length-1]:n=t,n}};return r},t.makeLink=function(e,t,n){e=jQuery.isArray(e)?e.join("/"):e;var r=jQuery.param(t||{});return n=n||"",e+(r.length>0?"?"+r:"")+(n.length>0?"#"+n:"")},t.setPath=function(e,t,n){if(typeof e=="object"&&e!==null){var r=0,i=t.length;while(r0&&s.push(r),o=t.lastIndex;var u=n[0][1];switch(u){case"s":case"o":i");break;case"%":s.push("%");break;default:s.push("<%"+u+"?>")}}return s.push(e.substring(o)),s.join("")},t.formatNumber=function(e,t,n,r){var i=e,s=isNaN(t=Math.abs(t))?2:t,o=n===undefined?",":n,u=r===undefined?".":r,a=i<0?"-":"",f=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",l=f.length>3?f.length%3:0;return a+(l?f.substr(0,l)+u:"")+f.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+u)+(s?o+Math.abs(i-f).toFixed(s).slice(2):"")},t.formatSize=function(e){return e>=1073741824?e=t.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?e=t.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?e=t.formatNumber(e/1024,0)+" KiB":e=t.formatNumber(e,0)+" bytes",e}}var t="util";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o0)i.push(n.getByte());e.deepEqual(i,[1,2,3,4,0,0,0,4,1,2,3,255,255,255,255])}),it("should convert bytes from hex",function(){var n="0102030400000004010203ffffffff",r=t.createBuffer();r.putBytes(t.hexToBytes(n)),e.equal(r.toHex(),n)}),it("should base64 encode some bytes",function(){var n="00010203050607080A0B0C0D0F1011121415161719",r="MDAwMTAyMDMwNTA2MDcwODBBMEIwQzBEMEYxMDExMTIxNDE1MTYxNzE5";e.equal(t.encode64(n),r)}),it("should base64 decode some bytes",function(){var n="00010203050607080A0B0C0D0F1011121415161719",r="MDAwMTAyMDMwNTA2MDcwODBBMEIwQzBEMEYxMDExMTIxNDE1MTYxNzE5";e.equal(t.decode64(r),n)})})}typeof define=="function"?define("test/util",["forge/util"],function(t){e(ASSERT,t())}):typeof module=="object"&&module.exports&&e(require("assert"),require("../../js/util")())}(),function(){function e(e){var t=e.md5=e.md5||{};e.md=e.md||{},e.md.algorithms=e.md.algorithms||{},e.md.md5=e.md.algorithms.md5=t;var n=null,r=null,i=null,s=null,o=!1,u=function(){n=String.fromCharCode(128),n+=e.util.fillString(String.fromCharCode(0),64),r=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],i=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],s=new Array(64);for(var t=0;t<64;++t)s[t]=Math.floor(Math.abs(Math.sin(t+1))*4294967296);o=!0},a=function(e,t,n){var o,u,a,f,l,c,h,p,d=n.length();while(d>=64){u=e.h0,a=e.h1,f=e.h2,l=e.h3;for(p=0;p<16;++p)t[p]=n.getInt32Le(),c=l^a&(f^l),o=u+c+s[p]+t[p],h=i[p],u=l,l=f,f=a,a+=o<>>32-h;for(;p<32;++p)c=f^l&(a^f),o=u+c+s[p]+t[r[p]],h=i[p],u=l,l=f,f=a,a+=o<>>32-h;for(;p<48;++p)c=a^f^l,o=u+c+s[p]+t[r[p]],h=i[p],u=l,l=f,f=a,a+=o<>>32-h;for(;p<64;++p)c=f^(a|~l),o=u+c+s[p]+t[r[p]],h=i[p],u=l,l=f,f=a,a+=o<>>32-h;e.h0=e.h0+u&4294967295,e.h1=e.h1+a&4294967295,e.h2=e.h2+f&4294967295,e.h3=e.h3+l&4294967295,d-=64}};t.create=function(){o||u();var t=null,r=e.util.createBuffer(),i=new Array(16),s={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0};return s.start=function(){return s.messageLength=0,r=e.util.createBuffer(),t={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},s},s.start(),s.update=function(n,o){return o==="utf8"&&(n=e.util.encodeUtf8(n)),s.messageLength+=n.length,r.putBytes(n),a(t,i,r),(r.read>2048||r.length()===0)&&r.compact(),s},s.digest=function(){var o=s.messageLength,u=e.util.createBuffer();u.putBytes(r.bytes()),u.putBytes(n.substr(0,64-(o+8)%64)),u.putInt32Le(o<<3&4294967295),u.putInt32Le(o>>>29&255);var f={h0:t.h0,h1:t.h1,h2:t.h2,h3:t.h3};a(f,i,u);var l=e.util.createBuffer();return l.putInt32Le(f.h0),l.putInt32Le(f.h1),l.putInt32Le(f.h2),l.putInt32Le(f.h3),l},s}}var t="md5";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o=64){i=e.h0,s=e.h1,o=e.h2,u=e.h3,a=e.h4;for(l=0;l<16;++l)r=n.getInt32(),t[l]=r,f=u^s&(o^u),r=(i<<5|i>>>27)+f+a+1518500249+r,a=u,u=o,o=s<<30|s>>>2,s=i,i=r;for(;l<20;++l)r=t[l-3]^t[l-8]^t[l-14]^t[l-16],r=r<<1|r>>>31,t[l]=r,f=u^s&(o^u),r=(i<<5|i>>>27)+f+a+1518500249+r,a=u,u=o,o=s<<30|s>>>2,s=i,i=r;for(;l<32;++l)r=t[l-3]^t[l-8]^t[l-14]^t[l-16],r=r<<1|r>>>31,t[l]=r,f=s^o^u,r=(i<<5|i>>>27)+f+a+1859775393+r,a=u,u=o,o=s<<30|s>>>2,s=i,i=r;for(;l<40;++l)r=t[l-6]^t[l-16]^t[l-28]^t[l-32],r=r<<2|r>>>30,t[l]=r,f=s^o^u,r=(i<<5|i>>>27)+f+a+1859775393+r,a=u,u=o,o=s<<30|s>>>2,s=i,i=r;for(;l<60;++l)r=t[l-6]^t[l-16]^t[l-28]^t[l-32],r=r<<2|r>>>30,t[l]=r,f=s&o|u&(s^o),r=(i<<5|i>>>27)+f+a+2400959708+r,a=u,u=o,o=s<<30|s>>>2,s=i,i=r;for(;l<80;++l)r=t[l-6]^t[l-16]^t[l-28]^t[l-32],r=r<<2|r>>>30,t[l]=r,f=s^o^u,r=(i<<5|i>>>27)+f+a+3395469782+r,a=u,u=o,o=s<<30|s>>>2,s=i,i=r;e.h0+=i,e.h1+=s,e.h2+=o,e.h3+=u,e.h4+=a,c-=64}};t.create=function(){r||i();var t=null,o=e.util.createBuffer(),u=new Array(80),a={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0};return a.start=function(){return a.messageLength=0,o=e.util.createBuffer(),t={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},a},a.start(),a.update=function(n,r){return r==="utf8"&&(n=e.util.encodeUtf8(n)),a.messageLength+=n.length,o.putBytes(n),s(t,u,o),(o.read>2048||o.length()===0)&&o.compact(),a},a.digest=function(){var r=a.messageLength,i=e.util.createBuffer();i.putBytes(o.bytes()),i.putBytes(n.substr(0,64-(r+8)%64)),i.putInt32(r>>>29&255),i.putInt32(r<<3&4294967295);var f={h0:t.h0,h1:t.h1,h2:t.h2,h3:t.h3,h4:t.h4};s(f,u,i);var l=e.util.createBuffer();return l.putInt32(f.h0),l.putInt32(f.h1),l.putInt32(f.h2),l.putInt32(f.h3),l.putInt32(f.h4),l},a}}var t="sha1";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o=64){for(l=0;l<16;++l)t[l]=n.getInt32();for(;l<64;++l)r=t[l-2],r=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,s=t[l-15],s=(s>>>7|s<<25)^(s>>>18|s<<14)^s>>>3,t[l]=r+t[l-7]+s+t[l-16]&4294967295;c=e.h0,h=e.h1,p=e.h2,d=e.h3,v=e.h4,m=e.h5,g=e.h6,y=e.h7;for(l=0;l<64;++l)u=(v>>>6|v<<26)^(v>>>11|v<<21)^(v>>>25|v<<7),a=g^v&(m^g),o=(c>>>2|c<<30)^(c>>>13|c<<19)^(c>>>22|c<<10),f=c&h|p&(c^h),r=y+u+a+i[l]+t[l],s=o+f,y=g,g=m,m=v,v=d+r&4294967295,d=p,p=h,h=c,c=r+s&4294967295;e.h0=e.h0+c&4294967295,e.h1=e.h1+h&4294967295,e.h2=e.h2+p&4294967295,e.h3=e.h3+d&4294967295,e.h4=e.h4+v&4294967295,e.h5=e.h5+m&4294967295,e.h6=e.h6+g&4294967295,e.h7=e.h7+y&4294967295,b-=64}};t.create=function(){r||s();var t=null,i=e.util.createBuffer(),u=new Array(64),a={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0};return a.start=function(){return a.messageLength=0,i=e.util.createBuffer(),t={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},a},a.start(),a.update=function(n,r){return r==="utf8"&&(n=e.util.encodeUtf8(n)),a.messageLength+=n.length,i.putBytes(n),o(t,u,i),(i.read>2048||i.length()===0)&&i.compact(),a},a.digest=function(){var r=a.messageLength,s=e.util.createBuffer();s.putBytes(i.bytes()),s.putBytes(n.substr(0,64-(r+8)%64)),s.putInt32(r>>>29&255),s.putInt32(r<<3&4294967295);var f={h0:t.h0,h1:t.h1,h2:t.h2,h3:t.h3,h4:t.h4,h5:t.h5,h6:t.h6,h7:t.h7};o(f,u,s);var l=e.util.createBuffer();return l.putInt32(f.h0),l.putInt32(f.h1),l.putInt32(f.h2),l.putInt32(f.h3),l.putInt32(f.h4),l.putInt32(f.h5),l.putInt32(f.h6),l.putInt32(f.h7),l},a}}var t="sha256";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;on.blockLength&&(n.start(),n.update(o.bytes()),o=n.digest()),r=e.util.createBuffer(),i=e.util.createBuffer(),f=o.length();for(var a=0;a4294967295*o)throw{message:"Derived key is too long."};var u=Math.ceil(i/o),a=i-(u-1)*o,f=e.hmac.create();f.start(s,t);var l="",c,h,p;for(var d=1;d<=u;++d){f.update(n),f.update(e.util.int32ToBytes(d)),c=p=f.digest().getBytes();for(var v=2;v<=r;++v)f.start(null,null),f.update(p),h=f.digest().getBytes(),c=e.util.xorBytes(c,h,o),p=h;l+=d>8^p&255^99,r[a]=p,i[p]=a,d=e[p],l=e[a],c=e[l],h=e[c],v=d<<24^p<<16^p<<8^(p^d),m=(l^c^h)<<24^(a^h)<<16^(a^c^h)<<8^(a^l^h);for(var g=0;g<4;++g)o[g][a]=v,u[g][p]=m,v=v<<24|v>>>8,m=m<<24|m>>>8;a===0?a=f=1:(a=l^e[e[e[l^h]]],f^=e[e[f]])}},f=function(e,t){var i=e.slice(0),o,a=1,f=i.length,l=f+6+1,c=n*l;for(var h=f;h>>16&255]<<24^r[o>>>8&255]<<16^r[o&255]<<8^r[o>>>24]^s[a]<<24,a++):f>6&&h%f===4&&(o=r[o>>>24]<<24^r[o>>>16&255]<<16^r[o>>>8&255]<<8^r[o&255]),i[h]=i[h-f]^o;if(t){var p,d=u[0],v=u[1],m=u[2],g=u[3],y=i.slice(0),c=i.length;for(var h=0,b=c-n;h>>24]]^v[r[p>>>16&255]]^m[r[p>>>8&255]]^g[r[p&255]];i=y}return i},l=function(e,t,n,s){var a=e.length/4-1,f,l,c,h,p;s?(f=u[0],l=u[1],c=u[2],h=u[3],p=i):(f=o[0],l=o[1],c=o[2],h=o[3],p=r);var d,v,m,g,y,b,w;d=t[0]^e[0],v=t[s?3:1]^e[1],m=t[2]^e[2],g=t[s?1:3]^e[3];var E=3;for(var S=1;S>>24]^l[v>>>16&255]^c[m>>>8&255]^h[g&255]^e[++E],b=f[v>>>24]^l[m>>>16&255]^c[g>>>8&255]^h[d&255]^e[++E],w=f[m>>>24]^l[g>>>16&255]^c[d>>>8&255]^h[v&255]^e[++E],g=f[g>>>24]^l[d>>>16&255]^c[v>>>8&255]^h[m&255]^e[++E],d=y,v=b,m=w;n[0]=p[d>>>24]<<24^p[v>>>16&255]<<16^p[m>>>8&255]<<8^p[g&255]^e[++E],n[s?3:1]=p[v>>>24]<<24^p[m>>>16&255]<<16^p[g>>>8&255]<<8^p[d&255]^e[++E],n[2]=p[m>>>24]<<24^p[g>>>16&255]<<16^p[d>>>8&255]<<8^p[v&255]^e[++E],n[s?1:3]=p[g>>>24]<<24^p[d>>>16&255]<<16^p[v>>>8&255]<<8^p[m&255]^e[++E]},c=function(r,i,s,o,u){function C(){if(o)for(var e=0;e=0;--e){if(E[e]!==4294967295){++E[e];break}E[e]=0}for(var e=0;e>>=2;for(var p=0;p=y||b.length()>0&&T)N()},c.finish=function(e){var t=!0,r=b.length()%y;if(!o)if(e)t=e(y,b,o);else if(m){var i=b.length()===y?y:y-b.length();b.fillWithByte(i,i)}t&&(T=!0,c.update());if(o){m&&(t=r===0);if(t)if(e)t=e(y,w,o);else if(m){var s=w.length(),u=w.at(s-1);u>n<<2?t=!1:w.truncate(u)}}return!m&&!e&&r>0&&w.truncate(y-r),t},c.start=function(t,r){t===null&&(t=x.slice(0));if(typeof t=="string"&&t.length===16)t=e.util.createBuffer(t);else if(e.util.isArray(t)&&t.length===16){var i=t,t=e.util.createBuffer();for(var s=0;s<16;++s)t.putByte(i[s])}if(!e.util.isArray(t)){var i=t;t=new Array(4),t[0]=i.getInt32(),t[1]=i.getInt32(),t[2]=i.getInt32(),t[3]=i.getInt32()}b=e.util.createBuffer(),w=r||e.util.createBuffer(),x=t.slice(0),E=new Array(n),S=new Array(n),T=!1,c.output=w;if(["CFB","OFB","CTR"].indexOf(u)!==-1){for(var s=0;s=32)return f(),e();var t=32-r.pools[0].messageLength<<5;r.seedFile(t,function(t,n){if(t)return e(t);r.collect(n),f(),e()})}function a(){if(r.pools[0].messageLength>=32)return f();var e=32-r.pools[0].messageLength<<5;r.collect(r.seedFileSync(e)),f()}function f(){var t=e.md.sha1.create();t.update(r.pools[0].digest().getBytes()),r.pools[0].start();var n=1;for(var i=1;i<32;++i)n=n===31?2147483648:n<<2,n%r.reseeds===0&&(t.update(r.pools[i].digest().getBytes()),r.pools[i].start());var s=t.digest().getBytes();t.start(),t.update(s);var o=t.digest().getBytes();r.key=r.plugin.formatKey(s),r.seed=r.plugin.formatSeed(o),++r.reseeds,r.generated=0,r.time=+(new Date)}function l(t){var n=e.util.createBuffer();if(typeof window!="undefined"&&window.crypto&&window.crypto.getRandomValues){var r=new Uint32Array(t/4);try{window.crypto.getRandomValues(r);for(var i=0;i>16),u+=(o&32767)<<16,u+=o>>15,u=(u&2147483647)+(u>>31),f=u&4294967295;for(var i=0;i<3;++i)a=f>>>(i<<3),a^=Math.floor(Math.random()*255),n.putByte(String.fromCharCode(a&255))}}return n.getBytes()}var r={plugin:t,key:null,seed:null,time:null,reseeds:0,generated:0},i=t.md,s=new Array(32);for(var o=0;o<32;++o)s[o]=i.create();return r.pools=s,r.pool=0,r.generate=function(t,n){function l(c){if(c)return n(c);if(f.length()>=t)return n(null,f.getBytes(t));if(r.generated>=1048576){var h=+(new Date);if(r.time===null||h-r.time>100)r.key=null}if(r.key===null)return u(l);var p=i(r.key,r.seed);r.generated+=p.length,f.putBytes(p),r.key=o(i(r.key,s(r.seed))),r.seed=a(i(r.key,r.seed)),e.util.setImmediate(l)}if(!n)return r.generateSync(t);var i=r.plugin.cipher,s=r.plugin.increment,o=r.plugin.formatKey,a=r.plugin.formatSeed,f=e.util.createBuffer();l()},r.generateSync=function(t){var n=r.plugin.cipher,i=r.plugin.increment,s=r.plugin.formatKey,o=r.plugin.formatSeed,u=e.util.createBuffer();while(u.length()=1048576){var f=+(new Date);if(r.time===null||f-r.time>100)r.key=null}r.key===null&&a();var l=n(r.key,r.seed);r.generated+=l.length,u.putBytes(l),r.key=s(n(r.key,i(r.seed))),r.seed=o(n(r.key,r.seed))}return u.getBytes(t)},n?(r.seedFile=function(e,t){n.randomBytes(e,function(e,n){if(e)return t(e);t(null,n.toString())})},r.seedFileSync=function(e){return n.randomBytes(e).toString()}):(r.seedFile=function(e,t){try{t(null,l(e))}catch(n){t(n)}},r.seedFileSync=l),r.collect=function(e){var t=e.length;for(var n=0;n>i&255);r.collect(n)},r.registerWorker=function(e){if(e===self)r.seedFile=function(e,t){function n(e){var r=e.data;r.forge&&r.forge.prng&&(self.removeEventListener("message",n),t(r.forge.prng.err,r.forge.prng.bytes))}self.addEventListener("message",n),self.postMessage({forge:{prng:{needed:e}}})};else{function t(t){var n=t.data;n.forge&&n.forge.prng&&r.seedFile(n.forge.prng.needed,function(t,n){e.postMessage({forge:{prng:{err:t,bytes:n}}})})}e.addEventListener("message",t)}},r}}var t="prng";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o1){var h=r.read,p=r.getByte();if(p===0){s=r.getByte();var d=s&192;if(d===t.Class.UNIVERSAL||d===t.Class.CONTEXT_SPECIFIC)try{var v=n(r);c=v===a-(r.read-h),c&&(++h,--a)}catch(m){}}r.read=h}if(c){f=[];if(a===undefined)for(;;){if(r.bytes(2)===String.fromCharCode(0,0)){r.getBytes(2);break}f.push(t.fromDer(r,i))}else{var g=r.length();while(a>0)f.push(t.fromDer(r,i)),a-=g-r.length(),g=r.length()}}else{if(a===undefined)throw{message:"Non-constructed ASN.1 object of indefinite length."};if(u===t.Type.BMPSTRING){f="";for(var y=0;y>>=8;while(u>0);r.putByte(a.length|128);for(var o=a.length-1;o>=0;--o)r.putByte(a.charCodeAt(o))}return r.putBuffer(s),r},t.oidToDer=function(t){var n=t.split("."),r=e.util.createBuffer();r.putByte(40*parseInt(n[0],10)+parseInt(n[1],10));var i,s,o,u;for(var a=2;a>>=7,i||(u|=128),s.push(u),i=!1;while(o>0);for(var f=s.length-1;f>=0;--f)r.putByte(s[f])}return r},t.derToOid=function(t){var n;typeof t=="string"&&(t=e.util.createBuffer(t));var r=t.getByte();n=Math.floor(r/40)+"."+r%40;var i=0;while(t.length()>0)r=t.getByte(),i<<=7,r&128?i+=r&127:(n+="."+(i+r),i=0);return n},t.utcTimeToDate=function(e){var t=new Date,n=parseInt(e.substr(0,2),10);n=n>=50?1900+n:2e3+n;var r=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),s=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),u=0;if(e.length>11){var a=e.charAt(10),f=10;a!=="+"&&a!=="-"&&(u=parseInt(e.substr(10,2),10),f+=2)}t.setUTCFullYear(n,r,i),t.setUTCHours(s,o,u,0);if(f){a=e.charAt(f);if(a==="+"||a==="-"){var l=parseInt(e.substr(f+1,2),10),c=parseInt(e.substr(f+4,2),10),h=l*60+c;h*=6e4,a==="+"?t.setTime(+t-h):t.setTime(+t+h)}}return t},t.generalizedTimeToDate=function(e){var t=new Date,n=parseInt(e.substr(0,4),10),r=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=parseInt(e.substr(10,2),10),u=parseInt(e.substr(12,2),10),a=0,f=0,l=!1;e.charAt(e.length-1)==="Z"&&(l=!0);var c=e.length-5,h=e.charAt(c);if(h==="+"||h==="-"){var p=parseInt(e.substr(c+1,2),10),d=parseInt(e.substr(c+4,2),10);f=p*60+d,f*=6e4,h==="+"&&(f*=-1),l=!0}return e.charAt(14)==="."&&(a=parseFloat(e.substr(14),10)*1e3),l?(t.setUTCFullYear(n,r,i),t.setUTCHours(s,o,u,a),t.setTime(+t+f)):(t.setFullYear(n,r,i),t.setHours(s,o,u,a)),t},t.dateToUtcTime=function(e){var t="",n=[];n.push((""+e.getUTCFullYear()).substr(2)),n.push(""+(e.getUTCMonth()+1)),n.push(""+e.getUTCDate()),n.push(""+e.getUTCHours()),n.push(""+e.getUTCMinutes()),n.push(""+e.getUTCSeconds());for(var r=0;r0&&(o+="\n");var u="";for(var a=0;a65&&s!==-1){var o=t[s];o===","?(++s,t=t.substr(0,s)+"\r\n "+t.substr(s)):t=t.substr(0,s)+"\r\n"+o+t.substr(s+1),i=r-s-1,s=-1,++r}else if(t[r]===" "||t[r]===" "||t[r]===",")s=r;return t}function r(e){return e.replace(/^\s+/,"")}var t=e.pem=e.pem||{};t.encode=function(t,r){r=r||{};var i="-----BEGIN "+t.type+"-----\r\n",s;t.procType&&(s={name:"Proc-Type",values:[String(t.procType.version),t.procType.type]},i+=n(s)),t.contentDomain&&(s={name:"Content-Domain",values:[t.contentDomain]},i+=n(s)),t.dekInfo&&(s={name:"DEK-Info",values:[t.dekInfo.algorithm]},t.dekInfo.parameters&&s.values.push(t.dekInfo.parameters),i+=n(s));if(t.headers)for(var o=0;o8?3:1,m=[],g=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],y=0,b;for(var w=0;w>>4^S)&252645135,S^=b,E^=b<<4,b=(S>>>-16^E)&65535,E^=b,S^=b<<-16,b=(E>>>2^S)&858993459,S^=b,E^=b<<2,b=(S>>>-16^E)&65535,E^=b,S^=b<<-16,b=(E>>>1^S)&1431655765,S^=b,E^=b<<1,b=(S>>>8^E)&16711935,E^=b,S^=b<<8,b=(E>>>1^S)&1431655765,S^=b,E^=b<<1,b=E<<8|S>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=b;for(var x=0;x>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27),E&=-15,S&=-15;var T=t[E>>>28]|n[E>>>24&15]|r[E>>>20&15]|i[E>>>16&15]|s[E>>>12&15]|o[E>>>8&15]|u[E>>>4&15],N=a[S>>>28]|f[S>>>24&15]|l[S>>>20&15]|c[S>>>16&15]|h[S>>>12&15]|p[S>>>8&15]|d[S>>>4&15];b=(N>>>16^T)&65535,m[y++]=T^b,m[y++]=N^b<<16}}return m}var t=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],n=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],r=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],i=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],s=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],o=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],u=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],a=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696],l=function(l,c){typeof l=="string"&&(l.length===8||l.length===24)&&(l=e.util.createBuffer(l));var h=f(l),p=1,d=0,v=0,m=0,g=0,y=!1,b=null,w=null,E=h.length===32?3:9,S;E===3?S=c?[0,32,2]:[30,-2,-2]:S=c?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2];var x=null;return x={start:function(t,n){t?(typeof t=="string"&&t.length===8&&(t=e.util.createBuffer(t)),p=1,d=t.getInt32(),m=t.getInt32()):p=0,y=!1,b=e.util.createBuffer(),w=n||e.util.createBuffer(),x.output=w},update:function(e){y||b.putBuffer(e);while(b.length()>=8){var f,l=b.getInt32(),x=b.getInt32();p===1&&(c?(l^=d,x^=m):(v=d,g=m,d=l,m=x)),f=(l>>>4^x)&252645135,x^=f,l^=f<<4,f=(l>>>16^x)&65535,x^=f,l^=f<<16,f=(x>>>2^l)&858993459,l^=f,x^=f<<2,f=(x>>>8^l)&16711935,l^=f,x^=f<<8,f=(l>>>1^x)&1431655765,x^=f,l^=f<<1,l=l<<1|l>>>31,x=x<<1|x>>>31;for(var T=0;T>>4|x<<28)^h[k+1];f=l,l=x,x=f^(n[L>>>24&63]|i[L>>>16&63]|o[L>>>8&63]|a[L&63]|t[A>>>24&63]|r[A>>>16&63]|s[A>>>8&63]|u[A&63])}f=l,l=x,x=f}l=l>>>1|l<<31,x=x>>>1|x<<31,f=(l>>>1^x)&1431655765,x^=f,l^=f<<1,f=(x>>>8^l)&16711935,l^=f,x^=f<<8,f=(x>>>2^l)&858993459,l^=f,x^=f<<2,f=(l>>>16^x)&65535,x^=f,l^=f<<16,f=(l>>>4^x)&252645135,x^=f,l^=f<<4,p===1&&(c?(d=l,m=x):(l^=v,x^=g)),w.putInt32(l),w.putInt32(x)}},finish:function(e){var t=!0;if(c)if(e)t=e(8,b,!c);else{var n=b.length()===8?8:8-b.length();b.fillWithByte(n,n)}t&&(y=!0,x.update());if(!c){t=b.length()===0;if(t)if(e)t=e(8,w,!c);else{var r=w.length(),i=w.at(r-1);i>r?t=!1:w.truncate(i)}}return t}},x};e.des=e.des||{},e.des.startEncrypting=function(e,t,n){var r=l(e,!0);return r.start(t,n),r},e.des.createEncryptionCipher=function(e){return l(e,!0)},e.des.startDecrypting=function(e,t,n){var r=l(e,!1);return r.start(t,n),r},e.des.createDecryptionCipher=function(e){return l(e,!1)}}var t="des";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o=0){var o=t*this.data[e++]+n.data[r]+i;i=Math.floor(o/67108864),n.data[r++]=o&67108863}return i}function u(e,t,n,r,i,s){var o=t&32767,u=t>>15;while(--s>=0){var a=this.data[e]&32767,f=this.data[e++]>>15,l=u*a+f*o;a=o*a+((l&32767)<<15)+n.data[r]+(i&1073741823),i=(a>>>30)+(l>>>15)+u*f+(i>>>30),n.data[r++]=a&1073741823}return i}function a(e,t,n,r,i,s){var o=t&16383,u=t>>14;while(--s>=0){var a=this.data[e]&16383,f=this.data[e++]>>14,l=u*a+f*o;a=o*a+((l&16383)<<14)+n.data[r]+i,i=(a>>28)+(l>>14)+u*f,n.data[r++]=a&268435455}return i}function d(e){return l.charAt(e)}function v(e,t){var n=c[e.charCodeAt(t)];return n==null?-1:n}function m(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function g(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+DV:this.t=0}function y(e){var t=s();return t.fromInt(e),t}function b(e,t){var n;if(t==16)n=4;else if(t==8)n=3;else if(t==256)n=8;else if(t==2)n=1;else if(t==32)n=5;else{if(t!=4){this.fromRadix(e,t);return}n=2}this.t=0,this.s=0;var r=e.length,s=!1,o=0;while(--r>=0){var u=n==8?e[r]&255:v(e,r);if(u<0){e.charAt(r)=="-"&&(s=!0);continue}s=!1,o==0?this.data[this.t++]=u:o+n>this.DB?(this.data[this.t-1]|=(u&(1<>this.DB-o):this.data[this.t-1]|=u<=this.DB&&(o-=this.DB)}n==8&&(e[0]&128)!=0&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e)--this.t}function E(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else{if(e!=4)return this.toRadix(e);t=2}var n=(1<0){u>u)>0&&(i=!0,s=d(r));while(o>=0)u>(u+=this.DB-t)):(r=this.data[o]>>(u-=t)&n,u<=0&&(u+=this.DB,--o)),r>0&&(i=!0),i&&(s+=d(r))}return i?s:"0"}function S(){var e=s();return i.ZERO.subTo(this,e),e}function x(){return this.s<0?this.negate():this}function T(e){var t=this.s-e.s;if(t!=0)return t;var n=this.t;t=n-e.t;if(t!=0)return this.s<0?-t:t;while(--n>=0)if((t=this.data[n]-e.data[n])!=0)return t;return 0}function N(e){var t=1,n;return(n=e>>>16)!=0&&(e=n,t+=16),(n=e>>8)!=0&&(e=n,t+=8),(n=e>>4)!=0&&(e=n,t+=4),(n=e>>2)!=0&&(e=n,t+=2),(n=e>>1)!=0&&(e=n,t+=1),t}function C(){return this.t<=0?0:this.DB*(this.t-1)+N(this.data[this.t-1]^this.s&this.DM)}function k(e,t){var n;for(n=this.t-1;n>=0;--n)t.data[n+e]=this.data[n];for(n=e-1;n>=0;--n)t.data[n]=0;t.t=this.t+e,t.s=this.s}function L(e,t){for(var n=e;n=0;--u)t.data[u+s+1]=this.data[u]>>r|o,o=(this.data[u]&i)<=0;--u)t.data[u]=0;t.data[s]=o,t.t=this.t+s+1,t.s=this.s,t.clamp()}function O(e,t){t.s=this.s;var n=Math.floor(e/this.DB);if(n>=this.t){t.t=0;return}var r=e%this.DB,i=this.DB-r,s=(1<>r;for(var o=n+1;o>r;r>0&&(t.data[this.t-n-1]|=(this.s&s)<>=this.DB;if(e.t>=this.DB;r+=this.s}else{r+=this.s;while(n>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t.data[n++]=this.DV+r:r>0&&(t.data[n++]=r),t.t=n,t.clamp()}function _(e,t){var n=this.abs(),r=e.abs(),s=n.t;t.t=s+r.t;while(--s>=0)t.data[s]=0;for(s=0;s=0)e.data[n]=0;for(n=0;n=t.DV&&(e.data[n+t.t]-=t.DV,e.data[n+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(n,t.data[n],e,2*n,0,1)),e.s=0,e.clamp()}function P(e,t,n){var r=e.abs();if(r.t<=0)return;var o=this.abs();if(o.t0?(r.lShiftTo(l,u),o.lShiftTo(l,n)):(r.copyTo(u),o.copyTo(n));var c=u.t,h=u.data[c-1];if(h==0)return;var p=h*(1<1?u.data[c-2]>>this.F2:0),d=this.FV/p,v=(1<=0&&(n.data[n.t++]=1,n.subTo(b,n)),i.ONE.dlShiftTo(c,b),b.subTo(u,u);while(u.t=0){var w=n.data[--g]==h?this.DM:Math.floor(n.data[g]*d+(n.data[g-1]+m)*v);if((n.data[g]+=u.am(0,w,n,y,0,c))0&&n.rShiftTo(l,n),a<0&&i.ZERO.subTo(n,n)}function H(e){var t=s();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(i.ZERO)>0&&e.subTo(t,t),t}function B(e){this.m=e}function j(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function F(e){return e}function I(e){e.divRemTo(this.m,null,e)}function q(e,t,n){e.multiplyTo(t,n),this.reduce(n)}function R(e,t){e.squareTo(t),this.reduce(t)}function U(){if(this.t<1)return 0;var e=this.data[0];if((e&1)==0)return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function z(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(t,t),t}function X(e){var t=s();return e.copyTo(t),this.reduce(t),t}function V(e){while(e.t<=this.mt2)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;n=t+this.m.t,e.data[n]+=this.m.am(0,r,e,t,0,this.m.t);while(e.data[n]>=e.DV)e.data[n]-=e.DV,e.data[++n]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function $(e,t){e.squareTo(t),this.reduce(t)}function J(e,t,n){e.multiplyTo(t,n),this.reduce(n)}function K(){return(this.t>0?this.data[0]&1:this.s)==0}function Q(e,t){if(e>4294967295||e<1)return i.ONE;var n=s(),r=s(),o=t.convert(this),u=N(e)-1;o.copyTo(n);while(--u>=0){t.sqrTo(n,r);if((e&1<0)t.mulTo(r,o,n);else{var a=n;n=r,r=a}}return t.revert(n)}function G(e,t){var n;return e<256||t.isEven()?n=new B(t):n=new z(t),this.exp(e,n)}function Y(){var e=s();return this.copyTo(e),e}function Z(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function tt(){return this.t==0?this.s:this.data[0]<<16>>16}function nt(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function rt(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function it(e){e==null&&(e=10);if(this.signum()==0||e<2||e>36)return"0";var t=this.chunkSize(e),n=Math.pow(e,t),r=y(n),i=s(),o=s(),u="";this.divRemTo(r,i,o);while(i.signum()>0)u=(n+o.intValue()).toString(e).substr(1)+u,i.divRemTo(r,i,o);return o.intValue().toString(e)+u}function st(e,t){this.fromInt(0),t==null&&(t=10);var n=this.chunkSize(t),r=Math.pow(t,n),s=!1,o=0,u=0;for(var a=0;a=n&&(this.dMultiply(r),this.dAddOffset(u,0),o=0,u=0)}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(u,0)),s&&i.ZERO.subTo(this,this)}function ot(e,t,n){if("number"==typeof t)if(e<2)this.fromInt(1);else{this.fromNumber(e,n),this.testBit(e-1)||this.bitwiseTo(i.ONE.shiftLeft(e-1),dt,this),this.isEven()&&this.dAddOffset(1,0);while(!this.isProbablePrime(t))this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(i.ONE.shiftLeft(e-1),this)}else{var r=new Array,s=e&7;r.length=(e>>3)+1,t.nextBytes(r),s>0?r[0]&=(1<0){n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0){n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),(r&128)!=0&&(r|=-256),i==0&&(this.s&128)!=(r&128)&&++i;if(i>0||r!=this.s)t[i++]=r}}return t}function at(e){return this.compareTo(e)==0}function ft(e){return this.compareTo(e)<0?this:e}function lt(e){return this.compareTo(e)>0?this:e}function ct(e,t,n){var r,i,s=Math.min(e.t,this.t);for(r=0;r>=16,t+=16),(e&255)==0&&(e>>=8,t+=8),(e&15)==0&&(e>>=4,t+=4),(e&3)==0&&(e>>=2,t+=2),(e&1)==0&&++t,t}function Tt(){for(var e=0;e=this.t?this.s!=0:(this.data[t]&1<>=this.DB;if(e.t>=this.DB;r+=this.s}else{r+=this.s;while(n>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t.data[n++]=r:r<-1&&(t.data[n++]=this.DV+r),t.t=n,t.clamp()}function Dt(e){var t=s();return this.addTo(e,t),t}function Pt(e){var t=s();return this.subTo(e,t),t}function Ht(e){var t=s();return this.multiplyTo(e,t),t}function Bt(e){var t=s();return this.divRemTo(e,t,null),t}function jt(e){var t=s();return this.divRemTo(e,null,t),t}function Ft(e){var t=s(),n=s();return this.divRemTo(e,t,n),new Array(t,n)}function It(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function qt(e,t){if(e==0)return;while(this.t<=t)this.data[this.t++]=0;this.data[t]+=e;while(this.data[t]>=this.DV)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}function Rt(){}function Ut(e){return e}function zt(e,t,n){e.multiplyTo(t,n)}function Wt(e,t){e.squareTo(t)}function Xt(e){return this.exp(e,new Rt)}function Vt(e,t,n){var r=Math.min(this.t+e.t,t);n.s=0,n.t=r;while(r>0)n.data[--r]=0;var i;for(i=n.t-this.t;r=0)n.data[r]=0;for(r=Math.max(t-this.t,0);r2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=s();return e.copyTo(t),this.reduce(t),t}function Qt(e){return e}function Gt(e){e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(e.compareTo(this.r2)<0)e.dAddOffset(1,this.m.t+1);e.subTo(this.r2,e);while(e.compareTo(this.m)>=0)e.subTo(this.m,e)}function Yt(e,t){e.squareTo(t),this.reduce(t)}function Zt(e,t,n){e.multiplyTo(t,n),this.reduce(n)}function en(e,t){var n=e.bitLength(),r,i=y(1),o;if(n<=0)return i;n<18?r=1:n<48?r=3:n<144?r=4:n<768?r=5:r=6,n<8?o=new B(t):t.isEven()?o=new Jt(t):o=new z(t);var u=new Array,a=3,f=r-1,l=(1<1){var c=s();o.sqrTo(u[1],c);while(a<=l)u[a]=s(),o.mulTo(c,u[a-2],u[a]),a+=2}var h=e.t-1,p,d=!0,v=s(),m;n=N(e.data[h])-1;while(h>=0){n>=f?p=e.data[h]>>n-f&l:(p=(e.data[h]&(1<0&&(p|=e.data[h-1]>>this.DB+n-f)),a=r;while((p&1)==0)p>>=1,--a;(n-=a)<0&&(n+=this.DB,--h);if(d)u[p].copyTo(i),d=!1;else{while(a>1)o.sqrTo(i,v),o.sqrTo(v,i),a-=2;a>0?o.sqrTo(i,v):(m=i,i=v,v=m),o.mulTo(v,u[p],i)}while(h>=0&&(e.data[h]&1<0&&(t.rShiftTo(s,t),n.rShiftTo(s,n));while(t.signum()>0)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=n.getLowestSetBit())>0&&n.rShiftTo(i,n),t.compareTo(n)>=0?(t.subTo(n,t),t.rShiftTo(1,t)):(n.subTo(t,n),n.rShiftTo(1,n));return s>0&&n.lShiftTo(s,n),n}function nn(e){if(e<=0)return 0;var t=this.DV%e,n=this.s<0?e-1:0;if(this.t>0)if(t==0)n=this.data[0]%e;else for(var r=this.t-1;r>=0;--r)n=(t*n+this.data[r])%e;return n}function rn(e){var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return i.ZERO;var n=e.clone(),r=this.clone(),s=y(1),o=y(0),u=y(0),a=y(1);while(n.signum()!=0){while(n.isEven()){n.rShiftTo(1,n);if(t){if(!s.isEven()||!o.isEven())s.addTo(this,s),o.subTo(e,o);s.rShiftTo(1,s)}else o.isEven()||o.subTo(e,o);o.rShiftTo(1,o)}while(r.isEven()){r.rShiftTo(1,r);if(t){if(!u.isEven()||!a.isEven())u.addTo(this,u),a.subTo(e,a);u.rShiftTo(1,u)}else a.isEven()||a.subTo(e,a);a.rShiftTo(1,a)}n.compareTo(r)>=0?(n.subTo(r,n),t&&s.subTo(u,s),o.subTo(a,o)):(r.subTo(n,r),t&&u.subTo(s,u),a.subTo(o,a))}return r.compareTo(i.ONE)!=0?i.ZERO:a.compareTo(e)>=0?a.subtract(e):a.signum()<0?(a.addTo(e,a),a.signum()<0?a.add(e):a):a}function un(e){var t,n=this.abs();if(n.t==1&&n.data[0]<=sn[sn.length-1]){for(t=0;t>1,e>sn.length&&(e=sn.length);var o=s();for(var u=0;u=0&&i.push(u)}return i}function l(e,r,s,o){r=t.fromDer(r,s);if(r.tagClass!==t.Class.UNIVERSAL||r.type!==t.Type.SEQUENCE||r.constructed!==!0)throw{message:"PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo"};for(var u=0;u0&&(f=t.create(t.Class.UNIVERSAL,t.Type.SET,!0,h));var p=[],d=[];s!==null&&(e.util.isArray(s)?d=s:d=[s]);var v=[];for(var m=0;m0){var w=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,v),E=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(n.oids.data).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,t.toDer(w).getBytes())])]);p.push(E)}var S=null;if(i!==null){var x=n.wrapRsaPrivateKey(n.privateKeyToAsn1(i));o===null?S=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(n.oids.keyBag).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[x]),f]):S=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(n.oids.pkcs8ShroudedKeyBag).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[n.encryptPrivateKeyInfo(x,o,u)]),f]);var T=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[S]),N=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(n.oids.data).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,t.toDer(T).getBytes())])]);p.push(N)}var C=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,p),k=undefined;if(u.useMac){var c=e.md.sha1.create(),L=new e.util.ByteBuffer(e.random.getBytes(u.saltSize)),A=u.count,i=r.generateKey(o||"",L,3,A,20),O=e.hmac.create();O.start(c,i),O.update(t.toDer(C).getBytes());var M=O.getMac();k=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(n.oids.sha1).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")]),t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,M.getBytes())]),t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,L.getBytes()),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,e.util.hexToBytes(A.toString(16)))])}return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,String.fromCharCode(3)),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(n.oids.data).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,t.toDer(C).getBytes())])]),k])},r.generateKey=function(t,n,r,i,s,o){var u,a;if(typeof o=="undefined"||o===null)o=e.md.sha1.create();var f=o.digestLength,l=o.blockLength,c=new e.util.ByteBuffer,h=new e.util.ByteBuffer;for(a=0;a=0;a--)A>>=8,A+=N.at(a)+L.at(a),L.setAt(a,A&255);k.putBuffer(L)}w=k,c.putBuffer(x)}return c.truncate(c.length()-s),c}}var t="pkcs12";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o>8*l-f&255;if((h.charCodeAt(0)&d)!==0)throw{message:"Bits beyond keysize not zero as expected."};var v=n.generate(p,c),m="";for(a=0;a>8*f-a&255;return y=String.fromCharCode(y.charCodeAt(0)&~b)+y.substr(1),y+p+String.fromCharCode(188)},s}}var t="pss";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o>16-t},i=function(e,t){return(e&65535)>>t|e<<16-t&65535};e.rc2=e.rc2||{},e.rc2.expandKey=function(n,r){typeof n=="string"&&(n=e.util.createBuffer(n)),r=r||128;var i=n,s=n.length(),o=r,u=Math.ceil(o/8),a=255>>(o&7),f;for(f=s;f<128;f++)i.putByte(t[i.at(f-1)+i.at(f-s)&255]);i.setAt(128-u,t[i.at(128-u)&a]);for(f=127-u;f>=0;f--)i.setAt(f,t[i.at(f+1)^i.at(f+u)]);return i};var s=function(t,s,o){var u=!1,a=null,f=null,l=null,c,h,p,d,v=[];t=e.rc2.expandKey(t,s);for(p=0;p<64;p++)v.push(t.getInt16Le());o?(c=function(e){for(p=0;p<4;p++)e[p]+=v[d]+(e[(p+3)%4]&e[(p+2)%4])+(~e[(p+3)%4]&e[(p+1)%4]),e[p]=r(e[p],n[p]),d++},h=function(e){for(p=0;p<4;p++)e[p]+=v[e[(p+3)%4]&63]}):(c=function(e){for(p=3;p>=0;p--)e[p]=i(e[p],n[p]),e[p]-=v[d]+(e[(p+3)%4]&e[(p+2)%4])+(~e[(p+3)%4]&e[(p+1)%4]),d--},h=function(e){for(p=3;p>=0;p--)e[p]-=v[e[(p+3)%4]&63]});var m=function(e){var t=[];for(p=0;p<4;p++){var n=a.getInt16Le();l!==null&&(o?n^=l.getInt16Le():l.putInt16Le(n)),t.push(n&65535)}d=o?0:63;for(var r=0;r=8)m([[5,c],[1,h],[6,c],[1,h],[5,c]])},finish:function(e){var t=!0;if(o)if(e)t=e(8,a,!o);else{var n=a.length()===8?8:8-a.length();a.fillWithByte(n,n)}t&&(u=!0,g.update());if(!o){t=a.length()===0;if(t)if(e)t=e(8,f,!o);else{var r=f.length(),i=f.at(r-1);i>r?t=!1:f.truncate(i)}}return t}},g};e.rc2.startEncrypting=function(t,n,r){var i=e.rc2.createEncryptionCipher(t,128);return i.start(n,r),i},e.rc2.createEncryptionCipher=function(e,t){return s(e,t,!0)},e.rc2.startDecrypting=function(t,n,r){var i=e.rc2.createDecryptionCipher(t,128);return i.start(n,r),i},e.rc2.createDecryptionCipher=function(e,t){return s(e,t,!1)}}var t="rc2";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o>24&255,s>>16&255,s>>8&255,s&255);n.start(),n.update(e+o),r+=n.digest().getBytes()}return r.substring(0,t)}var t=e.pkcs1=e.pkcs1||{};t.encode_rsa_oaep=function(t,r,i){var s=undefined,o=undefined,u=undefined;typeof i=="string"?(s=i,o=arguments[3]||undefined,u=arguments[4]||undefined):i&&(s=i.label||undefined,o=i.seed||undefined,u=i.md||undefined),u?u.start():u=e.md.sha1.create();var a=Math.ceil(t.n.bitLength()/8),f=a-2*u.digestLength-2;if(r.length>f)throw{message:"RSAES-OAEP input message length is too long.",length:r.length,maxLength:f};s||(s=""),u.update(s,"raw");var l=u.digest(),c="",h=f-r.length;for(var p=0;ps-11)throw{message:"Message is too long for PKCS#1 v1.5 padding.",length:t.length,max:s-11};i.putByte(0),i.putByte(r);var o=s-3-t.length,u;if(r===0||r===1){u=r===0?0:255;for(var a=0;a1){if(o.getByte()!==255){--o.read;break}++f}}else if(a===2){f=0;while(o.length()>1){if(o.getByte()===0){--o.read;break}++f}}var c=o.getByte();if(c!==0||f!==s-3-o.length())throw{message:"Encryption block is invalid."};return o.getBytes()}function a(t,n,r){function c(){h(t.pBits,function(e,n){if(e)return r(e);t.p=n,h(t.qBits,p)})}function h(e,n){function p(){var n=e-1,r=new BigInteger(e,t.rng);return r.testBit(n)||r.bitwiseTo(BigInteger.ONE.shiftLeft(n),l,r),r.dAddOffset(31-r.mod(f).byteValue(),0),r}function v(i){if(d)return;--c;var s=i.data;if(s.found){for(var a=0;ae&&(h=p());var f=h.toString(16);i.target.postMessage({e:t.eInt,hex:f,workLoad:o}),h.dAddOffset(u,0)}var r=[];for(var i=0;i0)h.putByte(0),--p;return h.putBytes(e.util.hexToBytes(c)),h.getBytes()},n.rsa.decrypt=function(t,n,r,i){var o=Math.ceil(n.n.bitLength()/8);if(t.length!==o)throw{message:"Encrypted message length is invalid.",length:t.length,expected:o};var a=new BigInteger(e.util.createBuffer(t).toHex(),16);if(a.compareTo(n.n)>=0)throw{message:"Encrypted message is invalid."};var f=s(a,n,r),l=f.toString(16),c=e.util.createBuffer(),h=o-Math.ceil(l.length/2);while(h>0)c.putByte(0),--h;return c.putBytes(e.util.hexToBytes(l)),i!==!1?u(c.getBytes(),n,r):c.getBytes()},n.rsa.createKeyPairGenerationState=function(t,n){typeof t=="string"&&(t=parseInt(t,10)),t=t||1024;var r={nextBytes:function(t){var n=e.random.getBytes(t.length);for(var r=0;r>1,pBits:t-(t>>1),pqState:0,num:null,keys:null};return i.e.fromInt(i.eInt),i},n.rsa.stepKeyPairGenerationState=function(t,n){var i=new BigInteger(null);i.fromInt(30);var s=0,o=function(e,t){return e|t},u=+(new Date),a,f=0;while(t.keys===null&&(n<=0||fl?t.pqState=0:t.num.isProbablePrime(1)?++t.pqState:t.num.dAddOffset(r[s++%8],0):t.pqState===2?t.pqState=t.num.subtract(BigInteger.ONE).gcd(t.e).compareTo(BigInteger.ONE)===0?3:0:t.pqState===3&&(t.pqState=0,t.num.isProbablePrime(10)&&(t.p===null?t.p=t.num:t.q=t.num,t.p!==null&&t.q!==null&&++t.state),t.num=null)}else if(t.state===1)t.p.compareTo(t.q)<0&&(t.num=t.p,t.p=t.q,t.q=t.num),++t.state;else if(t.state===2)t.p1=t.p.subtract(BigInteger.ONE),t.q1=t.q.subtract(BigInteger.ONE),t.phi=t.p1.multiply(t.q1),++t.state;else if(t.state===3)t.phi.gcd(t.e).compareTo(BigInteger.ONE)===0?++t.state:(t.p=null,t.q=null,t.state=0);else if(t.state===4)t.n=t.p.multiply(t.q),t.n.bitLength()===t.bits?++t.state:(t.q=null,t.state=0);else if(t.state===5){var h=t.e.modInverse(t.phi);t.keys={privateKey:e.pki.rsa.setPrivateKey(t.n,t.e,h,t.p,t.q,h.mod(t.p1),h.mod(t.q1),t.q.modInverse(t.p)),publicKey:e.pki.rsa.setPublicKey(t.n,t.e)}}a=+(new Date),f+=a-u,u=a}return t.keys!==null},n.rsa.generateKeyPair=function(e,t,r,i){arguments.length===1?typeof e=="object"?(r=e,e=undefined):typeof e=="function"&&(i=e,e=undefined):arguments.length===2?(typeof e=="number"?typeof t=="function"?i=t:r=t:(r=e,i=t,e=undefined),t=undefined):arguments.length===3&&(typeof t=="number"?typeof r=="function"&&(i=r,r=undefined):(i=r,r=t,t=undefined)),r=r||{},e===undefined&&(e=r.bits||1024),t===undefined&&(t=r.e||65537);var s=n.rsa.createKeyPairGenerationState(e,t);if(!i)return n.rsa.stepKeyPairGenerationState(s,0),s.keys;a(s,r,i)},n.rsa.setPublicKey=function(r,i){var s={n:r,e:i};return s.encrypt=function(t,r,i){typeof r=="string"?r=r.toUpperCase():r===undefined&&(r="RSAES-PKCS1-V1_5");if(r==="RSAES-PKCS1-V1_5")r={encode:function(e,t,n){return o(e,t,2).getBytes()}};else if(r==="RSA-OAEP"||r==="RSAES-OAEP")r={encode:function(t,n){return e.pkcs1.encode_rsa_oaep(n,t,i)}};else{if(["RAW","NONE","NULL",null].indexOf(r)===-1)throw{message:'Unsupported encryption scheme: "'+r+'".'};r={encode:function(e){return e}}}var u=r.encode(t,s,!0);return n.rsa.encrypt(u,s,!0)},s.verify=function(e,r,i){typeof i=="string"?i=i.toUpperCase():i===undefined&&(i="RSASSA-PKCS1-V1_5");if(i==="RSASSA-PKCS1-V1_5")i={verify:function(e,n){n=u(n,s,!0);var r=t.fromDer(n);return e===r.value[1].value}};else if(i==="NONE"||i==="NULL"||i===null)i={verify:function(e,t){return t=u(t,s,!0),e===t}};var o=n.rsa.decrypt(r,s,!0,!1);return i.verify(e,o,s.n.bitLength())},s},n.rsa.setPrivateKey=function(t,r,s,o,a,f,l,c){var h={n:t,e:r,d:s,p:o,q:a,dP:f,dQ:l,qInv:c};return h.decrypt=function(t,r,i){typeof r=="string"?r=r.toUpperCase():r===undefined&&(r="RSAES-PKCS1-V1_5");var s=n.rsa.decrypt(t,h,!1,!1);if(r==="RSAES-PKCS1-V1_5")r={decode:u};else if(r==="RSA-OAEP"||r==="RSAES-OAEP")r={decode:function(t,n){return e.pkcs1.decode_rsa_oaep(n,t,i)}};else{if(["RAW","NONE","NULL",null].indexOf(r)===-1)throw{message:'Unsupported encryption scheme: "'+r+'".'};r={decode:function(e){return e}}}return r.decode(s,h,!1)},h.sign=function(e,t){var r=!1;typeof t=="string"&&(t=t.toUpperCase());if(t===undefined||t==="RSASSA-PKCS1-V1_5")t={encode:i},r=1;else if(t==="NONE"||t==="NULL"||t===null)t={encode:function(){return e}},r=1;var s=t.encode(e,h.n.bitLength());return n.rsa.encrypt(s,h,r)},h}}var t="rsa";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o1&&(c=l.value.charCodeAt(1),h=l.value.length>2?l.value.charCodeAt(2):0),s.digitalSignature=(c&128)===128,s.nonRepudiation=(c&64)===64,s.keyEncipherment=(c&32)===32,s.dataEncipherment=(c&16)===16,s.keyAgreement=(c&8)===8,s.keyCertSign=(c&4)===4,s.cRLSign=(c&2)===2,s.encipherOnly=(c&1)===1,s.decipherOnly=(h&128)===128}else if(s.name==="basicConstraints"){var l=t.fromDer(s.value);l.value.length>0?s.cA=l.value[0].value.charCodeAt(0)!==0:s.cA=!1;if(l.value.length>1){var p=e.util.createBuffer(l.value[1].value);s.pathLenConstraint=p.getInt(p.length()<<3)}}else if(s.name==="extKeyUsage"){var l=t.fromDer(s.value);for(var d=0;d1&&(c=l.value.charCodeAt(1)),s.client=(c&128)===128,s.server=(c&64)===64,s.email=(c&32)===32,s.objsign=(c&16)===16,s.reserved=(c&8)===8,s.sslCA=(c&4)===4,s.emailCA=(c&2)===2,s.objCA=(c&1)===1}else if(s.name==="subjectAltName"||s.name==="issuerAltName"){s.altNames=[];var m,l=t.fromDer(s.value);for(var g=0;g="8"&&(n="00"+n),e.util.hexToBytes(n)},b=function(e,n,i){var s={};if(e!==r["RSASSA-PSS"])return s;i&&(s={hash:{algorithmOid:r.sha1},mgf:{algorithmOid:r.mgf1,hash:{algorithmOid:r.sha1}},saltLength:20});var o={},u=[];if(!t.validate(n,p,o,u))throw{message:"Cannot read RSASSA-PSS parameter block.",errors:u};return o.hashOid!==undefined&&(s.hash=s.hash||{},s.hash.algorithmOid=t.derToOid(o.hashOid)),o.maskGenOid!==undefined&&(s.mgf=s.mgf||{},s.mgf.algorithmOid=t.derToOid(o.maskGenOid),s.mgf.hash=s.mgf.hash||{},s.mgf.hash.algorithmOid=t.derToOid(o.maskGenHashOid)),o.saltLength!==undefined&&(s.saltLength=o.saltLength.charCodeAt(0)),s};n.certificateFromPem=function(r,i,s){var o=e.pem.decode(r)[0];if(o.type!=="CERTIFICATE"&&o.type!=="X509 CERTIFICATE"&&o.type!=="TRUSTED CERTIFICATE")throw{message:'Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".',headerType:o.type};if(o.procType&&o.procType.type==="ENCRYPTED")throw{message:"Could not convert certificate from PEM; PEM is encrypted."};var u=t.fromDer(o.body,s);return n.certificateFromAsn1(u,i)},n.certificateToPem=function(r,i){var s={type:"CERTIFICATE",body:t.toDer(n.certificateToAsn1(r)).getBytes()};return e.pem.encode(s,{maxline:i})},n.publicKeyFromPem=function(r){var i=e.pem.decode(r)[0];if(i.type!=="PUBLIC KEY"&&i.type!=="RSA PUBLIC KEY")throw{message:'Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".',headerType:i.type};if(i.procType&&i.procType.type==="ENCRYPTED")throw{message:"Could not convert public key from PEM; PEM is encrypted."};var s=t.fromDer(i.body);return n.publicKeyFromAsn1(s)},n.publicKeyToPem=function(r,i){var s={type:"PUBLIC KEY",body:t.toDer(n.publicKeyToAsn1(r)).getBytes()};return e.pem.encode(s,{maxline:i})},n.publicKeyToRSAPublicKeyPem=function(r,i){var s={type:"RSA PUBLIC KEY",body:t.toDer(n.publicKeyToRSAPublicKey(r)).getBytes()};return e.pem.encode(s,{maxline:i})},n.privateKeyFromPem=function(r){var i=e.pem.decode(r)[0];if(i.type!=="PRIVATE KEY"&&i.type!=="RSA PRIVATE KEY")throw{message:'Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".',headerType:i.type};if(i.procType&&i.procType.type==="ENCRYPTED")throw{message:"Could not convert private key from PEM; PEM is encrypted."};var s=t.fromDer(i.body);return n.privateKeyFromAsn1(s)},n.privateKeyToPem=function(r,i){var s={type:"RSA PRIVATE KEY",body:t.toDer(n.privateKeyToAsn1(r)).getBytes()};return e.pem.encode(s,{maxline:i})},n.certificationRequestFromPem=function(r,i,s){var o=e.pem.decode(r)[0];if(o.type!=="CERTIFICATE REQUEST")throw{message:'Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".',headerType:o.type};if(o.procType&&o.procType.type==="ENCRYPTED")throw{message:"Could not convert certification request from PEM; PEM is encrypted."};var u=t.fromDer(o.body,s);return n.certificationRequestFromAsn1(u,i)},n.certificationRequestToPem=function(r,i){var s={type:"CERTIFICATE REQUEST",body:t.toDer(n.certificationRequestToAsn1(r)).getBytes()};return e.pem.encode(s,{maxline:i})},n.createCertificate=function(){var s={};s.version=2,s.serialNumber="00",s.signatureOid=null,s.signature=null,s.siginfo={},s.siginfo.algorithmOid=null,s.validity={},s.validity.notBefore=new Date,s.validity.notAfter=new Date,s.issuer={},s.issuer.getField=function(e){return m(s.issuer,e)},s.issuer.addField=function(e){o([e]),s.issuer.attributes.push(e)},s.issuer.attributes=[],s.issuer.hash=null,s.subject={},s.subject.getField=function(e){return m(s.subject,e)},s.subject.addField=function(e){o([e]),s.subject.attributes.push(e)},s.subject.attributes=[],s.subject.hash=null,s.extensions=[],s.publicKey=null,s.md=null;var o=function(e){var t;for(var r=0;r2)throw{message:"Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate."};if(v.length<2)throw{message:"Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime."};h.validity.notBefore=v[0],h.validity.notAfter=v[1],h.tbsCertificate=o.tbsCertificate;if(s){h.md=null;if(h.signatureOid in r){var c=r[h.signatureOid];switch(c){case"sha1WithRSAEncryption":h.md=e.md.sha1.create();break;case"md5WithRSAEncryption":h.md=e.md.md5.create();break;case"sha256WithRSAEncryption":h.md=e.md.sha256.create();break;case"RSASSA-PSS":h.md=e.md.sha256.create()}}if(h.md===null)throw{message:"Could not compute certificate digest. Unknown signature OID.",signatureOid:h.signatureOid};var y=t.toDer(h.tbsCertificate);h.md.update(y.getBytes())}var w=e.md.sha1.create();h.issuer.getField=function(e){return m(h.issuer,e)},h.issuer.addField=function(e){_fillMissingFields([e]),h.issuer.attributes.push(e)},h.issuer.attributes=n.RDNAttributesAsArray(o.certIssuer,w),o.certIssuerUniqueId&&(h.issuer.uniqueId=o.certIssuerUniqueId),h.issuer.hash=w.digest().toHex();var E=e.md.sha1.create();return h.subject.getField=function(e){return m(h.subject,e)},h.subject.addField=function(e){_fillMissingFields([e]),h.subject.attributes.push(e)},h.subject.attributes=n.RDNAttributesAsArray(o.certSubject,E),o.certSubjectUniqueId&&(h.subject.uniqueId=o.certSubjectUniqueId),h.subject.hash=E.digest().toHex(),o.certExtensions?h.extensions=g(o.certExtensions):h.extensions=[],h.publicKey=n.publicKeyFromAsn1(o.subjectPublicKeyInfo),h},n.certificationRequestFromAsn1=function(i,s){var o={},u=[];if(!t.validate(i,v,o,u))throw{message:"Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.",errors:u};if(typeof o.csrSignature!="string"){var a="\0";for(var f=0;f0&&i.value.push(E(r.extensions)),i},n.getCertificationRequestInfo=function(e){var r=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,String.fromCharCode(e.version)),w(e.subject),n.publicKeyToAsn1(e.publicKey),x(e)]);return r},n.distinguishedNameToAsn1=function(e){return w(e)},n.certificateToAsn1=function(e){var r=e.tbsCertificate||n.getTBSCertificate(e);return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[r,t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(e.signatureOid).getBytes()),S(e.signatureOid,e.signatureParameters)]),t.create(t.Class.UNIVERSAL,t.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},n.certificationRequestToAsn1=function(e){var r=e.certificationRequestInfo||n.getCertificationRequestInfo(e);return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[r,t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(e.signatureOid).getBytes()),S(e.signatureOid,e.signatureParameters)]),t.create(t.Class.UNIVERSAL,t.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},n.createCaStore=function(t){var r={certs:{}};r.getIssuer=function(t){var i=null;if(!t.issuer.hash){var s=e.md.sha1.create();t.issuer.attributes=n.RDNAttributesAsArray(w(t.issuer),s),t.issuer.hash=s.digest().toHex()}if(t.issuer.hash in r.certs){i=r.certs[t.issuer.hash];if(e.util.isArray(i))throw{message:"Resolving multiple issuer matches not implemented yet."}}return i},r.addCertificate=function(t){typeof t=="string"&&(t=e.pki.certificateFromPem(t));if(!t.subject.hash){var i=e.md.sha1.create();t.subject.attributes=n.RDNAttributesAsArray(w(t.subject),i),t.subject.hash=i.digest().toHex()}if(t.subject.hash in r.certs){var s=r.certs[t.subject.hash];e.util.isArray(s)||(s=[s]),s.push(t)}else r.certs[t.subject.hash]=t};if(t)for(var i=0;ic.validity.notAfter)a={message:"Certificate is not valid yet or has expired.",error:n.certificateError.certificate_expired,notBefore:c.validity.notBefore,notAfter:c.validity.notAfter,now:o};else{var h=!1;if(r.length>0){l=r[0];try{h=l.verify(c)}catch(p){}}else{var d=t.getIssuer(c);if(d===null)a={message:"Certificate is not trusted.",error:n.certificateError.unknown_ca};else{e.util.isArray(d)||(d=[d]);while(!h&&d.length>0){l=d.shift();try{h=l.verify(c)}catch(p){}}}}a===null&&!h&&(a={message:"Certificate signature is invalid.",error:n.certificateError.bad_certificate})}a===null&&!c.isIssuer(l)&&(a={message:"Certificate issuer is invalid.",error:n.certificateError.bad_certificate});if(a===null){var v={keyUsage:!0,basicConstraints:!0};for(var m=0;a===null&&m0);return!0},n.publicKeyFromAsn1=function(r){var i={},u=[];if(t.validate(r,s,i,u)){var a=t.derToOid(i.publicKeyOid);if(a!==n.oids.rsaEncryption)throw{message:"Cannot read public key. Unknown OID.",oid:a};r=i.rsaPublicKey}u=[];if(!t.validate(r,o,i,u))throw{message:"Cannot read public key. ASN.1 object does not contain an RSAPublicKey.",errors:u};var f=e.util.createBuffer(i.publicKeyModulus).toHex(),l=e.util.createBuffer(i.publicKeyExponent).toHex();return n.setRsaPublicKey(new BigInteger(f,16),new BigInteger(l,16))},n.publicKeyToAsn1=n.publicKeyToSubjectPublicKeyInfo=function(e){return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(n.oids.rsaEncryption).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")]),t.create(t.Class.UNIVERSAL,t.Type.BITSTRING,!1,[n.publicKeyToRSAPublicKey(e)])])},n.publicKeyToRSAPublicKey=function(e){return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.n)),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.e))])},n.privateKeyFromAsn1=function(r){var i={},s=[];t.validate(r,a,i,s)&&(r=t.fromDer(e.util.createBuffer(i.privateKey))),i={},s=[];if(!t.validate(r,f,i,s))throw{message:"Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.",errors:s};var o,u,l,c,h,p,d,v;return o=e.util.createBuffer(i.privateKeyModulus).toHex(),u=e.util.createBuffer(i.privateKeyPublicExponent).toHex(),l=e.util.createBuffer(i.privateKeyPrivateExponent).toHex(),c=e.util.createBuffer(i.privateKeyPrime1).toHex(),h=e.util.createBuffer(i.privateKeyPrime2).toHex(),p=e.util.createBuffer(i.privateKeyExponent1).toHex(),d=e.util.createBuffer(i.privateKeyExponent2).toHex(),v=e.util.createBuffer(i.privateKeyCoefficient).toHex(),n.setRsaPrivateKey(new BigInteger(o,16),new BigInteger(u,16),new BigInteger(l,16),new BigInteger(c,16),new BigInteger(h,16),new BigInteger(p,16),new BigInteger(d,16),new BigInteger(v,16))},n.privateKeyToAsn1=n.privateKeyToRSAPrivateKey=function(e){return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,String.fromCharCode(0)),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.n)),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.e)),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.d)),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.p)),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.q)),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.dP)),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.dQ)),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,y(e.qInv))])},n.wrapRsaPrivateKey=function(e){return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,"\0"),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(r.rsaEncryption).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")]),t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,t.toDer(e).getBytes())])},n.encryptPrivateKeyInfo=function(n,i,s){s=s||{},s.saltSize=s.saltSize||8,s.count=s.count||2048,s.algorithm=s.algorithm||"aes128";var o=e.random.getBytes(s.saltSize),u=s.count,a=e.util.createBuffer();a.putInt16(u);var f,l,c;if(s.algorithm.indexOf("aes")===0){var h;if(s.algorithm==="aes128")f=16,h=r["aes128-CBC"];else if(s.algorithm==="aes192")f=24,h=r["aes192-CBC"];else{if(s.algorithm!=="aes256")throw{message:"Cannot encrypt private key. Unknown encryption algorithm.",algorithm:s.algorithm};f=32,h=r["aes256-CBC"]}var p=e.pkcs5.pbkdf2(i,o,u,f),d=e.random.getBytes(16),v=e.aes.createEncryptionCipher(p);v.start(d),v.update(t.toDer(n)),v.finish(),c=v.output.getBytes(),l=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(r.pkcs5PBES2).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(r.pkcs5PBKDF2).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,o),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,a.getBytes())])]),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(h).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,d)])])])}else{if(s.algorithm!=="3des")throw{message:"Cannot encrypt private key. Unknown encryption algorithm.",algorithm:s.algorithm};f=24;var m=new e.util.ByteBuffer(o),p=e.pkcs12.generateKey(i,m,1,u,f),d=e.pkcs12.generateKey(i,m,2,u,f),v=e.des.createEncryptionCipher(p);v.start(d),v.update(t.toDer(n)),v.finish(),c=v.output.getBytes(),l=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(r["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,o),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,a.getBytes())])])}var g=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[l,t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,c)]);return g},n.pbe.getCipherForPBES2=function(r,i,s){var o={},u=[];if(!t.validate(i,c,o,u))throw{message:"Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.",errors:u};r=t.derToOid(o.kdfOid);if(r!==n.oids.pkcs5PBKDF2)throw{message:"Cannot read encrypted private key. Unsupported key derivation function OID.",oid:r,supportedOids:["pkcs5PBKDF2"]};r=t.derToOid(o.encOid);if(r!==n.oids["aes128-CBC"]&&r!==n.oids["aes192-CBC"]&&r!==n.oids["aes256-CBC"])throw{message:"Cannot read encrypted private key. Unsupported encryption scheme OID.",oid:r,supportedOids:["aes128-CBC","aes192-CBC","aes256-CBC"]};var a=o.kdfSalt,f=e.util.createBuffer(o.kdfIterationCount);f=f.getInt(f.length()<<3);var l;r===n.oids["aes128-CBC"]?l=16:r===n.oids["aes192-CBC"]?l=24:r===n.oids["aes256-CBC"]&&(l=32);var h=e.pkcs5.pbkdf2(s,a,f,l),p=o.encIv,d=e.aes.createDecryptionCipher(h);return d.start(p),d},n.pbe.getCipherForPKCS12PBE=function(r,i,s){var o={},u=[];if(!t.validate(i,h,o,u))throw{message:"Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.",errors:u};var a=e.util.createBuffer(o.salt),f=e.util.createBuffer(o.iterations);f=f.getInt(f.length()<<3);var l,c,p;switch(r){case n.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:l=24,c=8,p=e.des.startDecrypting;break;case n.oids["pbewithSHAAnd40BitRC2-CBC"]:l=5,c=8,p=function(t,n){var r=e.rc2.createDecryptionCipher(t,40);return r.start(n,null),r};break;default:throw{message:"Cannot read PKCS #12 PBE data block. Unsupported OID.",oid:r}}var d=e.pkcs12.generateKey(s,a,1,f,l),v=e.pkcs12.generateKey(s,a,2,f,c);return p(d,v)},n.pbe.getCipher=function(e,t,r){switch(e){case n.oids.pkcs5PBES2:return n.pbe.getCipherForPBES2(e,t,r);case n.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case n.oids["pbewithSHAAnd40BitRC2-CBC"]:return n.pbe.getCipherForPKCS12PBE(e,t,r);default:throw{message:"Cannot read encrypted PBE data block. Unsupported OID.",oid:e,supportedOids:["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"]}}},n.decryptPrivateKeyInfo=function(r,i){var s=null,o={},u=[];if(!t.validate(r,l,o,u))throw{message:"Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.",errors:u};var a=t.derToOid(o.encryptionOid),f=n.pbe.getCipher(a,o.encryptionParams,i),c=e.util.createBuffer(o.encryptedData);return f.update(c),f.finish()&&(s=t.fromDer(f.output)),s},n.encryptedPrivateKeyToPem=function(n,r){var i={type:"ENCRYPTED PRIVATE KEY",body:t.toDer(n).getBytes()};return e.pem.encode(i,{maxline:r})},n.encryptedPrivateKeyFromPem=function(n){var r=e.pem.decode(n)[0];if(r.type!=="ENCRYPTED PRIVATE KEY")throw{message:'Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".',headerType:r.type};if(r.procType&&r.procType.type==="ENCRYPTED")throw{message:"Could not convert encrypted private key from PEM; PEM is encrypted."};return t.fromDer(r.body)},n.encryptRsaPrivateKey=function(r,i,s){s=s||{};if(!s.legacy){var o=n.wrapRsaPrivateKey(n.privateKeyToAsn1(r));return o=n.encryptPrivateKeyInfo(o,i,s),n.encryptedPrivateKeyToPem(o)}var u,a,f,l;switch(s.algorithm){case"aes128":u="AES-128-CBC",f=16,a=e.random.getBytes(16),l=e.aes.createEncryptionCipher;break;case"aes192":u="AES-192-CBC",f=24,a=e.random.getBytes(16),l=e.aes.createEncryptionCipher;break;case"aes256":u="AES-256-CBC",f=32,a=e.random.getBytes(16),l=e.aes.createEncryptionCipher;break;case"3des":u="DES-EDE3-CBC",f=24,a=e.random.getBytes(8),l=e.des.createEncryptionCipher;break;default:throw{message:'Could not encrypt RSA private key; unsupported encryption algorithm "'+s.algorithm+'".',algorithm:s.algorithm}}var c=T(i,a.substr(0,8),f),h=l(c);h.start(a),h.update(t.toDer(n.privateKeyToAsn1(r))),h.finish();var p={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:u,parameters:e.util.bytesToHex(a).toUpperCase()},body:h.output.getBytes()};return e.pem.encode(p)},n.decryptRsaPrivateKey=function(r,i){var s=null,o=e.pem.decode(r)[0];if(o.type!=="ENCRYPTED PRIVATE KEY"&&o.type!=="PRIVATE KEY"&&o.type!=="RSA PRIVATE KEY")throw{message:'Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".',headerType:o.type};if(o.procType&&o.procType.type==="ENCRYPTED"){var u,a;switch(o.dekInfo.algorithm){case"DES-EDE3-CBC":u=24,a=e.des.createDecryptionCipher;break;case"AES-128-CBC":u=16,a=e.aes.createDecryptionCipher;break;case"AES-192-CBC":u=24,a=e.aes.createDecryptionCipher;break;case"AES-256-CBC":u=32,a=e.aes.createDecryptionCipher;break;case"RC2-40-CBC":u=5,a=function(t){return e.rc2.createDecryptionCipher(t,40)};break;case"RC2-64-CBC":u=8,a=function(t){return e.rc2.createDecryptionCipher(t,64)};break;case"RC2-128-CBC":u=16,a=function(t){return e.rc2.createDecryptionCipher(t,128)};break;default:throw{message:'Could not decrypt private key; unsupported encryption algorithm "'+o.dekInfo.algorithm+'".',algorithm:o.dekInfo.algorithm}}var f=e.util.hexToBytes(o.dekInfo.parameters),l=T(i,f.substr(0,8),u),c=a(l);c.start(f),c.update(e.util.createBuffer(o.body));if(!c.finish())return s;s=c.output.getBytes()}else s=o.body;return o.type==="ENCRYPTED PRIVATE KEY"?s=n.decryptPrivateKeyInfo(t.fromDer(s),i):s=t.fromDer(s),s!==null&&(s=n.privateKeyFromAsn1(s)),s},n.setRsaPublicKey=n.rsa.setPublicKey,n.setRsaPrivateKey=n.rsa.setPrivateKey}var t="pki";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o>1,u=o+(t.length&1),a=t.substr(0,u),f=t.substr(o,u),l=e.util.createBuffer(),c=e.hmac.create();r=n+r;var h=Math.ceil(i/16),p=Math.ceil(i/20);c.start("MD5",a);var d=e.util.createBuffer();l.putBytes(r);for(var v=0;v0&&(a.queue(e,a.createAlert({level:a.Alert.Level.warning,description:a.Alert.Description.no_renegotiation})),a.flush(e)),e.process()},a.parseHelloMessage=function(t,n,r){var i=null,s=t.entity===a.ConnectionEnd.client;if(r<38)t.error(t,{message:s?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});else{var u=n.fragment,f=u.length();i={version:{major:u.getByte(),minor:u.getByte()},random:e.util.createBuffer(u.getBytes(32)),session_id:o(u,1),extensions:[]},s?(i.cipher_suite=u.getBytes(2),i.compression_method=u.getByte()):(i.cipher_suites=o(u,2),i.compression_methods=o(u,1)),f=r-(f-u.length());if(f>0){var l=o(u,2);while(l.length()>0)i.extensions.push({type:[l.getByte(),l.getByte()],data:o(l,2)});if(!s)for(var c=0;c0){var d=p.getByte();if(d!==0)break;t.session.serverNameList.push(o(p,2).getBytes())}}}}(i.version.major!==a.Version.major||i.version.minor!==a.Version.minor)&&t.error(t,{message:"Incompatible TLS version.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.protocol_version}});if(s)t.session.cipherSuite=a.getCipherSuite(i.cipher_suite);else{var v=e.util.createBuffer(i.cipher_suites.bytes());while(v.length()>0){t.session.cipherSuite=a.getCipherSuite(v.getBytes(2));if(t.session.cipherSuite!==null)break}}if(t.session.cipherSuite===null)return t.error(t,{message:"No cipher suites in common.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.handshake_failure},cipherSuite:e.util.bytesToHex(i.cipher_suite)});s?t.session.compressionMethod=i.compression_method:t.session.compressionMethod=a.CompressionMethod.none}return i},a.createSecurityParameters=function(e,t){var n=e.entity===a.ConnectionEnd.client,r=t.random.bytes(),i=n?e.session.sp.client_random:r,s=n?r:a.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:a.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:i,server_random:s}},a.handleServerHello=function(e,t,n){var r=a.parseHelloMessage(e,t,n);if(!e.fail){var i=r.session_id.bytes();i===e.session.id?(e.expect=d,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes()):(e.expect=l,e.session.resuming=!1,a.createSecurityParameters(e,r)),e.session.id=i,e.process()}},a.handleClientHello=function(t,n,r){var i=a.parseHelloMessage(t,n,r);if(!t.fail){var s=i.session_id.bytes(),o=null;t.sessionCache&&(o=t.sessionCache.getSession(s),o===null&&(s="")),s.length===0&&(s=e.random.getBytes(32)),t.session.id=s,t.session.clientHelloVersion=i.version,t.session.sp=o?o.sp:{},o!==null?(t.expect=S,t.session.resuming=!0,t.session.sp.client_random=i.random.bytes()):(t.expect=t.verifyClient!==!1?b:w,t.session.resuming=!1,a.createSecurityParameters(t,i)),t.open=!0,a.queue(t,a.createRecord({type:a.ContentType.handshake,data:a.createServerHello(t)})),t.session.resuming?(a.queue(t,a.createRecord({type:a.ContentType.change_cipher_spec,data:a.createChangeCipherSpec()})),t.state.pending=a.createConnectionState(t),t.state.current.write=t.state.pending.write,a.queue(t,a.createRecord({type:a.ContentType.handshake,data:a.createFinished(t)}))):(a.queue(t,a.createRecord({type:a.ContentType.handshake,data:a.createCertificate(t)})),t.fail||(a.queue(t,a.createRecord({type:a.ContentType.handshake,data:a.createServerKeyExchange(t)})),t.verifyClient!==!1&&a.queue(t,a.createRecord({type:a.ContentType.handshake,data:a.createCertificateRequest(t)})),a.queue(t,a.createRecord({type:a.ContentType.handshake,data:a.createServerHelloDone(t)})))),a.flush(t),t.process()}},a.handleCertificate=function(t,n,r){if(r<3)t.error(t,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});else{var i=n.fragment,s={certificate_list:o(i,3)},u,f,l=[];try{while(s.certificate_list.length()>0)u=o(s.certificate_list,3),f=e.asn1.fromDer(u),u=e.pki.certificateFromAsn1(f,!0),l.push(u)}catch(h){t.error(t,{message:"Could not parse certificate list.",cause:h,send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.bad_certificate}})}if(!t.fail){var p=t.entity===a.ConnectionEnd.client;!p&&t.verifyClient!==!0||l.length!==0?l.length===0?t.expect=p?c:w:(p?t.session.serverCertificate=l[0]:t.session.clientCertificate=l[0],a.verifyCertificateChain(t,l)&&(t.expect=p?c:w)):t.error(t,{message:p?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}}),t.process()}}},a.handleServerKeyExchange=function(e,t,n){n>0?e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.unsupported_certificate}}):(e.expect=h,e.process())},a.handleClientKeyExchange=function(t,n,r){if(r<48)t.error(t,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.unsupported_certificate}});else{var i=n.fragment,s={enc_pre_master_secret:o(i,2).getBytes()},u=null;if(t.getPrivateKey)try{u=t.getPrivateKey(t,t.session.serverCertificate),u=e.pki.privateKeyFromPem(u)}catch(f){t.error(t,{message:"Could not get private key.",cause:f,send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}})}if(u===null)t.error(t,{message:"No private key set.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}});else try{var l=t.session.sp;l.pre_master_secret=u.decrypt(s.enc_pre_master_secret);var c=t.session.clientHelloVersion;if(c.major!==l.pre_master_secret.charCodeAt(0)||c.minor!==l.pre_master_secret.charCodeAt(1))throw{message:"TLS version rollback attack detected."}}catch(f){l.pre_master_secret=e.random.getBytes(48)}}t.fail||(t.expect=S,t.session.clientCertificate!==null&&(t.expect=E),t.process())},a.handleCertificateRequest=function(e,t,n){if(n<3)e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});else{var r=t.fragment,i={certificate_types:o(r,1),certificate_authorities:o(r,2)};e.session.certificateRequest=i,e.expect=p,e.process()}},a.handleCertificateVerify=function(t,n,r){if(r<2)t.error(t,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});else{var i=n.fragment;i.read-=4;var s=i.bytes();i.read+=4;var u={signature:o(i,2).getBytes()},f=e.util.createBuffer();f.putBuffer(t.session.md5.digest()),f.putBuffer(t.session.sha1.digest()),f=f.getBytes();try{var l=t.session.clientCertificate;if(!l.publicKey.verify(f,u.signature,"NONE"))throw{message:"CertificateVerify signature does not match."};t.session.md5.update(s),t.session.sha1.update(s)}catch(c){t.error(t,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.handshake_failure}})}t.fail||(t.expect=S,t.process())}},a.handleServerHelloDone=function(t,n,r){if(r>0)t.error(t,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.record_overflow}});else if(t.serverCertificate===null){var i={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.insufficient_security}},s=t.verify(t,i.alert.description,depth,[]);if(s===!0)i=null;else{if(s||s===0)typeof s=="object"&&!e.util.isArray(s)?(s.message&&(i.message=s.message),s.alert&&(i.alert.description=s.alert)):typeof s=="number"&&(i.alert.description=s);t.error(t,i)}}!t.fail&&t.session.certificateRequest!==null&&(n=a.createRecord({type:a.ContentType.handshake,data:a.createCertificate(t)}),a.queue(t,n));if(!t.fail){n=a.createRecord({type:a.ContentType.handshake,data:a.createClientKeyExchange(t)}),a.queue(t,n),t.expect=g;var o=function(e,t){e.session.certificateRequest!==null&&e.session.clientCertificate!==null&&a.queue(e,a.createRecord({type:a.ContentType.handshake,data:a.createCertificateVerify(e,t)})),a.queue(e,a.createRecord({type:a.ContentType.change_cipher_spec,data:a.createChangeCipherSpec()})),e.state.pending=a.createConnectionState(e),e.state.current.write=e.state.pending.write,a.queue(e,a.createRecord({type:a.ContentType.handshake,data:a.createFinished(e)})),e.expect=d,a.flush(e),e.process()};t.session.certificateRequest===null||t.session.clientCertificate===null?o(t,null):a.getClientSignature(t,o)}},a.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});else{var n=e.entity===a.ConnectionEnd.client;if(e.session.resuming&&n||!e.session.resuming&&!n)e.state.pending=a.createConnectionState(e);e.state.current.read=e.state.pending.read;if(!e.session.resuming&&n||e.session.resuming&&!n)e.state.pending=null;e.expect=n?v:x,e.process()}},a.handleFinished=function(n,r,i){var s=r.fragment;s.read-=4;var o=s.bytes();s.read+=4;var u=r.fragment.getBytes();s=e.util.createBuffer(),s.putBuffer(n.session.md5.digest()),s.putBuffer(n.session.sha1.digest());var f=n.entity===a.ConnectionEnd.client,l=f?"server finished":"client finished",c=n.session.sp,h=12,p=t;s=p(c.master_secret,l,s.getBytes(),h);if(s.getBytes()!==u)n.error(n,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.decrypt_error}});else{n.session.md5.update(o),n.session.sha1.update(o);if(n.session.resuming&&f||!n.session.resuming&&!f)a.queue(n,a.createRecord({type:a.ContentType.change_cipher_spec,data:a.createChangeCipherSpec()})),n.state.current.write=n.state.pending.write,n.state.pending=null,a.queue(n,a.createRecord({type:a.ContentType.handshake,data:a.createFinished(n)}));n.expect=f?m:T,n.handshaking=!1,++n.handshakes,n.peerCertificate=f?n.session.serverCertificate:n.session.clientCertificate,n.sessionCache?(n.session={id:n.session.id,sp:n.session.sp},n.session.sp.keys=null):n.session=null,a.flush(n),n.isConnected=!0,n.connected(n),n.process()}},a.handleAlert=function(e,t){var n=t.fragment,r={level:n.getByte(),description:n.getByte()},i;switch(r.description){case a.Alert.Description.close_notify:i="Connection closed.";break;case a.Alert.Description.unexpected_message:i="Unexpected message.";break;case a.Alert.Description.bad_record_mac:i="Bad record MAC.";break;case a.Alert.Description.decryption_failed:i="Decryption failed.";break;case a.Alert.Description.record_overflow:i="Record overflow.";break;case a.Alert.Description.decompression_failure:i="Decompression failed.";break;case a.Alert.Description.handshake_failure:i="Handshake failure.";break;case a.Alert.Description.bad_certificate:i="Bad certificate.";break;case a.Alert.Description.unsupported_certificate:i="Unsupported certificate.";break;case a.Alert.Description.certificate_revoked:i="Certificate revoked.";break;case a.Alert.Description.certificate_expired:i="Certificate expired.";break;case a.Alert.Description.certificate_unknown:i="Certificate unknown.";break;case a.Alert.Description.illegal_parameter:i="Illegal parameter.";break;case a.Alert.Description.unknown_ca:i="Unknown certificate authority.";break;case a.Alert.Description.access_denied:i="Access denied.";break;case a.Alert.Description.decode_error:i="Decode error.";break;case a.Alert.Description.decrypt_error:i="Decrypt error.";break;case a.Alert.Description.export_restriction:i="Export restriction.";break;case a.Alert.Description.protocol_version:i="Unsupported protocol version.";break;case a.Alert.Description.insufficient_security:i="Insufficient security.";break;case a.Alert.Description.internal_error:i="Internal error.";break;case a.Alert.Description.user_canceled:i="User canceled.";break;case a.Alert.Description.no_renegotiation:i="Renegotiation not supported.";break;default:i="Unknown error."}r.description===a.Alert.Description.close_notify?e.close():(e.error(e,{message:i,send:!1,origin:e.entity===a.ConnectionEnd.client?"server":"client",alert:r}),e.process())},a.handleHandshake=function(t,n){var r=n.fragment,i=r.getByte(),s=r.getInt24();if(s>r.length())t.fragmented=n,n.fragment=e.util.createBuffer(),r.read-=4,t.process();else{t.fragmented=null,r.read-=4;var o=r.bytes(s+4);r.read+=4,i in I[t.entity][t.expect]?(t.entity===a.ConnectionEnd.server&&!t.open&&!t.fail&&(t.handshaking=!0,t.session={serverNameList:[],cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:e.md.md5.create(),sha1:e.md.sha1.create()}),i!==a.HandshakeType.hello_request&&i!==a.HandshakeType.certificate_verify&&i!==a.HandshakeType.finished&&(t.session.md5.update(o),t.session.sha1.update(o)),I[t.entity][t.expect][i](t,n,s)):a.handleUnexpected(t,n)}},a.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};var f=0,l=1,c=2,h=3,p=4,d=5,v=6,m=7,g=8,y=0,b=1,w=2,E=3,S=4,x=5,T=6,N=7,C=a.handleUnexpected,k=a.handleChangeCipherSpec,L=a.handleAlert,A=a.handleHandshake,O=a.handleApplicationData,M=[];M[a.ConnectionEnd.client]=[[C,L,A,C],[C,L,A,C],[C,L,A,C],[C,L,A,C],[C,L,A,C],[k,L,C,C],[C,L,A,C],[C,L,A,O],[C,L,A,C]],M[a.ConnectionEnd.server]=[[C,L,A,C],[C,L,A,C],[C,L,A,C],[C,L,A,C],[k,L,C,C],[C,L,A,C],[C,L,A,O],[C,L,A,C]];var _=a.handleHelloRequest,D=a.handleServerHello,P=a.handleCertificate,H=a.handleServerKeyExchange,B=a.handleCertificateRequest,j=a.handleServerHelloDone,F=a.handleFinished,I=[];I[a.ConnectionEnd.client]=[[C,C,D,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C],[_,C,C,C,C,C,C,C,C,C,C,P,H,B,j,C,C,C,C,C,C],[_,C,C,C,C,C,C,C,C,C,C,C,H,B,j,C,C,C,C,C,C],[_,C,C,C,C,C,C,C,C,C,C,C,C,B,j,C,C,C,C,C,C],[_,C,C,C,C,C,C,C,C,C,C,C,C,C,j,C,C,C,C,C,C],[_,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C],[_,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,F],[_,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C],[_,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C]];var q=a.handleClientHello,R=a.handleClientKeyExchange,U=a.handleCertificateVerify;I[a.ConnectionEnd.server]=[[C,q,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C],[C,C,C,C,C,C,C,C,C,C,C,P,C,C,C,C,C,C,C,C,C],[C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,R,C,C,C,C],[C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,U,C,C,C,C,C],[C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C],[C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,F],[C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C],[C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C]],a.generateKeys=function(e,n){var r=t,i=n.client_random+n.server_random;e.session.resuming||(n.master_secret=r(n.pre_master_secret,"master secret",i,48).bytes(),n.pre_master_secret=null),i=n.server_random+n.client_random;var s=2*n.mac_key_length+2*n.enc_key_length+2*n.fixed_iv_length,o=r(n.master_secret,"key expansion",i,s);return{client_write_MAC_key:o.getBytes(n.mac_key_length),server_write_MAC_key:o.getBytes(n.mac_key_length),client_write_key:o.getBytes(n.enc_key_length),server_write_key:o.getBytes(n.enc_key_length),client_write_IV:o.getBytes(n.fixed_iv_length),server_write_IV:o.getBytes(n.fixed_iv_length)}},a.createConnectionState=function(e){var t=e.entity===a.ConnectionEnd.client,n=function(){var e={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(e){return!0},compressionState:null,compressFunction:function(e){return!0},updateSequenceNumber:function(){e.sequenceNumber[1]===4294967295?(e.sequenceNumber[1]=0,++e.sequenceNumber[0]):++e.sequenceNumber[1]}};return e},r={read:n(),write:n()};r.read.update=function(e,t){return r.read.cipherFunction(t,r.read)?r.read.compressFunction(e,t,r.read)||e.error(e,{message:"Could not decompress record.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.decompression_failure}}):e.error(e,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.bad_record_mac}}),!e.fail},r.write.update=function(e,t){return r.write.compressFunction(e,t,r.write)?r.write.cipherFunction(t,r.write)||e.error(e,{message:"Could not encrypt record.",send:!1,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}}):e.error(e,{message:"Could not compress record.",send:!1,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}}),!e.fail};if(e.session){var o=e.session.sp;e.session.cipherSuite.initSecurityParameters(o),o.keys=a.generateKeys(e,o),r.read.macKey=t?o.keys.server_write_MAC_key:o.keys.client_write_MAC_key,r.write.macKey=t?o.keys.client_write_MAC_key:o.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(r,e,o);switch(o.compression_algorithm){case a.CompressionMethod.none:break;case a.CompressionMethod.deflate:r.read.compressFunction=s,r.write.compressFunction=i;break;default:throw{message:"Unsupported compression algorithm."}}}return r},a.createRandom=function(){var t=new Date,n=+t+t.getTimezoneOffset()*6e4,r=e.util.createBuffer();return r.putInt32(n),r.putBytes(e.random.getBytes(28)),r},a.createRecord=function(e){if(!e.data)return null;var t={type:e.type,version:{major:a.Version.major,minor:a.Version.minor},length:e.data.length(),fragment:e.data};return t},a.createAlert=function(t){var n=e.util.createBuffer();return n.putByte(t.level),n.putByte(t.description),a.createRecord({type:a.ContentType.alert,data:n})},a.createClientHello=function(t){var n=e.util.createBuffer();for(var r=0;r0&&(d+=2);var v=t.session.id,m=v.length+1+2+4+28+2+s+1+f+d,g=e.util.createBuffer();return g.putByte(a.HandshakeType.client_hello),g.putInt24(m),g.putByte(a.Version.major),g.putByte(a.Version.minor),g.putBytes(t.session.sp.client_random),u(g,1,e.util.createBuffer(v)),u(g,2,n),u(g,1,o),d>0&&u(g,2,l),g},a.createServerHello=function(t){var n=t.session.id,r=n.length+1+2+4+28+2+1,i=e.util.createBuffer();return i.putByte(a.HandshakeType.server_hello),i.putInt24(r),i.putByte(a.Version.major),i.putByte(a.Version.minor),i.putBytes(t.session.sp.server_random),u(i,1,e.util.createBuffer(n)),i.putByte(t.session.cipherSuite.id[0]),i.putByte(t.session.cipherSuite.id[1]),i.putByte(t.session.compressionMethod),i},a.createCertificate=function(t){var n=t.entity===a.ConnectionEnd.client,r=null;t.getCertificate&&(r=t.getCertificate(t,n?t.session.certificateRequest:t.session.serverNameList));var i=e.util.createBuffer();if(r!==null)try{e.util.isArray(r)||(r=[r]);var s=null;for(var o=0;o0&&(r.putByte(a.HandshakeType.server_key_exchange),r.putInt24(n)),r},a.getClientSignature=function(t,n){var r=e.util.createBuffer();r.putBuffer(t.session.md5.digest()),r.putBuffer(t.session.sha1.digest()),r=r.getBytes(),t.getSignature=t.getSignature||function(t,n,r){var i=null;if(t.getPrivateKey)try{i=t.getPrivateKey(t,t.session.clientCertificate),i=e.pki.privateKeyFromPem(i)}catch(s){t.error(t,{message:"Could not get private key.",cause:s,send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}})}i===null?t.error(t,{message:"No private key set.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}}):n=i.sign(n,null),r(t,n)},t.getSignature(t,r,n)},a.createCertificateVerify=function(t,n){var r=n.length+2,i=e.util.createBuffer();return i.putByte(a.HandshakeType.certificate_verify),i.putInt24(r),i.putInt16(n.length),i.putBytes(n),i},a.createCertificateRequest=function(t){var n=e.util.createBuffer();n.putByte(1);var r=e.util.createBuffer();for(var i in t.caStore.certs){var s=t.caStore.certs[i],o=e.pki.distinguishedNameToAsn1(s.subject);r.putBuffer(e.asn1.toDer(o))}var f=1+n.length()+2+r.length(),l=e.util.createBuffer();return l.putByte(a.HandshakeType.certificate_request),l.putInt24(f),u(l,1,n),u(l,2,r),l},a.createServerHelloDone=function(t){var n=e.util.createBuffer();return n.putByte(a.HandshakeType.server_hello_done),n.putInt24(0),n},a.createChangeCipherSpec=function(){var t=e.util.createBuffer();return t.putByte(1),t},a.createFinished=function(n){var r=e.util.createBuffer();r.putBuffer(n.session.md5.digest()),r.putBuffer(n.session.sha1.digest());var i=n.entity===a.ConnectionEnd.client,s=n.session.sp,o=12,u=t,f=i?"client finished":"server finished";r=u(s.master_secret,f,r.getBytes(),o);var l=e.util.createBuffer();return l.putByte(a.HandshakeType.finished),l.putInt24(r.length()),l.putBuffer(r),l},a.queue=function(t,n){if(!n)return;if(n.type===a.ContentType.handshake){var r=n.fragment.bytes();t.session.md5.update(r),t.session.sha1.update(r),r=null}var i;if(n.fragment.length()<=a.MaxFragment)i=[n];else{i=[];var s=n.fragment.bytes();while(s.length>a.MaxFragment)i.push(a.createRecord({type:n.type,data:e.util.createBuffer(s.slice(0,a.MaxFragment))})),s=s.slice(a.MaxFragment);s.length>0&&i.push(a.createRecord({type:n.type,data:e.util.createBuffer(s)}))}for(var o=0;o0&&(i=r.order[0]);if(i!==null&&i in r.cache){n=r.cache[i],delete r.cache[i];for(var s in r.order)if(r.order[s]===i){r.order.splice(s,1);break}}return n},r.setSession=function(t,n){if(r.order.length===r.capacity){var i=r.order.shift();delete r.cache[i]}var i=e.util.bytesToHex(t);r.order.push(i),r.cache[i]=n}}return r},a.createConnection=function(t){var n=null;t.caStore?e.util.isArray(t.caStore)?n=e.pki.createCaStore(t.caStore):n=t.caStore:n=e.pki.createCaStore();var r=t.cipherSuites||null;if(r===null){r=[];for(var i in a.CipherSuites)r.push(a.CipherSuites[i])}var s=t.server||!1?a.ConnectionEnd.server:a.ConnectionEnd.client,o=t.sessionCache?a.createSessionCache(t.sessionCache):null,u={entity:s,sessionId:t.sessionId,caStore:n,sessionCache:o,cipherSuites:r,connected:t.connected,virtualHost:t.virtualHost||null,verifyClient:t.verifyClient||!1,verify:t.verify||function(e,t,n,r){return t},getCertificate:t.getCertificate||null,getPrivateKey:t.getPrivateKey||null,getSignature:t.getSignature||null,input:e.util.createBuffer(),tlsData:e.util.createBuffer(),data:e.util.createBuffer(),tlsDataReady:t.tlsDataReady,dataReady:t.dataReady,closed:t.closed,error:function(e,n){n.origin=n.origin||(e.entity===a.ConnectionEnd.client?"client":"server"),n.send&&(a.queue(e,a.createAlert(n.alert)),a.flush(e));var r=n.fatal!==!1;r&&(e.fail=!0),t.error(e,n),r&&e.close(!1)},deflate:t.deflate||null,inflate:t.inflate||null};u.reset=function(e){u.record=null,u.session=null,u.peerCertificate=null,u.state={pending:null,current:null},u.expect=u.entity===a.ConnectionEnd.client?f:y,u.fragmented=null,u.records=[],u.open=!1,u.handshakes=0,u.handshaking=!1,u.isConnected=!1,u.fail=!e&&typeof e!="undefined",u.input.clear(),u.tlsData.clear(),u.data.clear(),u.state.current=a.createConnectionState(u)},u.reset();var l=function(e,t){var n=t.type-a.ContentType.change_cipher_spec,r=M[e.entity][e.expect];n in r?r[n](e,t):a.handleUnexpected(e,t)},c=function(t){var n=0,r=t.input,i=r.length();return i<5?n=5-i:(t.record={type:r.getByte(),version:{major:r.getByte(),minor:r.getByte()},length:r.getInt16(),fragment:e.util.createBuffer(),ready:!1},(t.record.version.major!==a.Version.major||t.record.version.minor!==a.Version.minor)&&t.error(t,{message:"Incompatible TLS version.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.protocol_version}})),n},h=function(e){var t=0,n=e.input,r=n.length();if(r0&&(u.sessionCache&&(n=u.sessionCache.getSession(t)),n===null&&(t="")),t.length===0&&u.sessionCache&&(n=u.sessionCache.getSession(),n!==null&&(t=n.id)),u.session={id:t,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:n?n.sp:{},md5:e.md.md5.create(),sha1:e.md.sha1.create()},u.session.sp.client_random=a.createRandom().getBytes(),u.open=!0,a.queue(u,a.createRecord({type:a.ContentType.handshake,data:a.createClientHello(u)})),a.flush(u)}},u.process=function(e){var t=0;return e&&u.input.putBytes(e),u.fail||(u.record!==null&&u.record.ready&&u.record.fragment.isEmpty()&&(u.record=null),u.record===null&&(t=c(u)),!u.fail&&u.record!==null&&!u.record.ready&&(t=h(u)),!u.fail&&u.record!==null&&u.record.ready&&l(u,u.record)),t},u.prepare=function(t){return a.queue(u,a.createRecord({type:a.ContentType.application_data,data:e.util.createBuffer(t)})),a.flush(u)},u.close=function(e){!u.fail&&u.sessionCache&&u.session&&u.sessionCache.setSession(u.session.id,u.session);if(u.open){u.open=!1,u.input.clear();if(u.isConnected||u.handshaking)u.isConnected=u.handshaking=!1,a.queue(u,a.createAlert({level:a.Alert.Level.warning,description:a.Alert.Description.close_notify})),a.flush(u);u.closed(u)}u.reset(e)},u},e.tls=e.tls||{};for(var X in a)typeof a[X]!="function"&&(e.tls[X]=a[X]);e.tls.prf_tls1=t,e.tls.hmac_sha1=r,e.tls.createSessionCache=a.createSessionCache,e.tls.createConnection=a.createConnection}var t="tls";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o1?o=e.random.getBytes(16):o=n.cipherState.init?null:n.cipherState.iv,n.cipherState.init=!0;var u=n.cipherState.cipher;return u.start(o),t.version.minor>1&&u.output.putBytes(o),u.update(t.fragment),u.finish(i)&&(t.fragment=u.output,t.length=t.fragment.length(),r=!0),r}function i(e,t,n){if(!n){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function s(e,t,n){var r=!0;if(n){var i=t.length(),s=t.last();for(var o=i-1-s;o=u?(t.fragment=o.output.getBytes(l-u),a=o.output.getBytes(u)):t.fragment=o.output.getBytes(),t.fragment=e.util.createBuffer(t.fragment),t.length=t.fragment.length();var c=n.macFunction(n.macKey,n.sequenceNumber,t);return n.updateSequenceNumber(),r=c===a&&r,r}var t=e.tls;t.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=t.BulkCipherAlgorithm.aes,e.cipher_type=t.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=t.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:n},t.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=t.BulkCipherAlgorithm.aes,e.cipher_type=t.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=t.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:n}}var t="aesCipherSuites";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o=1&&e.log.verbose(t,"[%s][%s] init",this.id,this.name,this)};T.prototype.debug=function(n){n=n||"",e.log.debug(t,n,"[%s][%s] task:",this.id,this.name,this,"subtasks:",this.subtasks.length,"queue:",s)},T.prototype.next=function(e,t){typeof e=="function"&&(t=e,e=this.name);var n=new T({run:t,name:e,parent:this});return n.state=l,n.type=this.type,n.successCallback=this.successCallback||null,n.failureCallback=this.failureCallback||null,this.subtasks.push(n),this},T.prototype.parallel=function(t,n){return e.util.isArray(t)&&(n=t,t=this.name),this.next(t,function(r){var i=r;i.block(n.length);var s=function(t,r){e.task.start({type:t,run:function(e){n[r](e)},success:function(e){i.unblock()},failure:function(e){i.unblock()}})};for(var o=0;o0&&(this.state=x[this.state][g])},T.prototype.unblock=function(e){return e=typeof e=="undefined"?1:e,this.blocks-=e,this.blocks===0&&this.state!==p&&(this.state=l,C(this,0)),this.blocks},T.prototype.sleep=function(e){e=typeof e=="undefined"?0:e,this.state=x[this.state][b];var t=this;this.timeoutId=setTimeout(function(){t.timeoutId=null,t.state=l,C(t,0)},e)},T.prototype.wait=function(e){e.wait(this)},T.prototype.wakeup=function(){this.state===h&&(cancelTimeout(this.timeoutId),this.timeoutId=null,this.state=l,C(this,0))},T.prototype.cancel=function(){this.state=x[this.state][E],this.permitsNeeded=0,this.timeoutId!==null&&(cancelTimeout(this.timeoutId),this.timeoutId=null),this.subtasks=[]},T.prototype.fail=function(e){this.error=!0,k(this,!0);if(e)e.error=this.error,e.swapTime=this.swapTime,e.userData=this.userData,C(e,0);else{if(this.parent!==null){var t=this.parent;while(t.parent!==null)t.error=this.error,t.swapTime=this.swapTime,t.userData=this.userData,t=t.parent;k(t,!0)}this.failureCallback&&this.failureCallback(this)}};var N=function(e){e.error=!1,e.state=x[e.state][m],setTimeout(function(){e.state===l&&(e.swapTime=+(new Date),e.run(e),C(e,0))},0)},C=function(e,t){var n=t>u||+(new Date)-e.swapTime>a,r=function(t){t++;if(e.state===l){n&&(e.swapTime=+(new Date));if(e.subtasks.length>0){var r=e.subtasks.shift();r.error=e.error,r.swapTime=e.swapTime,r.userData=e.userData,r.run(r),r.error||C(r,t)}else k(e),e.error||e.parent!==null&&(e.parent.error=e.error,e.parent.swapTime=e.swapTime,e.parent.userData=e.userData,C(e.parent,t))}};n?setTimeout(r,0):r(t)},k=function(i,o){i.state=p,delete r[i.id],n>=1&&e.log.verbose(t,"[%s][%s] finish",i.id,i.name,i),i.parent===null&&(i.type in s?s[i.type].length===0?e.log.error(t,"[%s][%s] task queue empty [%s]",i.id,i.name,i.type):s[i.type][0]!==i?e.log.error(t,"[%s][%s] task not first in queue [%s]",i.id,i.name,i.type):(s[i.type].shift(),s[i.type].length===0?(n>=1&&e.log.verbose(t,"[%s][%s] delete queue [%s]",i.id,i.name,i.type),delete s[i.type]):(n>=1&&e.log.verbose(t,"[%s][%s] queue start next [%s] remain:%s",i.id,i.name,i.type,s[i.type].length),s[i.type][0].start())):e.log.error(t,"[%s][%s] task queue missing [%s]",i.id,i.name,i.type),o||(i.error&&i.failureCallback?i.failureCallback(i):!i.error&&i.successCallback&&i.successCallback(i)))};e.task=e.task||{},e.task.start=function(r){var i=new T({run:r.run,name:r.name||o});i.type=r.type,i.successCallback=r.success||null,i.failureCallback=r.failure||null,i.type in s?s[r.type].push(i):(n>=1&&e.log.verbose(t,"[%s][%s] create queue [%s]",i.id,i.name,i.type),s[i.type]=[i],N(i))},e.task.cancel=function(e){e in s&&(s[e]=[s[e][0]])},e.task.createCondition=function(){var e={tasks:{}};return e.wait=function(t){t.id in e.tasks||(t.block(),e.tasks[t.id]=t)},e.notify=function(){var t=e.tasks;e.tasks={};for(var n in t)t[n].unblock()},e}}var t="task";if(typeof define!="function"){if(typeof module!="object"||!module.exports)return typeof forge=="undefined"&&(forge={}),e(forge);var n=!0;define=function(e,t){t(require,module)}}var r,i=function(n,i){i.exports=function(i){var s=r.map(function(e){return n(e)}).concat(e);i=i||{},i.defined=i.defined||{};if(i.defined[t])return i[t];i.defined[t]=!0;for(var o=0;o -# Updated to only warn and unset PYTHON if no good one is found - -AC_DEFUN([AS_PATH_PYTHON], - [ - dnl Find a version of Python. I could check for python versions 1.4 - dnl or earlier, but the default installation locations changed from - dnl $prefix/lib/site-python in 1.4 to $prefix/lib/python1.5/site-packages - dnl in 1.5, and I don't want to maintain that logic. - - dnl should we do the version check? - PYTHON_CANDIDATES="$PYTHON python python2 \ - python2.7 python2.6 pyton2.5 python2.4 python2.3 \ - python2.2 python2.1 python2.0 \ - python1.6 python1.5" - dnl Declare PYTHON as a special var - AC_ARG_VAR([PYTHON], [path to Python interpreter]) - ifelse([$1],[], - [AC_PATH_PROG(PYTHON, $PYTHON_CANDIDATES)], - [ - AC_MSG_NOTICE(Looking for Python version >= $1) - changequote(<<, >>)dnl - prog=" -import sys, string -minver = '$1' -# split string by '.' and convert to numeric -minver_info = map(string.atoi, string.split(minver, '.')) -# we can now do comparisons on the two lists: -if sys.version_info >= tuple(minver_info): - sys.exit(0) -else: - sys.exit(1)" - changequote([, ])dnl - - python_good=false - for python_candidate in $PYTHON_CANDIDATES; do - unset PYTHON - AC_PATH_PROG(PYTHON, $python_candidate) 1> /dev/null 2> /dev/null - - if test "x$PYTHON" = "x"; then continue; fi - - if $PYTHON -c "$prog" 1>&AC_FD_CC 2>&AC_FD_CC; then - AC_MSG_CHECKING(["$PYTHON":]) - AC_MSG_RESULT([okay]) - python_good=true - break; - else - dnl clear the cache val - unset ac_cv_path_PYTHON - fi - done - ]) - - if test "$python_good" != "true"; then - AC_MSG_WARN([No suitable version of python found]) - PYTHON= - else - - AC_MSG_CHECKING([local Python configuration]) - - dnl Query Python for its version number. Getting [:3] seems to be - dnl the best way to do this; it's what "site.py" does in the standard - dnl library. Need to change quote character because of [:3] - - AC_SUBST(PYTHON_VERSION) - changequote(<<, >>)dnl - PYTHON_VERSION=`$PYTHON -c "import sys; print sys.version[:3]"` - changequote([, ])dnl - - - dnl Use the values of $prefix and $exec_prefix for the corresponding - dnl values of PYTHON_PREFIX and PYTHON_EXEC_PREFIX. These are made - dnl distinct variables so they can be overridden if need be. However, - dnl general consensus is that you shouldn't need this ability. - - AC_SUBST(PYTHON_PREFIX) - PYTHON_PREFIX='${prefix}' - - AC_SUBST(PYTHON_EXEC_PREFIX) - PYTHON_EXEC_PREFIX='${exec_prefix}' - - dnl At times (like when building shared libraries) you may want - dnl to know which OS platform Python thinks this is. - - AC_SUBST(PYTHON_PLATFORM) - PYTHON_PLATFORM=`$PYTHON -c "import sys; print sys.platform"` - - - dnl Set up 4 directories: - - dnl pythondir -- where to install python scripts. This is the - dnl site-packages directory, not the python standard library - dnl directory like in previous automake betas. This behaviour - dnl is more consistent with lispdir.m4 for example. - dnl - dnl Also, if the package prefix isn't the same as python's prefix, - dnl then the old $(pythondir) was pretty useless. - - AC_SUBST(pythondir) - pythondir=$PYTHON_PREFIX"/lib/python"$PYTHON_VERSION/site-packages - - dnl pkgpythondir -- $PACKAGE directory under pythondir. Was - dnl PYTHON_SITE_PACKAGE in previous betas, but this naming is - dnl more consistent with the rest of automake. - dnl Maybe this should be put in python.am? - - AC_SUBST(pkgpythondir) - pkgpythondir=\${pythondir}/$PACKAGE - - dnl pyexecdir -- directory for installing python extension modules - dnl (shared libraries) Was PYTHON_SITE_EXEC in previous betas. - - AC_SUBST(pyexecdir) - pyexecdir=$PYTHON_EXEC_PREFIX"/lib/python"$PYTHON_VERSION/site-packages - - dnl pkgpyexecdir -- $(pyexecdir)/$(PACKAGE) - dnl Maybe this should be put in python.am? - - AC_SUBST(pkgpyexecdir) - pkgpyexecdir=\${pyexecdir}/$PACKAGE - - AC_MSG_RESULT([looks good]) - - fi -]) diff --git a/alarm/node_modules/node-forge/start.frag b/alarm/node_modules/node-forge/start.frag deleted file mode 100644 index dad9d0f..0000000 --- a/alarm/node_modules/node-forge/start.frag +++ /dev/null @@ -1,7 +0,0 @@ -(function(root, factory) { - if(typeof define === 'function' && define.amd) { - define([], factory); - } else { - root.forge = factory(); - } -})(this, function() { diff --git a/alarm/node_modules/node-forge/swf/SocketPool.swf b/alarm/node_modules/node-forge/swf/SocketPool.swf deleted file mode 100644 index c6cdaf9..0000000 Binary files a/alarm/node_modules/node-forge/swf/SocketPool.swf and /dev/null differ diff --git a/alarm/node_modules/node-forge/tests/aes-speed.js b/alarm/node_modules/node-forge/tests/aes-speed.js deleted file mode 100644 index 2049a8a..0000000 --- a/alarm/node_modules/node-forge/tests/aes-speed.js +++ /dev/null @@ -1,62 +0,0 @@ -var forge = require('../js/forge'); - -console.log('Times in 1000s of bytes/sec processed.'); - -aes_128('AES-CBC'); -aes_128('AES-CFB'); -aes_128('AES-OFB'); -aes_128('AES-CTR'); -aes_128('AES-GCM'); - -function aes_128(algorithm) { - console.log('Running ' + algorithm + ' for 5 seconds...'); - - var size = 1024; - var key = forge.random.getBytesSync(16); - var iv = forge.random.getBytes(algorithm === 'AES-GCM' ? 12 : 16); - var plain = forge.random.getBytesSync(size); - - // run for 5 seconds - var start = new Date().getTime(); - - var now; - var totalEncrypt = 0; - var totalDecrypt = 0; - var cipher; - var count = 0; - var passed = 0; - while(passed < 5000) { - var input = forge.util.createBuffer(plain); - - // encrypt, only measuring update() and finish() - cipher = forge.cipher.createCipher(algorithm, key); - cipher.start({iv: iv}); - now = new Date().getTime(); - cipher.update(input); - cipher.finish(); - totalEncrypt += new Date().getTime() - now; - - var ciphertext = cipher.output; - var tag = cipher.mode.tag; - count += cipher.output.length(); - - // decrypt, only measuring update() and finish() - cipher = forge.cipher.createDecipher(algorithm, key); - cipher.start({iv: iv, tag: tag}); - now = new Date().getTime(); - cipher.update(ciphertext); - if(!cipher.finish()) { - throw new Error('Decryption error.'); - } - totalDecrypt += new Date().getTime() - now; - - passed = new Date().getTime() - start; - } - - count = count / 1000; - totalEncrypt /= 1000; - totalDecrypt /= 1000; - console.log('encrypt: ' + (count / totalEncrypt) + ' k/sec'); - console.log('decrypt: ' + (count / totalDecrypt) + ' k/sec'); - console.log(); -} diff --git a/alarm/node_modules/node-forge/tests/common.html b/alarm/node_modules/node-forge/tests/common.html deleted file mode 100644 index 0fb4705..0000000 --- a/alarm/node_modules/node-forge/tests/common.html +++ /dev/null @@ -1,84 +0,0 @@ - - - - - Forge Common Test - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
-

Common Tests

-
- -
- -
-
    -
  • Test various Forge components.
  • -
  • See JavaScript console for more detailed output.
  • -
-
- -
-Control - - -
- Scroll Tests -
- - - bits -
- -
-Progress -Status: ?
-Pass: ?/?
-Fail: ? -
- -
-Tests -
-
- -
- - - diff --git a/alarm/node_modules/node-forge/tests/common.js b/alarm/node_modules/node-forge/tests/common.js deleted file mode 100644 index 57dfbc4..0000000 --- a/alarm/node_modules/node-forge/tests/common.js +++ /dev/null @@ -1,2199 +0,0 @@ -/** - * Forge Common Tests - * - * @author Dave Longley - * - * Copyright (c) 2009-2012 Digital Bazaar, Inc. All rights reserved. - */ -jQuery(function($) -{ - // logging category - var cat = 'forge.tests.common'; - - // local alias - var forge = window.forge; - - var tests = []; - var passed = 0; - var failed = 0; - - var init = function() - { - passed = failed = 0; - $('.ready,.testing,.pass,.fail') - .removeClass('ready testing pass fail'); - $('#status') - .text('Ready.') - .addClass('ready'); - $('#total').text(tests.length); - $('#pass').text(passed); - $('#fail').text(failed); - $('.expect').empty(); - $('.result').empty(); - $('.time').empty(); - $('.timePer').empty(); - $('#start').attr('disabled', ''); - }; - - var start = function() - { - $('#start').attr('disabled', 'true'); - // meta! use tasks to run the task tests - forge.task.start({ - type: 'test', - run: function(task) { - task.next('starting', function(task) { - forge.log.debug(cat, 'start'); - $('#status') - .text('Testing...') - .addClass('testing') - .removeClass('idle'); - }); - $.each(tests, function(i, test) { - task.next('test', function(task) { - var title = $('li:first', test.container); - if($('#scroll:checked').length === 1) - { - $('html,body').animate({scrollTop: title.offset().top}); - } - title.addClass('testing'); - test.run(task, test); - }); - task.next('test', function(task) { - $('li:first', test.container).removeClass('testing'); - }); - }); - task.next('success', function(task) { - forge.log.debug(cat, 'done'); - if(failed === 0) { - $('#status') - .text('PASS') - .addClass('pass') - .removeClass('testing'); - } else { - // FIXME: should just be hitting failure() below - $('#status') - .text('FAIL') - .addClass('fail') - .removeClass('testing'); - } - }); - }, - failure: function() { - $('#status') - .text('FAIL') - .addClass('fail') - .removeClass('testing'); - } - }); - }; - - $('#start').click(function() { - start(); - }); - - $('#reset').click(function() { - init(); - }); - - $('#keygen').click(function() { - var bits = $('#bits')[0].value; - var keys = forge.pki.rsa.generateKeyPair(bits); - forge.log.debug(cat, 'generating ' + bits + '-bit RSA key-pair...'); - setTimeout(function() - { - forge.log.debug(cat, 'private key:', keys.privateKey); - forge.log.debug(cat, forge.pki.privateKeyToPem(keys.privateKey)); - forge.log.debug(cat, 'public key:', keys.publicKey); - forge.log.debug(cat, forge.pki.publicKeyToPem(keys.publicKey)); - - forge.log.debug(cat, 'testing sign/verify...'); - setTimeout(function() - { - // do sign/verify test - try - { - var md = forge.md.sha1.create(); - md.update('foo'); - var signature = keys.privateKey.sign(md); - keys.publicKey.verify(md.digest().getBytes(), signature); - forge.log.debug(cat, 'sign/verify success'); - } - catch(ex) - { - forge.log.error(cat, 'sign/verify failure', ex); - } - }, 0); - }, 0); - }); - - $('#certgen').click(function() { - var bits = $('#bits')[0].value; - forge.log.debug(cat, 'generating ' + bits + - '-bit RSA key-pair and certificate...'); - setTimeout(function() - { - try - { - var keys = forge.pki.rsa.generateKeyPair(bits); - var cert = forge.pki.createCertificate(); - cert.serialNumber = '01'; - cert.validity.notBefore = new Date(); - cert.validity.notAfter = new Date(); - cert.validity.notAfter.setFullYear( - cert.validity.notBefore.getFullYear() + 1); - var attrs = [{ - name: 'commonName', - value: 'mycert' - }, { - name: 'countryName', - value: 'US' - }, { - shortName: 'ST', - value: 'Virginia' - }, { - name: 'localityName', - value: 'Blacksburg' - }, { - name: 'organizationName', - value: 'Test' - }, { - shortName: 'OU', - value: 'Test' - }]; - cert.setSubject(attrs); - cert.setIssuer(attrs); - cert.setExtensions([{ - name: 'basicConstraints', - cA: true - }, { - name: 'keyUsage', - keyCertSign: true - }, { - name: 'subjectAltName', - altNames: [{ - type: 6, // URI - value: 'http://localhost/dataspace/person/myname#this' - }] - }]); - // FIXME: add subjectKeyIdentifier extension - // FIXME: add authorityKeyIdentifier extension - cert.publicKey = keys.publicKey; - - // self-sign certificate - cert.sign(keys.privateKey); - - forge.log.debug(cat, 'certificate:', cert); - //forge.log.debug(cat, - // forge.asn1.prettyPrint(forge.pki.certificateToAsn1(cert))); - forge.log.debug(cat, forge.pki.certificateToPem(cert)); - - // verify certificate - forge.log.debug(cat, 'verified', cert.verify(cert)); - } - catch(ex) - { - forge.log.error(cat, ex, ex.message ? ex.message : ''); - } - }, 0); - }); - - var addTest = function(name, run) - { - var container = $('