From 46261b467ef7ad8886531ef0848217777e4585eb Mon Sep 17 00:00:00 2001 From: Braintree Date: Tue, 7 Jun 2011 16:46:50 -0500 Subject: [PATCH] initial version --- .gitignore | 2 + README.md | 61 + Rakefile | 95 + build/bundle_footer.js | 3 + build/bundle_header.js | 1 + build/jsmin.rb | 205 ++ build/minified_header.js | 14 + lib/braintree.js | 54 + lib/pidCrypt/aes_cbc.js | 417 +++ lib/pidCrypt/aes_core.js | 239 ++ lib/pidCrypt/aes_ctr.js | 335 +++ lib/pidCrypt/asn1.js | 494 ++++ lib/pidCrypt/gpl-3.0.txt | 675 +++++ lib/pidCrypt/history.txt | 119 + lib/pidCrypt/jsbn.js | 1232 +++++++++ lib/pidCrypt/md5.js | 185 ++ lib/pidCrypt/oids.js | 1578 +++++++++++ lib/pidCrypt/pidcrypt.js | 212 ++ lib/pidCrypt/pidcrypt_util.js | 347 +++ lib/pidCrypt/prng4.js | 47 + lib/pidCrypt/rng.js | 73 + lib/pidCrypt/rsa.js | 373 +++ lib/pidCrypt/sha1.js | 152 ++ lib/pidCrypt/sha256.js | 81 + lib/pidCrypt/sha512.js | 276 ++ lib/pidCrypt/string_extend.js | 60 + lib/sjcl/README/COPYRIGHT | 32 + lib/sjcl/README/INSTALL | 36 + lib/sjcl/README/bsd.txt | 30 + lib/sjcl/README/gpl-2.0.txt | 339 +++ lib/sjcl/README/gpl-3.0.txt | 674 +++++ lib/sjcl/config.mk | 2 + lib/sjcl/configure | 141 + lib/sjcl/core/aes.js | 208 ++ lib/sjcl/core/bitArray.js | 187 ++ lib/sjcl/core/bn.js | 534 ++++ lib/sjcl/core/cbc.js | 115 + lib/sjcl/core/ccm.js | 185 ++ lib/sjcl/core/codecBase64.js | 56 + lib/sjcl/core/codecBytes.js | 37 + lib/sjcl/core/codecHex.js | 30 + lib/sjcl/core/codecString.js | 39 + lib/sjcl/core/convenience.js | 271 ++ lib/sjcl/core/ecc.js | 380 +++ lib/sjcl/core/hmac.js | 40 + lib/sjcl/core/ocb2.js | 171 ++ lib/sjcl/core/pbkdf2.js | 54 + lib/sjcl/core/random.js | 368 +++ lib/sjcl/core/sha1.js | 165 ++ lib/sjcl/core/sha256.js | 216 ++ lib/sjcl/core/sjcl.js | 69 + lib/sjcl/core/srp.js | 113 + lib/sjcl/sjcl.js | 40 + spec/SpecRunner.html.erb | 26 + spec/brainree_spec.js | 58 + .../jasmine-standalone-1.0.0/SpecRunner.html | 27 + .../lib/jasmine-1.0.0/MIT.LICENSE | 20 + .../lib/jasmine-1.0.0/jasmine-html.js | 182 ++ .../lib/jasmine-1.0.0/jasmine.css | 166 ++ .../lib/jasmine-1.0.0/jasmine.js | 2421 +++++++++++++++++ .../spec/PlayerSpec.js | 58 + .../spec/SpecHelper.js | 9 + .../jasmine-standalone-1.0.0/src/Player.js | 22 + .../jasmine-standalone-1.0.0/src/Song.js | 7 + 64 files changed, 14858 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 Rakefile create mode 100644 build/bundle_footer.js create mode 100644 build/bundle_header.js create mode 100644 build/jsmin.rb create mode 100644 build/minified_header.js create mode 100644 lib/braintree.js create mode 100644 lib/pidCrypt/aes_cbc.js create mode 100644 lib/pidCrypt/aes_core.js create mode 100644 lib/pidCrypt/aes_ctr.js create mode 100644 lib/pidCrypt/asn1.js create mode 100644 lib/pidCrypt/gpl-3.0.txt create mode 100644 lib/pidCrypt/history.txt create mode 100644 lib/pidCrypt/jsbn.js create mode 100644 lib/pidCrypt/md5.js create mode 100644 lib/pidCrypt/oids.js create mode 100644 lib/pidCrypt/pidcrypt.js create mode 100644 lib/pidCrypt/pidcrypt_util.js create mode 100644 lib/pidCrypt/prng4.js create mode 100644 lib/pidCrypt/rng.js create mode 100644 lib/pidCrypt/rsa.js create mode 100644 lib/pidCrypt/sha1.js create mode 100644 lib/pidCrypt/sha256.js create mode 100644 lib/pidCrypt/sha512.js create mode 100644 lib/pidCrypt/string_extend.js create mode 100644 lib/sjcl/README/COPYRIGHT create mode 100644 lib/sjcl/README/INSTALL create mode 100644 lib/sjcl/README/bsd.txt create mode 100644 lib/sjcl/README/gpl-2.0.txt create mode 100644 lib/sjcl/README/gpl-3.0.txt create mode 100644 lib/sjcl/config.mk create mode 100755 lib/sjcl/configure create mode 100644 lib/sjcl/core/aes.js create mode 100644 lib/sjcl/core/bitArray.js create mode 100644 lib/sjcl/core/bn.js create mode 100644 lib/sjcl/core/cbc.js create mode 100644 lib/sjcl/core/ccm.js create mode 100644 lib/sjcl/core/codecBase64.js create mode 100644 lib/sjcl/core/codecBytes.js create mode 100644 lib/sjcl/core/codecHex.js create mode 100644 lib/sjcl/core/codecString.js create mode 100644 lib/sjcl/core/convenience.js create mode 100644 lib/sjcl/core/ecc.js create mode 100644 lib/sjcl/core/hmac.js create mode 100644 lib/sjcl/core/ocb2.js create mode 100644 lib/sjcl/core/pbkdf2.js create mode 100644 lib/sjcl/core/random.js create mode 100644 lib/sjcl/core/sha1.js create mode 100644 lib/sjcl/core/sha256.js create mode 100644 lib/sjcl/core/sjcl.js create mode 100644 lib/sjcl/core/srp.js create mode 100644 lib/sjcl/sjcl.js create mode 100644 spec/SpecRunner.html.erb create mode 100644 spec/brainree_spec.js create mode 100644 spec/infrastructure/jasmine-standalone-1.0.0/SpecRunner.html create mode 100644 spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/MIT.LICENSE create mode 100644 spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine-html.js create mode 100644 spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.css create mode 100644 spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.js create mode 100644 spec/infrastructure/jasmine-standalone-1.0.0/spec/PlayerSpec.js create mode 100644 spec/infrastructure/jasmine-standalone-1.0.0/spec/SpecHelper.js create mode 100644 spec/infrastructure/jasmine-standalone-1.0.0/src/Player.js create mode 100644 spec/infrastructure/jasmine-standalone-1.0.0/src/Song.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eec2c68 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/spec/SpecRunner.html diff --git a/README.md b/README.md new file mode 100644 index 0000000..eddfacb --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +# Braintree Client-Side Encryption + +This library is for use with [Braintree's payment gateway](http://braintreepayments.com/) in concert with one of [the supported client libraries](http://braintreepayments.com/docs). It encrypts sensitive payment information in a web browser using the public key of an asymmetric key pair. + +## NOTICE: This Project is in Beta + +While Client-Side Encryption is currently in use in production environments, you should be aware of the following if you are interested in using this technology during the beta period. + +* This library is not yet a drop-in solution, so implementation will be more technically complicated than just using a Braintree client library. +* The public API of the library may change across releases. We use [semantic versioning](http://semver.org/) to make it obvious when this happens. +* We may require you to upgrade to a new version of the library as we develop this technology. (We'll contact you if this is the case; we won't deprecate an in-use version out from under you.) + +## Getting Started + +Here's a quick example. First, include this library using a script tag: + +```html + + + +``` +Then, configure the library to use your public key. + +```javascript +var braintree = Braintree.create("YOUR_CLIENT_SIDE_PUBLIC_ENCRYPTION_KEY"); +``` + +And call the `encrypt` method passing in the data you wish to be encrypted. + +```javascript +var encryptedValue = braintree.encrypt("sensitiveValue"); +``` + +Because we are using asymmetric encryption, you will be unable to decrypt the data you have encrypted using your public encryption key. Only the Braintree Gateway will be able to decrypt these encrypted values. This means that `encryptedValue` is now safe to pass through your servers to be used in the Server-to-Server API of one of our client libraries. + +## Encrypting Form Values + +The normal use case for this library is to encrypt a credit number and CVV code before a form is submitted to your servers. A simple example of this using [jQuery](http://jquery.com/) might look something like this: + +```javascript +$('#transaction_form').submit(function () { + $('#transaction_credit_card_number').val(braintree.encrypt($('#transaction_credit_card_number').val())); + $('#transaction_credit_card_cvv').val(braintree.encrypt($('#transaction_credit_card_cvv').val())); +}); +``` +## Issues to Consider + +Early releases of this library contain the core functionality of Client-Side Encryption, but there are a few issues that are left to your application to solve. + +### User Experience on Form Submission + +The simple example provided above will result in the encrypted values being momentarily visible in the browser before the form is submitted. This is not ideal from a user interface standpoint. One strategy to prevent this visual blip from happening is to make a hidden copy of the form to encrypt and submit, leaving the user's input visible in the original form. + +### Maintain Security for Users without JavaScript + +In a naive implementation, users without JavaScript could end up submitting their credit cards to your server in the clear. You'll need to take steps to ensure that a user can never enter their credit card without it being securely handled. The simplest way to achieve is to wrap your payment form in a `noscript` tag. + +## Retrieving your Encryption Key + +When Client-Side encryption is enabled for your Braintree Gateway account, a key pair is generated and you are given a specially formatted version of the public key. + diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..5e28add --- /dev/null +++ b/Rakefile @@ -0,0 +1,95 @@ +require 'erb' + +ROOT_DIR = File.expand_path(File.dirname(__FILE__)) +BUILD_DIR = File.join(ROOT_DIR, "build") +SPEC_DIR = File.join(ROOT_DIR, "spec") +LIB_DIR = File.join(ROOT_DIR, "lib") +PIDCRYPT_DIR = File.join(LIB_DIR, "pidCrypt") +TARGET_DIR = File.join(ROOT_DIR, "target") +SPEC_RUNNER = File.join(SPEC_DIR, "SpecRunner.html") +SJCL_DIR = File.join(LIB_DIR, "sjcl/core") + +BRAINTREE_VERSION = File.read("#{LIB_DIR}/braintree.js")[/version: '([0-9.]+)'/, 1] + +task :default => "test:run_default" + +namespace :test do + task :all do + %w[chrome safari firefox].each do |browser| + Rake::Task["test:run_#{browser}"].invoke + sleep 3 + end + end + + task :clean do + rm_rf "#{File.dirname(__FILE__)}/spec/SpecRunner.html" + end + + task :prepare => ["test:clean", "build"] do + template = ERB.new(File.read("#{SPEC_DIR}/SpecRunner.html.erb")) + spec_files = Dir.glob("#{SPEC_DIR}/*.js") + + result = template.result(binding) + + File.open("#{SPEC_DIR}/SpecRunner.html", "w") do |f| + f << result + end + end + + task :run_chrome => :prepare do + `open -a 'Google Chrome' #{SPEC_RUNNER}` + end + + task :run_safari => :prepare do + `open -a Safari #{SPEC_RUNNER}` + end + + task :run_firefox => :prepare do + `open -a Firefox #{SPEC_RUNNER}` + end + + task :run_default => :prepare do + `open #{SPEC_RUNNER}` + end +end + +namespace :build do + task :clean do + rm_rf TARGET_DIR + mkdir TARGET_DIR + end + + task :bundle => ["build:clean"] do + files = %W[ + #{BUILD_DIR}/bundle_header.js + #{PIDCRYPT_DIR}/pidcrypt.js + #{PIDCRYPT_DIR}/pidcrypt_util.js + #{PIDCRYPT_DIR}/prng4.js + #{PIDCRYPT_DIR}/rng.js + #{PIDCRYPT_DIR}/asn1.js + #{PIDCRYPT_DIR}/jsbn.js + #{PIDCRYPT_DIR}/rsa.js + + #{SJCL_DIR}/sjcl.js + #{SJCL_DIR}/aes.js + #{SJCL_DIR}/bitArray.js + #{SJCL_DIR}/codecHex.js + #{SJCL_DIR}/codecString.js + #{SJCL_DIR}/codecBase64.js + #{SJCL_DIR}/cbc.js + #{SJCL_DIR}/sha256.js + #{SJCL_DIR}/random.js + + #{LIB_DIR}/braintree.js + #{BUILD_DIR}/bundle_footer.js + ] + `cat #{files.join(' ')} >> #{TARGET_DIR}/braintree-#{BRAINTREE_VERSION}.js` + end + + task :minify => ["build:bundle"] do + `cat #{BUILD_DIR}/minified_header.js > #{TARGET_DIR}/braintree-#{BRAINTREE_VERSION}.min.js` + `ruby #{BUILD_DIR}/jsmin.rb < #{TARGET_DIR}/braintree-#{BRAINTREE_VERSION}.js >> #{TARGET_DIR}/braintree-#{BRAINTREE_VERSION}.min.js` + end +end + +task :build => ["build:clean", "build:bundle", "build:minify"] diff --git a/build/bundle_footer.js b/build/bundle_footer.js new file mode 100644 index 0000000..9843d71 --- /dev/null +++ b/build/bundle_footer.js @@ -0,0 +1,3 @@ +return Braintree; +})(); + diff --git a/build/bundle_header.js b/build/bundle_header.js new file mode 100644 index 0000000..0cc8b92 --- /dev/null +++ b/build/bundle_header.js @@ -0,0 +1 @@ +Braintree = (function () { diff --git a/build/jsmin.rb b/build/jsmin.rb new file mode 100644 index 0000000..11199b0 --- /dev/null +++ b/build/jsmin.rb @@ -0,0 +1,205 @@ +#!/usr/bin/ruby +# jsmin.rb 2007-07-20 +# Author: Uladzislau Latynski +# This work is a translation from C to Ruby of jsmin.c published by +# Douglas Crockford. Permission is hereby granted to use the Ruby +# version under the same conditions as the jsmin.c on which it is +# based. +# +# /* jsmin.c +# 2003-04-21 +# +# Copyright (c) 2002 Douglas Crockford (www.crockford.com) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy of +# this software and associated documentation files (the "Software"), to deal in +# the Software without restriction, including without limitation the rights to +# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +# of the Software, and to permit persons to whom the Software is furnished to do +# so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# The Software shall be used for Good, not Evil. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +EOF = -1 +$theA = "" +$theB = "" + +# isAlphanum -- return true if the character is a letter, digit, underscore, +# dollar sign, or non-ASCII character +def isAlphanum(c) + return false if !c || c == EOF + return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || + c == '\\' || (c[0].class == String ? c[0].ord : c[0]) > 126) +end + +# get -- return the next character from stdin. Watch out for lookahead. If +# the character is a control character, translate it to a space or linefeed. +def get() + c = $stdin.getc + return EOF if(!c) + c = c.chr + return c if (c >= " " || c == "\n" || c.unpack("c") == EOF) + return "\n" if (c == "\r") + return " " +end + +# Get the next character without getting it. +def peek() + lookaheadChar = $stdin.getc + $stdin.ungetc(lookaheadChar) + return lookaheadChar.chr +end + +# mynext -- get the next character, excluding comments. +# peek() is used to see if a '/' is followed by a '/' or '*'. +def mynext() + c = get + if (c == "/") + if(peek == "/") + while(true) + c = get + if (c <= "\n") + return c + end + end + end + if(peek == "*") + get + while(true) + case get + when "*" + if (peek == "/") + get + return " " + end + when EOF + raise "Unterminated comment" + end + end + end + end + return c +end + + +# action -- do something! What you do is determined by the argument: 1 +# Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B. +# (Delete A). 3 Get the next B. (Delete B). action treats a string as a +# single character. Wow! action recognizes a regular expression if it is +# preceded by ( or , or =. +def action(a) + if(a==1) + $stdout.write $theA + end + if(a==1 || a==2) + $theA = $theB + if ($theA == "\'" || $theA == "\"") + while (true) + $stdout.write $theA + $theA = get + break if ($theA == $theB) + raise "Unterminated string literal" if ($theA <= "\n") + if ($theA == "\\") + $stdout.write $theA + $theA = get + end + end + end + end + if(a==1 || a==2 || a==3) + $theB = mynext + if ($theB == "/" && ($theA == "(" || $theA == "," || $theA == "=" || + $theA == ":" || $theA == "[" || $theA == "!" || + $theA == "&" || $theA == "|" || $theA == "?" || + $theA == "{" || $theA == "}" || $theA == ";" || + $theA == "\n")) + $stdout.write $theA + $stdout.write $theB + while (true) + $theA = get + if ($theA == "/") + break + elsif ($theA == "\\") + $stdout.write $theA + $theA = get + elsif ($theA <= "\n") + raise "Unterminated RegExp Literal" + end + $stdout.write $theA + end + $theB = mynext + end + end +end + +# jsmin -- Copy the input to the output, deleting the characters which are +# insignificant to JavaScript. Comments will be removed. Tabs will be +# replaced with spaces. Carriage returns will be replaced with linefeeds. +# Most spaces and linefeeds will be removed. +def jsmin + $theA = "\n" + action(3) + while ($theA != EOF) + case $theA + when " " + if (isAlphanum($theB)) + action(1) + else + action(2) + end + when "\n" + case ($theB) + when "{","[","(","+","-" + action(1) + when " " + action(3) + else + if (isAlphanum($theB)) + action(1) + else + action(2) + end + end + else + case ($theB) + when " " + if (isAlphanum($theA)) + action(1) + else + action(3) + end + when "\n" + case ($theA) + when "}","]",")","+","-","\"","\\", "'", '"' + action(1) + else + if (isAlphanum($theA)) + action(1) + else + action(3) + end + end + else + action(1) + end + end + end +end + +ARGV.each do |anArg| + $stdout.write "// #{anArg}\n" +end + +jsmin diff --git a/build/minified_header.js b/build/minified_header.js new file mode 100644 index 0000000..823d843 --- /dev/null +++ b/build/minified_header.js @@ -0,0 +1,14 @@ +/*! + * Braintree End-to-End Encryption Library + * http://www.braintreepayments.com + * + * Licensed under the MIT or GPL Version 2 licenses. + * + * Includes pidCrypt + * Copyright (c) 2009 pidder + * Released under the GPL License. + * + * Includes SJCL + * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh, Stanford University. + * Released under the GPL Version 2 License. + */ diff --git a/lib/braintree.js b/lib/braintree.js new file mode 100644 index 0000000..5f01f60 --- /dev/null +++ b/lib/braintree.js @@ -0,0 +1,54 @@ +for (k in sjcl.beware) { if (sjcl.beware.hasOwnProperty(k)) { sjcl.beware[k](); } } + +Braintree = { + pidCrypt: pidCrypt, + pidCryptUtil: pidCryptUtil, + sjcl: sjcl +}; + +Braintree.create = function (publicKey) { + var my = { + publicKey: publicKey + }; + + var generateAesKey = function () { + return { + key: sjcl.random.randomWords(8, 0), + encrypt: function(plainText) { + var aes = new sjcl.cipher.aes(this.key); + var iv = sjcl.random.randomWords(4, 0); + var plainTextBits = sjcl.codec.utf8String.toBits(plainText); + var cipherTextBits = sjcl.mode.cbc.encrypt(aes, plainTextBits, iv); + return sjcl.codec.base64.fromBits(sjcl.bitArray.concat(iv, cipherTextBits)); + }, + encryptKeyWithRsa: function(rsaKey) { + var encryptedKeyHex = rsaKey.encryptRaw(sjcl.codec.base64.fromBits(this.key)); + return pidCryptUtil.encodeBase64(pidCryptUtil.convertFromHex(encryptedKeyHex)); + } + }; + }; + + var rsaKey = function () { + var key = pidCryptUtil.decodeBase64(my.publicKey); + var rsa = new pidCrypt.RSA(); + var keyBytes = pidCryptUtil.toByteArray(key); + var asn = pidCrypt.ASN1.decode(keyBytes); + var tree = asn.toHexTree(); + rsa.setPublicKeyFromASN(tree); + + return rsa; + }; + + var encrypt = function (text) { + var key = generateAesKey(); + var aesEncryptedData = key.encrypt(text); + + return "$bt2$" + key.encryptKeyWithRsa(rsaKey()) + "$" + aesEncryptedData; + }; + + return { + encrypt: encrypt, + publicKey: my.publicKey, + version: '1.1.0' + }; +}; diff --git a/lib/pidCrypt/aes_cbc.js b/lib/pidCrypt/aes_cbc.js new file mode 100644 index 0000000..4378ece --- /dev/null +++ b/lib/pidCrypt/aes_cbc.js @@ -0,0 +1,417 @@ + /*----------------------------------------------------------------------------*/ + // Copyright (c) 2009 pidder + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*----------------------------------------------------------------------------*/ +/* +* AES CBC (Cipher Block Chaining) Mode for use in pidCrypt Library +* The pidCrypt AES CBC mode is compatible with openssl aes-xxx-cbc mode +* using the same algorithms for key and iv creation and padding as openssl. +* +* Depends on pidCrypt (pidcrypt.js, pidcrypt_util.js), AES (aes_core.js) +* and MD5 (md5.js) +* +/*----------------------------------------------------------------------------*/ + +if(typeof(pidCrypt) != 'undefined' && + typeof(pidCrypt.AES) != 'undefined' && + typeof(pidCrypt.MD5) != 'undefined') +{ + pidCrypt.AES.CBC = function () { + this.pidcrypt = new pidCrypt(); + this.aes = new pidCrypt.AES(this.pidcrypt); + //shortcuts to pidcrypt methods + this.getOutput = function(){ + return this.pidcrypt.getOutput(); + } + this.getAllMessages = function(lnbrk){ + return this.pidcrypt.getAllMessages(lnbrk); + } + this.isError = function(){ + return this.pidcrypt.isError(); + } + } +/** +* Initialize CBC for encryption from password. +* Note: Only for encrypt operation! +* @param password: String +* @param options { +* nBits: aes bit size (128, 192 or 256) +* } +*/ + pidCrypt.AES.CBC.prototype.init = function(password, options) { + if(!options) options = {}; + var pidcrypt = this.pidcrypt; + pidcrypt.setDefaults(); + var pObj = this.pidcrypt.getParams(); //loading defaults + for(var o in options) + pObj[o] = options[o]; + var k_iv = this.createKeyAndIv({password:password, salt: pObj.salt, bits: pObj.nBits}); + pObj.key = k_iv.key; + pObj.iv = k_iv.iv; + pObj.dataOut = ''; + pidcrypt.setParams(pObj) + this.aes.init(); + } + +/** +* Initialize CBC for encryption from password. +* @param dataIn: plain text +* @param password: String +* @param options { +* nBits: aes bit size (128, 192 or 256) +* } +*/ + pidCrypt.AES.CBC.prototype.initEncrypt = function(dataIn, password, options) { + this.init(password,options);//call standard init + this.pidcrypt.setParams({dataIn:dataIn, encryptIn: pidCryptUtil.toByteArray(dataIn)})//setting input for encryption + } +/** +* Initialize CBC for decryption from encrypted text (compatible with openssl). +* see thread http://thedotnet.com/nntp/300307/showpost.aspx +* @param crypted: base64 encoded aes encrypted text +* @param passwd: String +* @param options { +* nBits: aes bit size (128, 192 or 256), +* UTF8: boolean, set to false when decrypting certificates, +* A0_PAD: boolean, set to false when decrypting certificates +* } +*/ + pidCrypt.AES.CBC.prototype.initDecrypt = function(crypted, password, options){ + if(!options) options = {}; + var pidcrypt = this.pidcrypt; + pidcrypt.setParams({dataIn:crypted}) + if(!password) + pidcrypt.appendError('pidCrypt.AES.CBC.initFromEncryption: Sorry, can not crypt or decrypt without password.\n'); + var ciphertext = pidCryptUtil.decodeBase64(crypted); + if(ciphertext.indexOf('Salted__') != 0) + pidcrypt.appendError('pidCrypt.AES.CBC.initFromCrypt: Sorry, unknown encryption method.\n'); + var salt = ciphertext.substr(8,8);//extract salt from crypted text + options.salt = pidCryptUtil.convertToHex(salt);//salt is always hex string + this.init(password,options);//call standard init + ciphertext = ciphertext.substr(16); + pidcrypt.setParams({decryptIn:pidCryptUtil.toByteArray(ciphertext)}) + } +/** +* Init CBC En-/Decryption from given parameters. +* @param input: plain text or base64 encrypted text +* @param key: HEX String (16, 24 or 32 byte) +* @param iv: HEX String (16 byte) +* @param options { +* salt: array of bytes (8 byte), +* nBits: aes bit size (128, 192 or 256) +* } +*/ + pidCrypt.AES.CBC.prototype.initByValues = function(dataIn, key, iv, options){ + var pObj = {}; + this.init('',options);//empty password, we are setting key, iv manually + pObj.dataIn = dataIn; + pObj.key = key + pObj.iv = iv + this.pidcrypt.setParams(pObj) + } + + pidCrypt.AES.CBC.prototype.getAllMessages = function(lnbrk){ + return this.pidcrypt.getAllMessages(lnbrk); + } +/** +* Creates key of length nBits and an iv form password+salt +* compatible to openssl. +* See thread http://thedotnet.com/nntp/300307/showpost.aspx +* +* @param pObj { +* password: password as String +* [salt]: salt as String, default 8 byte random salt +* [bits]: no of bits, default pidCrypt.params.nBits = 256 +* } +* +* @return {iv: HEX String, key: HEX String} +*/ + pidCrypt.AES.CBC.prototype.createKeyAndIv = function(pObj){ + var pidcrypt = this.pidcrypt; + var retObj = {}; + var count = 1;//openssl rounds + var miter = "3"; + if(!pObj) pObj = {}; + if(!pObj.salt) { + pObj.salt = pidcrypt.getRandomBytes(8); + pObj.salt = pidCryptUtil.convertToHex(pidCryptUtil.byteArray2String(pObj.salt)); + pidcrypt.setParams({salt: pObj.salt}); + } + var data00 = pObj.password + pidCryptUtil.convertFromHex(pObj.salt); + var hashtarget = ''; + var result = ''; + var keymaterial = []; + var loop = 0; + keymaterial[loop++] = data00; + for(var j=0; j*/ +/*----------------------------------------------------------------------------*/ +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 3 of the +// License, or (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +// 02111-1307 USA or check at http://www.gnu.org/licenses/gpl.html + +/*----------------------------------------------------------------------------*/ +/* +* pidCrypt AES core implementation for block en-/decryption for use in pidCrypt +* Library. +* Derived from jsaes version 0.1 (See original license below) +* Only minor Changes (e.g. using a precompiled this.SBoxInv) and port to an +* AES Core Class for use with different AES modes. +* +* Depends on pidCrypt (pidcrypt.js, pidcrypt_util.js) +/*----------------------------------------------------------------------------*/ +/* jsaes version 0.1 - Copyright 2006 B. Poettering + * http://point-at-infinity.org/jsaes/ + * Report bugs to: jsaes AT point-at-infinity.org + * + * + * This is a javascript implementation of the AES block cipher. Key lengths + * of 128, 192 and 256 bits are supported. + * The well-functioning of the encryption/decryption routines has been + * verified for different key lengths with the test vectors given in + * FIPS-197, Appendix C. + * The following code example enciphers the plaintext block '00 11 22 .. EE FF' + * with the 256 bit key '00 01 02 .. 1E 1F'. + * AES_Init(); + * var block = new Array(16); + * for(var i = 0; i < 16; i++) + * block[i] = 0x11 * i; + * var key = new Array(32); + * for(var i = 0; i < 32; i++) + * key[i] = i; + * AES_ExpandKey(key); + * AES_Encrypt(block, key); + * AES_Done(); +/*----------------------------------------------------------------------------*/ + +if(typeof(pidCrypt) != 'undefined'){ + pidCrypt.AES = function(env) { + this.env = (env) ? env : new pidCrypt(); + this.blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES + this.ShiftRowTabInv; //initialized by init() + this.xtime; //initialized by init() + this.SBox = new Array( + 99,124,119,123,242,107,111,197,48,1,103,43,254,215,171, + 118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253, + 147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154, + 7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227, + 47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170, + 251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245, + 188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61, + 100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224, + 50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213, + 78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221, + 116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29, + 158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161, + 137,13,191,230,66,104,65,153,45,15,176,84,187,22 + ); + this.SBoxInv = new Array( + 82,9,106,213,48,54,165,56,191,64,163,158,129,243,215, + 251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50, + 166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91, + 162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101, + 182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216, + 171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193, + 175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180, + 230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241, + 26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32, + 154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39, + 128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224, + 59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38, + 225,105,20,99,85,33,12,125 + ); + this.ShiftRowTab = new Array(0,5,10,15,4,9,14,3,8,13,2,7,12,1,6,11); + } +/* +init: initialize the tables needed at runtime. Call this function +before the (first) key expansion. +*/ + pidCrypt.AES.prototype.init = function() { + this.env.setParams({blockSize:this.blockSize}); + this.ShiftRowTabInv = new Array(16); + for(var i = 0; i < 16; i++) + this.ShiftRowTabInv[this.ShiftRowTab[i]] = i; + this.xtime = new Array(256); + for(i = 0; i < 128; i++) { + this.xtime[i] = i << 1; + this.xtime[128 + i] = (i << 1) ^ 0x1b; + } + } +/* +AES_ExpandKey: expand a cipher key. Depending on the desired encryption +strength of 128, 192 or 256 bits 'key' has to be a byte array of length +16, 24 or 32, respectively. The key expansion is done "in place", meaning +that the array 'key' is modified. +*/ + pidCrypt.AES.prototype.expandKey = function(input) { + var key = input.slice(); + var kl = key.length, ks, Rcon = 1; + switch (kl) { + case 16: ks = 16 * (10 + 1); break; + case 24: ks = 16 * (12 + 1); break; + case 32: ks = 16 * (14 + 1); break; + default: + alert("AESCore.expandKey: Only key lengths of 16, 24 or 32 bytes allowed!"); + } + for(var i = kl; i < ks; i += 4) { + var temp = key.slice(i - 4, i); + if (i % kl == 0) { + temp = new Array(this.SBox[temp[1]] ^ Rcon, this.SBox[temp[2]], + this.SBox[temp[3]], this.SBox[temp[0]]); + if ((Rcon <<= 1) >= 256) + Rcon ^= 0x11b; + } + else if ((kl > 24) && (i % kl == 16)) + temp = new Array(this.SBox[temp[0]], this.SBox[temp[1]], + this.SBox[temp[2]], this.SBox[temp[3]]); + for(var j = 0; j < 4; j++) + key[i + j] = key[i + j - kl] ^ temp[j]; + } + return key; + } +/* +AES_Encrypt: encrypt the 16 byte array 'block' with the previously +expanded key 'key'. +*/ + pidCrypt.AES.prototype.encrypt = function(input, key) { + var l = key.length; + var block = input.slice(); + this.addRoundKey(block, key.slice(0, 16)); + for(var i = 16; i < l - 16; i += 16) { + this.subBytes(block); + this.shiftRows(block); + this.mixColumns(block); + this.addRoundKey(block, key.slice(i, i + 16)); + } + this.subBytes(block); + this.shiftRows(block); + this.addRoundKey(block, key.slice(i, l)); + + return block; + } +/* +AES_Decrypt: decrypt the 16 byte array 'block' with the previously +expanded key 'key'. +*/ + pidCrypt.AES.prototype.decrypt = function(input, key) { + var l = key.length; + var block = input.slice(); + this.addRoundKey(block, key.slice(l - 16, l)); + this.shiftRows(block, 1);//1=inverse operation + this.subBytes(block, 1);//1=inverse operation + for(var i = l - 32; i >= 16; i -= 16) { + this.addRoundKey(block, key.slice(i, i + 16)); + this.mixColumns_Inv(block); + this.shiftRows(block, 1);//1=inverse operation + this.subBytes(block, 1);//1=inverse operation + } + this.addRoundKey(block, key.slice(0, 16)); + + return block; + } + pidCrypt.AES.prototype.subBytes = function(state, inv) { + var box = (typeof(inv) == 'undefined') ? this.SBox.slice() : this.SBoxInv.slice(); + for(var i = 0; i < 16; i++) + state[i] = box[state[i]]; + } + pidCrypt.AES.prototype.addRoundKey = function(state, rkey) { + for(var i = 0; i < 16; i++) + state[i] ^= rkey[i]; + } + pidCrypt.AES.prototype.shiftRows = function(state, inv) { + var shifttab = (typeof(inv) == 'undefined') ? this.ShiftRowTab.slice() : this.ShiftRowTabInv.slice(); + var h = new Array().concat(state); + for(var i = 0; i < 16; i++) + state[i] = h[shifttab[i]]; + } + pidCrypt.AES.prototype.mixColumns = function(state) { + for(var i = 0; i < 16; i += 4) { + var s0 = state[i + 0], s1 = state[i + 1]; + var s2 = state[i + 2], s3 = state[i + 3]; + var h = s0 ^ s1 ^ s2 ^ s3; + state[i + 0] ^= h ^ this.xtime[s0 ^ s1]; + state[i + 1] ^= h ^ this.xtime[s1 ^ s2]; + state[i + 2] ^= h ^ this.xtime[s2 ^ s3]; + state[i + 3] ^= h ^ this.xtime[s3 ^ s0]; + } + } + pidCrypt.AES.prototype.mixColumns_Inv = function(state) { + for(var i = 0; i < 16; i += 4) { + var s0 = state[i + 0], s1 = state[i + 1]; + var s2 = state[i + 2], s3 = state[i + 3]; + var h = s0 ^ s1 ^ s2 ^ s3; + var xh = this.xtime[h]; + var h1 = this.xtime[this.xtime[xh ^ s0 ^ s2]] ^ h; + var h2 = this.xtime[this.xtime[xh ^ s1 ^ s3]] ^ h; + state[i + 0] ^= h1 ^ this.xtime[s0 ^ s1]; + state[i + 1] ^= h2 ^ this.xtime[s1 ^ s2]; + state[i + 2] ^= h1 ^ this.xtime[s2 ^ s3]; + state[i + 3] ^= h2 ^ this.xtime[s3 ^ s0]; + } + } +// xor the elements of two arrays together + pidCrypt.AES.prototype.xOr_Array = function( a1, a2 ){ + var i; + var res = Array(); + for( i=0; i>> i*8) & 0xff; + for (var i=0; i<4; i++) ctrBlk[i+4] = nonceMs & 0xff; + + return ctrBlk.slice(); + } +} diff --git a/lib/pidCrypt/aes_ctr.js b/lib/pidCrypt/aes_ctr.js new file mode 100644 index 0000000..ea3240c --- /dev/null +++ b/lib/pidCrypt/aes_ctr.js @@ -0,0 +1,335 @@ + /*----------------------------------------------------------------------------*/ + // Copyright (c) 2009 pidder + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*----------------------------------------------------------------------------*/ +/* +* AES CTR (Counter) Mode for use in pidCrypt Library +* The pidCrypt AES CTR is based on the implementation by Chris Veness 2005-2008. +* See http://www.movable-type.co.uk/scripts/aes.html for details and for his +* great job. +* +* Depends on pidCrypt (pcrypt.js, pidcrypt_util.js), AES (aes_core.js) +/*----------------------------------------------------------------------------*/ +/* AES implementation in JavaScript (c) Chris Veness 2005-2008 +* You are welcome to re-use these scripts [without any warranty express or +* implied] provided you retain my copyright notice and when possible a link to +* my website (under a LGPL license). §ection numbers relate the code back to +* sections in the standard. +/*----------------------------------------------------------------------------*/ +if(typeof(pidCrypt) != 'undefined' && typeof(pidCrypt.AES) != 'undefined') +{ + pidCrypt.AES.CTR = function () { + this.pidcrypt = new pidCrypt(); + this.aes = new pidCrypt.AES(this.pidcrypt); + //shortcuts to pidcrypt methods + this.getOutput = function(){ + return this.pidcrypt.getOutput(); + } + this.getAllMessages = function(lnbrk){ + return this.pidcrypt.getAllMessages(lnbrk); + } + this.isError = function(){ + return this.pidcrypt.isError(); + } + } +/** + * Initialize CTR for encryption from password. + * @param password: String + * @param options { + * nBits: aes bit size (128, 192 or 256) + * } +*/ + pidCrypt.AES.CTR.prototype.init = function(password, options) { + if(!options) options = {}; + if(!password) + this.pidcrypt.appendError('pidCrypt.AES.CTR.initFromEncryption: Sorry, can not crypt or decrypt without password.\n'); + this.pidcrypt.setDefaults(); + var pObj = this.pidcrypt.getParams(); //loading defaults + for(var o in options) + pObj[o] = options[o]; + pObj.password = password; + pObj.key = password; + pObj.dataOut = ''; + this.pidcrypt.setParams(pObj); + this.aes.init(); + } + +/** +* Init CTR Encryption from password. +* @param dataIn: plain text +* @param password: String +* @param options { +* nBits: aes bit size (128, 192 or 256) +* } +*/ + pidCrypt.AES.CTR.prototype.initEncrypt = function(dataIn, password, options) { + this.init(password, options); + this.pidcrypt.setParams({dataIn:dataIn, encryptIn: pidCryptUtil.toByteArray(dataIn)})//setting input for encryption + } +/** +* Init CTR for decryption from encrypted text (encrypted with pidCrypt.AES.CTR) +* @param crypted: base64 encrypted text +* @param password: String +* @param options { +* nBits: aes bit size (128, 192 or 256) +* } +*/ + pidCrypt.AES.CTR.prototype.initDecrypt = function(crypted, password, options){ + var pObj = {}; + this.init(password, options); + pObj.dataIn = crypted; + var cipherText = pidCryptUtil.decodeBase64(crypted); + // recover nonce from 1st 8 bytes of ciphertext + var salt = cipherText.substr(0,8);//nonce in ctr + pObj.salt = pidCryptUtil.convertToHex(salt); + cipherText = cipherText.substr(8) + pObj.decryptIn = pidCryptUtil.toByteArray(cipherText); + this.pidcrypt.setParams(pObj); + } + + pidCrypt.AES.CTR.prototype.getAllMessages = function(lnbrk){ + return this.pidcrypt.getAllMessages(lnbrk); + } + + pidCrypt.AES.CTR.prototype.getCounterBlock = function(bs){ +// initialise counter block (NIST SP800-38A §B.2): millisecond time-stamp for +// nonce in 1st 8 bytes, block counter in 2nd 8 bytes + var ctrBlk = new Array(bs); + var nonce = (new Date()).getTime(); // timestamp: milliseconds since 1-Jan-1970 + var nonceSec = Math.floor(nonce/1000); + var nonceMs = nonce%1000; + // encode nonce with seconds in 1st 4 bytes, and (repeated) ms part filling + // 2nd 4 bytes + for (var i=0; i<4; i++) ctrBlk[i] = (nonceSec >>> i*8) & 0xff; + for (i=0; i<4; i++) ctrBlk[i+4] = nonceMs & 0xff; + + return ctrBlk.slice(); + } + +/** +* Encrypt a text using AES encryption in CTR mode of operation +* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf +* one of the pidCrypt.AES.CTR init funtions must be called before execution +* +* @param plaintext: text to encrypt +* +* +* @return encrypted text +*/ + pidCrypt.AES.CTR.prototype.encryptRaw = function(byteArray) { + var aes = this.aes; + var pidcrypt = this.pidcrypt; + var p = pidcrypt.getParams(); //get parameters for operation set by init + if(!byteArray) + byteArray = p.encryptIn; + pidcrypt.setParams({encryptIn:byteArray}); + var password = p.key; + // use AES itself to encrypt password to get cipher key (using plain + // password as source for key expansion) - gives us well encrypted key + var nBytes = Math.floor(p.nBits/8); // no bytes in key + var pwBytes = new Array(nBytes); + for (var i=0; i>> c*8) & 0xff; + for (var c=0; c<4; c++) counterBlock[15-c-4] = (b/0x100000000 >>> c*8) + var cipherCntr = aes.encrypt(counterBlock, keySchedule); // -- encrypt counter block -- + // block size is reduced on final block + var blockLength = b>> c*8) & 0xff; + for (c=0; c<4; c++) counterBlock[15-c-4] = (((b+1)/0x100000000-1) >>> c*8) & 0xff; + cipherCntr = aes.encrypt(counterBlock, keySchedule); // encrypt counter block + plaintxtByte = new Array(blockArray[b].length); + for (i=0; i + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*----------------------------------------------------------------------------*/ +/* +* ASN1 parser for use in pidCrypt Library +* The pidCrypt ASN1 parser is based on the implementation +* by Lapo Luchini 2008-2009. See http://lapo.it/asn1js/ for details and +* for his great job. +* +* Depends on pidCrypt (pcrypt.js & pidcrypt_util). +* For supporting Object Identifiers found in ASN.1 structure you must +* include oids (oids.js). +* But be aware that oids.js is really big (~> 1500 lines). +*/ +/*----------------------------------------------------------------------------*/ +// ASN.1 JavaScript decoder +// Copyright (c) 2008-2009 Lapo Luchini + +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*----------------------------------------------------------------------------*/ + +function Stream(enc, pos) { + if (enc instanceof Stream) { + this.enc = enc.enc; + this.pos = enc.pos; + } else { + this.enc = enc; + this.pos = pos; + } +} + +//pidCrypt extensions start +//hex string +Stream.prototype.parseStringHex = function(start, end) { + if(typeof(end) == 'undefined') end = this.enc.length; + var s = ""; + for (var i = start; i < end; ++i) { + var h = this.get(i); + s += this.hexDigits.charAt(h >> 4) + this.hexDigits.charAt(h & 0xF); + } + return s; +} +//pidCrypt extensions end + +Stream.prototype.get = function(pos) { + if (pos == undefined) + pos = this.pos++; + if (pos >= this.enc.length) + throw 'Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length; + + return this.enc[pos]; +} +Stream.prototype.hexDigits = "0123456789ABCDEF"; +Stream.prototype.hexDump = function(start, end) { + var s = ""; + for (var i = start; i < end; ++i) { + var h = this.get(i); + s += this.hexDigits.charAt(h >> 4) + this.hexDigits.charAt(h & 0xF); + if ((i & 0xF) == 0x7) + s += ' '; + s += ((i & 0xF) == 0xF) ? '\n' : ' '; + } + + return s; +} +Stream.prototype.parseStringISO = function(start, end) { + var s = ""; + for (var i = start; i < end; ++i) + s += String.fromCharCode(this.get(i)); + + return s; +} +Stream.prototype.parseStringUTF = function(start, end) { + var s = "", c = 0; + for (var i = start; i < end; ) { + var c = this.get(i++); + if (c < 128) + s += String.fromCharCode(c); + else + if ((c > 191) && (c < 224)) + s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F)); + else + s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F)); + //TODO: this doesn't check properly 'end', some char could begin before and end after + } + return s; +} +Stream.prototype.reTime = /^((?:1[89]|2\d)?\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; +Stream.prototype.parseTime = function(start, end) { + var s = this.parseStringISO(start, end); + var m = this.reTime.exec(s); + if (!m) + return "Unrecognized time: " + s; + s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4]; + if (m[5]) { + s += ":" + m[5]; + if (m[6]) { + s += ":" + m[6]; + if (m[7]) + s += "." + m[7]; + } + } + if (m[8]) { + s += " UTC"; + if (m[8] != 'Z') { + s += m[8]; + if (m[9]) + s += ":" + m[9]; + } + } + return s; +} +Stream.prototype.parseInteger = function(start, end) { + if ((end - start) > 4) + return undefined; + //TODO support negative numbers + var n = 0; + for (var i = start; i < end; ++i) + n = (n << 8) | this.get(i); + + return n; +} +Stream.prototype.parseOID = function(start, end) { + var s, n = 0, bits = 0; + for (var i = start; i < end; ++i) { + var v = this.get(i); + n = (n << 7) | (v & 0x7F); + bits += 7; + if (!(v & 0x80)) { // finished + if (s == undefined) + s = parseInt(n / 40) + "." + (n % 40); + else + s += "." + ((bits >= 31) ? "big" : n); + n = bits = 0; + } + s += String.fromCharCode(); + } + return s; +} + +if(typeof(pidCrypt) != 'undefined') +{ + pidCrypt.ASN1 = function(stream, header, length, tag, sub) { + this.stream = stream; + this.header = header; + this.length = length; + this.tag = tag; + this.sub = sub; + } + //pidCrypt extensions start + // + //gets the ASN data as tree of hex strings + //@returns node: as javascript object tree with hex strings as values + //e.g. RSA Public Key gives + // { + // SEQUENCE: + // { + // INTEGER: modulus, + // INTEGER: public exponent + // } + //} + pidCrypt.ASN1.prototype.toHexTree = function() { + var node = {}; + node.type = this.typeName(); + if(node.type != 'SEQUENCE') + node.value = this.stream.parseStringHex(this.posContent(),this.posEnd()); + if (this.sub != null) { + node.sub = []; + for (var i = 0, max = this.sub.length; i < max; ++i) + node.sub[i] = this.sub[i].toHexTree(); + } + return node; + } + //pidCrypt extensions end + + pidCrypt.ASN1.prototype.typeName = function() { + if (this.tag == undefined) + return "unknown"; + var tagClass = this.tag >> 6; + var tagConstructed = (this.tag >> 5) & 1; + var tagNumber = this.tag & 0x1F; + switch (tagClass) { + case 0: // universal + switch (tagNumber) { + case 0x00: return "EOC"; + case 0x01: return "BOOLEAN"; + case 0x02: return "INTEGER"; + case 0x03: return "BIT_STRING"; + case 0x04: return "OCTET_STRING"; + case 0x05: return "NULL"; + case 0x06: return "OBJECT_IDENTIFIER"; + case 0x07: return "ObjectDescriptor"; + case 0x08: return "EXTERNAL"; + case 0x09: return "REAL"; + case 0x0A: return "ENUMERATED"; + case 0x0B: return "EMBEDDED_PDV"; + case 0x0C: return "UTF8String"; + case 0x10: return "SEQUENCE"; + case 0x11: return "SET"; + case 0x12: return "NumericString"; + case 0x13: return "PrintableString"; // ASCII subset + case 0x14: return "TeletexString"; // aka T61String + case 0x15: return "VideotexString"; + case 0x16: return "IA5String"; // ASCII + case 0x17: return "UTCTime"; + case 0x18: return "GeneralizedTime"; + case 0x19: return "GraphicString"; + case 0x1A: return "VisibleString"; // ASCII subset + case 0x1B: return "GeneralString"; + case 0x1C: return "UniversalString"; + case 0x1E: return "BMPString"; + default: return "Universal_" + tagNumber.toString(16); + } + case 1: return "Application_" + tagNumber.toString(16); + case 2: return "[" + tagNumber + "]"; // Context + case 3: return "Private_" + tagNumber.toString(16); + } + } + pidCrypt.ASN1.prototype.content = function() { + if (this.tag == undefined) + return null; + var tagClass = this.tag >> 6; + if (tagClass != 0) // universal + return null; + var tagNumber = this.tag & 0x1F; + var content = this.posContent(); + var len = Math.abs(this.length); + switch (tagNumber) { + case 0x01: // BOOLEAN + return (this.stream.get(content) == 0) ? "false" : "true"; + case 0x02: // INTEGER + return this.stream.parseInteger(content, content + len); + //case 0x03: // BIT_STRING + //case 0x04: // OCTET_STRING + //case 0x05: // NULL + case 0x06: // OBJECT_IDENTIFIER + return this.stream.parseOID(content, content + len); + //case 0x07: // ObjectDescriptor + //case 0x08: // EXTERNAL + //case 0x09: // REAL + //case 0x0A: // ENUMERATED + //case 0x0B: // EMBEDDED_PDV + //case 0x10: // SEQUENCE + //case 0x11: // SET + case 0x0C: // UTF8String + return this.stream.parseStringUTF(content, content + len); + case 0x12: // NumericString + case 0x13: // PrintableString + case 0x14: // TeletexString + case 0x15: // VideotexString + case 0x16: // IA5String + //case 0x19: // GraphicString + case 0x1A: // VisibleString + //case 0x1B: // GeneralString + //case 0x1C: // UniversalString + //case 0x1E: // BMPString + return this.stream.parseStringISO(content, content + len); + case 0x17: // UTCTime + case 0x18: // GeneralizedTime + return this.stream.parseTime(content, content + len); + } + return null; + } + pidCrypt.ASN1.prototype.toString = function() { + return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub == null) ? 'null' : this.sub.length) + "]"; + } + pidCrypt.ASN1.prototype.print = function(indent) { + if (indent == undefined) indent = ''; + document.writeln(indent + this); + if (this.sub != null) { + indent += ' '; + for (var i = 0, max = this.sub.length; i < max; ++i) + this.sub[i].print(indent); + } + } + pidCrypt.ASN1.prototype.toPrettyString = function(indent) { + if (indent == undefined) indent = ''; + var s = indent + this.typeName() + " @" + this.stream.pos; + if (this.length >= 0) + s += "+"; + s += this.length; + if (this.tag & 0x20) + s += " (constructed)"; + else + if (((this.tag == 0x03) || (this.tag == 0x04)) && (this.sub != null)) + s += " (encapsulates)"; + s += "\n"; + if (this.sub != null) { + indent += ' '; + for (var i = 0, max = this.sub.length; i < max; ++i) + s += this.sub[i].toPrettyString(indent); + } + return s; + } + pidCrypt.ASN1.prototype.toDOM = function() { + var node = document.createElement("div"); + node.className = "node"; + node.asn1 = this; + var head = document.createElement("div"); + head.className = "head"; + var s = this.typeName(); + head.innerHTML = s; + node.appendChild(head); + this.head = head; + var value = document.createElement("div"); + value.className = "value"; + s = "Offset: " + this.stream.pos + "
"; + s += "Length: " + this.header + "+"; + if (this.length >= 0) + s += this.length; + else + s += (-this.length) + " (undefined)"; + if (this.tag & 0x20) + s += "
(constructed)"; + else if (((this.tag == 0x03) || (this.tag == 0x04)) && (this.sub != null)) + s += "
(encapsulates)"; + var content = this.content(); + if (content != null) { + s += "
Value:
" + content + ""; + if ((typeof(oids) == 'object') && (this.tag == 0x06)) { + var oid = oids[content]; + if (oid) { + if (oid.d) s += "
" + oid.d; + if (oid.c) s += "
" + oid.c; + if (oid.w) s += "
(warning!)"; + } + } + } + value.innerHTML = s; + node.appendChild(value); + var sub = document.createElement("div"); + sub.className = "sub"; + if (this.sub != null) { + for (var i = 0, max = this.sub.length; i < max; ++i) + sub.appendChild(this.sub[i].toDOM()); + } + node.appendChild(sub); + head.switchNode = node; + head.onclick = function() { + var node = this.switchNode; + node.className = (node.className == "node collapsed") ? "node" : "node collapsed"; + }; + return node; + } + pidCrypt.ASN1.prototype.posStart = function() { + return this.stream.pos; + } + pidCrypt.ASN1.prototype.posContent = function() { + return this.stream.pos + this.header; + } + pidCrypt.ASN1.prototype.posEnd = function() { + return this.stream.pos + this.header + Math.abs(this.length); + } + pidCrypt.ASN1.prototype.toHexDOM_sub = function(node, className, stream, start, end) { + if (start >= end) + return; + var sub = document.createElement("span"); + sub.className = className; + sub.appendChild(document.createTextNode( + stream.hexDump(start, end))); + node.appendChild(sub); + } + pidCrypt.ASN1.prototype.toHexDOM = function() { + var node = document.createElement("span"); + node.className = 'hex'; + this.head.hexNode = node; + this.head.onmouseover = function() { this.hexNode.className = 'hexCurrent'; } + this.head.onmouseout = function() { this.hexNode.className = 'hex'; } + this.toHexDOM_sub(node, "tag", this.stream, this.posStart(), this.posStart() + 1); + this.toHexDOM_sub(node, (this.length >= 0) ? "dlen" : "ulen", this.stream, this.posStart() + 1, this.posContent()); + if (this.sub == null) + node.appendChild(document.createTextNode( + this.stream.hexDump(this.posContent(), this.posEnd()))); + else if (this.sub.length > 0) { + var first = this.sub[0]; + var last = this.sub[this.sub.length - 1]; + this.toHexDOM_sub(node, "intro", this.stream, this.posContent(), first.posStart()); + for (var i = 0, max = this.sub.length; i < max; ++i) + node.appendChild(this.sub[i].toHexDOM()); + this.toHexDOM_sub(node, "outro", this.stream, last.posEnd(), this.posEnd()); + } + return node; + } + + /* + pidCrypt.ASN1.prototype.getValue = function() { + TODO + } + */ + pidCrypt.ASN1.decodeLength = function(stream) { + var buf = stream.get(); + var len = buf & 0x7F; + if (len == buf) + return len; + if (len > 3) + throw "Length over 24 bits not supported at position " + (stream.pos - 1); + if (len == 0) + return -1; // undefined + buf = 0; + for (var i = 0; i < len; ++i) + buf = (buf << 8) | stream.get(); + return buf; + } + pidCrypt.ASN1.hasContent = function(tag, len, stream) { + if (tag & 0x20) // constructed + return true; + if ((tag < 0x03) || (tag > 0x04)) + return false; + var p = new Stream(stream); + if (tag == 0x03) p.get(); // BitString unused bits, must be in [0, 7] + var subTag = p.get(); + if ((subTag >> 6) & 0x01) // not (universal or context) + return false; + try { + var subLength = pidCrypt.ASN1.decodeLength(p); + return ((p.pos - stream.pos) + subLength == len); + } catch (exception) { + return false; + } + } + pidCrypt.ASN1.decode = function(stream) { + if (!(stream instanceof Stream)) + stream = new Stream(stream, 0); + var streamStart = new Stream(stream); + var tag = stream.get(); + var len = pidCrypt.ASN1.decodeLength(stream); + var header = stream.pos - streamStart.pos; + var sub = null; + if (pidCrypt.ASN1.hasContent(tag, len, stream)) { + // it has content, so we decode it + var start = stream.pos; + if (tag == 0x03) stream.get(); // skip BitString unused bits, must be in [0, 7] + sub = []; + if (len >= 0) { + // definite length + var end = start + len; + while (stream.pos < end) + sub[sub.length] = pidCrypt.ASN1.decode(stream); + if (stream.pos != end) + throw "Content size is not correct for container starting at offset " + start; + } else { + // undefined length + try { + for (;;) { + var s = pidCrypt.ASN1.decode(stream); + if (s.tag == 0) + break; + sub[sub.length] = s; + } + len = start - stream.pos; + } catch (e) { + throw "Exception while decoding undefined length content: " + e; + } + } + } else + stream.pos += len; // skip content + return new pidCrypt.ASN1(streamStart, header, len, tag, sub); + } + pidCrypt.ASN1.test = function() { + var test = [ + { value: [0x27], expected: 0x27 }, + { value: [0x81, 0xC9], expected: 0xC9 }, + { value: [0x83, 0xFE, 0xDC, 0xBA], expected: 0xFEDCBA }, + ]; + for (var i = 0, max = test.length; i < max; ++i) { + var pos = 0; + var stream = new Stream(test[i].value, 0); + var res = pidCrypt.ASN1.decodeLength(stream); + if (res != test[i].expected) + document.write("In test[" + i + "] expected " + test[i].expected + " got " + res + "\n"); + } + } +} \ No newline at end of file diff --git a/lib/pidCrypt/gpl-3.0.txt b/lib/pidCrypt/gpl-3.0.txt new file mode 100644 index 0000000..10926e8 --- /dev/null +++ b/lib/pidCrypt/gpl-3.0.txt @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. 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 +them 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 prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. 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. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey 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; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + 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. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +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. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/lib/pidCrypt/history.txt b/lib/pidCrypt/history.txt new file mode 100644 index 0000000..4f0c1f8 --- /dev/null +++ b/lib/pidCrypt/history.txt @@ -0,0 +1,119 @@ +Release 005, +************** Changes ************** +- Removed the extending of javascript core classes removed of security issues in some enviroments + (e.g. Firefox AddOns) + - String.encodeBase64(utf8encode) -> pidCryptUtil.encodeBase64(str,utf8encode) + - String.decodeBase64(utf8decode) -> pidCryptUtil.decodeBase64(str,utf8decode) + - String.encodeUTF8() -> pidCryptUtil.encodeUTF8(str) + - String.decodeUTF8() -> pidCryptUtil.decodeUTF8(str) + - String.convertToHex() -> pidCryptUtil.convertToHex(str) + - String.convertFromHex() -> pidCryptUtil.convertFromHex(str) + - String.stripLineFeeds() -> pidCryptUtil.stripLineFeeds(str) + - String.toByteArray() -> pidCryptUtil.toByteArray(str) + - String.fragment(length,lf) -> pidCryptUtil.fragment(str,length,lf) + - String.formatHex(length) -> pidCryptUtil.formatHex(str,length) + For downward compatibility you can include string_extends.js + +************** New ************** +String + - Extending the javascript string class is now optional (string_extend.js) +Test + - test_hashes.html + + +Release 004, 02.11.2009 +Corrected distribution license to GPL v3 because the original code of the aes-core module is under +GNU license. + +Release 003, 09.06.2009 +************** Bug fixes ************** +- RSA decryption now returns an empty string instead of runtime error in case of + decryption failure + +************** New ************** +RSA + - new functions encryptRaw() and decryptRaw(). These functions do not encode + or decode the in-/output. + - getParameters(): returns the actual parameters as object + (n,e,d,p,q,dmp1,dmq1,c) +SHA + - new SHA-384 and SHA-512 Hash algorithms available +Test + - test: a simple html test page for each modul. Currently + - test_aes_cbc.html + - test_aes_ctr.html + - other test and demo pages visit http://www.pidder.com/pidcrypt + +Release 002, 31.03.2009 +************** Bug fixes ************** +- init now clears old output from previous operation +- appendError, appendInfo and appendDebug now return an empty string + to avoid runtime errors in the calling function +- the convert functions for hex strings now use native JS functions (parseInt, + toString(16)) making pidCrypt compatible with IE and Opera + +************** New ************** +pidCrypt + - setDefaults(), set all default values + - new enviroment parameter params.dataIn: stores input data + - new enviroment parameter params.dataOut: stores output data + - new enviroment parameter params.encryptIn: stores input data of encrypt + - new enviroment parameter params.encryptOut: stores output data of encrypt + - new enviroment parameter params.decryptIn: stores input data of decrypt + - new enviroment parameter params.decryptOut: stores output data of decrypt function + - new enviroment parameter params.clear. If set to false with options + the params are not cleared from memory (clear=true is overwritten by debug=true!). + - removed obsolete enviroment parameters input and output +pidCrypt util + - String.fragment(length,linefeed): fractionalizes a string into lines with + length and appends linefeed at the end of each line. + - String.stripLineFeeds: removes line feeds (0x10 und 0x13) from string + - String.formatHex: Formats a hex string in two lower case chars + : + and lines of given length characters +AES-CBC + - init(password, options), init without input (for decrypt you have to specify + the salt in options) + - isError() returns true if error messages are set by an operation + - new function encryptRaw(byteArray): no coding operations are done (eg. base64) + - new function decryptRaw(byteArray): no coding operations are done (eg. base64) + - new function encryptText(text,password,options): no init call is needed + - new function decryptText(text,password,options): no init call is needed +AES-CTR + - init(password, options), init without input (for decrypt you have to specify + the salt in options) + - isError() returns true if error messages are set by an operation + - new function encryptRaw(byteArray): no coding operations are done (eg. base64) + - new function decryptRaw(byteArray): no coding operations are done (eg. base64) + - new function encryptText(text,password,options): no init call is needed + - new function decryptText(text,password,options): no init call is needed + +************** Changes ************** +pidCrypt + - getAllMessages(options) has a new options parameter: With options.verbose + you can set the verbose level of the messages with any combination of 4 bits. + 1 = Error,2 = Warnings, 4 = Info, 8 = Debug. e.g. 10 (1010) gives you + warnings and debugs. options.clr_mes = true clears all previous messages. + - setParams(pObj) now sets all pObj parameters as params (eg. pObj.newParam + will create params.newParam with value pObj[newParam] +AES-CBC + - encrypt(text) and decrypt(cryptedtext) now understand the parameter input. + You can now call init() once and encrypt more than once with same parameters. +AES-CTR + - encrypt(input) and decrypt(input) now understand the parameter input. + You can now call init() once and encrypt more than once with same parameters. +SHA-1, SHA-256 + - SHA hashing routines without automatic UTF-8 encoding + +Release 001, 03.03.2009 +************** New ************** +Initial release supporting the following functions: + - Base64 + - UTF-8 + - MD5 + - SHA-1 + - SHA-256 + - AES CBC Mode + - AES CTR Mode + - RSA Encryption + - RSA encrypted private key files + - ASN.1 diff --git a/lib/pidCrypt/jsbn.js b/lib/pidCrypt/jsbn.js new file mode 100644 index 0000000..8dfc097 --- /dev/null +++ b/lib/pidCrypt/jsbn.js @@ -0,0 +1,1232 @@ +/* + * Copyright (c) 2003-2005 Tom Wu + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, + * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF + * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * In addition, the following condition applies: + * + * All redistributions must retain an intact copy of this copyright notice + * and disclaimer. + */ +//Address all questions regarding this license to: +// Tom Wu +// tjw@cs.Stanford.EDU +// Basic JavaScript BN library - subset useful for RSA encryption. + +// Bits per digit +var dbits; + +// JavaScript engine analysis +var canary = 0xdeadbeefcafe; +var j_lm = ((canary&0xffffff)==0xefcafe); + +// (public) Constructor +function BigInteger(a,b,c) { + + if(a != null) + if("number" == typeof a) this.fromNumber(a,b,c); + else if(b == null && "string" != typeof a) this.fromString(a,256); + else this.fromString(a,b); +} + +// return new, unset BigInteger +function nbi() { return new BigInteger(null); } + +// am: Compute w_j += (x*this_i), propagate carries, +// c is initial carry, returns final carry. +// c < 3*dvalue, x < 2*dvalue, this_i < dvalue +// We need to select the fastest one that works in this environment. + +// am1: use a single mult and divide to get the high bits, +// max digit bits should be 26 because +// max internal value = 2*dvalue^2-2*dvalue (< 2^53) +function am1(i,x,w,j,c,n) { + while(--n >= 0) { + var v = x*this[i++]+w[j]+c; + c = Math.floor(v/0x4000000); + w[j++] = v&0x3ffffff; + } + return c; +} +// am2 avoids a big mult-and-extract completely. +// Max digit bits should be <= 30 because we do bitwise ops +// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) +function am2(i,x,w,j,c,n) { + var xl = x&0x7fff, xh = x>>15; + while(--n >= 0) { + var l = this[i]&0x7fff; + var h = this[i++]>>15; + var m = xh*l+h*xl; + l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); + c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); + w[j++] = l&0x3fffffff; + } + return c; +} +// Alternately, set max digit bits to 28 since some +// browsers slow down when dealing with 32-bit numbers. +function am3(i,x,w,j,c,n) { + var xl = x&0x3fff, xh = x>>14; + while(--n >= 0) { + var l = this[i]&0x3fff; + var h = this[i++]>>14; + var m = xh*l+h*xl; + l = xl*l+((m&0x3fff)<<14)+w[j]+c; + c = (l>>28)+(m>>14)+xh*h; + w[j++] = l&0xfffffff; + } + return c; +} +if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { + BigInteger.prototype.am = am2; + dbits = 30; +} +else if(j_lm && (navigator.appName != "Netscape")) { + BigInteger.prototype.am = am1; + dbits = 26; +} +else { // Mozilla/Netscape seems to prefer am3 + BigInteger.prototype.am = am3; + dbits = 28; +} + +BigInteger.prototype.DB = dbits; +BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; + r.t = this.t; + r.s = this.s; +} + +// (protected) set from integer value x, -DV <= x < DV +function bnpFromInt(x) { + this.t = 1; + this.s = (x<0)?-1:0; + if(x > 0) this[0] = x; + else if(x < -1) this[0] = x+DV; + else this.t = 0; +} + +// return bigint initialized to value +function nbv(i) { var r = nbi(); r.fromInt(i); return r; } + +// (protected) set from string and radix +function bnpFromString(s,b) { + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 256) k = 8; // byte array + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else { this.fromRadix(s,b); return; } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while(--i >= 0) { + var x = (k==8)?s[i]&0xff:intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if(sh == 0) + this[this.t++] = x; + else if(sh+k > this.DB) { + this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); + } + else + this[this.t-1] |= x<= this.DB) sh -= this.DB; + } + if(k == 8 && (s[0]&0x80) != 0) { + this.s = -1; + if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; +} + +// (public) return string representation in given radix +function bnToString(b) { + if(this.s < 0) return "-"+this.negate().toString(b); + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else return this.toRadix(b); + var km = (1< 0) { + if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } + while(i >= 0) { + if(p < k) { + d = (this[i]&((1<>(p+=this.DB-k); + } + else { + d = (this[i]>>(p-=k))&km; + if(p <= 0) { p += this.DB; --i; } + } + if(d > 0) m = true; + if(m) r += int2char(d); + } + } + return m?r:"0"; +} + +// (public) -this +function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } + +// (public) |this| +function bnAbs() { return (this.s<0)?this.negate():this; } + +// (public) return + if this > a, - if this < a, 0 if equal +function bnCompareTo(a) { + var r = this.s-a.s; + if(r != 0) return r; + var i = this.t; + r = i-a.t; + if(r != 0) return r; + while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; + return 0; +} + +// returns bit length of the integer x +function nbits(x) { + var r = 1, t; + if((t=x>>>16) != 0) { x = t; r += 16; } + if((t=x>>8) != 0) { x = t; r += 8; } + if((t=x>>4) != 0) { x = t; r += 4; } + if((t=x>>2) != 0) { x = t; r += 2; } + if((t=x>>1) != 0) { x = t; r += 1; } + return r; +} + +// (public) return the number of bits in "this" +function bnBitLength() { + if(this.t <= 0) return 0; + return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); +} + +// (protected) r = this << n*DB +function bnpDLShiftTo(n,r) { + var i; + for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; + for(i = n-1; i >= 0; --i) r[i] = 0; + r.t = this.t+n; + r.s = this.s; +} + +// (protected) r = this >> n*DB +function bnpDRShiftTo(n,r) { + for(var i = n; i < this.t; ++i) r[i-n] = this[i]; + r.t = Math.max(this.t-n,0); + r.s = this.s; +} + +// (protected) r = this << n +function bnpLShiftTo(n,r) { + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<= 0; --i) { + r[i+ds+1] = (this[i]>>cbs)|c; + c = (this[i]&bm)<= 0; --i) r[i] = 0; + r[ds] = c; + r.t = this.t+ds+1; + r.s = this.s; + r.clamp(); +} + +// (protected) r = this >> n +function bnpRShiftTo(n,r) { + r.s = this.s; + var ds = Math.floor(n/this.DB); + if(ds >= this.t) { r.t = 0; return; } + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<>bs; + for(var i = ds+1; i < this.t; ++i) { + r[i-ds-1] |= (this[i]&bm)<>bs; + } + if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; + } + if(a.t < this.t) { + c -= a.s; + while(i < this.t) { + c += this[i]; + r[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while(i < a.t) { + c -= a[i]; + r[i++] = c&this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c<0)?-1:0; + if(c < -1) r[i++] = this.DV+c; + else if(c > 0) r[i++] = c; + r.t = i; + r.clamp(); +} + +// (protected) r = this * a, r != this,a (HAC 14.12) +// "this" should be the larger one if appropriate. +function bnpMultiplyTo(a,r) { + var x = this.abs(), y = a.abs(); + var i = x.t; + r.t = i+y.t; + while(--i >= 0) r[i] = 0; + for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); + r.s = 0; + r.clamp(); + if(this.s != a.s) BigInteger.ZERO.subTo(r,r); +} + +// (protected) r = this^2, r != this (HAC 14.16) +function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2*x.t; + while(--i >= 0) r[i] = 0; + for(i = 0; i < x.t-1; ++i) { + var c = x.am(i,x[i],r,2*i,0,1); + if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { + r[i+x.t] -= x.DV; + r[i+x.t+1] = 1; + } + } + if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); + r.s = 0; + r.clamp(); +} + +// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) +// r != q, this != m. q or r may be null. +function bnpDivRemTo(m,q,r) { + var pm = m.abs(); + if(pm.t <= 0) return; + var pt = this.abs(); + if(pt.t < pm.t) { + if(q != null) q.fromInt(0); + if(r != null) this.copyTo(r); + return; + } + if(r == null) r = nbi(); + var y = nbi(), ts = this.s, ms = m.s; + var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus + if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } + else { pm.copyTo(y); pt.copyTo(r); } + var ys = y.t; + var y0 = y[ys-1]; + if(y0 == 0) return; + var yt = y0*(1<1)?y[ys-2]>>this.F2:0); + var d1 = this.FV/yt, d2 = (1<= 0) { + r[r.t++] = 1; + r.subTo(t,r); + } + BigInteger.ONE.dlShiftTo(ys,t); + t.subTo(y,y); // "negative" y so we can replace sub with am later + while(y.t < ys) y[y.t++] = 0; + while(--j >= 0) { + // Estimate quotient digit + var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); + if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out + y.dlShiftTo(j,t); + r.subTo(t,r); + while(r[i] < --qd) r.subTo(t,r); + } + } + if(q != null) { + r.drShiftTo(ys,q); + if(ts != ms) BigInteger.ZERO.subTo(q,q); + } + r.t = ys; + r.clamp(); + if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder + if(ts < 0) BigInteger.ZERO.subTo(r,r); +} + +// (public) this mod a +function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a,null,r); + if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); + return r; +} + +// Modular reduction using "classic" algorithm +function Classic(m) { this.m = m; } +function cConvert(x) { + if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; +} +function cRevert(x) { return x; } +function cReduce(x) { x.divRemTo(this.m,null,x); } +function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +Classic.prototype.convert = cConvert; +Classic.prototype.revert = cRevert; +Classic.prototype.reduce = cReduce; +Classic.prototype.mulTo = cMulTo; +Classic.prototype.sqrTo = cSqrTo; + +// (protected) return "-1/this % 2^DB"; useful for Mont. reduction +// justification: +// xy == 1 (mod m) +// xy = 1+km +// xy(2-xy) = (1+km)(1-km) +// x[y(2-xy)] = 1-k^2m^2 +// x[y(2-xy)] == 1 (mod m^2) +// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 +// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. +// JS multiply "overflows" differently from C/C++, so care is needed here. +function bnpInvDigit() { + if(this.t < 1) return 0; + var x = this[0]; + if((x&1) == 0) return 0; + var y = x&3; // y == 1/x mod 2^2 + y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 + y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 + y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y>0)?this.DV-y:-y; +} + +// Montgomery reduction +function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp&0x7fff; + this.mph = this.mp>>15; + this.um = (1<<(m.DB-15))-1; + this.mt2 = 2*m.t; +} + +// xR mod m +function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t,r); + r.divRemTo(this.m,null,r); + if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); + return r; +} + +// x/R mod m +function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; +} + +// x = x/R mod m (HAC 14.32) +function montReduce(x) { + while(x.t <= this.mt2) // pad x so am has enough room later + x[x.t++] = 0; + for(var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i]&0x7fff; + var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; + // use am to combine the multiply-shift-add into one call + j = i+this.m.t; + x[j] += this.m.am(0,u0,x,i,0,this.m.t); + // propagate carry + while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } + } + x.clamp(); + x.drShiftTo(this.m.t,x); + if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +// r = "x^2/R mod m"; x != r +function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +// r = "xy/R mod m"; x,y != r +function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Montgomery.prototype.convert = montConvert; +Montgomery.prototype.revert = montRevert; +Montgomery.prototype.reduce = montReduce; +Montgomery.prototype.mulTo = montMulTo; +Montgomery.prototype.sqrTo = montSqrTo; + +// (protected) true iff this is even +function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } + +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) +function bnpExp(e,z) { + if(e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; + g.copyTo(r); + while(--i >= 0) { + z.sqrTo(r,r2); + if((e&(1< 0) z.mulTo(r2,g,r); + else { var t = r; r = r2; r2 = t; } + } + return z.revert(r); +} + +// (public) this^e % m, 0 <= e < 2^32 +function bnModPowInt(e,m) { + var z; + if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); + return this.exp(e,z); +} + +// protected +BigInteger.prototype.copyTo = bnpCopyTo; +BigInteger.prototype.fromInt = bnpFromInt; +BigInteger.prototype.fromString = bnpFromString; +BigInteger.prototype.clamp = bnpClamp; +BigInteger.prototype.dlShiftTo = bnpDLShiftTo; +BigInteger.prototype.drShiftTo = bnpDRShiftTo; +BigInteger.prototype.lShiftTo = bnpLShiftTo; +BigInteger.prototype.rShiftTo = bnpRShiftTo; +BigInteger.prototype.subTo = bnpSubTo; +BigInteger.prototype.multiplyTo = bnpMultiplyTo; +BigInteger.prototype.squareTo = bnpSquareTo; +BigInteger.prototype.divRemTo = bnpDivRemTo; +BigInteger.prototype.invDigit = bnpInvDigit; +BigInteger.prototype.isEven = bnpIsEven; +BigInteger.prototype.exp = bnpExp; + +// public +BigInteger.prototype.toString = bnToString; +BigInteger.prototype.negate = bnNegate; +BigInteger.prototype.abs = bnAbs; +BigInteger.prototype.compareTo = bnCompareTo; +BigInteger.prototype.bitLength = bnBitLength; +BigInteger.prototype.mod = bnMod; +BigInteger.prototype.modPowInt = bnModPowInt; + +// "constants" +BigInteger.ZERO = nbv(0); +BigInteger.ONE = nbv(1); + + +// Extended JavaScript BN functions, required for RSA private ops. + +// (public) +function bnClone() { var r = nbi(); this.copyTo(r); return r; } + +// (public) return value as integer +function bnIntValue() { + if(this.s < 0) { + if(this.t == 1) return this[0]-this.DV; + else if(this.t == 0) return -1; + } + else if(this.t == 1) return this[0]; + else if(this.t == 0) return 0; + // assumes 16 < DB < 32 + return ((this[1]&((1<<(32-this.DB))-1))<>24; } + +// (public) return value as short (assumes DB>=16) +function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } + +// (protected) return x s.t. r^x < DV +function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } + +// (public) 0 if this == 0, 1 if this > 0 +function bnSigNum() { + if(this.s < 0) return -1; + else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; + else return 1; +} + +// (protected) convert to radix string +function bnpToRadix(b) { + if(b == null) b = 10; + if(this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this.chunkSize(b); + var a = Math.pow(b,cs); + var d = nbv(a), y = nbi(), z = nbi(), r = ""; + this.divRemTo(d,y,z); + while(y.signum() > 0) { + r = (a+z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d,y,z); + } + return z.intValue().toString(b) + r; +} + +// (protected) convert from radix string +function bnpFromRadix(s,b) { + this.fromInt(0); + if(b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b,cs), mi = false, j = 0, w = 0; + for(var i = 0; i < s.length; ++i) { + var x = intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b*w+x; + if(++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w,0); + j = 0; + w = 0; + } + } + if(j > 0) { + this.dMultiply(Math.pow(b,j)); + this.dAddOffset(w,0); + } + if(mi) BigInteger.ZERO.subTo(this,this); +} + +// (protected) alternate constructor +function bnpFromNumber(a,b,c) { +if("number" == typeof b) { + // new BigInteger(int,int,RNG) + if(a < 2) this.fromInt(1); + else { + this.fromNumber(a,c); + if(!this.testBit(a-1)) // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); + if(this.isEven()) this.dAddOffset(1,0); // force odd + while(!this.isProbablePrime(b)) { + this.dAddOffset(2,0); + if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); + } + } + } + else { + // new BigInteger(int,RNG) + var x = new Array(), t = a&7; + x.length = (a>>3)+1; + b.nextBytes(x); + if(t > 0) x[0] &= ((1< 0) { + if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) + r[k++] = d|(this.s<<(this.DB-p)); + while(i >= 0) { + if(p < 8) { + d = (this[i]&((1<>(p+=this.DB-8); + } + else { + d = (this[i]>>(p-=8))&0xff; + if(p <= 0) { p += this.DB; --i; } + } + if((d&0x80) != 0) d |= -256; + if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; + if(k > 0 || d != this.s) r[k++] = d; + } + } + return r; +} + +function bnEquals(a) { return(this.compareTo(a)==0); } +function bnMin(a) { return(this.compareTo(a)<0)?this:a; } +function bnMax(a) { return(this.compareTo(a)>0)?this:a; } + +// (protected) r = this op a (bitwise) +function bnpBitwiseTo(a,op,r) { + var i, f, m = Math.min(a.t,this.t); + for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); + if(a.t < this.t) { + f = a.s&this.DM; + for(i = m; i < this.t; ++i) r[i] = op(this[i],f); + r.t = this.t; + } + else { + f = this.s&this.DM; + for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); + r.t = a.t; + } + r.s = op(this.s,a.s); + r.clamp(); +} + +// (public) this & a +function op_and(x,y) { return x&y; } +function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } + +// (public) this | a +function op_or(x,y) { return x|y; } +function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } + +// (public) this ^ a +function op_xor(x,y) { return x^y; } +function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } + +// (public) this & ~a +function op_andnot(x,y) { return x&~y; } +function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } + +// (public) ~this +function bnNot() { + var r = nbi(); + for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; + r.t = this.t; + r.s = ~this.s; + return r; +} + +// (public) this << n +function bnShiftLeft(n) { + var r = nbi(); + if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); + return r; +} + +// (public) this >> n +function bnShiftRight(n) { + var r = nbi(); + if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); + return r; +} + +// return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { + if(x == 0) return -1; + var r = 0; + if((x&0xffff) == 0) { x >>= 16; r += 16; } + if((x&0xff) == 0) { x >>= 8; r += 8; } + if((x&0xf) == 0) { x >>= 4; r += 4; } + if((x&3) == 0) { x >>= 2; r += 2; } + if((x&1) == 0) ++r; + return r; +} + +// (public) returns index of lowest 1-bit (or -1 if none) +function bnGetLowestSetBit() { + for(var i = 0; i < this.t; ++i) + if(this[i] != 0) return i*this.DB+lbit(this[i]); + if(this.s < 0) return this.t*this.DB; + return -1; +} + +// return number of 1 bits in x +function cbit(x) { + var r = 0; + while(x != 0) { x &= x-1; ++r; } + return r; +} + +// (public) return number of set bits +function bnBitCount() { + var r = 0, x = this.s&this.DM; + for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); + return r; +} + +// (public) true iff nth bit is set +function bnTestBit(n) { + var j = Math.floor(n/this.DB); + if(j >= this.t) return(this.s!=0); + return((this[j]&(1<<(n%this.DB)))!=0); +} + +// (protected) this op (1<>= this.DB; + } + if(a.t < this.t) { + c += a.s; + while(i < this.t) { + c += this[i]; + r[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while(i < a.t) { + c += a[i]; + r[i++] = c&this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = (c<0)?-1:0; + if(c > 0) r[i++] = c; + else if(c < -1) r[i++] = this.DV+c; + r.t = i; + r.clamp(); +} + +// (public) this + a +function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } + +// (public) this - a +function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } + +// (public) this * a +function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } + +// (public) this / a +function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } + +// (public) this % a +function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + +// (public) [this/a,this%a] +function bnDivideAndRemainder(a) { + var q = nbi(), r = nbi(); + this.divRemTo(a,q,r); + return new Array(q,r); +} + +// (protected) this *= n, this >= 0, 1 < n < DV +function bnpDMultiply(n) { + this[this.t] = this.am(0,n-1,this,0,0,this.t); + ++this.t; + this.clamp(); +} + +// (protected) this += n << w words, this >= 0 +function bnpDAddOffset(n,w) { + while(this.t <= w) this[this.t++] = 0; + this[w] += n; + while(this[w] >= this.DV) { + this[w] -= this.DV; + if(++w >= this.t) this[this.t++] = 0; + ++this[w]; + } +} + +// A "null" reducer +function NullExp() {} +function nNop(x) { return x; } +function nMulTo(x,y,r) { x.multiplyTo(y,r); } +function nSqrTo(x,r) { x.squareTo(r); } + +NullExp.prototype.convert = nNop; +NullExp.prototype.revert = nNop; +NullExp.prototype.mulTo = nMulTo; +NullExp.prototype.sqrTo = nSqrTo; + +// (public) this^e +function bnPow(e) { return this.exp(e,new NullExp()); } + +// (protected) r = lower n words of "this * a", a.t <= n +// "this" should be the larger one if appropriate. +function bnpMultiplyLowerTo(a,n,r) { + var i = Math.min(this.t+a.t,n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while(i > 0) r[--i] = 0; + var j; + for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); + for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); + r.clamp(); +} + +// (protected) r = "this * a" without lower n words, n > 0 +// "this" should be the larger one if appropriate. +function bnpMultiplyUpperTo(a,n,r) { + --n; + var i = r.t = this.t+a.t-n; + r.s = 0; // assumes a,this >= 0 + while(--i >= 0) r[i] = 0; + for(i = Math.max(n-this.t,0); i < a.t; ++i) + r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); + r.clamp(); + r.drShiftTo(1,r); +} + +// Barrett modular reduction +function Barrett(m) { + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2*m.t,this.r2); + this.mu = this.r2.divide(m); + this.m = m; +} + +function barrettConvert(x) { + if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); + else if(x.compareTo(this.m) < 0) return x; + else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } +} + +function barrettRevert(x) { return x; } + +// x = x mod m (HAC 14.42) +function barrettReduce(x) { + x.drShiftTo(this.m.t-1,this.r2); + if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } + this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); + this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); + while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); + x.subTo(this.r2,x); + while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +// r = x^2 mod m; x != r +function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +// r = x*y mod m; x,y != r +function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Barrett.prototype.convert = barrettConvert; +Barrett.prototype.revert = barrettRevert; +Barrett.prototype.reduce = barrettReduce; +Barrett.prototype.mulTo = barrettMulTo; +Barrett.prototype.sqrTo = barrettSqrTo; + +// (public) this^e % m (HAC 14.85) +function bnModPow(e,m) { + var i = e.bitLength(), k, r = nbv(1), z; + if(i <= 0) return r; + else if(i < 18) k = 1; + else if(i < 48) k = 3; + else if(i < 144) k = 4; + else if(i < 768) k = 5; + else k = 6; + if(i < 8) + z = new Classic(m); + else if(m.isEven()) + z = new Barrett(m); + else + z = new Montgomery(m); + + // precomputation + var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1],g2); + while(n <= km) { + g[n] = nbi(); + z.mulTo(g2,g[n-2],g[n]); + n += 2; + } + } + + var j = e.t-1, w, is1 = true, r2 = nbi(), t; + i = nbits(e[j])-1; + while(j >= 0) { + if(i >= k1) w = (e[j]>>(i-k1))&km; + else { + w = (e[j]&((1<<(i+1))-1))<<(k1-i); + if(j > 0) w |= e[j-1]>>(this.DB+i-k1); + } + + n = k; + while((w&1) == 0) { w >>= 1; --n; } + if((i -= n) < 0) { i += this.DB; --j; } + if(is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } + else { + while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } + if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } + z.mulTo(r2,g[w],r); + } + + while(j >= 0 && (e[j]&(1< 0) { + x.rShiftTo(g,x); + y.rShiftTo(g,y); + } + while(x.signum() > 0) { + if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); + if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); + if(x.compareTo(y) >= 0) { + x.subTo(y,x); + x.rShiftTo(1,x); + } + else { + y.subTo(x,y); + y.rShiftTo(1,y); + } + } + if(g > 0) y.lShiftTo(g,y); + return y; +} + +// (protected) this % n, n < 2^26 +function bnpModInt(n) { + if(n <= 0) return 0; + var d = this.DV%n, r = (this.s<0)?n-1:0; + if(this.t > 0) + if(d == 0) r = this[0]%n; + else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; + return r; +} + +// (public) 1/this % m (HAC 14.61) +function bnModInverse(m) { + var ac = m.isEven(); + if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), v = this.clone(); + var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); + while(u.signum() != 0) { + while(u.isEven()) { + u.rShiftTo(1,u); + if(ac) { + if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } + a.rShiftTo(1,a); + } + else if(!b.isEven()) b.subTo(m,b); + b.rShiftTo(1,b); + } + while(v.isEven()) { + v.rShiftTo(1,v); + if(ac) { + if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } + c.rShiftTo(1,c); + } + else if(!d.isEven()) d.subTo(m,d); + d.rShiftTo(1,d); + } + if(u.compareTo(v) >= 0) { + u.subTo(v,u); + if(ac) a.subTo(c,a); + b.subTo(d,b); + } + else { + v.subTo(u,v); + if(ac) c.subTo(a,c); + d.subTo(b,d); + } + } + if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if(d.compareTo(m) >= 0) return d.subtract(m); + if(d.signum() < 0) d.addTo(m,d); else return d; + if(d.signum() < 0) return d.add(m); else return d; +} + +var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; +var lplim = (1<<26)/lowprimes[lowprimes.length-1]; + +// (public) test primality with certainty >= 1-.5^t +function bnIsProbablePrime(t) { + var i, x = this.abs(); + if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { + for(i = 0; i < lowprimes.length; ++i) + if(x[0] == lowprimes[i]) return true; + return false; + } + if(x.isEven()) return false; + i = 1; + while(i < lowprimes.length) { + var m = lowprimes[i], j = i+1; + while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while(i < j) if(m%lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); +} + +// (protected) true if probably prime (HAC 4.24, Miller-Rabin) +function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if(k <= 0) return false; + var r = n1.shiftRight(k); + t = (t+1)>>1; + if(t > lowprimes.length) t = lowprimes.length; + var a = nbi(); + for(var i = 0; i < t; ++i) { + a.fromInt(lowprimes[i]); + var y = a.modPow(r,this); + if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while(j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2,this); + if(y.compareTo(BigInteger.ONE) == 0) return false; + } + if(y.compareTo(n1) != 0) return false; + } + } + return true; +} + +// protected +BigInteger.prototype.chunkSize = bnpChunkSize; +BigInteger.prototype.toRadix = bnpToRadix; +BigInteger.prototype.fromRadix = bnpFromRadix; +BigInteger.prototype.fromNumber = bnpFromNumber; +BigInteger.prototype.bitwiseTo = bnpBitwiseTo; +BigInteger.prototype.changeBit = bnpChangeBit; +BigInteger.prototype.addTo = bnpAddTo; +BigInteger.prototype.dMultiply = bnpDMultiply; +BigInteger.prototype.dAddOffset = bnpDAddOffset; +BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; +BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; +BigInteger.prototype.modInt = bnpModInt; +BigInteger.prototype.millerRabin = bnpMillerRabin; + +// public +BigInteger.prototype.clone = bnClone; +BigInteger.prototype.intValue = bnIntValue; +BigInteger.prototype.byteValue = bnByteValue; +BigInteger.prototype.shortValue = bnShortValue; +BigInteger.prototype.signum = bnSigNum; +BigInteger.prototype.toByteArray = bnToByteArray; +BigInteger.prototype.equals = bnEquals; +BigInteger.prototype.min = bnMin; +BigInteger.prototype.max = bnMax; +BigInteger.prototype.and = bnAnd; +BigInteger.prototype.or = bnOr; +BigInteger.prototype.xor = bnXor; +BigInteger.prototype.andNot = bnAndNot; +BigInteger.prototype.not = bnNot; +BigInteger.prototype.shiftLeft = bnShiftLeft; +BigInteger.prototype.shiftRight = bnShiftRight; +BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; +BigInteger.prototype.bitCount = bnBitCount; +BigInteger.prototype.testBit = bnTestBit; +BigInteger.prototype.setBit = bnSetBit; +BigInteger.prototype.clearBit = bnClearBit; +BigInteger.prototype.flipBit = bnFlipBit; +BigInteger.prototype.add = bnAdd; +BigInteger.prototype.subtract = bnSubtract; +BigInteger.prototype.multiply = bnMultiply; +BigInteger.prototype.divide = bnDivide; +BigInteger.prototype.remainder = bnRemainder; +BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; +BigInteger.prototype.modPow = bnModPow; +BigInteger.prototype.modInverse = bnModInverse; +BigInteger.prototype.pow = bnPow; +BigInteger.prototype.gcd = bnGCD; +BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + +// BigInteger interfaces not implemented in jsbn: + +// BigInteger(int signum, byte[] magnitude) +// double doubleValue() +// float floatValue() +// int hashCode() +// long longValue() +// static BigInteger valueOf(long val) diff --git a/lib/pidCrypt/md5.js b/lib/pidCrypt/md5.js new file mode 100644 index 0000000..4d441b8 --- /dev/null +++ b/lib/pidCrypt/md5.js @@ -0,0 +1,185 @@ +/** +* +* MD5 (Message-Digest Algorithm) for use in pidCrypt Library +* Depends on pidCrypt (pidcrypt.js, pidcrypt_util.js) +* +* For original source see http://www.webtoolkit.info/ +* Download: 15.02.2009 from http://www.webtoolkit.info/javascript-md5.html +**/ + +if(typeof(pidCrypt) != 'undefined') { + pidCrypt.MD5 = function(string) { + + function RotateLeft(lValue, iShiftBits) { + return (lValue<>>(32-iShiftBits)); + } + + function AddUnsigned(lX,lY) { + var lX4,lY4,lX8,lY8,lResult; + lX8 = (lX & 0x80000000); + lY8 = (lY & 0x80000000); + lX4 = (lX & 0x40000000); + lY4 = (lY & 0x40000000); + lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF); + if (lX4 & lY4) { + return (lResult ^ 0x80000000 ^ lX8 ^ lY8); + } + if (lX4 | lY4) { + if (lResult & 0x40000000) { + return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); + } else { + return (lResult ^ 0x40000000 ^ lX8 ^ lY8); + } + } else { + return (lResult ^ lX8 ^ lY8); + } + } + + function F(x,y,z) { return (x & y) | ((~x) & z); } + function G(x,y,z) { return (x & z) | (y & (~z)); } + function H(x,y,z) { return (x ^ y ^ z); } + function I(x,y,z) { return (y ^ (x | (~z))); } + + function FF(a,b,c,d,x,s,ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + }; + + function GG(a,b,c,d,x,s,ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + }; + + function HH(a,b,c,d,x,s,ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + }; + + function II(a,b,c,d,x,s,ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + }; + + function ConvertToWordArray(string) { + var lWordCount; + var lMessageLength = string.length; + var lNumberOfWords_temp1=lMessageLength + 8; + var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64; + var lNumberOfWords = (lNumberOfWords_temp2+1)*16; + var lWordArray=Array(lNumberOfWords-1); + var lBytePosition = 0; + var lByteCount = 0; + while ( lByteCount < lMessageLength ) { + lWordCount = (lByteCount-(lByteCount % 4))/4; + lBytePosition = (lByteCount % 4)*8; + lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<>>29; + return lWordArray; + }; + + function WordToHex(lValue) { + var WordToHexValue="",WordToHexValue_temp="",lByte,lCount; + for (lCount = 0;lCount<=3;lCount++) { + lByte = (lValue>>>(lCount*8)) & 255; + WordToHexValue_temp = "0" + lByte.toString(16); + WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2); + } + return WordToHexValue; + }; + + //** function Utf8Encode(string) removed. Aready defined in pidcrypt_utils.js + + var x=Array(); + var k,AA,BB,CC,DD,a,b,c,d; + var S11=7, S12=12, S13=17, S14=22; + var S21=5, S22=9 , S23=14, S24=20; + var S31=4, S32=11, S33=16, S34=23; + var S41=6, S42=10, S43=15, S44=21; + + // string = Utf8Encode(string); #function call removed + + x = ConvertToWordArray(string); + + a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; + + for (k=0;k*/ +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +// 02111-1307 USA or check at http://www.gnu.org/licenses/gpl.html + +/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ +/* pidCrypt is pidders JavaScript Crypto Library - www.pidder.com/pidcrypt + * Version 0.04, 10/2009 + + * + * pidCrypt is a combination of different JavaScript functions for client side + * encryption technologies with enhancements for openssl compatibility cast into + * a modular class concept. + * + * Client side encryption is a must have for developing host proof applications: + * There must be no knowledge of the clear text data at the server side, all + * data is enrycpted prior to being submitted to the server. + * Client side encryption is mandatory for protecting the privacy of the users. + * "Dont't trust us, check our source code!" + * + * "As a cryptography and computer security expert, I have never understood + * the current fuss about the open source software movement. In the + * cryptography world, we consider open source necessary for good security; + * we have for decades. Public security is always more secure than proprietary + * security. It's true for cryptographic algorithms, security protocols, and + * security source code. For us, open source isn't just a business model; + * it's smart engineering practice." + * Bruce Schneier, Crypto-Gram 1999/09/15 + * copied form keepassx site - keepassx is a cross plattform password manager + * + * pidCrypt comes with modules under different licenses and copyright terms. + * Make sure that you read and respect the individual module license conditions + * before using it. + * + * The pidCrypt base library contains: + * 1. pidcrypt.js + * class pidCrypt: the base class of the library + * 2. pidcrypt_util.js + * base64 en-/decoding as new methods of the JavaScript String class + * UTF8 en-/decoding as new methods of the JavaScript String class + * String/HexString conversions as new methods of the JavaScript String class + * + * The pidCrypt v0.01 modules and the original authors (see files for detailed + * copyright and license terms) are: + * + * - md5.js: MD5 (Message-Digest Algorithm), www.webtoolkit.info + * - aes_core.js: AES (Advanced Encryption Standard ) Core algorithm, B. Poettering + * - aes-ctr.js: AES CTR (Counter) Mode, Chis Veness + * - aes-cbc.js: AES CBC (Cipher Block Chaining) Mode, pidder + * - jsbn.js: BigInteger for JavaScript, Tom Wu + * - prng.js: PRNG (Pseudo-Random Number Generator), Tom Wu + * - rng.js: Random Numbers, Tom Wu + * - rsa.js: RSA (Rivest, Shamir, Adleman Algorithm), Tom Wu + * - oids.js: oids (Object Identifiers found in ASN.1), Peter Gutmann + * - asn1.js: ASN1 (Abstract Syntax Notation One) parser, Lapo Luchini + * - sha256.js SHA-256 hashing, Angel Marin + * - sha2.js: SHA-384 and SHA-512 hashing, Brian Turek + * + * IMPORTANT: + * Please report any bugs at http://sourceforge.net/projects/pidcrypt/ + * Vist http://www.pidder.com/pidcrypt for online demo an documentation + */ +/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + +function pidCrypt(){ + //TODO: better radomness! + function getRandomBytes(len){ + if(!len) len = 8; + var bytes = new Array(len); + var field = []; + for(var i=0;i<256;i++) field[i] = i; + for(i=0;i0) + return true; + return false + } + this.appendInfo = function(str){ + this.infos += str; + return ''; + } + this.getInfos = function() + { + return this.infos; + } + this.setDebug = function(flag){ + this.debug = flag; + } + this.appendDebug = function(str) + { + this.debugMsg += str; + return ''; + } + this.isDebug = function(){ + return this.debug; + } + this.getAllMessages = function(options){ + var defaults = {lf:'\n', + clr_mes: false, + verbose: 15//verbose level bits = 1111 + }; + if(!options) options = defaults; + for(var d in defaults) + if(typeof(options[d]) == 'undefined') options[d] = defaults[d]; + var mes = ''; + var tmp = ''; + for(var p in this.params){ + switch(p){ + case 'encryptOut': + tmp = pidCryptUtil.toByteArray(this.params[p].toString()); + tmp = pidCryptUtil.fragment(tmp.join(),64, options.lf) + break; + case 'key': + case 'iv': + tmp = pidCryptUtil.formatHex(this.params[p],48); + break; + default: + tmp = pidCryptUtil.fragment(this.params[p].toString(),64, options.lf); + } + mes += '

'+p+':

' + tmp + '

'; + } + if(this.debug) mes += 'debug: ' + this.debug + options.lf; + if(this.errors.length>0 && ((options.verbose & 1) == 1)) mes += 'Errors:' + options.lf + this.errors + options.lf; + if(this.warnings.length>0 && ((options.verbose & 2) == 2)) mes += 'Warnings:' +options.lf + this.warnings + options.lf; + if(this.infos.length>0 && ((options.verbose & 4) == 4)) mes += 'Infos:' +options.lf+ this.infos + options.lf; + if(this.debug && ((options.verbose & 8) == 8)) mes += 'Debug messages:' +options.lf+ this.debugMsg + options.lf; + if(options.clr_mes) + this.errors = this.infos = this.warnings = this.debug = ''; + return mes; + } + this.getRandomBytes = function(len){ + return getRandomBytes(len); + } + //TODO warnings +} + diff --git a/lib/pidCrypt/pidcrypt_util.js b/lib/pidCrypt/pidcrypt_util.js new file mode 100644 index 0000000..e65806d --- /dev/null +++ b/lib/pidCrypt/pidcrypt_util.js @@ -0,0 +1,347 @@ + /*----------------------------------------------------------------------------*/ + // Copyright (c) 2009 pidder + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*----------------------------------------------------------------------------*/ +/* (c) Chris Veness 2005-2008 +* You are welcome to re-use these scripts [without any warranty express or +* implied] provided you retain my copyright notice and when possible a link to +* my website (under a LGPL license). §ection numbers relate the code back to +* sections in the standard. +/*----------------------------------------------------------------------------*/ +/* Helper methods (base64 conversion etc.) needed for different operations in + * encryption. + +/*----------------------------------------------------------------------------*/ +/* Intance methods extanding the String object */ +/*----------------------------------------------------------------------------*/ +/** + * Encode string into Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648] + * As per RFC 4648, no newlines are added. + * + * @param utf8encode optional parameter, if set to true Unicode string is + * encoded into UTF-8 before conversion to base64; + * otherwise string is assumed to be 8-bit characters + * @return coded base64-encoded string + */ +pidCryptUtil = {}; +pidCryptUtil.encodeBase64 = function(str,utf8encode) { // http://tools.ietf.org/html/rfc4648 + if(!str) str = ""; + var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + utf8encode = (typeof utf8encode == 'undefined') ? false : utf8encode; + var o1, o2, o3, bits, h1, h2, h3, h4, e=[], pad = '', c, plain, coded; + + plain = utf8encode ? pidCryptUtil.encodeUTF8(str) : str; + + c = plain.length % 3; // pad string to length of multiple of 3 + if (c > 0) { while (c++ < 3) { pad += '='; plain += '\0'; } } + // note: doing padding here saves us doing special-case packing for trailing 1 or 2 chars + + for (c=0; c>18 & 0x3f; + h2 = bits>>12 & 0x3f; + h3 = bits>>6 & 0x3f; + h4 = bits & 0x3f; + + // use hextets to index into b64 string + e[c/3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); + } + coded = e.join(''); // join() is far faster than repeated string concatenation + + // replace 'A's from padded nulls with '='s + coded = coded.slice(0, coded.length-pad.length) + pad; + return coded; +} + +/** + * Decode string from Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648] + * As per RFC 4648, newlines are not catered for. + * + * @param utf8decode optional parameter, if set to true UTF-8 string is decoded + * back into Unicode after conversion from base64 + * @return decoded string + */ +pidCryptUtil.decodeBase64 = function(str,utf8decode) { + if(!str) str = ""; + var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + utf8decode = (typeof utf8decode == 'undefined') ? false : utf8decode; + var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded; + + coded = utf8decode ? pidCryptUtil.decodeUTF8(str) : str; + + for (var c=0; c>>16 & 0xff; + o2 = bits>>>8 & 0xff; + o3 = bits & 0xff; + + d[c/4] = String.fromCharCode(o1, o2, o3); + // check for padding + if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2); + if (h3 == 0x40) d[c/4] = String.fromCharCode(o1); + } + plain = d.join(''); // join() is far faster than repeated string concatenation + + plain = utf8decode ? pidCryptUtil.decodeUTF8(plain) : plain + + return plain; +} + +/** + * Encode multi-byte Unicode string into utf-8 multiple single-byte characters + * (BMP / basic multilingual plane only) + * + * Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars + * + * @return encoded string + */ +pidCryptUtil.encodeUTF8 = function(str) { + if(!str) str = ""; + // use regular expressions & String.replace callback function for better efficiency + // than procedural approaches + str = str.replace( + /[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz + function(c) { + var cc = c.charCodeAt(0); + return String.fromCharCode(0xc0 | cc>>6, 0x80 | cc&0x3f); } + ); + str = str.replace( + /[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz + function(c) { + var cc = c.charCodeAt(0); + return String.fromCharCode(0xe0 | cc>>12, 0x80 | cc>>6&0x3F, 0x80 | cc&0x3f); } + ); + return str; +} + +// If you encounter problems with the UTF8 encode function (e.g. for use in a +// Firefox) AddOn) you can use the following instead. +// code from webtoolkit.com + +//pidCryptUtil.encodeUTF8 = function(str) { +// str = str.replace(/\r\n/g,"\n"); +// var utftext = ""; +// +// for (var n = 0; n < str.length; n++) { +// +// var c = str.charCodeAt(n); +// +// if (c < 128) { +// utftext += String.fromCharCode(c); +// } +// else if((c > 127) && (c < 2048)) { +// utftext += String.fromCharCode((c >> 6) | 192); +// utftext += String.fromCharCode((c & 63) | 128); +// } +// else { +// utftext += String.fromCharCode((c >> 12) | 224); +// utftext += String.fromCharCode(((c >> 6) & 63) | 128); +// utftext += String.fromCharCode((c & 63) | 128); +// } +// +// } +// +// return utftext; +//} + + + +/** + * Decode utf-8 encoded string back into multi-byte Unicode characters + * + * @return decoded string + */ +pidCryptUtil.decodeUTF8 = function(str) { + if(!str) str = ""; + str = str.replace( + /[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars + function(c) { // (note parentheses for precence) + var cc = (c.charCodeAt(0)&0x1f)<<6 | c.charCodeAt(1)&0x3f; + return String.fromCharCode(cc); } + ); + str = str.replace( + /[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars + function(c) { // (note parentheses for precence) + var cc = ((c.charCodeAt(0)&0x0f)<<12) | ((c.charCodeAt(1)&0x3f)<<6) | ( c.charCodeAt(2)&0x3f); + return String.fromCharCode(cc); } + ); + return str; +} + +// If you encounter problems with the UTF8 decode function (e.g. for use in a +// Firefox) AddOn) you can use the following instead. +// code from webtoolkit.com + +//pidCryptUtil.decodeUTF8 = function(utftext) { +// var str = ""; +// var i = 0; +// var c = 0; +// var c1 = 0; +// var c2 = 0; +// +// while ( i < utftext.length ) { +// +// c = utftext.charCodeAt(i); +// +// if (c < 128) { +// str += String.fromCharCode(c); +// i++; +// } +// else if((c > 191) && (c < 224)) { +// c1 = utftext.charCodeAt(i+1); +// str += String.fromCharCode(((c & 31) << 6) | (c1 & 63)); +// i += 2; +// } +// else { +// c1 = utftext.charCodeAt(i+1); +// c2 = utftext.charCodeAt(i+2); +// str += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63)); +// i += 3; +// } +// +// } +// +// +// return str; +//} + + + + +/** + * Converts a string into a hexadecimal string + * returns the characters of a string to their hexadecimal charcode equivalent + * Works only on byte chars with charcode < 256. All others chars are converted + * into "xx" + * + * @return hex string e.g. "hello world" => "68656c6c6f20776f726c64" + */ +pidCryptUtil.convertToHex = function(str) { + if(!str) str = ""; + var hs =''; + var hv =''; + for (var i=0; i "hello world" + */ +pidCryptUtil.convertFromHex = function(str){ + if(!str) str = ""; + var s = ""; + for(var i= 0;i "hello world" + */ + pidCryptUtil.toByteArray = function(str){ + if(!str) str = ""; + var ba = []; + for(var i=0;i "abc\ndef\nghi\n" + */ +pidCryptUtil.fragment = function(str,length,lf){ + if(!str) str = ""; + if(!length || length>=str.length) return str; + if(!lf) lf = '\n' + var tmp=''; + for(var i=0;i "68:65:6c:6c:6f:20:\n" +*/ +pidCryptUtil.formatHex = function(str,length){ + if(!str) str = ""; + if(!length) length = 45; + var str_new=''; + var j = 0; + var hex = str.toLowerCase(); + for(var i=0;i +// in your main HTML document. + +function SecureRandom() { + this.rng_state; + this.rng_pool; + this.rng_pptr; + + + // Mix in a 32-bit integer into the pool + this.rng_seed_int = function(x) { + this.rng_pool[this.rng_pptr++] ^= x & 255; + this.rng_pool[this.rng_pptr++] ^= (x >> 8) & 255; + this.rng_pool[this.rng_pptr++] ^= (x >> 16) & 255; + this.rng_pool[this.rng_pptr++] ^= (x >> 24) & 255; + if(this.rng_pptr >= rng_psize) this.rng_pptr -= rng_psize; + } + + // Mix in the current time (w/milliseconds) into the pool + this.rng_seed_time = function() { + this.rng_seed_int(new Date().getTime()); + } + + // Initialize the pool with junk if needed. + if(this.rng_pool == null) { + this.rng_pool = new Array(); + this.rng_pptr = 0; + var t; + if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) { + // Extract entropy (256 bits) from NS4 RNG if available + var z = window.crypto.random(32); + for(t = 0; t < z.length; ++t) + this.rng_pool[this.rng_pptr++] = z.charCodeAt(t) & 255; + } + while(this.rng_pptr < rng_psize) { // extract some randomness from Math.random() + t = Math.floor(65536 * Math.random()); + this.rng_pool[this.rng_pptr++] = t >>> 8; + this.rng_pool[this.rng_pptr++] = t & 255; + } + this.rng_pptr = 0; + this.rng_seed_time(); + //this.rng_seed_int(window.screenX); + //this.rng_seed_int(window.screenY); + } + + this.rng_get_byte = function() { + if(this.rng_state == null) { + this.rng_seed_time(); + this.rng_state = prng_newstate(); + this.rng_state.init(this.rng_pool); + for(this.rng_pptr = 0; this.rng_pptr < this.rng_pool.length; ++this.rng_pptr) + this.rng_pool[this.rng_pptr] = 0; + this.rng_pptr = 0; + //this.rng_pool = null; + } + // TODO: allow reseeding after first request + return this.rng_state.next(); + } + + //public function + this.nextBytes = function(ba) { + var i; + for(i = 0; i < ba.length; ++i) ba[i] = this.rng_get_byte(); + } +} + + + diff --git a/lib/pidCrypt/rsa.js b/lib/pidCrypt/rsa.js new file mode 100644 index 0000000..d51a746 --- /dev/null +++ b/lib/pidCrypt/rsa.js @@ -0,0 +1,373 @@ + /*----------------------------------------------------------------------------*/ + // Copyright (c) 2009 pidder + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*----------------------------------------------------------------------------*/ +/** +* +* PKCS#1 encryption-style padding (type 2) En- / Decryption for use in +* pidCrypt Library. The pidCrypt RSA module is based on the implementation +* by Tom Wu. +* See http://www-cs-students.stanford.edu/~tjw/jsbn/ for details and for his +* great job. +* +* Depends on pidCrypt (pidcrypt.js, pidcrypt_util.js), BigInteger (jsbn.js), +* random number generator (rng.js) and a PRNG backend (prng4.js) (the random +* number scripts are only needed for key generation). +/*----------------------------------------------------------------------------*/ + /* + * Copyright (c) 2003-2005 Tom Wu + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, + * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF + * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * In addition, the following condition applies: + * + * All redistributions must retain an intact copy of this copyright notice + * and disclaimer. + */ +//Address all questions regarding this license to: +// Tom Wu +// tjw@cs.Stanford.EDU +/*----------------------------------------------------------------------------*/ +if(typeof(pidCrypt) != 'undefined' && + typeof(BigInteger) != 'undefined' &&//must have for rsa + typeof(SecureRandom) != 'undefined' &&//only needed for key generation + typeof(Arcfour) != 'undefined'//only needed for key generation +) +{ + +// Author: Tom Wu +// tjw@cs.Stanford.EDU + // convert a (hex) string to a bignum object + function parseBigInt(str,r) { + return new BigInteger(str,r); + } + + function linebrk(s,n) { + var ret = ""; + var i = 0; + while(i + n < s.length) { + ret += s.substring(i,i+n) + "\n"; + i += n; + } + return ret + s.substring(i,s.length); + } + + function byte2Hex(b) { + if(b < 0x10) + return "0" + b.toString(16); + else + return b.toString(16); + } + + // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext + function pkcs1unpad2(d,n) { + var b = d.toByteArray(); + var i = 0; + while(i < b.length && b[i] == 0) ++i; + if(b.length-i != n-1 || b[i] != 2) + return null; + ++i; + while(b[i] != 0) + if(++i >= b.length) return null; + var ret = ""; + while(++i < b.length) + ret += String.fromCharCode(b[i]); + return ret; + } + + // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint + function pkcs1pad2(s,n) { + if(n < s.length + 11) { + alert("Message too long for RSA"); + return null; + } + var ba = new Array(); + var i = s.length - 1; + while(i >= 0 && n > 0) {ba[--n] = s.charCodeAt(i--);}; + ba[--n] = 0; + var rng = new SecureRandom(); + var x = new Array(); + while(n > 2) { // random non-zero pad + x[0] = 0; + while(x[0] == 0) rng.nextBytes(x); + ba[--n] = x[0]; + } + ba[--n] = 2; + ba[--n] = 0; + return new BigInteger(ba); + } + //RSA key constructor + pidCrypt.RSA = function() { + this.n = null; + this.e = 0; + this.d = null; + this.p = null; + this.q = null; + this.dmp1 = null; + this.dmq1 = null; + this.coeff = null; + + } + // protected + // Perform raw private operation on "x": return x^d (mod n) + pidCrypt.RSA.prototype.doPrivate = function(x) { + if(this.p == null || this.q == null) + return x.modPow(this.d, this.n); + + // TODO: re-calculate any missing CRT params + var xp = x.mod(this.p).modPow(this.dmp1, this.p); + var xq = x.mod(this.q).modPow(this.dmq1, this.q); + + while(xp.compareTo(xq) < 0) + xp = xp.add(this.p); + return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); + } + + + // Set the public key fields N and e from hex strings + pidCrypt.RSA.prototype.setPublic = function(N,E,radix) { + if (typeof(radix) == 'undefined') radix = 16; + + if(N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N,radix); + this.e = parseInt(E,radix); + } + else + alert("Invalid RSA public key"); + +// alert('N='+this.n+'\nE='+this.e); +//document.writeln('Schlüssellaenge = ' + this.n.toString().length +'
'); + } + + // Perform raw public operation on "x": return x^e (mod n) + pidCrypt.RSA.prototype.doPublic = function(x) { + return x.modPowInt(this.e, this.n); + } + + // Return the PKCS#1 RSA encryption of "text" as an even-length hex string + pidCrypt.RSA.prototype.encryptRaw = function(text) { + var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); + if(m == null) return null; + var c = this.doPublic(m); + if(c == null) return null; + var h = c.toString(16); + if((h.length & 1) == 0) return h; else return "0" + h; + } + + pidCrypt.RSA.prototype.encrypt = function(text) { + //base64 coding for supporting 8bit chars + text = pidCryptUtil.encodeBase64(text); + return this.encryptRaw(text) + } + // Return the PKCS#1 RSA decryption of "ctext". + // "ctext" is an even-length hex string and the output is a plain string. + pidCrypt.RSA.prototype.decryptRaw = function(ctext) { +// alert('N='+this.n+'\nE='+this.e+'\nD='+this.d+'\nP='+this.p+'\nQ='+this.q+'\nDP='+this.dmp1+'\nDQ='+this.dmq1+'\nC='+this.coeff); + var c = parseBigInt(ctext, 16); + var m = this.doPrivate(c); + if(m == null) return null; + return pkcs1unpad2(m, (this.n.bitLength()+7)>>3) + } + + pidCrypt.RSA.prototype.decrypt = function(ctext) { + var str = this.decryptRaw(ctext) + //base64 coding for supporting 8bit chars + str = (str) ? pidCryptUtil.decodeBase64(str) : ""; + return str; + } + +/* + // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string + pidCrypt.RSA.prototype.b64_encrypt = function(text) { + var h = this.encrypt(text); + if(h) return hex2b64(h); else return null; + } +*/ + // Set the private key fields N, e, and d from hex strings + pidCrypt.RSA.prototype.setPrivate = function(N,E,D,radix) { + if (typeof(radix) == 'undefined') radix = 16; + + if(N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N,radix); + this.e = parseInt(E,radix); + this.d = parseBigInt(D,radix); + } + else + alert("Invalid RSA private key"); + } + + // Set the private key fields N, e, d and CRT params from hex strings + pidCrypt.RSA.prototype.setPrivateEx = function(N,E,D,P,Q,DP,DQ,C,radix) { + if (typeof(radix) == 'undefined') radix = 16; + + if(N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N,radix);//modulus + this.e = parseInt(E,radix);//publicExponent + this.d = parseBigInt(D,radix);//privateExponent + this.p = parseBigInt(P,radix);//prime1 + this.q = parseBigInt(Q,radix);//prime2 + this.dmp1 = parseBigInt(DP,radix);//exponent1 + this.dmq1 = parseBigInt(DQ,radix);//exponent2 + this.coeff = parseBigInt(C,radix);//coefficient + } + else + alert("Invalid RSA private key"); +// alert('N='+this.n+'\nE='+this.e+'\nD='+this.d+'\nP='+this.p+'\nQ='+this.q+'\nDP='+this.dmp1+'\nDQ='+this.dmq1+'\nC='+this.coeff); + + } + + // Generate a new random private key B bits long, using public expt E + pidCrypt.RSA.prototype.generate = function(B,E) { + var rng = new SecureRandom(); + var qs = B>>1; + this.e = parseInt(E,16); + var ee = new BigInteger(E,16); + for(;;) { + for(;;) { + this.p = new BigInteger(B-qs,1,rng); + if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break; + } + for(;;) { + this.q = new BigInteger(qs,1,rng); + if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break; + } + if(this.p.compareTo(this.q) <= 0) { + var t = this.p; + this.p = this.q; + this.q = t; + } + var p1 = this.p.subtract(BigInteger.ONE); + var q1 = this.q.subtract(BigInteger.ONE); + var phi = p1.multiply(q1); + if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { + this.n = this.p.multiply(this.q); + this.d = ee.modInverse(phi); + this.dmp1 = this.d.mod(p1); + this.dmq1 = this.d.mod(q1); + this.coeff = this.q.modInverse(this.p); + break; + } + } + } + + +//pidCrypt extensions start +// + pidCrypt.RSA.prototype.getASNData = function(tree) { + var params = {}; + var data = []; + var p=0; + + if(tree.value && tree.type == 'INTEGER') + data[p++] = tree.value; + if(tree.sub) + for(var i=0;i>>(32-s)); + return t4; + }; + + function lsb_hex(val) { + var str=""; + var i; + var vh; + var vl; + + for( i=0; i<=6; i+=2 ) { + vh = (val>>>(i*4+4))&0x0f; + vl = (val>>>(i*4))&0x0f; + str += vh.toString(16) + vl.toString(16); + } + return str; + }; + + function cvt_hex(val) { + var str=""; + var i; + var v; + + for( i=7; i>=0; i-- ) { + v = (val>>>(i*4))&0x0f; + str += v.toString(16); + } + return str; + }; + + //** function Utf8Encode(string) removed. Aready defined in pidcrypt_utils.js + + var blockstart; + var i, j; + var W = new Array(80); + var H0 = 0x67452301; + var H1 = 0xEFCDAB89; + var H2 = 0x98BADCFE; + var H3 = 0x10325476; + var H4 = 0xC3D2E1F0; + var A, B, C, D, E; + var temp; + + //msg = pidCryptUtil.encodeUTF8(msg); + + var msg_len = msg.length; + + var word_array = new Array(); + for( i=0; i>>29 ); + word_array.push( (msg_len<<3)&0x0ffffffff ); + + + for ( blockstart=0; blockstart> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); + } + function S (X, n) {return ( X >>> n ) | (X << (32 - n));} + function R (X, n) {return ( X >>> n );} + function Ch(x, y, z) {return ((x & y) ^ ((~x) & z));} + function Maj(x, y, z) {return ((x & y) ^ (x & z) ^ (y & z));} + function Sigma0256(x) {return (S(x, 2) ^ S(x, 13) ^ S(x, 22));} + function Sigma1256(x) {return (S(x, 6) ^ S(x, 11) ^ S(x, 25));} + function Gamma0256(x) {return (S(x, 7) ^ S(x, 18) ^ R(x, 3));} + function Gamma1256(x) {return (S(x, 17) ^ S(x, 19) ^ R(x, 10));} + function core_sha256 (m, l) { + var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2); + var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19); + var W = new Array(64); + var a, b, c, d, e, f, g, h, i, j; + var T1, T2; + /* append padding */ + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >> 9) << 4) + 15] = l; + for ( var i = 0; i>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32); + return bin; + } + function binb2hex (binarray) { + var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ + var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; + var str = ""; + for (var i = 0; i < binarray.length * 4; i++) { + str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF); + } + return str; + } + function hex_sha256(s){return binb2hex(core_sha256(str2binb(s),s.length * chrsz));} + //s = pidCryptUtil.encodeUTF8(s); + return binb2hex(core_sha256(str2binb(s), s.length * chrsz)); + + } +} \ No newline at end of file diff --git a/lib/pidCrypt/sha512.js b/lib/pidCrypt/sha512.js new file mode 100644 index 0000000..9c36be4 --- /dev/null +++ b/lib/pidCrypt/sha512.js @@ -0,0 +1,276 @@ +/** +* +* SHA512 (Secure Hash Algorithm) for use in pidCrypt Library +* Depends on pidCrypt (pidcrypt.js, pidcrypt_util.js) +* +* +**/ +/* A JavaScript implementation of the SHA family of hashes, as defined in FIPS PUB 180-2 + * Version 1.11 Copyright Brian Turek 2008 + * Distributed under the BSD License + * See http://jssha.sourceforge.net/ for more information + * + * Several functions taken from Paul Johnson + */ +if(typeof(pidCrypt) != 'undefined') +{ + + function Int_64(msint_32,lsint_32) + { + this.highOrder=msint_32; + this.lowOrder=lsint_32; + } + function jsSHA(srcString) + { + jsSHA.charSize=8; + jsSHA.b64pad =""; + jsSHA.hexCase=0; + var sha384=null; + var sha512=null; + var str2binb=function(str) + { + var bin=[]; + var mask =(1 << jsSHA.charSize)- 1; + var length=str.length*jsSHA.charSize; + for(var i=0;i> 5] |=(str.charCodeAt(i/jsSHA.charSize)& mask)<<(32-jsSHA.charSize-i%32); + } + return bin; + }; + var strBinLen=srcString.length*jsSHA.charSize; + var strToHash=str2binb(srcString); + + var binb2hex=function(binarray) + { + var hex_tab=jsSHA.hexCase?"0123456789ABCDEF":"0123456789abcdef"; + var str=""; + var length=binarray.length*4; + for(var i=0;i> 2] >>((3-i%4)* 8+4))& 0xF)+ hex_tab.charAt((binarray[i >> 2] >>((3-i%4)* 8))& 0xF); + } + return str; + }; + + var binb2b64=function(binarray) + { + var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var str=""; + var length=binarray.length*4; + for(var i=0;i> 2] >> 8 *(3-i%4))& 0xFF)<< 16)|(((binarray[i+1 >> 2] >> 8 *(3 -(i+1)% 4))& 0xFF)<< 8)|((binarray[i+2 >> 2] >> 8 *(3 -(i+2)% 4))& 0xFF); + for(var j=0;j<4;j++) + { + if(i*8+j*6>binarray.length*32) + { + str += jsSHA.b64pad; + } + else + { + str += tab.charAt((triplet >> 6 *(3-j))& 0x3F); + } + } + } + return str; + }; + + var rotr=function(x,n) + { + if(n<32) + { + return new Int_64((x.highOrder >>> n)|(x.lowOrder <<(32-n)),(x.lowOrder >>> n)|(x.highOrder <<(32-n))); + } + else if(n===32) + { + return new Int_64(x.lowOrder,x.highOrder); + } + else + { + return rotr(rotr(x,32),n-32); + } + }; + + var shr=function(x,n){if(n<32){return new Int_64(x.highOrder >>> n,x.lowOrder >>> n |(x.highOrder <<(32-n))); + } + else if(n===32) + { + return new Int_64(0,x.highOrder); + } + else + { + return shr(shr(x,32),n-32); + } + }; + + var ch=function(x,y,z) + { + return new Int_64((x.highOrder & y.highOrder)^(~x.highOrder & z.highOrder),(x.lowOrder & y.lowOrder)^(~x.lowOrder & z.lowOrder)); + }; + + var maj=function(x,y,z) + { + return new Int_64((x.highOrder & y.highOrder)^(x.highOrder & z.highOrder)^(y.highOrder & z.highOrder),(x.lowOrder & y.lowOrder)^(x.lowOrder & z.lowOrder)^(y.lowOrder & z.lowOrder)); + }; + + var sigma0=function(x) + { + var rotr28=rotr(x,28); + var rotr34=rotr(x,34); + var rotr39=rotr(x,39); + return new Int_64(rotr28.highOrder ^ rotr34.highOrder ^ rotr39.highOrder,rotr28.lowOrder ^ rotr34.lowOrder ^ rotr39.lowOrder); + }; + + var sigma1=function(x) + { + var rotr14=rotr(x,14); + var rotr18=rotr(x,18); + var rotr41=rotr(x,41); + return new Int_64(rotr14.highOrder ^ rotr18.highOrder ^ rotr41.highOrder,rotr14.lowOrder ^ rotr18.lowOrder ^ rotr41.lowOrder); + }; + + var gamma0=function(x) + { + var rotr1=rotr(x,1); + var rotr8=rotr(x,8); + var shr7=shr(x,7); + return new Int_64(rotr1.highOrder ^ rotr8.highOrder ^ shr7.highOrder,rotr1.lowOrder ^ rotr8.lowOrder ^ shr7.lowOrder); + }; + + var gamma1=function(x) + { + var rotr19=rotr(x,19); + var rotr61=rotr(x,61); + var shr6=shr(x,6); + return new Int_64(rotr19.highOrder ^ rotr61.highOrder ^ shr6.highOrder,rotr19.lowOrder ^ rotr61.lowOrder ^ shr6.lowOrder); + }; + + var safeAdd=function(x,y) + { + var lsw =(x.lowOrder & 0xFFFF)+(y.lowOrder & 0xFFFF); + var msw =(x.lowOrder >>> 16)+(y.lowOrder >>> 16)+(lsw >>> 16); + var lowOrder =((msw & 0xFFFF)<< 16)|(lsw & 0xFFFF); + lsw =(x.highOrder & 0xFFFF)+(y.highOrder & 0xFFFF)+(msw >>> 16); + msw =(x.highOrder >>> 16)+(y.highOrder >>> 16)+(lsw >>> 16); + var highOrder =((msw & 0xFFFF)<< 16)|(lsw & 0xFFFF); + return new Int_64(highOrder,lowOrder); + }; + + var coreSHA2=function(variant) + { + var W=[]; + var a,b,c,d,e,f,g,h; + var T1,T2; + var H; + var K=[new Int_64(0x428a2f98,0xd728ae22),new Int_64(0x71374491,0x23ef65cd),new Int_64(0xb5c0fbcf,0xec4d3b2f),new Int_64(0xe9b5dba5,0x8189dbbc),new Int_64(0x3956c25b,0xf348b538),new Int_64(0x59f111f1,0xb605d019),new Int_64(0x923f82a4,0xaf194f9b),new Int_64(0xab1c5ed5,0xda6d8118),new Int_64(0xd807aa98,0xa3030242),new Int_64(0x12835b01,0x45706fbe),new Int_64(0x243185be,0x4ee4b28c),new Int_64(0x550c7dc3,0xd5ffb4e2),new Int_64(0x72be5d74,0xf27b896f),new Int_64(0x80deb1fe,0x3b1696b1),new Int_64(0x9bdc06a7,0x25c71235),new Int_64(0xc19bf174,0xcf692694),new Int_64(0xe49b69c1,0x9ef14ad2),new Int_64(0xefbe4786,0x384f25e3),new Int_64(0x0fc19dc6,0x8b8cd5b5),new Int_64(0x240ca1cc,0x77ac9c65),new Int_64(0x2de92c6f,0x592b0275),new Int_64(0x4a7484aa,0x6ea6e483),new Int_64(0x5cb0a9dc,0xbd41fbd4),new Int_64(0x76f988da,0x831153b5),new Int_64(0x983e5152,0xee66dfab),new Int_64(0xa831c66d,0x2db43210),new Int_64(0xb00327c8,0x98fb213f),new Int_64(0xbf597fc7,0xbeef0ee4),new Int_64(0xc6e00bf3,0x3da88fc2),new Int_64(0xd5a79147,0x930aa725),new Int_64(0x06ca6351,0xe003826f),new Int_64(0x14292967,0x0a0e6e70),new Int_64(0x27b70a85,0x46d22ffc),new Int_64(0x2e1b2138,0x5c26c926),new Int_64(0x4d2c6dfc,0x5ac42aed),new Int_64(0x53380d13,0x9d95b3df),new Int_64(0x650a7354,0x8baf63de),new Int_64(0x766a0abb,0x3c77b2a8),new Int_64(0x81c2c92e,0x47edaee6),new Int_64(0x92722c85,0x1482353b),new Int_64(0xa2bfe8a1,0x4cf10364),new Int_64(0xa81a664b,0xbc423001),new Int_64(0xc24b8b70,0xd0f89791),new Int_64(0xc76c51a3,0x0654be30),new Int_64(0xd192e819,0xd6ef5218),new Int_64(0xd6990624,0x5565a910),new Int_64(0xf40e3585,0x5771202a),new Int_64(0x106aa070,0x32bbd1b8),new Int_64(0x19a4c116,0xb8d2d0c8),new Int_64(0x1e376c08,0x5141ab53),new Int_64(0x2748774c,0xdf8eeb99),new Int_64(0x34b0bcb5,0xe19b48a8),new Int_64(0x391c0cb3,0xc5c95a63),new Int_64(0x4ed8aa4a,0xe3418acb),new Int_64(0x5b9cca4f,0x7763e373),new Int_64(0x682e6ff3,0xd6b2b8a3),new Int_64(0x748f82ee,0x5defb2fc),new Int_64(0x78a5636f,0x43172f60),new Int_64(0x84c87814,0xa1f0ab72),new Int_64(0x8cc70208,0x1a6439ec),new Int_64(0x90befffa,0x23631e28),new Int_64(0xa4506ceb,0xde82bde9),new Int_64(0xbef9a3f7,0xb2c67915),new Int_64(0xc67178f2,0xe372532b),new Int_64(0xca273ece,0xea26619c),new Int_64(0xd186b8c7,0x21c0c207),new Int_64(0xeada7dd6,0xcde0eb1e),new Int_64(0xf57d4f7f,0xee6ed178),new Int_64(0x06f067aa,0x72176fba),new Int_64(0x0a637dc5,0xa2c898a6),new Int_64(0x113f9804,0xbef90dae),new Int_64(0x1b710b35,0x131c471b),new Int_64(0x28db77f5,0x23047d84),new Int_64(0x32caab7b,0x40c72493),new Int_64(0x3c9ebe0a,0x15c9bebc),new Int_64(0x431d67c4,0x9c100d4c),new Int_64(0x4cc5d4be,0xcb3e42b6),new Int_64(0x597f299c,0xfc657e2a),new Int_64(0x5fcb6fab,0x3ad6faec),new Int_64(0x6c44198c,0x4a475817)]; + if(variant==="SHA-384") + { + H=[new Int_64(0xcbbb9d5d,0xc1059ed8),new Int_64(0x0629a292a,0x367cd507),new Int_64(0x9159015a,0x3070dd17),new Int_64(0x152fecd8,0xf70e5939),new Int_64(0x67332667,0xffc00b31),new Int_64(0x98eb44a87,0x68581511),new Int_64(0xdb0c2e0d,0x64f98fa7),new Int_64(0x47b5481d,0xbefa4fa4)]; + } + else + { + H=[new Int_64(0x6a09e667,0xf3bcc908),new Int_64(0xbb67ae85,0x84caa73b),new Int_64(0x3c6ef372,0xfe94f82b),new Int_64(0xa54ff53a,0x5f1d36f1),new Int_64(0x510e527f,0xade682d1),new Int_64(0x9b05688c,0x2b3e6c1f),new Int_64(0x1f83d9ab,0xfb41bd6b),new Int_64(0x5be0cd19,0x137e2179)]; + } + var message=strToHash.slice(); + message[strBinLen >> 5] |= 0x80 <<(24-strBinLen%32); + message[((strBinLen+1+128 >> 10)<< 5)+ 31]=strBinLen; + var appendedMessageLength=message.length; + for(var i=0;i + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*----------------------------------------------------------------------------*/ +/* +* Maps the pidcrypt utillity functions for string operations to the +* javascript core class String +* +* +/*----------------------------------------------------------------------------*/ +String.prototype.encodeBase64 = function(utf8encode) +{ + return pidCryptUtil.encodeBase64(this,utf8encode); +} +String.prototype.decodeBase64 = function(utf8decode) +{ + return pidCryptUtil.decodeBase64(this,utf8decode); +} +String.prototype.encodeUTF8 = function() +{ + return pidCryptUtil.encodeUTF8(this); +} +String.prototype.decodeUTF8 = function() +{ + return pidCryptUtil.decodeUTF8(this); +} +String.prototype.convertToHex = function() +{ + return pidCryptUtil.convertToHex(this); +} +String.prototype.convertFromHex = function() +{ + return pidCryptUtil.convertFromHex(this); +} +String.prototype.stripLineFeeds = function() +{ + return pidCryptUtil.stripLineFeeds(this); +} +String.prototype.toByteArray = function() +{ + return pidCryptUtil.toByteArray(this); +} +String.prototype.fragment = function(length,lf) +{ + return pidCryptUtil.fragment(this,length,lf); +} +String.prototype.formatHex = function(length) +{ + return pidCryptUtil.formatHex(this,length); +} diff --git a/lib/sjcl/README/COPYRIGHT b/lib/sjcl/README/COPYRIGHT new file mode 100644 index 0000000..d573a05 --- /dev/null +++ b/lib/sjcl/README/COPYRIGHT @@ -0,0 +1,32 @@ +SJCL used to be in the public domain. Now it's: + +Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh, Stanford University. + +This is for liability reasons. (Speaking of which, SJCL comes with NO +WARRANTY WHATSOEVER, express or implied, to the limit of applicable +law.) + +SJCL is dual-licensed under the GNU GPL version 2.0 or higher, and a +2-clause BSD license. You may use SJCL under the terms of either of +these licenses. For your convenience, the GPL versions 2.0 and 3.0 +and the 2-clause BSD license are included here. Additionally, you may +serve "crunched" copies of sjcl (i.e. those with comments removed, +and other transformations to reduce code size) without any copyright +notice. + +SJCL includes JsDoc toolkit, YUI compressor, Closure compressor, +JSLint and the CodeView template in its build system. These programs' +copyrights are owned by other people. They are distributed here under +the MPL, MIT, BSD, Apache and JSLint licenses. Codeview is "free for +download" but has no license attached; it is Copyright 2010 Wouter Bos. + +The BSD license is (almost?) strictly more permissive, but the +additionally licensing under the GPL allows us to use OCB 2.0 code +royalty-free (at least, if OCB 2.0's creator Phil Rogaway has anything +to say about it). Note that if you redistribute SJCL under a license +other than the GPL, you or your users may need to pay patent licensing +fees for OCB 2.0. + +There may be patents which apply to SJCL other than Phil Rogaway's OCB +patents. We suggest that you consult legal counsel before using SJCL +in a commercial project. diff --git a/lib/sjcl/README/INSTALL b/lib/sjcl/README/INSTALL new file mode 100644 index 0000000..a5898c4 --- /dev/null +++ b/lib/sjcl/README/INSTALL @@ -0,0 +1,36 @@ +SJCL comes with a file sjcl.js pre-built. This default build includes +all the modules except for sjcl.codec.bytes (because the demo site doesn't +use it). All you need to do to install is copy this file to your web +server and start using it. + +SJCL is divided into modules implementing various cryptographic and +convenience functions. If you don't need them all for your application, +you can reconfigure SJCL for a smaller code size. To do this, you can +run + +./configure --without-all --with-aes --with-sha256 ... + +Then type + +make + +to rebuild sjcl.js. This will also create a few intermediate files +core*.js; you can delete these automatically by typing + +make sjcl.js tidy + +instead. You will need make, perl, bash and java to rebuild SJCL. + +Some of the modules depend on other modules; configure should handle this +automatically unless you tell it --without-FOO --with-BAR, where BAR +depends on FOO. If you do this, configure will yell at you. + +SJCL is compressed by stripping comments, shortening variable names, etc. +You can also pass a --compress argument to configure to change the +compressor. By default SJCL uses some perl/sh scripts and Google's +Closure compressor. + +If you reconfigure SJCL, it is recommended that you run the included test +suite by typing "make test". If this prints "FAIL" or segfaults, SJCL +doesn't work; please file a bug. + diff --git a/lib/sjcl/README/bsd.txt b/lib/sjcl/README/bsd.txt new file mode 100644 index 0000000..a0559ed --- /dev/null +++ b/lib/sjcl/README/bsd.txt @@ -0,0 +1,30 @@ +Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. 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. + +THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 OR CONTRIBUTORS 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. + +The views and conclusions contained in the software and documentation +are those of the authors and should not be interpreted as representing +official policies, either expressed or implied, of the authors. diff --git a/lib/sjcl/README/gpl-2.0.txt b/lib/sjcl/README/gpl-2.0.txt new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/lib/sjcl/README/gpl-2.0.txt @@ -0,0 +1,339 @@ + 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. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/lib/sjcl/README/gpl-3.0.txt b/lib/sjcl/README/gpl-3.0.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/lib/sjcl/README/gpl-3.0.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. 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 +them 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 prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. 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. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey 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; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + 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. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +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. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/lib/sjcl/config.mk b/lib/sjcl/config.mk new file mode 100644 index 0000000..14dec0d --- /dev/null +++ b/lib/sjcl/config.mk @@ -0,0 +1,2 @@ +SOURCES= core/sjcl.js core/aes.js core/bitArray.js core/codecString.js core/codecHex.js core/codecBase64.js core/sha256.js core/ccm.js core/ocb2.js core/hmac.js core/pbkdf2.js core/random.js core/convenience.js +COMPRESS= core_closure.js diff --git a/lib/sjcl/configure b/lib/sjcl/configure new file mode 100755 index 0000000..3222da2 --- /dev/null +++ b/lib/sjcl/configure @@ -0,0 +1,141 @@ +#!/usr/bin/env perl + +use strict; + +my ($arg, $i, $j, $targ); + +my @targets = qw/sjcl aes bitArray codecString codecHex codecBase64 codecBytes bn sha256 sha1 ccm cbc ecc ocb2 hmac pbkdf2 srp random convenience/; +my %deps = ('aes'=>'sjcl', + 'bitArray'=>'sjcl', + 'codecString'=>'bitArray', + 'codecHex'=>'bitArray', + 'codecBase64'=>'bitArray', + 'codecBytes'=>'bitArray', + 'sha256'=>'codecString', + 'sha1'=>'codecString', + 'ccm'=>'bitArray,aes', + 'ocb2'=>'bitArray,aes', + 'hmac'=>'sha256', + 'pbkdf2'=>'hmac', + 'srp'=>'sha1,bn,bitArray', + 'bn'=>'bitArray,random', + 'ecc'=>'bn', + 'cbc'=>'bitArray,aes', + 'random'=>'sha256,aes', + 'convenience'=>'ccm,pbkdf2,random'); + +my $compress = "closure"; + +my %enabled = (); +$enabled{$_} = 0 foreach (@targets); + +# by default, all but codecBytes, srp, bn +$enabled{$_} = 1 foreach (qw/aes bitArray codecString codecHex codecBase64 sha256 ccm ocb2 hmac pbkdf2 random convenience/); + +# argument parsing +while ($arg = shift @ARGV) { + if ($arg =~ /^--?with-all$/) { + foreach (@targets) { + if ($enabled{$_} == 0) { + $enabled{$_} = 1; + } + } + } elsif ($arg =~ /^--?without-all$/) { + foreach (@targets) { + if ($enabled{$_} == 1) { + $enabled{$_} = 0; + } + } + } elsif ($arg =~ /^--?with-(.*)$/) { + $targ = $1; + $targ =~ s/-(.)/uc $1/ge; + if (!defined $deps{$targ}) { + print STDERR "No such target $targ\n"; + exit 1; + } + $enabled{$targ} = 2; + } elsif ($arg =~ /^--?without-(.*)$/) { + $targ = $1; + $targ =~ s/-(.)/uc $1/ge; + if (!defined $deps{$targ}) { + print STDERR "No such target $targ\n"; + exit 1; + } + $enabled{$targ} = -1; + } elsif ($arg =~ /^--?compress(?:or|ion)?=(none|closure|yui)$/) { + $compress = $1; + } else { + my $targets = join " ", @targets; + $targets =~ s/sjcl //; + $targets =~ s/(.{50})\s+/$1\n /g; + print STDERR < 0) { + foreach $j (split /,/, $deps{$i}) { + if ($enabled{$j} == -1) { + if ($enabled{$i} == 2) { + print STDERR "Conflicting options: $i depends on $j\n"; + exit 1; + } else { + $enabled{$i} = -1; + last; + } + } + } + } +} + +# reverse +foreach $i (reverse @targets) { + if ($enabled{$i} > 0) { + foreach $j (split /,/, $deps{$i}) { + if ($enabled{$j} < $enabled{$i}) { + $enabled{$j} = $enabled{$i}; + } + } + $config = "$i $config"; + } +} + +open CONFIG, "> config.mk" or die "$!"; + + +($pconfig = $config) =~ s/^sjcl //; +$pconfig =~ s/ /\n /g; +print "Enabled components:\n $pconfig\n"; +print "Compression: $compress\n"; + +$config =~ s=\S+=core/$&.js=g; +print CONFIG "SOURCES= $config\n"; + +$compress = "core_$compress.js"; +$compress = 'core.js' if ($compress eq 'core_none.js'); + +print CONFIG "COMPRESS= $compress\n"; + diff --git a/lib/sjcl/core/aes.js b/lib/sjcl/core/aes.js new file mode 100644 index 0000000..144cd24 --- /dev/null +++ b/lib/sjcl/core/aes.js @@ -0,0 +1,208 @@ +/** @fileOverview Low-level AES implementation. + * + * This file contains a low-level implementation of AES, optimized for + * size and for efficiency on several browsers. It is based on + * OpenSSL's aes_core.c, a public-domain implementation by Vincent + * Rijmen, Antoon Bosselaers and Paulo Barreto. + * + * An older version of this implementation is available in the public + * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh, + * Stanford University 2008-2010 and BSD-licensed for liability + * reasons. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** + * Schedule out an AES key for both encryption and decryption. This + * is a low-level class. Use a cipher mode to do bulk encryption. + * + * @constructor + * @param {Array} key The key as an array of 4, 6 or 8 words. + * + * @class Advanced Encryption Standard (low-level interface) + */ +sjcl.cipher.aes = function (key) { + if (!this._tables[0][0][0]) { + this._precompute(); + } + + var i, j, tmp, + encKey, decKey, + sbox = this._tables[0][4], decTable = this._tables[1], + keyLen = key.length, rcon = 1; + + if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) { + throw new sjcl.exception.invalid("invalid aes key size"); + } + + this._key = [encKey = key.slice(0), decKey = []]; + + // schedule encryption keys + for (i = keyLen; i < 4 * keyLen + 28; i++) { + tmp = encKey[i-1]; + + // apply sbox + if (i%keyLen === 0 || (keyLen === 8 && i%keyLen === 4)) { + tmp = sbox[tmp>>>24]<<24 ^ sbox[tmp>>16&255]<<16 ^ sbox[tmp>>8&255]<<8 ^ sbox[tmp&255]; + + // shift rows and add rcon + if (i%keyLen === 0) { + tmp = tmp<<8 ^ tmp>>>24 ^ rcon<<24; + rcon = rcon<<1 ^ (rcon>>7)*283; + } + } + + encKey[i] = encKey[i-keyLen] ^ tmp; + } + + // schedule decryption keys + for (j = 0; i; j++, i--) { + tmp = encKey[j&3 ? i : i - 4]; + if (i<=4 || j<4) { + decKey[j] = tmp; + } else { + decKey[j] = decTable[0][sbox[tmp>>>24 ]] ^ + decTable[1][sbox[tmp>>16 & 255]] ^ + decTable[2][sbox[tmp>>8 & 255]] ^ + decTable[3][sbox[tmp & 255]]; + } + } +}; + +sjcl.cipher.aes.prototype = { + // public + /* Something like this might appear here eventually + name: "AES", + blockSize: 4, + keySizes: [4,6,8], + */ + + /** + * Encrypt an array of 4 big-endian words. + * @param {Array} data The plaintext. + * @return {Array} The ciphertext. + */ + encrypt:function (data) { return this._crypt(data,0); }, + + /** + * Decrypt an array of 4 big-endian words. + * @param {Array} data The ciphertext. + * @return {Array} The plaintext. + */ + decrypt:function (data) { return this._crypt(data,1); }, + + /** + * The expanded S-box and inverse S-box tables. These will be computed + * on the client so that we don't have to send them down the wire. + * + * There are two tables, _tables[0] is for encryption and + * _tables[1] is for decryption. + * + * The first 4 sub-tables are the expanded S-box with MixColumns. The + * last (_tables[01][4]) is the S-box itself. + * + * @private + */ + _tables: [[[],[],[],[],[]],[[],[],[],[],[]]], + + /** + * Expand the S-box tables. + * + * @private + */ + _precompute: function () { + var encTable = this._tables[0], decTable = this._tables[1], + sbox = encTable[4], sboxInv = decTable[4], + i, x, xInv, d=[], th=[], x2, x4, x8, s, tEnc, tDec; + + // Compute double and third tables + for (i = 0; i < 256; i++) { + th[( d[i] = i<<1 ^ (i>>7)*283 )^i]=i; + } + + for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) { + // Compute sbox + s = xInv ^ xInv<<1 ^ xInv<<2 ^ xInv<<3 ^ xInv<<4; + s = s>>8 ^ s&255 ^ 99; + sbox[x] = s; + sboxInv[s] = x; + + // Compute MixColumns + x8 = d[x4 = d[x2 = d[x]]]; + tDec = x8*0x1010101 ^ x4*0x10001 ^ x2*0x101 ^ x*0x1010100; + tEnc = d[s]*0x101 ^ s*0x1010100; + + for (i = 0; i < 4; i++) { + encTable[i][x] = tEnc = tEnc<<24 ^ tEnc>>>8; + decTable[i][s] = tDec = tDec<<24 ^ tDec>>>8; + } + } + + // Compactify. Considerable speedup on Firefox. + for (i = 0; i < 5; i++) { + encTable[i] = encTable[i].slice(0); + decTable[i] = decTable[i].slice(0); + } + }, + + /** + * Encryption and decryption core. + * @param {Array} input Four words to be encrypted or decrypted. + * @param dir The direction, 0 for encrypt and 1 for decrypt. + * @return {Array} The four encrypted or decrypted words. + * @private + */ + _crypt:function (input, dir) { + if (input.length !== 4) { + throw new sjcl.exception.invalid("invalid aes block size"); + } + + var key = this._key[dir], + // state variables a,b,c,d are loaded with pre-whitened data + a = input[0] ^ key[0], + b = input[dir ? 3 : 1] ^ key[1], + c = input[2] ^ key[2], + d = input[dir ? 1 : 3] ^ key[3], + a2, b2, c2, + + nInnerRounds = key.length/4 - 2, + i, + kIndex = 4, + out = [0,0,0,0], + table = this._tables[dir], + + // load up the tables + t0 = table[0], + t1 = table[1], + t2 = table[2], + t3 = table[3], + sbox = table[4]; + + // Inner rounds. Cribbed from OpenSSL. + for (i = 0; i < nInnerRounds; i++) { + a2 = t0[a>>>24] ^ t1[b>>16 & 255] ^ t2[c>>8 & 255] ^ t3[d & 255] ^ key[kIndex]; + b2 = t0[b>>>24] ^ t1[c>>16 & 255] ^ t2[d>>8 & 255] ^ t3[a & 255] ^ key[kIndex + 1]; + c2 = t0[c>>>24] ^ t1[d>>16 & 255] ^ t2[a>>8 & 255] ^ t3[b & 255] ^ key[kIndex + 2]; + d = t0[d>>>24] ^ t1[a>>16 & 255] ^ t2[b>>8 & 255] ^ t3[c & 255] ^ key[kIndex + 3]; + kIndex += 4; + a=a2; b=b2; c=c2; + } + + // Last round. + for (i = 0; i < 4; i++) { + out[dir ? 3&-i : i] = + sbox[a>>>24 ]<<24 ^ + sbox[b>>16 & 255]<<16 ^ + sbox[c>>8 & 255]<<8 ^ + sbox[d & 255] ^ + key[kIndex++]; + a2=a; a=b; b=c; c=d; d=a2; + } + + return out; + } +}; + diff --git a/lib/sjcl/core/bitArray.js b/lib/sjcl/core/bitArray.js new file mode 100644 index 0000000..803b9c5 --- /dev/null +++ b/lib/sjcl/core/bitArray.js @@ -0,0 +1,187 @@ +/** @fileOverview Arrays of bits, encoded as arrays of Numbers. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** @namespace Arrays of bits, encoded as arrays of Numbers. + * + * @description + *

+ * These objects are the currency accepted by SJCL's crypto functions. + *

+ * + *

+ * Most of our crypto primitives operate on arrays of 4-byte words internally, + * but many of them can take arguments that are not a multiple of 4 bytes. + * This library encodes arrays of bits (whose size need not be a multiple of 8 + * bits) as arrays of 32-bit words. The bits are packed, big-endian, into an + * array of words, 32 bits at a time. Since the words are double-precision + * floating point numbers, they fit some extra data. We use this (in a private, + * possibly-changing manner) to encode the number of bits actually present + * in the last word of the array. + *

+ * + *

+ * Because bitwise ops clear this out-of-band data, these arrays can be passed + * to ciphers like AES which want arrays of words. + *

+ */ +sjcl.bitArray = { + /** + * Array slices in units of bits. + * @param {bitArray a} The array to slice. + * @param {Number} bstart The offset to the start of the slice, in bits. + * @param {Number} bend The offset to the end of the slice, in bits. If this is undefined, + * slice until the end of the array. + * @return {bitArray} The requested slice. + */ + bitSlice: function (a, bstart, bend) { + a = sjcl.bitArray._shiftRight(a.slice(bstart/32), 32 - (bstart & 31)).slice(1); + return (bend === undefined) ? a : sjcl.bitArray.clamp(a, bend-bstart); + }, + + /** + * Extract a number packed into a bit array. + * @param {bitArray} a The array to slice. + * @param {Number} bstart The offset to the start of the slice, in bits. + * @param {Number} length The length of the number to extract. + * @return {Number} The requested slice. + */ + extract: function(a, bstart, blength) { + // FIXME: this Math.floor is not necessary at all, but for some reason + // seems to suppress a bug in the Chromium JIT. + var x, sh = Math.floor((-bstart-blength) & 31); + if ((bstart + blength - 1 ^ bstart) & -32) { + // it crosses a boundary + x = (a[bstart/32|0] << (32 - sh)) ^ (a[bstart/32+1|0] >>> sh); + } else { + // within a single word + x = a[bstart/32|0] >>> sh; + } + return x & ((1< 0 && len) { + a[l-1] = sjcl.bitArray.partial(len, a[l-1] & 0x80000000 >> (len-1), 1); + } + return a; + }, + + /** + * Make a partial word for a bit array. + * @param {Number} len The number of bits in the word. + * @param {Number} x The bits. + * @param {Number} [0] _end Pass 1 if x has already been shifted to the high side. + * @return {Number} The partial word. + */ + partial: function (len, x, _end) { + if (len === 32) { return x; } + return (_end ? x|0 : x << (32-len)) + len * 0x10000000000; + }, + + /** + * Get the number of bits used by a partial word. + * @param {Number} x The partial word. + * @return {Number} The number of bits used by the partial word. + */ + getPartial: function (x) { + return Math.round(x/0x10000000000) || 32; + }, + + /** + * Compare two arrays for equality in a predictable amount of time. + * @param {bitArray} a The first array. + * @param {bitArray} b The second array. + * @return {boolean} true if a == b; false otherwise. + */ + equal: function (a, b) { + if (sjcl.bitArray.bitLength(a) !== sjcl.bitArray.bitLength(b)) { + return false; + } + var x = 0, i; + for (i=0; i= 32; shift -= 32) { + out.push(carry); + carry = 0; + } + if (shift === 0) { + return out.concat(a); + } + + for (i=0; i>>shift); + carry = a[i] << (32-shift); + } + last2 = a.length ? a[a.length-1] : 0; + shift2 = sjcl.bitArray.getPartial(last2); + out.push(sjcl.bitArray.partial(shift+shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(),1)); + return out; + }, + + /** xor a block of 4 words together. + * @private + */ + _xor4: function(x,y) { + return [x[0]^y[0],x[1]^y[1],x[2]^y[2],x[3]^y[3]]; + } +}; diff --git a/lib/sjcl/core/bn.js b/lib/sjcl/core/bn.js new file mode 100644 index 0000000..672fd08 --- /dev/null +++ b/lib/sjcl/core/bn.js @@ -0,0 +1,534 @@ +/** + * Constructs a new bignum from another bignum, a number or a hex string. + */ +sjcl.bn = function(it) { + this.initWith(it); +}; + +sjcl.bn.prototype = { + radix: 24, + maxMul: 8, + _class: sjcl.bn, + + copy: function() { + return new this._class(this); + }, + + /** + * Initializes this with it, either as a bn, a number, or a hex string. + */ + initWith: function(it) { + var i=0, k, n, l; + switch(typeof it) { + case "object": + this.limbs = it.limbs.slice(0); + break; + + case "number": + this.limbs = [it]; + this.normalize(); + break; + + case "string": + it = it.replace(/^0x/, ''); + this.limbs = []; + // hack + k = this.radix / 4; + for (i=0; i < it.length; i+=k) { + this.limbs.push(parseInt(it.substring(Math.max(it.length - i - k, 0), it.length - i),16)); + } + break; + + default: + this.limbs = [0]; + } + return this; + }, + + /** + * Returns true if "this" and "that" are equal. Calls fullReduce(). + * Equality test is in constant time. + */ + equals: function(that) { + if (typeof that === "number") { that = new this._class(that); } + var difference = 0, i; + this.fullReduce(); + that.fullReduce(); + for (i = 0; i < this.limbs.length || i < that.limbs.length; i++) { + difference |= this.getLimb(i) ^ that.getLimb(i); + } + return (difference === 0); + }, + + /** + * Get the i'th limb of this, zero if i is too large. + */ + getLimb: function(i) { + return (i >= this.limbs.length) ? 0 : this.limbs[i]; + }, + + /** + * Constant time comparison function. + * Returns 1 if this >= that, or zero otherwise. + */ + greaterEquals: function(that) { + if (typeof that === "number") { that = new this._class(that); } + var less = 0, greater = 0, i, a, b; + i = Math.max(this.limbs.length, that.limbs.length) - 1; + for (; i>= 0; i--) { + a = this.getLimb(i); + b = that.getLimb(i); + greater |= (b - a) & ~less; + less |= (a - b) & ~greater; + } + return (greater | ~less) >>> 31; + }, + + /** + * Convert to a hex string. + */ + toString: function() { + this.fullReduce(); + var out="", i, s, l = this.limbs; + for (i=0; i < this.limbs.length; i++) { + s = l[i].toString(16); + while (i < this.limbs.length - 1 && s.length < 6) { + s = "0" + s; + } + out = s + out; + } + return "0x"+out; + }, + + /** this += that. Does not normalize. */ + addM: function(that) { + if (typeof(that) !== "object") { that = new this._class(that); } + var i, l=this.limbs, ll=that.limbs; + for (i=l.length; i> r; + } + if (carry) { + l.push(carry); + } + return this; + }, + + /** this /= 2, rounded down. Requires normalized; ends up normalized. */ + halveM: function() { + var i, carry=0, tmp, r=this.radix, l=this.limbs; + for (i=l.length-1; i>=0; i--) { + tmp = l[i]; + l[i] = (tmp+carry)>>1; + carry = (tmp&1) << r; + } + if (!l[l.length-1]) { + l.pop(); + } + return this; + }, + + /** this -= that. Does not normalize. */ + subM: function(that) { + if (typeof(that) !== "object") { that = new this._class(that); } + var i, l=this.limbs, ll=that.limbs; + for (i=l.length; i 0; ci--) { + that.halveM(); + if (out.greaterEquals(that)) { + out.subM(that).normalize(); + } + } + return out.trim(); + }, + + /** return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. */ + inverseMod: function(p) { + var a = new sjcl.bn(1), b = new sjcl.bn(0), x = new sjcl.bn(this), y = new sjcl.bn(p), tmp, i, nz=1; + + if (!(p.limbs[0] & 1)) { + throw (new sjcl.exception.invalid("inverseMod: p must be odd")); + } + + // invariant: y is odd + do { + if (x.limbs[0] & 1) { + if (!x.greaterEquals(y)) { + // x < y; swap everything + tmp = x; x = y; y = tmp; + tmp = a; a = b; b = tmp; + } + x.subM(y); + x.normalize(); + + if (!a.greaterEquals(b)) { + a.addM(p); + } + a.subM(b); + } + + // cut everything in half + x.halveM(); + if (a.limbs[0] & 1) { + a.addM(p); + } + a.normalize(); + a.halveM(); + + // check for termination: x ?= 0 + for (i=nz=0; i= 0; i--) { + out = w.concat(out, [w.partial(this.radix, this.getLimb(i))]); + } + return out; + }, + + /** Return the length in bits, rounded up to the nearest byte. */ + bitLength: function() { + this.fullReduce(); + var out = this.radix * (this.limbs.length - 1), + b = this.limbs[this.limbs.length - 1]; + for (; b; b >>= 1) { + out ++; + } + return out+7 & -8; + } +}; + +sjcl.bn.fromBits = function(bits) { + var Class = this, out = new Class(), words=[], w=sjcl.bitArray, t = this.prototype, + l = Math.min(this.bitLength || 0x100000000, w.bitLength(bits)), e = l % t.radix || t.radix; + + words[0] = w.extract(bits, 0, e); + for (; e < l; e += t.radix) { + words.unshift(w.extract(bits, e, t.radix)); + } + + out.limbs = words; + return out; +}; + + + +sjcl.bn.prototype.ipv = 1 / (sjcl.bn.prototype.placeVal = Math.pow(2,sjcl.bn.prototype.radix)); +sjcl.bn.prototype.radixMask = (1 << sjcl.bn.prototype.radix) - 1; + +/** + * Creates a new subclass of bn, based on reduction modulo a pseudo-Mersenne prime, + * i.e. a prime of the form 2^e + sum(a * 2^b),where the sum is negative and sparse. + */ +sjcl.bn.pseudoMersennePrime = function(exponent, coeff) { + function p(it) { + this.initWith(it); + /*if (this.limbs[this.modOffset]) { + this.reduce(); + }*/ + } + + var ppr = p.prototype = new sjcl.bn(), i, tmp, mo; + mo = ppr.modOffset = Math.ceil(tmp = exponent / ppr.radix); + ppr.exponent = exponent; + ppr.offset = []; + ppr.factor = []; + ppr.minOffset = mo; + ppr.fullMask = 0; + ppr.fullOffset = []; + ppr.fullFactor = []; + ppr.modulus = p.modulus = new sjcl.bn(Math.pow(2,exponent)); + + ppr.fullMask = 0|-Math.pow(2, exponent % ppr.radix); + + for (i=0; i mo) { + l = limbs.pop(); + ll = limbs.length; + for (k=0; k> 3) & 15)) * 0x1010101; + + /* Pad and encrypt. */ + iv = prp.encrypt(xor(iv,w.concat(plaintext,[bl,bl,bl,bl]).slice(i,i+4))); + output.splice(i,0,iv[0],iv[1],iv[2],iv[3]); + return output; + }, + + /** Decrypt in CBC mode. + * @param {Object} prp The block cipher. It must have a block size of 16 bytes. + * @param {bitArray} ciphertext The ciphertext data. + * @param {bitArray} iv The initialization value. + * @param {bitArray} [adata=[]] The authenticated data. It must be empty. + * @return The decrypted data, an array of bytes. + * @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits, or if any adata is specified. + * @throws {sjcl.exception.corrupt} if if the message is corrupt. + */ + decrypt: function(prp, ciphertext, iv, adata) { + if (adata && adata.length) { + throw new sjcl.exception.invalid("cbc can't authenticate data"); + } + if (sjcl.bitArray.bitLength(iv) !== 128) { + throw new sjcl.exception.invalid("cbc iv must be 128 bits"); + } + if ((sjcl.bitArray.bitLength(ciphertext) & 127) || !ciphertext.length) { + throw new sjcl.exception.corrupt("cbc ciphertext must be a positive multiple of the block size"); + } + var i, + w = sjcl.bitArray, + xor = w._xor4, + bi, bo, + output = []; + + adata = adata || []; + + for (i=0; i 16) { + throw new sjcl.exception.corrupt("pkcs#5 padding corrupt"); + } + bo = bi * 0x1010101; + if (!w.equal(w.bitSlice([bo,bo,bo,bo], 0, bi*8), + w.bitSlice(output, output.length*32 - bi*8, output.length*32))) { + throw new sjcl.exception.corrupt("pkcs#5 padding corrupt"); + } + + return w.bitSlice(output, 0, output.length*32 - bi*8); + } + }; +}; diff --git a/lib/sjcl/core/ccm.js b/lib/sjcl/core/ccm.js new file mode 100644 index 0000000..8a32c5a --- /dev/null +++ b/lib/sjcl/core/ccm.js @@ -0,0 +1,185 @@ +/** @fileOverview CCM mode implementation. + * + * Special thanks to Roy Nicholson for pointing out a bug in our + * implementation. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** @namespace CTR mode with CBC MAC. */ +sjcl.mode.ccm = { + /** The name of the mode. + * @constant + */ + name: "ccm", + + /** Encrypt in CCM mode. + * @static + * @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes. + * @param {bitArray} plaintext The plaintext data. + * @param {bitArray} iv The initialization value. + * @param {bitArray} [adata=[]] The authenticated data. + * @param {Number} [tlen=64] the desired tag length, in bits. + * @return {bitArray} The encrypted data, an array of bytes. + */ + encrypt: function(prf, plaintext, iv, adata, tlen) { + var L, i, out = plaintext.slice(0), tag, w=sjcl.bitArray, ivl = w.bitLength(iv) / 8, ol = w.bitLength(out) / 8; + tlen = tlen || 64; + adata = adata || []; + + if (ivl < 7) { + throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"); + } + + // compute the length of the length + for (L=2; L<4 && ol >>> 8*L; L++) {} + if (L < 15 - ivl) { L = 15-ivl; } + iv = w.clamp(iv,8*(15-L)); + + // compute the tag + tag = sjcl.mode.ccm._computeTag(prf, plaintext, iv, adata, tlen, L); + + // encrypt + out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L); + + return w.concat(out.data, out.tag); + }, + + /** Decrypt in CCM mode. + * @static + * @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes. + * @param {bitArray} ciphertext The ciphertext data. + * @param {bitArray} iv The initialization value. + * @param {bitArray} [[]] adata The authenticated data. + * @param {Number} [64] tlen the desired tag length, in bits. + * @return {bitArray} The decrypted data. + */ + decrypt: function(prf, ciphertext, iv, adata, tlen) { + tlen = tlen || 64; + adata = adata || []; + var L, i, + w=sjcl.bitArray, + ivl = w.bitLength(iv) / 8, + ol = w.bitLength(ciphertext), + out = w.clamp(ciphertext, ol - tlen), + tag = w.bitSlice(ciphertext, ol - tlen), tag2; + + + ol = (ol - tlen) / 8; + + if (ivl < 7) { + throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"); + } + + // compute the length of the length + for (L=2; L<4 && ol >>> 8*L; L++) {} + if (L < 15 - ivl) { L = 15-ivl; } + iv = w.clamp(iv,8*(15-L)); + + // decrypt + out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L); + + // check the tag + tag2 = sjcl.mode.ccm._computeTag(prf, out.data, iv, adata, tlen, L); + if (!w.equal(out.tag, tag2)) { + throw new sjcl.exception.corrupt("ccm: tag doesn't match"); + } + + return out.data; + }, + + /* Compute the (unencrypted) authentication tag, according to the CCM specification + * @param {Object} prf The pseudorandom function. + * @param {bitArray} plaintext The plaintext data. + * @param {bitArray} iv The initialization value. + * @param {bitArray} adata The authenticated data. + * @param {Number} tlen the desired tag length, in bits. + * @return {bitArray} The tag, but not yet encrypted. + * @private + */ + _computeTag: function(prf, plaintext, iv, adata, tlen, L) { + // compute B[0] + var q, mac, field = 0, offset = 24, tmp, i, macData = [], w=sjcl.bitArray, xor = w._xor4; + + tlen /= 8; + + // check tag length and message length + if (tlen % 2 || tlen < 4 || tlen > 16) { + throw new sjcl.exception.invalid("ccm: invalid tag length"); + } + + if (adata.length > 0xFFFFFFFF || plaintext.length > 0xFFFFFFFF) { + // I don't want to deal with extracting high words from doubles. + throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data"); + } + + // mac the flags + mac = [w.partial(8, (adata.length ? 1<<6 : 0) | (tlen-2) << 2 | L-1)]; + + // mac the iv and length + mac = w.concat(mac, iv); + mac[3] |= w.bitLength(plaintext)/8; + mac = prf.encrypt(mac); + + + if (adata.length) { + // mac the associated data. start with its length... + tmp = w.bitLength(adata)/8; + if (tmp <= 0xFEFF) { + macData = [w.partial(16, tmp)]; + } else if (tmp <= 0xFFFFFFFF) { + macData = w.concat([w.partial(16,0xFFFE)], [tmp]); + } // else ... + + // mac the data itself + macData = w.concat(macData, adata); + for (i=0; i>>bits) >>> 26); + if (bits < 6) { + ta = arr[i] << (6-bits); + bits += 26; + i++; + } else { + ta <<= 6; + bits -= 6; + } + } + while ((out.length & 3) && !_noEquals) { out += "="; } + return out; + }, + + /** Convert from a base64 string to a bitArray */ + toBits: function(str) { + str = str.replace(/\s|=/g,''); + var out = [], i, bits=0, c = sjcl.codec.base64._chars, ta=0, x; + for (i=0; i 26) { + bits -= 26; + out.push(ta ^ x>>>bits); + ta = x << (32-bits); + } else { + bits += 6; + ta ^= x << (32-bits); + } + } + if (bits&56) { + out.push(sjcl.bitArray.partial(bits&56, ta, 1)); + } + return out; + } +}; diff --git a/lib/sjcl/core/codecBytes.js b/lib/sjcl/core/codecBytes.js new file mode 100644 index 0000000..cde2af3 --- /dev/null +++ b/lib/sjcl/core/codecBytes.js @@ -0,0 +1,37 @@ +/** @fileOverview Bit array codec implementations. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** @namespace Arrays of bytes */ +sjcl.codec.bytes = { + /** Convert from a bitArray to an array of bytes. */ + fromBits: function (arr) { + var out = [], bl = sjcl.bitArray.bitLength(arr), i, tmp; + for (i=0; i>> 24); + tmp <<= 8; + } + return out; + }, + /** Convert from an array of bytes to a bitArray. */ + toBits: function (bytes) { + var out = [], i, tmp=0; + for (i=0; i>> 24); + tmp <<= 8; + } + return decodeURIComponent(escape(out)); + }, + + /** Convert from a UTF-8 string to a bitArray. */ + toBits: function (str) { + str = unescape(encodeURIComponent(str)); + var out = [], i, tmp=0; + for (i=0; i 4)) { + throw new sjcl.exception.invalid("json encrypt: invalid parameters"); + } + + if (typeof password === "string") { + tmp = sjcl.misc.cachedPbkdf2(password, p); + password = tmp.key.slice(0,p.ks/32); + p.salt = tmp.salt; + } + if (typeof plaintext === "string") { + plaintext = sjcl.codec.utf8String.toBits(plaintext); + } + prp = new sjcl.cipher[p.cipher](password); + + /* return the json data */ + j._add(rp, p); + rp.key = password; + + /* do the encryption */ + p.ct = sjcl.mode[p.mode].encrypt(prp, plaintext, p.iv, p.adata, p.tag); + + return j.encode(j._subtract(p, j.defaults)); + }, + + /** Simple decryption function. + * @param {String|bitArray} password The password or key. + * @param {String} ciphertext The ciphertext to decrypt. + * @param {Object} [params] Additional non-default parameters. + * @param {Object} [rp] A returned object with filled parameters. + * @return {String} The plaintext. + * @throws {sjcl.exception.invalid} if a parameter is invalid. + * @throws {sjcl.exception.corrupt} if the ciphertext is corrupt. + */ + decrypt: function (password, ciphertext, params, rp) { + params = params || {}; + rp = rp || {}; + + var j = sjcl.json, p = j._add(j._add(j._add({},j.defaults),j.decode(ciphertext)), params, true), ct, tmp, prp; + if (typeof p.salt === "string") { + p.salt = sjcl.codec.base64.toBits(p.salt); + } + if (typeof p.iv === "string") { + p.iv = sjcl.codec.base64.toBits(p.iv); + } + + if (!sjcl.mode[p.mode] || + !sjcl.cipher[p.cipher] || + (typeof password === "string" && p.iter <= 100) || + (p.ts !== 64 && p.ts !== 96 && p.ts !== 128) || + (p.ks !== 128 && p.ks !== 192 && p.ks !== 256) || + (!p.iv) || + (p.iv.length < 2 || p.iv.length > 4)) { + throw new sjcl.exception.invalid("json decrypt: invalid parameters"); + } + + if (typeof password === "string") { + tmp = sjcl.misc.cachedPbkdf2(password, p); + password = tmp.key.slice(0,p.ks/32); + p.salt = tmp.salt; + } + prp = new sjcl.cipher[p.cipher](password); + + /* do the decryption */ + ct = sjcl.mode[p.mode].decrypt(prp, p.ct, p.iv, p.adata, p.tag); + + /* return the json data */ + j._add(rp, p); + rp.key = password; + + return sjcl.codec.utf8String.fromBits(ct); + }, + + /** Encode a flat structure into a JSON string. + * @param {Object} obj The structure to encode. + * @return {String} A JSON string. + * @throws {sjcl.exception.invalid} if obj has a non-alphanumeric property. + * @throws {sjcl.exception.bug} if a parameter has an unsupported type. + */ + encode: function (obj) { + var i, out='{', comma=''; + for (i in obj) { + if (obj.hasOwnProperty(i)) { + if (!i.match(/^[a-z0-9]+$/i)) { + throw new sjcl.exception.invalid("json encode: invalid property name"); + } + out += comma + i + ':'; + comma = ','; + + switch (typeof obj[i]) { + case 'number': + case 'boolean': + out += obj[i]; + break; + + case 'string': + out += '"' + escape(obj[i]) + '"'; + break; + + case 'object': + out += '"' + sjcl.codec.base64.fromBits(obj[i],1) + '"'; + break; + + default: + throw new sjcl.exception.bug("json encode: unsupported type"); + } + } + } + return out+'}'; + }, + + /** Decode a simple (flat) JSON string into a structure. The ciphertext, + * adata, salt and iv will be base64-decoded. + * @param {String} str The string. + * @return {Object} The decoded structure. + * @throws {sjcl.exception.invalid} if str isn't (simple) JSON. + */ + decode: function (str) { + str = str.replace(/\s/g,''); + if (!str.match(/^\{.*\}$/)) { + throw new sjcl.exception.invalid("json decode: this isn't json!"); + } + var a = str.replace(/^\{|\}$/g, '').split(/,/), out={}, i, m; + for (i=0; i=0; i--) { + for (j=sjcl.bn.prototype.radix-4; j>=0; j-=4) { + out = out.doubl().doubl().doubl().doubl().add(multiples[k[i]>>j & 0xF]); + } + } + + return out; + }, + + /** + * Multiply this point by k, added to affine2*k2, and return the answer in Jacobian coordinates. + * @param {bigInt} k The coefficient to multiply this by. + * @param {sjcl.ecc.point} affine This point in affine coordinates. + * @param {bigInt} k2 The coefficient to multiply affine2 this by. + * @param {sjcl.ecc.point} affine The other point in affine coordinates. + * @return {sjcl.ecc.pointJac} The result of the multiplication and addition, in Jacobian coordinates. + */ + mult2: function(k1, affine, k2, affine2) { + if (typeof(k1) === "number") { + k1 = [k1]; + } else if (k1.limbs !== undefined) { + k1 = k1.normalize().limbs; + } + + if (typeof(k2) === "number") { + k2 = [k2]; + } else if (k2.limbs !== undefined) { + k2 = k2.normalize().limbs; + } + + var i, j, out = new sjcl.ecc.point(this.curve).toJac(), m1 = affine.multiples(), + m2 = affine2.multiples(), l1, l2; + + for (i=Math.max(k1.length,k2.length)-1; i>=0; i--) { + l1 = k1[i] | 0; + l2 = k2[i] | 0; + for (j=sjcl.bn.prototype.radix-4; j>=0; j-=4) { + out = out.doubl().doubl().doubl().doubl().add(m1[l1>>j & 0xF]).add(m2[l2>>j & 0xF]); + } + } + + return out; + }, + + isValid: function() { + var z2 = this.z.square(), z4 = z2.square(), z6 = z4.mul(z2); + return this.y.square().equals( + this.curve.b.mul(z6).add(this.x.mul( + this.curve.a.mul(z4).add(this.x.square())))); + } +}; + +/** + * Construct an elliptic curve. Most users will not use this and instead start with one of the NIST curves defined below. + * + * @constructor + * @param {bigInt} p The prime modulus. + * @param {bigInt} r The prime order of the curve. + * @param {bigInt} a The constant a in the equation of the curve y^2 = x^3 + ax + b (for NIST curves, a is always -3). + * @param {bigInt} x The x coordinate of a base point of the curve. + * @param {bigInt} y The y coordinate of a base point of the curve. + */ +sjcl.ecc.curve = function(Field, r, a, b, x, y) { + this.field = Field; + this.r = Field.prototype.modulus.sub(r); + this.a = new Field(a); + this.b = new Field(b); + this.G = new sjcl.ecc.point(this, new Field(x), new Field(y)); +}; + +sjcl.ecc.curve.prototype.fromBits = function (bits) { + var w = sjcl.bitArray, l = this.field.prototype.exponent + 7 & -8, + p = new sjcl.ecc.point(this, this.field.fromBits(w.bitSlice(bits, 0, l)), + this.field.fromBits(w.bitSlice(bits, l, 2*l))); + if (!p.isValid()) { + throw new sjcl.exception.corrupt("not on the curve!"); + } + return p; +}; + +sjcl.ecc.curves = { + c192: new sjcl.ecc.curve( + sjcl.bn.prime.p192, + "0x662107c8eb94364e4b2dd7ce", + -3, + "0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", + "0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", + "0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811"), + + c224: new sjcl.ecc.curve( + sjcl.bn.prime.p224, + "0xe95c1f470fc1ec22d6baa3a3d5c4", + -3, + "0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4", + "0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21", + "0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34"), + + c256: new sjcl.ecc.curve( + sjcl.bn.prime.p256, + "0x4319055358e8617b0c46353d039cdaae", + -3, + "0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", + "0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", + "0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), + + c384: new sjcl.ecc.curve( + sjcl.bn.prime.p384, + "0x389cb27e0bc8d21fa7e5f24cb74f58851313e696333ad68c", + -3, + "0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef", + "0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7", + "0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f") +}; + + +/* Diffie-Hellman-like public-key system */ +sjcl.ecc._dh = function(cn) { + sjcl.ecc[cn] = { + publicKey: function(curve, point) { + this._curve = curve; + if (point instanceof Array) { + this._point = curve.fromBits(point); + } else { + this._point = point; + } + }, + + secretKey: function(curve, exponent) { + this._curve = curve; + this._exponent = exponent; + }, + + generateKeys: function(curve, paranoia) { + if (curve === undefined) { + curve = 256; + } + if (typeof curve === "number") { + curve = sjcl.ecc.curves['c'+curve]; + if (curve === undefined) { + throw new sjcl.exception.invalid("no such curve"); + } + } + var sec = sjcl.bn.random(curve.r, paranoia), pub = curve.G.mult(sec); + return { pub: new sjcl.ecc[cn].publicKey(curve, pub), + sec: new sjcl.ecc[cn].secretKey(curve, sec) }; + } + }; +}; + +sjcl.ecc._dh("elGamal"); + +sjcl.ecc.elGamal.publicKey.prototype = { + kem: function(paranoia) { + var sec = sjcl.bn.random(this._curve.r, paranoia), + tag = this._curve.G.mult(sec).toBits(), + key = sjcl.hash.sha256.hash(this._point.mult(sec).toBits()); + return { key: key, tag: tag }; + } +}; + +sjcl.ecc.elGamal.secretKey.prototype = { + unkem: function(tag) { + return sjcl.hash.sha256.hash(this._curve.fromBits(tag).mult(this._exponent).toBits()); + }, + + dh: function(pk) { + return sjcl.hash.sha256.hash(pk._point.mult(this._exponent).toBits()); + } +}; + +sjcl.ecc._dh("ecdsa"); + +sjcl.ecc.ecdsa.secretKey.prototype = { + sign: function(hash, paranoia) { + var R = this._curve.r, + l = R.bitLength(), + k = sjcl.bn.random(R.sub(1), paranoia).add(1), + r = this._curve.G.mult(k).x.mod(R), + s = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)).inverseMod(R).mul(k).mod(R); + return sjcl.bitArray.concat(r.toBits(l), s.toBits(l)); + } +}; + +sjcl.ecc.ecdsa.publicKey.prototype = { + verify: function(hash, rs) { + var w = sjcl.bitArray, + R = this._curve.r, + l = R.bitLength(), + r = sjcl.bn.fromBits(w.bitSlice(rs,0,l)), + s = sjcl.bn.fromBits(w.bitSlice(rs,l,2*l)), + hG = sjcl.bn.fromBits(hash).mul(s).mod(R), + hA = r.mul(s).mod(R), + r2 = this._curve.G.mult2(hG, hA, this._point).x; + + if (r.equals(0) || s.equals(0) || r.greaterEquals(R) || s.greaterEquals(R) || !r2.equals(r)) { + throw (new sjcl.exception.corrupt("signature didn't check out")); + } + return true; + } +}; diff --git a/lib/sjcl/core/hmac.js b/lib/sjcl/core/hmac.js new file mode 100644 index 0000000..87237b2 --- /dev/null +++ b/lib/sjcl/core/hmac.js @@ -0,0 +1,40 @@ +/** @fileOverview HMAC implementation. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** HMAC with the specified hash function. + * @constructor + * @param {bitArray} key the key for HMAC. + * @param {Object} [hash=sjcl.hash.sha256] The hash function to use. + */ +sjcl.misc.hmac = function (key, Hash) { + this._hash = Hash = Hash || sjcl.hash.sha256; + var exKey = [[],[]], i, + bs = Hash.prototype.blockSize / 32; + this._baseHash = [new Hash(), new Hash()]; + + if (key.length > bs) { + key = Hash.hash(key); + } + + for (i=0; i>>31, + x[1]<<1 ^ x[2]>>>31, + x[2]<<1 ^ x[3]>>>31, + x[3]<<1 ^ (x[0]>>>31)*0x87]; + } +}; diff --git a/lib/sjcl/core/pbkdf2.js b/lib/sjcl/core/pbkdf2.js new file mode 100644 index 0000000..869e4df --- /dev/null +++ b/lib/sjcl/core/pbkdf2.js @@ -0,0 +1,54 @@ +/** @fileOverview Password-based key-derivation function, version 2.0. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** Password-Based Key-Derivation Function, version 2.0. + * + * Generate keys from passwords using PBKDF2-HMAC-SHA256. + * + * This is the method specified by RSA's PKCS #5 standard. + * + * @param {bitArray|String} password The password. + * @param {bitArray} salt The salt. Should have lots of entropy. + * @param {Number} [count=1000] The number of iterations. Higher numbers make the function slower but more secure. + * @param {Number} [length] The length of the derived key. Defaults to the + output size of the hash function. + * @param {Object} [Prff=sjcl.misc.hmac] The pseudorandom function family. + * @return {bitArray} the derived key. + */ +sjcl.misc.pbkdf2 = function (password, salt, count, length, Prff) { + count = count || 1000; + + if (length < 0 || count < 0) { + throw sjcl.exception.invalid("invalid params to pbkdf2"); + } + + if (typeof password === "string") { + password = sjcl.codec.utf8String.toBits(password); + } + + Prff = Prff || sjcl.misc.hmac; + + var prf = new Prff(password), + u, ui, i, j, k, out = [], b = sjcl.bitArray; + + for (k = 1; 32 * out.length < (length || 1); k++) { + u = ui = prf.encrypt(b.concat(salt,[k])); + + for (i=1; i + * This random number generator is a derivative of Ferguson and Schneier's + * generator Fortuna. It collects entropy from various events into several + * pools, implemented by streaming SHA-256 instances. It differs from + * ordinary Fortuna in a few ways, though. + *

+ * + *

+ * Most importantly, it has an entropy estimator. This is present because + * there is a strong conflict here between making the generator available + * as soon as possible, and making sure that it doesn't "run on empty". + * In Fortuna, there is a saved state file, and the system is likely to have + * time to warm up. + *

+ * + *

+ * Second, because users are unlikely to stay on the page for very long, + * and to speed startup time, the number of pools increases logarithmically: + * a new pool is created when the previous one is actually used for a reseed. + * This gives the same asymptotic guarantees as Fortuna, but gives more + * entropy to early reseeds. + *

+ * + *

+ * The entire mechanism here feels pretty klunky. Furthermore, there are + * several improvements that should be made, including support for + * dedicated cryptographic functions that may be present in some browsers; + * state files in local storage; cookies containing randomness; etc. So + * look for improvements in future versions. + *

+ */ +sjcl.random = { + /** Generate several random words, and return them in an array + * @param {Number} nwords The number of words to generate. + */ + randomWords: function (nwords, paranoia) { + var out = [], i, readiness = this.isReady(paranoia), g; + + if (readiness === this._NOT_READY) { + throw new sjcl.exception.notReady("generator isn't seeded"); + } else if (readiness & this._REQUIRES_RESEED) { + this._reseedFromPools(!(readiness & this._READY)); + } + + for (i=0; i0) { + estimatedEntropy++; + tmp = tmp >>> 1; + } + } + } + this._pools[robin].update([id,this._eventId++,ty||2,estimatedEntropy,t,data.length].concat(data)); + break; + + case "string": + if (estimatedEntropy === undefined) { + /* English text has just over 1 bit per character of entropy. + * But this might be HTML or something, and have far less + * entropy than English... Oh well, let's just say one bit. + */ + estimatedEntropy = data.length; + } + this._pools[robin].update([id,this._eventId++,3,estimatedEntropy,t,data.length]); + this._pools[robin].update(data); + break; + + default: + + throw new sjcl.exception.bug("random: addEntropy only supports number, array or string"); + } + + /* record the new strength */ + this._poolEntropy[robin] += estimatedEntropy; + this._poolStrength += estimatedEntropy; + + /* fire off events */ + if (oldReady === this._NOT_READY) { + if (this.isReady() !== this._NOT_READY) { + this._fireEvent("seeded", Math.max(this._strength, this._poolStrength)); + } + this._fireEvent("progress", this.getProgress()); + } + }, + + /** Is the generator ready? */ + isReady: function (paranoia) { + var entropyRequired = this._PARANOIA_LEVELS[ (paranoia !== undefined) ? paranoia : this._defaultParanoia ]; + + if (this._strength && this._strength >= entropyRequired) { + return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ? + this._REQUIRES_RESEED | this._READY : + this._READY; + } else { + return (this._poolStrength >= entropyRequired) ? + this._REQUIRES_RESEED | this._NOT_READY : + this._NOT_READY; + } + }, + + /** Get the generator's progress toward readiness, as a fraction */ + getProgress: function (paranoia) { + var entropyRequired = this._PARANOIA_LEVELS[ paranoia ? paranoia : this._defaultParanoia ]; + + if (this._strength >= entropyRequired) { + return 1.0; + } else { + return (this._poolStrength > entropyRequired) ? + 1.0 : + this._poolStrength / entropyRequired; + } + }, + + /** start the built-in entropy collectors */ + startCollectors: function () { + if (this._collectorsStarted) { return; } + + if (window.addEventListener) { + window.addEventListener("load", this._loadTimeCollector, false); + window.addEventListener("mousemove", this._mouseCollector, false); + } else if (document.attachEvent) { + document.attachEvent("onload", this._loadTimeCollector); + document.attachEvent("onmousemove", this._mouseCollector); + } + else { + throw new sjcl.exception.bug("can't attach event"); + } + + this._collectorsStarted = true; + }, + + /** stop the built-in entropy collectors */ + stopCollectors: function () { + if (!this._collectorsStarted) { return; } + + if (window.removeEventListener) { + window.removeEventListener("load", this._loadTimeCollector); + window.removeEventListener("mousemove", this._mouseCollector); + } else if (window.detachEvent) { + window.detachEvent("onload", this._loadTimeCollector); + window.detachEvent("onmousemove", this._mouseCollector); + } + this._collectorsStarted = false; + }, + + /* use a cookie to store entropy. + useCookie: function (all_cookies) { + throw new sjcl.exception.bug("random: useCookie is unimplemented"); + },*/ + + /** add an event listener for progress or seeded-ness. */ + addEventListener: function (name, callback) { + this._callbacks[name][this._callbackI++] = callback; + }, + + /** remove an event listener for progress or seeded-ness */ + removeEventListener: function (name, cb) { + var i, j, cbs=this._callbacks[name], jsTemp=[]; + + /* I'm not sure if this is necessary; in C++, iterating over a + * collection and modifying it at the same time is a no-no. + */ + + for (j in cbs) { + if (cbs.hasOwnProperty(j) && cbs[j] === cb) { + jsTemp.push(j); + } + } + + for (i=0; i= 1 << this._pools.length) { + this._pools.push(new sjcl.hash.sha256()); + this._poolEntropy.push(0); + } + + /* how strong was this reseed? */ + this._poolStrength -= strength; + if (strength > this._strength) { + this._strength = strength; + } + + this._reseedCount ++; + this._reseed(reseedData); + }, + + _mouseCollector: function (ev) { + var x = ev.x || ev.clientX || ev.offsetX, y = ev.y || ev.clientY || ev.offsetY; + sjcl.random.addEntropy([x,y], 2, "mouse"); + }, + + _loadTimeCollector: function (ev) { + var d = new Date(); + sjcl.random.addEntropy(d, 2, "loadtime"); + }, + + _fireEvent: function (name, arg) { + var j, cbs=sjcl.random._callbacks[name], cbsTemp=[]; + /* TODO: there is a race condition between removing collectors and firing them */ + + /* I'm not sure if this is necessary; in C++, iterating over a + * collection and modifying it at the same time is a no-no. + */ + + for (j in cbs) { + if (cbs.hasOwnProperty(j)) { + cbsTemp.push(cbs[j]); + } + } + + for (j=0; j>> 32-n); + }, + + /** + * Perform one cycle of SHA-1. + * @param {bitArray} words one block of words. + * @private + */ + _block:function (words) { + var t, tmp, a, b, c, d, e, + w = words.slice(0), + h = this._h, + k = this._key; + + a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4]; + + for (t=0; t<=79; t++) { + if (t >= 16) { + w[t] = this._S(1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]); + } + tmp = (this._S(5, a) + this._f(t, b, c, d) + e + w[t] + + this._key[Math.floor(t/20)]) | 0; + e = d; + d = c; + c = this._S(30, b); + b = a; + a = tmp; + } + + h[0] = (h[0]+a) |0; + h[1] = (h[1]+b) |0; + h[2] = (h[2]+c) |0; + h[3] = (h[3]+d) |0; + h[4] = (h[4]+e) |0; + } +}; diff --git a/lib/sjcl/core/sha256.js b/lib/sjcl/core/sha256.js new file mode 100644 index 0000000..fd51609 --- /dev/null +++ b/lib/sjcl/core/sha256.js @@ -0,0 +1,216 @@ +/** @fileOverview Javascript SHA-256 implementation. + * + * An older version of this implementation is available in the public + * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh, + * Stanford University 2008-2010 and BSD-licensed for liability + * reasons. + * + * Special thanks to Aldo Cortesi for pointing out several bugs in + * this code. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** + * Context for a SHA-256 operation in progress. + * @constructor + * @class Secure Hash Algorithm, 256 bits. + */ +sjcl.hash.sha256 = function (hash) { + if (!this._key[0]) { this._precompute(); } + if (hash) { + this._h = hash._h.slice(0); + this._buffer = hash._buffer.slice(0); + this._length = hash._length; + } else { + this.reset(); + } +}; + +/** + * Hash a string or an array of words. + * @static + * @param {bitArray|String} data the data to hash. + * @return {bitArray} The hash value, an array of 16 big-endian words. + */ +sjcl.hash.sha256.hash = function (data) { + return (new sjcl.hash.sha256()).update(data).finalize(); +}; + +sjcl.hash.sha256.prototype = { + /** + * The hash's block size, in bits. + * @constant + */ + blockSize: 512, + + /** + * Reset the hash state. + * @return this + */ + reset:function () { + this._h = this._init.slice(0); + this._buffer = []; + this._length = 0; + return this; + }, + + /** + * Input several words to the hash. + * @param {bitArray|String} data the data to hash. + * @return this + */ + update: function (data) { + if (typeof data === "string") { + data = sjcl.codec.utf8String.toBits(data); + } + var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data), + ol = this._length, + nl = this._length = ol + sjcl.bitArray.bitLength(data); + for (i = 512+ol & -512; i <= nl; i+= 512) { + this._block(b.splice(0,16)); + } + return this; + }, + + /** + * Complete hashing and output the hash value. + * @return {bitArray} The hash value, an array of 16 big-endian words. + */ + finalize:function () { + var i, b = this._buffer, h = this._h; + + // Round out and push the buffer + b = sjcl.bitArray.concat(b, [sjcl.bitArray.partial(1,1)]); + + // Round out the buffer to a multiple of 16 words, less the 2 length words. + for (i = b.length + 2; i & 15; i++) { + b.push(0); + } + + // append the length + b.push(Math.floor(this._length / 0x100000000)); + b.push(this._length | 0); + + while (b.length) { + this._block(b.splice(0,16)); + } + + this.reset(); + return h; + }, + + /** + * The SHA-256 initialization vector, to be precomputed. + * @private + */ + _init:[], + /* + _init:[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19], + */ + + /** + * The SHA-256 hash key, to be precomputed. + * @private + */ + _key:[], + /* + _key: + [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2], + */ + + + /** + * Function to precompute _init and _key. + * @private + */ + _precompute: function () { + var i = 0, prime = 2, factor; + + function frac(x) { return (x-Math.floor(x)) * 0x100000000 | 0; } + + outer: for (; i<64; prime++) { + for (factor=2; factor*factor <= prime; factor++) { + if (prime % factor === 0) { + // not a prime + continue outer; + } + } + + if (i<8) { + this._init[i] = frac(Math.pow(prime, 1/2)); + } + this._key[i] = frac(Math.pow(prime, 1/3)); + i++; + } + }, + + /** + * Perform one cycle of SHA-256. + * @param {bitArray} words one block of words. + * @private + */ + _block:function (words) { + var i, tmp, a, b, + w = words.slice(0), + h = this._h, + k = this._key, + h0 = h[0], h1 = h[1], h2 = h[2], h3 = h[3], + h4 = h[4], h5 = h[5], h6 = h[6], h7 = h[7]; + + /* Rationale for placement of |0 : + * If a value can overflow is original 32 bits by a factor of more than a few + * million (2^23 ish), there is a possibility that it might overflow the + * 53-bit mantissa and lose precision. + * + * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that + * propagates around the loop, and on the hash state h[]. I don't believe + * that the clamps on h4 and on h0 are strictly necessary, but it's close + * (for h4 anyway), and better safe than sorry. + * + * The clamps on h[] are necessary for the output to be correct even in the + * common case and for short inputs. + */ + for (i=0; i<64; i++) { + // load up the input word for this round + if (i<16) { + tmp = w[i]; + } else { + a = w[(i+1 ) & 15]; + b = w[(i+14) & 15]; + tmp = w[i&15] = ((a>>>7 ^ a>>>18 ^ a>>>3 ^ a<<25 ^ a<<14) + + (b>>>17 ^ b>>>19 ^ b>>>10 ^ b<<15 ^ b<<13) + + w[i&15] + w[(i+9) & 15]) | 0; + } + + tmp = (tmp + h7 + (h4>>>6 ^ h4>>>11 ^ h4>>>25 ^ h4<<26 ^ h4<<21 ^ h4<<7) + (h6 ^ h4&(h5^h6)) + k[i]); // | 0; + + // shift register + h7 = h6; h6 = h5; h5 = h4; + h4 = h3 + tmp | 0; + h3 = h2; h2 = h1; h1 = h0; + + h0 = (tmp + ((h1&h2) ^ (h3&(h1^h2))) + (h1>>>2 ^ h1>>>13 ^ h1>>>22 ^ h1<<30 ^ h1<<19 ^ h1<<10)) | 0; + } + + h[0] = h[0]+h0 | 0; + h[1] = h[1]+h1 | 0; + h[2] = h[2]+h2 | 0; + h[3] = h[3]+h3 | 0; + h[4] = h[4]+h4 | 0; + h[5] = h[5]+h5 | 0; + h[6] = h[6]+h6 | 0; + h[7] = h[7]+h7 | 0; + } +}; + + diff --git a/lib/sjcl/core/sjcl.js b/lib/sjcl/core/sjcl.js new file mode 100644 index 0000000..6ac1f0e --- /dev/null +++ b/lib/sjcl/core/sjcl.js @@ -0,0 +1,69 @@ +/** @fileOverview Javascript cryptography implementation. + * + * Crush to remove comments, shorten variable names and + * generally reduce transmission size. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +"use strict"; +/*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */ +/*global document, window, escape, unescape */ + +/** @namespace The Stanford Javascript Crypto Library, top-level namespace. */ +var sjcl = { + /** @namespace Symmetric ciphers. */ + cipher: {}, + + /** @namespace Hash functions. Right now only SHA256 is implemented. */ + hash: {}, + + /** @namespace Key exchange functions. Right now only SRP is implemented. */ + keyexchange: {}, + + /** @namespace Block cipher modes of operation. */ + mode: {}, + + /** @namespace Miscellaneous. HMAC and PBKDF2. */ + misc: {}, + + /** + * @namespace Bit array encoders and decoders. + * + * @description + * The members of this namespace are functions which translate between + * SJCL's bitArrays and other objects (usually strings). Because it + * isn't always clear which direction is encoding and which is decoding, + * the method names are "fromBits" and "toBits". + */ + codec: {}, + + /** @namespace Exceptions. */ + exception: { + /** @class Ciphertext is corrupt. */ + corrupt: function(message) { + this.toString = function() { return "CORRUPT: "+this.message; }; + this.message = message; + }, + + /** @class Invalid parameter. */ + invalid: function(message) { + this.toString = function() { return "INVALID: "+this.message; }; + this.message = message; + }, + + /** @class Bug or missing feature in SJCL. */ + bug: function(message) { + this.toString = function() { return "BUG: "+this.message; }; + this.message = message; + }, + + /** @class Something isn't ready. */ + notReady: function(message) { + this.toString = function() { return "NOT READY: "+this.message; }; + this.message = message; + } + } +}; diff --git a/lib/sjcl/core/srp.js b/lib/sjcl/core/srp.js new file mode 100644 index 0000000..d1dba28 --- /dev/null +++ b/lib/sjcl/core/srp.js @@ -0,0 +1,113 @@ +/** @fileOverview Javascript SRP implementation. + * + * This file contains a partial implementation of the SRP (Secure Remote + * Password) password-authenticated key exchange protocol. Given a user + * identity, salt, and SRP group, it generates the SRP verifier that may + * be sent to a remote server to establish and SRP account. + * + * For more information, see http://srp.stanford.edu/. + * + * @author Quinn Slack + */ + +/** + * Compute the SRP verifier from the username, password, salt, and group. + * @class SRP + */ +sjcl.keyexchange.srp = { + /** + * Calculates SRP v, the verifier. + * v = g^x mod N [RFC 5054] + * @param {String} I The username. + * @param {String} P The password. + * @param {Object} s A bitArray of the salt. + * @param {Object} group The SRP group. Use sjcl.keyexchange.srp.knownGroup + to obtain this object. + * @return {Object} A bitArray of SRP v. + */ + makeVerifier: function(I, P, s, group) { + var x; + x = this.makeX(I, P, s); + x = sjcl.bn.fromBits(x); + return group.g.powermod(x, group.N); + }, + + /** + * Calculates SRP x. + * x = SHA1( | SHA( | ":" | )) [RFC 2945] + * @param {String} I The username. + * @param {String} P The password. + * @param {Object} s A bitArray of the salt. + * @return {Object} A bitArray of SRP x. + */ + makeX: function(I, P, s) { + var inner = sjcl.hash.sha1.hash(I + ':' + P); + return sjcl.hash.sha1.hash(sjcl.bitArray.concat(s, inner)); + }, + + /** + * Returns the known SRP group with the given size (in bits). + * @param {String} i The size of the known SRP group. + * @return {Object} An object with "N" and "g" properties. + */ + knownGroup:function(i) { + if (typeof i !== "string") { i = i.toString(); } + if (!this._didInitKnownGroups) { this._initKnownGroups(); } + return this._knownGroups[i]; + }, + + /** + * Initializes bignum objects for known group parameters. + * @private + */ + _didInitKnownGroups: false, + _initKnownGroups:function() { + var i, size, group; + for (i=0; i < this._knownGroupSizes.length; i++) { + size = this._knownGroupSizes[i].toString(); + group = this._knownGroups[size]; + group.N = new sjcl.bn(group.N); + group.g = new sjcl.bn(group.g); + } + this._didInitKnownGroups = true; + }, + + _knownGroupSizes: [1024, 1536, 2048], + _knownGroups: { + 1024: { + N: "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" + + "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" + + "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" + + "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" + + "FD5138FE8376435B9FC61D2FC0EB06E3", + g:2 + }, + + 1536: { + N: "9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961" + + "4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843" + + "80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B" + + "E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5" + + "6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A" + + "F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E" + + "8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB", + g: 2 + }, + + 2048: { + N: "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" + + "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" + + "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" + + "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" + + "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" + + "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" + + "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" + + "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" + + "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" + + "9E4AFF73", + g: 2 + } + } + +}; + diff --git a/lib/sjcl/sjcl.js b/lib/sjcl/sjcl.js new file mode 100644 index 0000000..01d6ff4 --- /dev/null +++ b/lib/sjcl/sjcl.js @@ -0,0 +1,40 @@ +"use strict";var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}}; +sjcl.cipher.aes=function(a){this.h[0][0][0]||this.w();var b,c,d,e,f=this.h[0][4],g=this.h[1];b=a.length;var h=1;if(b!==4&&b!==6&&b!==8)throw new sjcl.exception.invalid("invalid aes key size");this.a=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(a%b===0||b===8&&a%b===4){c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255];if(a%b===0){c=c<<8^c>>>24^h<<24;h=h<<1^(h>>7)*283}}d[a]=d[a-b]^c}for(b=0;a;b++,a--){c=d[b&3?a:a-4];e[b]=a<=4||b<4?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^ +g[3][f[c&255]]}}; +sjcl.cipher.aes.prototype={encrypt:function(a){return this.H(a,0)},decrypt:function(a){return this.H(a,1)},h:[[[],[],[],[],[]],[[],[],[],[],[]]],w:function(){var a=this.h[0],b=this.h[1],c=a[4],d=b[4],e,f,g,h=[],i=[],k,j,l,m;for(e=0;e<0x100;e++)i[(h[e]=e<<1^(e>>7)*283)^e]=e;for(f=g=0;!c[f];f^=k||1,g=i[g]||1){l=g^g<<1^g<<2^g<<3^g<<4;l=l>>8^l&255^99;c[f]=l;d[l]=f;j=h[e=h[k=h[f]]];m=j*0x1010101^e*0x10001^k*0x101^f*0x1010100;j=h[l]*0x101^l*0x1010100;for(e=0;e<4;e++){a[e][f]=j=j<<24^j>>>8;b[e][l]=m=m<<24^m>>>8}}for(e= +0;e<5;e++){a[e]=a[e].slice(0);b[e]=b[e].slice(0)}},H:function(a,b){if(a.length!==4)throw new sjcl.exception.invalid("invalid aes block size");var c=this.a[b],d=a[0]^c[0],e=a[b?3:1]^c[1],f=a[2]^c[2];a=a[b?1:3]^c[3];var g,h,i,k=c.length/4-2,j,l=4,m=[0,0,0,0];g=this.h[b];var n=g[0],o=g[1],p=g[2],q=g[3],r=g[4];for(j=0;j>>24]^o[e>>16&255]^p[f>>8&255]^q[a&255]^c[l];h=n[e>>>24]^o[f>>16&255]^p[a>>8&255]^q[d&255]^c[l+1];i=n[f>>>24]^o[a>>16&255]^p[d>>8&255]^q[e&255]^c[l+2];a=n[a>>>24]^o[d>>16& +255]^p[e>>8&255]^q[f&255]^c[l+3];l+=4;d=g;e=h;f=i}for(j=0;j<4;j++){m[b?3&-j:j]=r[d>>>24]<<24^r[e>>16&255]<<16^r[f>>8&255]<<8^r[a&255]^c[l++];g=d;d=e;e=f;f=a;a=g}return m}}; +sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.P(a.slice(b/32),32-(b&31)).slice(1);return c===undefined?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<0&&b)a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1);return a},partial:function(a,b,c){if(a===32)return b;return(c?b|0:b<<32-a)+a*0x10000000000},getPartial:function(a){return Math.round(a/0x10000000000)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d=32;b-=32){d.push(c);c=0}if(b===0)return d.concat(a);for(e=0;e>>b);c=a[e]<<32-b}e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,b+a>32?c:d.pop(),1));return d},k:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]}}; +sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d>>24);e<<=8}return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>e)>>>26);if(e<6){g=a[d]<<6-e;e+=26;d++}else{g<<=6;e-=6}}for(;c.length&3&&!b;)c+="=";return c},toBits:function(a){a=a.replace(/\s|=/g,"");var b=[],c,d=0,e=sjcl.codec.base64.D,f=0,g;for(c=0;c26){d-=26;b.push(f^g>>>d);f=g<<32-d}else{d+=6;f^=g<<32-d}}d&56&&b.push(sjcl.bitArray.partial(d&56,f,1));return b}};sjcl.hash.sha256=function(a){this.a[0]||this.w();if(a){this.n=a.n.slice(0);this.i=a.i.slice(0);this.e=a.e}else this.reset()};sjcl.hash.sha256.hash=function(a){return(new sjcl.hash.sha256).update(a).finalize()}; +sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.n=this.N.slice(0);this.i=[];this.e=0;return this},update:function(a){if(typeof a==="string")a=sjcl.codec.utf8String.toBits(a);var b,c=this.i=sjcl.bitArray.concat(this.i,a);b=this.e;a=this.e=b+sjcl.bitArray.bitLength(a);for(b=512+b&-512;b<=a;b+=512)this.C(c.splice(0,16));return this},finalize:function(){var a,b=this.i,c=this.n;b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0);b.push(Math.floor(this.e/ +4294967296));for(b.push(this.e|0);b.length;)this.C(b.splice(0,16));this.reset();return c},N:[],a:[],w:function(){function a(e){return(e-Math.floor(e))*0x100000000|0}var b=0,c=2,d;a:for(;b<64;c++){for(d=2;d*d<=c;d++)if(c%d===0)continue a;if(b<8)this.N[b]=a(Math.pow(c,0.5));this.a[b]=a(Math.pow(c,1/3));b++}},C:function(a){var b,c,d=a.slice(0),e=this.n,f=this.a,g=e[0],h=e[1],i=e[2],k=e[3],j=e[4],l=e[5],m=e[6],n=e[7];for(a=0;a<64;a++){if(a<16)b=d[a];else{b=d[a+1&15];c=d[a+14&15];b=d[a&15]=(b>>>7^b>>>18^ +b>>>3^b<<25^b<<14)+(c>>>17^c>>>19^c>>>10^c<<15^c<<13)+d[a&15]+d[a+9&15]|0}b=b+n+(j>>>6^j>>>11^j>>>25^j<<26^j<<21^j<<7)+(m^j&(l^m))+f[a];n=m;m=l;l=j;j=k+b|0;k=i;i=h;h=g;g=b+(h&i^k&(h^i))+(h>>>2^h>>>13^h>>>22^h<<30^h<<19^h<<10)|0}e[0]=e[0]+g|0;e[1]=e[1]+h|0;e[2]=e[2]+i|0;e[3]=e[3]+k|0;e[4]=e[4]+j|0;e[5]=e[5]+l|0;e[6]=e[6]+m|0;e[7]=e[7]+n|0}}; +sjcl.mode.ccm={name:"ccm",encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,i=h.bitLength(c)/8,k=h.bitLength(g)/8;e=e||64;d=d||[];if(i<7)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;f<4&&k>>>8*f;f++);if(f<15-i)f=15-i;c=h.clamp(c,8*(15-f));b=sjcl.mode.ccm.G(a,b,c,d,e,f);g=sjcl.mode.ccm.I(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),i=f.clamp(b,h-e),k=f.bitSlice(b, +h-e);h=(h-e)/8;if(g<7)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;b<4&&h>>>8*b;b++);if(b<15-g)b=15-g;c=f.clamp(c,8*(15-b));i=sjcl.mode.ccm.I(a,i,c,k,e,b);a=sjcl.mode.ccm.G(a,i.data,c,d,e,b);if(!f.equal(i.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");return i.data},G:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,i=h.k;e/=8;if(e%2||e<4||e>16)throw new sjcl.exception.invalid("ccm: invalid tag length");if(d.length>0xffffffff||b.length>0xffffffff)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data"); +f=[h.partial(8,(d.length?64:0)|e-2<<2|f-1)];f=h.concat(f,c);f[3]|=h.bitLength(b)/8;f=a.encrypt(f);if(d.length){c=h.bitLength(d)/8;if(c<=65279)g=[h.partial(16,c)];else if(c<=0xffffffff)g=h.concat([h.partial(16,65534)],[c]);g=h.concat(g,d);for(d=0;d>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^(a[0]>>>31)*135]}};sjcl.misc.hmac=function(a,b){this.M=b=b||sjcl.hash.sha256;var c=[[],[]],d=b.prototype.blockSize/32;this.l=[new b,new b];if(a.length>d)a=b.hash(a);for(b=0;b0;){b++;e>>>=1}this.b[g].update([d,this.J++,2,b,f,a.length].concat(a));break;case "string":if(b===undefined)b=a.length;this.b[g].update([d,this.J++,3,b,f,a.length]);this.b[g].update(a);break;default:throw new sjcl.exception.bug("random: addEntropy only supports number, array or string");}this.j[g]+=b;this.f+=b;if(h===0){this.isReady()!==0&&this.K("seeded",Math.max(this.g, +this.f));this.K("progress",this.getProgress())}},isReady:function(a){a=this.B[a!==undefined?a:this.t];return this.g&&this.g>=a?this.j[0]>80&&(new Date).valueOf()>this.O?3:1:this.f>=a?2:0},getProgress:function(a){a=this.B[a?a:this.t];return this.g>=a?1["0"]:this.f>a?1["0"]:this.f/a},startCollectors:function(){if(!this.m){if(window.addEventListener){window.addEventListener("load",this.o,false);window.addEventListener("mousemove",this.p,false)}else if(document.attachEvent){document.attachEvent("onload", +this.o);document.attachEvent("onmousemove",this.p)}else throw new sjcl.exception.bug("can't attach event");this.m=true}},stopCollectors:function(){if(this.m){if(window.removeEventListener){window.removeEventListener("load",this.o);window.removeEventListener("mousemove",this.p)}else if(window.detachEvent){window.detachEvent("onload",this.o);window.detachEvent("onmousemove",this.p)}this.m=false}},addEventListener:function(a,b){this.r[a][this.Q++]=b},removeEventListener:function(a,b){var c;a=this.r[a]; +var d=[];for(c in a)a.hasOwnProperty(c)&&a[c]===b&&d.push(c);for(b=0;b=1<this.g)this.g=c;this.z++;this.T(b)},p:function(a){sjcl.random.addEntropy([a.x|| +a.clientX||a.offsetX,a.y||a.clientY||a.offsetY],2,"mouse")},o:function(){sjcl.random.addEntropy(new Date,2,"loadtime")},K:function(a,b){var c;a=sjcl.random.r[a];var d=[];for(c in a)a.hasOwnProperty(c)&&d.push(a[c]);for(c=0;c +4)throw new sjcl.exception.invalid("json encrypt: invalid parameters");if(typeof a==="string"){c=sjcl.misc.cachedPbkdf2(a,f);a=c.key.slice(0,f.ks/32);f.salt=c.salt}if(typeof b==="string")b=sjcl.codec.utf8String.toBits(b);c=new sjcl.cipher[f.cipher](a);e.c(d,f);d.key=a;f.ct=sjcl.mode[f.mode].encrypt(c,b,f.iv,f.adata,f.tag);return e.encode(e.V(f,e.defaults))},decrypt:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json;b=e.c(e.c(e.c({},e.defaults),e.decode(b)),c,true);if(typeof b.salt==="string")b.salt= +sjcl.codec.base64.toBits(b.salt);if(typeof b.iv==="string")b.iv=sjcl.codec.base64.toBits(b.iv);if(!sjcl.mode[b.mode]||!sjcl.cipher[b.cipher]||typeof a==="string"&&b.iter<=100||b.ts!==64&&b.ts!==96&&b.ts!==128||b.ks!==128&&b.ks!==192&&b.ks!==0x100||!b.iv||b.iv.length<2||b.iv.length>4)throw new sjcl.exception.invalid("json decrypt: invalid parameters");if(typeof a==="string"){c=sjcl.misc.cachedPbkdf2(a,b);a=c.key.slice(0,b.ks/32);b.salt=c.salt}c=new sjcl.cipher[b.cipher](a);c=sjcl.mode[b.mode].decrypt(c, +b.ct,b.iv,b.adata,b.tag);e.c(d,b);d.key=a;return sjcl.codec.utf8String.fromBits(c)},encode:function(a){var b,c="{",d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode: invalid property name");c+=d+b+":";d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec.base64.fromBits(a[b],1)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type"); +}}return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c + + + Jasmine Test Runner + + + + + + + + + <% spec_files.each do |source_file| %> + + <% end %> + + + + + + + diff --git a/spec/brainree_spec.js b/spec/brainree_spec.js new file mode 100644 index 0000000..0501b40 --- /dev/null +++ b/spec/brainree_spec.js @@ -0,0 +1,58 @@ +describe("Braintree", function () { + it("has a public encryption key", function () { + var braintree = Braintree.create("a public key"); + expect(braintree.publicKey).toMatch("a public key"); + }); + + describe("encrypt", function () { + var privateKey = "MIICXgIBAAKBgQsuU3jiFN8sWjjk/CvhpBUuKTVvDdAN7+3P+PAJxkeuq/c+/+F2KeW8aW4ABmtO6y+TYtvJCVtha/mx4rr9RnUa309sBekaXV3gjk5j91/z2/PNzmvuHnn2YAOUZhOM/2za+triLlm/h52quyoEL5B5wH3XgxAaWRxiHvLH66B1BwIDAQABAoGBCc4ACNtIrkP4gjfbIqfl+WTXYjIWjMIMCiD8DZKku6tixZgLTy0NpJZKZdnDx0oXV0sJv+5VNDsEMpxZVNxRcs3V8UTDJZu6QnKLkH3gGP9kfSMncfrz1jt1riBBd0PKGkgGU3FxjEIq7EawTv/xus7A+K2RLPZePAEN57N6tWvhAkEDb9B8NhAenON3FiN9IraCKAvRnHgbZOaJhFV+zaGIzv0bxx1GivQ9eHPmk0xPlx2k9hfPm0FcmqntgDxlcuNl/wJBA0DaMoeO79UMWwcicM08n39OHEzxD0DhZBeRcTVhJWMOntVBFDwkgBgPrrNEOFs2s8ZdhThXsTr5soCUL44NwPkCQQDYN9puxuNfFx+rFymnoEa4ZL8svu+simN9XC1/h5VBmT58Xpt5hrCcq48c4AInVye1OwDQXO3PLLerbixYYb4tAkAsh34MIWhRS8fSKdU+I++jLtn0gy79mQ9w8yXKZNdK5I05ebFLRehTYQNGMm+Q8OvLv1RQHuAq9w7EMSgZwEKBAkECZ3PhNh7S8KIPyrVjzdQZP+XXvpZj7yZbKosskk2cFUUc5zXOgIrMXCu2hyMWZF1qxKYHus5z1hbo3oNMYDeDrQ=="; + + var publicKey = "MIGJAoGBCy5TeOIU3yxaOOT8K+GkFS4pNW8N0A3v7c/48AnGR66r9z7/4XYp5bxpbgAGa07rL5Ni28kJW2Fr+bHiuv1GdRrfT2wF6RpdXeCOTmP3X/Pb883Oa+4eefZgA5RmE4z/bNr62uIuWb+Hnaq7KgQvkHnAfdeDEBpZHGIe8sfroHUHAgMBAAE="; + + var decrypt = function (value) { + var key = Braintree.pidCryptUtil.decodeBase64(privateKey); + var rsa = new Braintree.pidCrypt.RSA(); + var asn = Braintree.pidCrypt.ASN1.decode(Braintree.pidCryptUtil.toByteArray(key)); + var tree = asn.toHexTree(); + rsa.setPrivateKeyFromASN(tree); + + var aesKeyAndCipherText = value.substring("$bt2$".length); + var cryptedAesKey = aesKeyAndCipherText.split('$')[0]; + var ivAndCipherText = aesKeyAndCipherText.split('$')[1]; + var aesKey = rsa.decryptRaw(Braintree.pidCryptUtil.convertToHex(Braintree.pidCryptUtil.decodeBase64(cryptedAesKey))); + var aesKeyBits = Braintree.sjcl.codec.base64.toBits(aesKey); + var aes = new Braintree.sjcl.cipher.aes(aesKeyBits); + + var ivAndCipherTextBits = Braintree.sjcl.codec.base64.toBits(ivAndCipherText); + var ivBits = ivAndCipherTextBits.slice(0,4); + var cipherTextBits = ivAndCipherTextBits.slice(4); + + var plainTextBits = Braintree.sjcl.mode.cbc.decrypt(aes, cipherTextBits, ivBits); + var plainText = Braintree.sjcl.codec.utf8String.fromBits(plainTextBits); + + return plainText; + }; + + it("encrypts the given text with the public key", function () { + var braintree = Braintree.create(publicKey); + var encrypted = braintree.encrypt("test data"); + + expect(decrypt(encrypted)).toEqual("test data"); + }); + + it("encrypts the given lengthy text with the public key", function () { + var braintree = Braintree.create(publicKey); + var plainText = "lengthy test data lenghty test data lengthy test data 123456"; + var encrypted = braintree.encrypt(plainText); + + expect(decrypt(encrypted)).toEqual(plainText); + }); + + it("prepends the encrypted data with $bt2$", function () { + var braintree = Braintree.create(publicKey); + var encrypted = braintree.encrypt("test data"); + + expect(encrypted).toMatch(/^\$bt2\$/); + }); + }); +}); diff --git a/spec/infrastructure/jasmine-standalone-1.0.0/SpecRunner.html b/spec/infrastructure/jasmine-standalone-1.0.0/SpecRunner.html new file mode 100644 index 0000000..446ef1a --- /dev/null +++ b/spec/infrastructure/jasmine-standalone-1.0.0/SpecRunner.html @@ -0,0 +1,27 @@ + + + + Jasmine Test Runner + + + + + + + + + + + + + + + + + + + diff --git a/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/MIT.LICENSE b/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/MIT.LICENSE new file mode 100644 index 0000000..1eb9b49 --- /dev/null +++ b/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/MIT.LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2008-2010 Pivotal Labs + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine-html.js b/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine-html.js new file mode 100644 index 0000000..c59f2de --- /dev/null +++ b/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine-html.js @@ -0,0 +1,182 @@ +jasmine.TrivialReporter = function(doc) { + this.document = doc || document; + this.suiteDivs = {}; + this.logRunningSpecs = false; +}; + +jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { + var el = document.createElement(type); + + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + + if (typeof child === 'string') { + el.appendChild(document.createTextNode(child)); + } else { + if (child) { el.appendChild(child); } + } + } + + for (var attr in attrs) { + if (attr == "className") { + el[attr] = attrs[attr]; + } else { + el.setAttribute(attr, attrs[attr]); + } + } + + return el; +}; + +jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { + var showPassed, showSkipped; + + this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' }, + this.createDom('div', { className: 'banner' }, + this.createDom('div', { className: 'logo' }, + this.createDom('a', { href: 'http://pivotal.github.com/jasmine/', target: "_blank" }, "Jasmine"), + this.createDom('span', { className: 'version' }, runner.env.versionString())), + this.createDom('div', { className: 'options' }, + "Show ", + showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), + this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), + showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), + this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") + ) + ), + + this.runnerDiv = this.createDom('div', { className: 'runner running' }, + this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), + this.runnerMessageSpan = this.createDom('span', {}, "Running..."), + this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) + ); + + this.document.body.appendChild(this.outerDiv); + + var suites = runner.suites(); + for (var i = 0; i < suites.length; i++) { + var suite = suites[i]; + var suiteDiv = this.createDom('div', { className: 'suite' }, + this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), + this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); + this.suiteDivs[suite.id] = suiteDiv; + var parentDiv = this.outerDiv; + if (suite.parentSuite) { + parentDiv = this.suiteDivs[suite.parentSuite.id]; + } + parentDiv.appendChild(suiteDiv); + } + + this.startedAt = new Date(); + + var self = this; + showPassed.onchange = function(evt) { + if (evt.target.checked) { + self.outerDiv.className += ' show-passed'; + } else { + self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); + } + }; + + showSkipped.onchange = function(evt) { + if (evt.target.checked) { + self.outerDiv.className += ' show-skipped'; + } else { + self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); + } + }; +}; + +jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { + var results = runner.results(); + var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; + this.runnerDiv.setAttribute("class", className); + //do it twice for IE + this.runnerDiv.setAttribute("className", className); + var specs = runner.specs(); + var specCount = 0; + for (var i = 0; i < specs.length; i++) { + if (this.specFilter(specs[i])) { + specCount++; + } + } + var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); + message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; + this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); + + this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); +}; + +jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { + var results = suite.results(); + var status = results.passed() ? 'passed' : 'failed'; + if (results.totalCount == 0) { // todo: change this to check results.skipped + status = 'skipped'; + } + this.suiteDivs[suite.id].className += " " + status; +}; + +jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { + if (this.logRunningSpecs) { + this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); + } +}; + +jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { + var results = spec.results(); + var status = results.passed() ? 'passed' : 'failed'; + if (results.skipped) { + status = 'skipped'; + } + var specDiv = this.createDom('div', { className: 'spec ' + status }, + this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), + this.createDom('a', { + className: 'description', + href: '?spec=' + encodeURIComponent(spec.getFullName()), + title: spec.getFullName() + }, spec.description)); + + + var resultItems = results.getItems(); + var messagesDiv = this.createDom('div', { className: 'messages' }); + for (var i = 0; i < resultItems.length; i++) { + var result = resultItems[i]; + + if (result.type == 'log') { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); + } else if (result.type == 'expect' && result.passed && !result.passed()) { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); + + if (result.trace.stack) { + messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); + } + } + } + + if (messagesDiv.childNodes.length > 0) { + specDiv.appendChild(messagesDiv); + } + + this.suiteDivs[spec.suite.id].appendChild(specDiv); +}; + +jasmine.TrivialReporter.prototype.log = function() { + var console = jasmine.getGlobal().console; + if (console && console.log) console.log.apply(console, arguments); +}; + +jasmine.TrivialReporter.prototype.getLocation = function() { + return this.document.location; +}; + +jasmine.TrivialReporter.prototype.specFilter = function(spec) { + var paramMap = {}; + var params = this.getLocation().search.substring(1).split('&'); + for (var i = 0; i < params.length; i++) { + var p = params[i].split('='); + paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); + } + + if (!paramMap["spec"]) return true; + return spec.getFullName().indexOf(paramMap["spec"]) == 0; +}; diff --git a/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.css b/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.css new file mode 100644 index 0000000..6583fe7 --- /dev/null +++ b/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.css @@ -0,0 +1,166 @@ +body { + font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; +} + + +.jasmine_reporter a:visited, .jasmine_reporter a { + color: #303; +} + +.jasmine_reporter a:hover, .jasmine_reporter a:active { + color: blue; +} + +.run_spec { + float:right; + padding-right: 5px; + font-size: .8em; + text-decoration: none; +} + +.jasmine_reporter { + margin: 0 5px; +} + +.banner { + color: #303; + background-color: #fef; + padding: 5px; +} + +.logo { + float: left; + font-size: 1.1em; + padding-left: 5px; +} + +.logo .version { + font-size: .6em; + padding-left: 1em; +} + +.runner.running { + background-color: yellow; +} + + +.options { + text-align: right; + font-size: .8em; +} + + + + +.suite { + border: 1px outset gray; + margin: 5px 0; + padding-left: 1em; +} + +.suite .suite { + margin: 5px; +} + +.suite.passed { + background-color: #dfd; +} + +.suite.failed { + background-color: #fdd; +} + +.spec { + margin: 5px; + padding-left: 1em; + clear: both; +} + +.spec.failed, .spec.passed, .spec.skipped { + padding-bottom: 5px; + border: 1px solid gray; +} + +.spec.failed { + background-color: #fbb; + border-color: red; +} + +.spec.passed { + background-color: #bfb; + border-color: green; +} + +.spec.skipped { + background-color: #bbb; +} + +.messages { + border-left: 1px dashed gray; + padding-left: 1em; + padding-right: 1em; +} + +.passed { + background-color: #cfc; + display: none; +} + +.failed { + background-color: #fbb; +} + +.skipped { + color: #777; + background-color: #eee; + display: none; +} + + +/*.resultMessage {*/ + /*white-space: pre;*/ +/*}*/ + +.resultMessage span.result { + display: block; + line-height: 2em; + color: black; +} + +.resultMessage .mismatch { + color: black; +} + +.stackTrace { + white-space: pre; + font-size: .8em; + margin-left: 10px; + max-height: 5em; + overflow: auto; + border: 1px inset red; + padding: 1em; + background: #eef; +} + +.finished-at { + padding-left: 1em; + font-size: .6em; +} + +.show-passed .passed, +.show-skipped .skipped { + display: block; +} + + +#jasmine_content { + position:fixed; + right: 100%; +} + +.runner { + border: 1px solid gray; + display: block; + margin: 5px 0; + padding: 2px 0 2px 10px; +} diff --git a/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.js b/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.js new file mode 100644 index 0000000..68baf53 --- /dev/null +++ b/spec/infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.js @@ -0,0 +1,2421 @@ +/** + * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. + * + * @namespace + */ +var jasmine = {}; + +/** + * @private + */ +jasmine.unimplementedMethod_ = function() { + throw new Error("unimplemented method"); +}; + +/** + * Use jasmine.undefined instead of undefined, since undefined is just + * a plain old variable and may be redefined by somebody else. + * + * @private + */ +jasmine.undefined = jasmine.___undefined___; + +/** + * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. + * + */ +jasmine.DEFAULT_UPDATE_INTERVAL = 250; + +/** + * Default timeout interval in milliseconds for waitsFor() blocks. + */ +jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; + +jasmine.getGlobal = function() { + function getGlobal() { + return this; + } + + return getGlobal(); +}; + +/** + * Allows for bound functions to be compared. Internal use only. + * + * @ignore + * @private + * @param base {Object} bound 'this' for the function + * @param name {Function} function to find + */ +jasmine.bindOriginal_ = function(base, name) { + var original = base[name]; + if (original.apply) { + return function() { + return original.apply(base, arguments); + }; + } else { + // IE support + return jasmine.getGlobal()[name]; + } +}; + +jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); +jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); +jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); +jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); + +jasmine.MessageResult = function(values) { + this.type = 'log'; + this.values = values; + this.trace = new Error(); // todo: test better +}; + +jasmine.MessageResult.prototype.toString = function() { + var text = ""; + for(var i = 0; i < this.values.length; i++) { + if (i > 0) text += " "; + if (jasmine.isString_(this.values[i])) { + text += this.values[i]; + } else { + text += jasmine.pp(this.values[i]); + } + } + return text; +}; + +jasmine.ExpectationResult = function(params) { + this.type = 'expect'; + this.matcherName = params.matcherName; + this.passed_ = params.passed; + this.expected = params.expected; + this.actual = params.actual; + + this.message = this.passed_ ? 'Passed.' : params.message; + this.trace = this.passed_ ? '' : new Error(this.message); +}; + +jasmine.ExpectationResult.prototype.toString = function () { + return this.message; +}; + +jasmine.ExpectationResult.prototype.passed = function () { + return this.passed_; +}; + +/** + * Getter for the Jasmine environment. Ensures one gets created + */ +jasmine.getEnv = function() { + return jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); +}; + +/** + * @ignore + * @private + * @param value + * @returns {Boolean} + */ +jasmine.isArray_ = function(value) { + return jasmine.isA_("Array", value); +}; + +/** + * @ignore + * @private + * @param value + * @returns {Boolean} + */ +jasmine.isString_ = function(value) { + return jasmine.isA_("String", value); +}; + +/** + * @ignore + * @private + * @param value + * @returns {Boolean} + */ +jasmine.isNumber_ = function(value) { + return jasmine.isA_("Number", value); +}; + +/** + * @ignore + * @private + * @param {String} typeName + * @param value + * @returns {Boolean} + */ +jasmine.isA_ = function(typeName, value) { + return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; +}; + +/** + * Pretty printer for expecations. Takes any object and turns it into a human-readable string. + * + * @param value {Object} an object to be outputted + * @returns {String} + */ +jasmine.pp = function(value) { + var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); + stringPrettyPrinter.format(value); + return stringPrettyPrinter.string; +}; + +/** + * Returns true if the object is a DOM Node. + * + * @param {Object} obj object to check + * @returns {Boolean} + */ +jasmine.isDomNode = function(obj) { + return obj['nodeType'] > 0; +}; + +/** + * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. + * + * @example + * // don't care about which function is passed in, as long as it's a function + * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); + * + * @param {Class} clazz + * @returns matchable object of the type clazz + */ +jasmine.any = function(clazz) { + return new jasmine.Matchers.Any(clazz); +}; + +/** + * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. + * + * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine + * expectation syntax. Spies can be checked if they were called or not and what the calling params were. + * + * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). + * + * Spies are torn down at the end of every spec. + * + * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. + * + * @example + * // a stub + * var myStub = jasmine.createSpy('myStub'); // can be used anywhere + * + * // spy example + * var foo = { + * not: function(bool) { return !bool; } + * } + * + * // actual foo.not will not be called, execution stops + * spyOn(foo, 'not'); + + // foo.not spied upon, execution will continue to implementation + * spyOn(foo, 'not').andCallThrough(); + * + * // fake example + * var foo = { + * not: function(bool) { return !bool; } + * } + * + * // foo.not(val) will return val + * spyOn(foo, 'not').andCallFake(function(value) {return value;}); + * + * // mock example + * foo.not(7 == 7); + * expect(foo.not).toHaveBeenCalled(); + * expect(foo.not).toHaveBeenCalledWith(true); + * + * @constructor + * @see spyOn, jasmine.createSpy, jasmine.createSpyObj + * @param {String} name + */ +jasmine.Spy = function(name) { + /** + * The name of the spy, if provided. + */ + this.identity = name || 'unknown'; + /** + * Is this Object a spy? + */ + this.isSpy = true; + /** + * The actual function this spy stubs. + */ + this.plan = function() { + }; + /** + * Tracking of the most recent call to the spy. + * @example + * var mySpy = jasmine.createSpy('foo'); + * mySpy(1, 2); + * mySpy.mostRecentCall.args = [1, 2]; + */ + this.mostRecentCall = {}; + + /** + * Holds arguments for each call to the spy, indexed by call count + * @example + * var mySpy = jasmine.createSpy('foo'); + * mySpy(1, 2); + * mySpy(7, 8); + * mySpy.mostRecentCall.args = [7, 8]; + * mySpy.argsForCall[0] = [1, 2]; + * mySpy.argsForCall[1] = [7, 8]; + */ + this.argsForCall = []; + this.calls = []; +}; + +/** + * Tells a spy to call through to the actual implemenatation. + * + * @example + * var foo = { + * bar: function() { // do some stuff } + * } + * + * // defining a spy on an existing property: foo.bar + * spyOn(foo, 'bar').andCallThrough(); + */ +jasmine.Spy.prototype.andCallThrough = function() { + this.plan = this.originalValue; + return this; +}; + +/** + * For setting the return value of a spy. + * + * @example + * // defining a spy from scratch: foo() returns 'baz' + * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); + * + * // defining a spy on an existing property: foo.bar() returns 'baz' + * spyOn(foo, 'bar').andReturn('baz'); + * + * @param {Object} value + */ +jasmine.Spy.prototype.andReturn = function(value) { + this.plan = function() { + return value; + }; + return this; +}; + +/** + * For throwing an exception when a spy is called. + * + * @example + * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' + * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); + * + * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' + * spyOn(foo, 'bar').andThrow('baz'); + * + * @param {String} exceptionMsg + */ +jasmine.Spy.prototype.andThrow = function(exceptionMsg) { + this.plan = function() { + throw exceptionMsg; + }; + return this; +}; + +/** + * Calls an alternate implementation when a spy is called. + * + * @example + * var baz = function() { + * // do some stuff, return something + * } + * // defining a spy from scratch: foo() calls the function baz + * var foo = jasmine.createSpy('spy on foo').andCall(baz); + * + * // defining a spy on an existing property: foo.bar() calls an anonymnous function + * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); + * + * @param {Function} fakeFunc + */ +jasmine.Spy.prototype.andCallFake = function(fakeFunc) { + this.plan = fakeFunc; + return this; +}; + +/** + * Resets all of a spy's the tracking variables so that it can be used again. + * + * @example + * spyOn(foo, 'bar'); + * + * foo.bar(); + * + * expect(foo.bar.callCount).toEqual(1); + * + * foo.bar.reset(); + * + * expect(foo.bar.callCount).toEqual(0); + */ +jasmine.Spy.prototype.reset = function() { + this.wasCalled = false; + this.callCount = 0; + this.argsForCall = []; + this.calls = []; + this.mostRecentCall = {}; +}; + +jasmine.createSpy = function(name) { + + var spyObj = function() { + spyObj.wasCalled = true; + spyObj.callCount++; + var args = jasmine.util.argsToArray(arguments); + spyObj.mostRecentCall.object = this; + spyObj.mostRecentCall.args = args; + spyObj.argsForCall.push(args); + spyObj.calls.push({object: this, args: args}); + return spyObj.plan.apply(this, arguments); + }; + + var spy = new jasmine.Spy(name); + + for (var prop in spy) { + spyObj[prop] = spy[prop]; + } + + spyObj.reset(); + + return spyObj; +}; + +/** + * Determines whether an object is a spy. + * + * @param {jasmine.Spy|Object} putativeSpy + * @returns {Boolean} + */ +jasmine.isSpy = function(putativeSpy) { + return putativeSpy && putativeSpy.isSpy; +}; + +/** + * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something + * large in one call. + * + * @param {String} baseName name of spy class + * @param {Array} methodNames array of names of methods to make spies + */ +jasmine.createSpyObj = function(baseName, methodNames) { + if (!jasmine.isArray_(methodNames) || methodNames.length == 0) { + throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); + } + var obj = {}; + for (var i = 0; i < methodNames.length; i++) { + obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); + } + return obj; +}; + +/** + * All parameters are pretty-printed and concatenated together, then written to the current spec's output. + * + * Be careful not to leave calls to jasmine.log in production code. + */ +jasmine.log = function() { + var spec = jasmine.getEnv().currentSpec; + spec.log.apply(spec, arguments); +}; + +/** + * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. + * + * @example + * // spy example + * var foo = { + * not: function(bool) { return !bool; } + * } + * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops + * + * @see jasmine.createSpy + * @param obj + * @param methodName + * @returns a Jasmine spy that can be chained with all spy methods + */ +var spyOn = function(obj, methodName) { + return jasmine.getEnv().currentSpec.spyOn(obj, methodName); +}; + +/** + * Creates a Jasmine spec that will be added to the current suite. + * + * // TODO: pending tests + * + * @example + * it('should be true', function() { + * expect(true).toEqual(true); + * }); + * + * @param {String} desc description of this specification + * @param {Function} func defines the preconditions and expectations of the spec + */ +var it = function(desc, func) { + return jasmine.getEnv().it(desc, func); +}; + +/** + * Creates a disabled Jasmine spec. + * + * A convenience method that allows existing specs to be disabled temporarily during development. + * + * @param {String} desc description of this specification + * @param {Function} func defines the preconditions and expectations of the spec + */ +var xit = function(desc, func) { + return jasmine.getEnv().xit(desc, func); +}; + +/** + * Starts a chain for a Jasmine expectation. + * + * It is passed an Object that is the actual value and should chain to one of the many + * jasmine.Matchers functions. + * + * @param {Object} actual Actual value to test against and expected value + */ +var expect = function(actual) { + return jasmine.getEnv().currentSpec.expect(actual); +}; + +/** + * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. + * + * @param {Function} func Function that defines part of a jasmine spec. + */ +var runs = function(func) { + jasmine.getEnv().currentSpec.runs(func); +}; + +/** + * Waits a fixed time period before moving to the next block. + * + * @deprecated Use waitsFor() instead + * @param {Number} timeout milliseconds to wait + */ +var waits = function(timeout) { + jasmine.getEnv().currentSpec.waits(timeout); +}; + +/** + * Waits for the latchFunction to return true before proceeding to the next block. + * + * @param {Function} latchFunction + * @param {String} optional_timeoutMessage + * @param {Number} optional_timeout + */ +var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { + jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); +}; + +/** + * A function that is called before each spec in a suite. + * + * Used for spec setup, including validating assumptions. + * + * @param {Function} beforeEachFunction + */ +var beforeEach = function(beforeEachFunction) { + jasmine.getEnv().beforeEach(beforeEachFunction); +}; + +/** + * A function that is called after each spec in a suite. + * + * Used for restoring any state that is hijacked during spec execution. + * + * @param {Function} afterEachFunction + */ +var afterEach = function(afterEachFunction) { + jasmine.getEnv().afterEach(afterEachFunction); +}; + +/** + * Defines a suite of specifications. + * + * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared + * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization + * of setup in some tests. + * + * @example + * // TODO: a simple suite + * + * // TODO: a simple suite with a nested describe block + * + * @param {String} description A string, usually the class under test. + * @param {Function} specDefinitions function that defines several specs. + */ +var describe = function(description, specDefinitions) { + return jasmine.getEnv().describe(description, specDefinitions); +}; + +/** + * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. + * + * @param {String} description A string, usually the class under test. + * @param {Function} specDefinitions function that defines several specs. + */ +var xdescribe = function(description, specDefinitions) { + return jasmine.getEnv().xdescribe(description, specDefinitions); +}; + + +// Provide the XMLHttpRequest class for IE 5.x-6.x: +jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { + try { + return new ActiveXObject("Msxml2.XMLHTTP.6.0"); + } catch(e) { + } + try { + return new ActiveXObject("Msxml2.XMLHTTP.3.0"); + } catch(e) { + } + try { + return new ActiveXObject("Msxml2.XMLHTTP"); + } catch(e) { + } + try { + return new ActiveXObject("Microsoft.XMLHTTP"); + } catch(e) { + } + throw new Error("This browser does not support XMLHttpRequest."); +} : XMLHttpRequest; +/** + * @namespace + */ +jasmine.util = {}; + +/** + * Declare that a child class inherit it's prototype from the parent class. + * + * @private + * @param {Function} childClass + * @param {Function} parentClass + */ +jasmine.util.inherit = function(childClass, parentClass) { + /** + * @private + */ + var subclass = function() { + }; + subclass.prototype = parentClass.prototype; + childClass.prototype = new subclass; +}; + +jasmine.util.formatException = function(e) { + var lineNumber; + if (e.line) { + lineNumber = e.line; + } + else if (e.lineNumber) { + lineNumber = e.lineNumber; + } + + var file; + + if (e.sourceURL) { + file = e.sourceURL; + } + else if (e.fileName) { + file = e.fileName; + } + + var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); + + if (file && lineNumber) { + message += ' in ' + file + ' (line ' + lineNumber + ')'; + } + + return message; +}; + +jasmine.util.htmlEscape = function(str) { + if (!str) return str; + return str.replace(/&/g, '&') + .replace(//g, '>'); +}; + +jasmine.util.argsToArray = function(args) { + var arrayOfArgs = []; + for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); + return arrayOfArgs; +}; + +jasmine.util.extend = function(destination, source) { + for (var property in source) destination[property] = source[property]; + return destination; +}; + +/** + * Environment for Jasmine + * + * @constructor + */ +jasmine.Env = function() { + this.currentSpec = null; + this.currentSuite = null; + this.currentRunner_ = new jasmine.Runner(this); + + this.reporter = new jasmine.MultiReporter(); + + this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; + this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; + this.lastUpdate = 0; + this.specFilter = function() { + return true; + }; + + this.nextSpecId_ = 0; + this.nextSuiteId_ = 0; + this.equalityTesters_ = []; + + // wrap matchers + this.matchersClass = function() { + jasmine.Matchers.apply(this, arguments); + }; + jasmine.util.inherit(this.matchersClass, jasmine.Matchers); + + jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); +}; + + +jasmine.Env.prototype.setTimeout = jasmine.setTimeout; +jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; +jasmine.Env.prototype.setInterval = jasmine.setInterval; +jasmine.Env.prototype.clearInterval = jasmine.clearInterval; + +/** + * @returns an object containing jasmine version build info, if set. + */ +jasmine.Env.prototype.version = function () { + if (jasmine.version_) { + return jasmine.version_; + } else { + throw new Error('Version not set'); + } +}; + +/** + * @returns string containing jasmine version build info, if set. + */ +jasmine.Env.prototype.versionString = function() { + if (jasmine.version_) { + var version = this.version(); + return version.major + "." + version.minor + "." + version.build + " revision " + version.revision; + } else { + return "version unknown"; + } +}; + +/** + * @returns a sequential integer starting at 0 + */ +jasmine.Env.prototype.nextSpecId = function () { + return this.nextSpecId_++; +}; + +/** + * @returns a sequential integer starting at 0 + */ +jasmine.Env.prototype.nextSuiteId = function () { + return this.nextSuiteId_++; +}; + +/** + * Register a reporter to receive status updates from Jasmine. + * @param {jasmine.Reporter} reporter An object which will receive status updates. + */ +jasmine.Env.prototype.addReporter = function(reporter) { + this.reporter.addReporter(reporter); +}; + +jasmine.Env.prototype.execute = function() { + this.currentRunner_.execute(); +}; + +jasmine.Env.prototype.describe = function(description, specDefinitions) { + var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); + + var parentSuite = this.currentSuite; + if (parentSuite) { + parentSuite.add(suite); + } else { + this.currentRunner_.add(suite); + } + + this.currentSuite = suite; + + var declarationError = null; + try { + specDefinitions.call(suite); + } catch(e) { + declarationError = e; + } + + this.currentSuite = parentSuite; + + if (declarationError) { + this.it("encountered a declaration exception", function() { + throw declarationError; + }); + } + + return suite; +}; + +jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { + if (this.currentSuite) { + this.currentSuite.beforeEach(beforeEachFunction); + } else { + this.currentRunner_.beforeEach(beforeEachFunction); + } +}; + +jasmine.Env.prototype.currentRunner = function () { + return this.currentRunner_; +}; + +jasmine.Env.prototype.afterEach = function(afterEachFunction) { + if (this.currentSuite) { + this.currentSuite.afterEach(afterEachFunction); + } else { + this.currentRunner_.afterEach(afterEachFunction); + } + +}; + +jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { + return { + execute: function() { + } + }; +}; + +jasmine.Env.prototype.it = function(description, func) { + var spec = new jasmine.Spec(this, this.currentSuite, description); + this.currentSuite.add(spec); + this.currentSpec = spec; + + if (func) { + spec.runs(func); + } + + return spec; +}; + +jasmine.Env.prototype.xit = function(desc, func) { + return { + id: this.nextSpecId(), + runs: function() { + } + }; +}; + +jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { + if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { + return true; + } + + a.__Jasmine_been_here_before__ = b; + b.__Jasmine_been_here_before__ = a; + + var hasKey = function(obj, keyName) { + return obj != null && obj[keyName] !== jasmine.undefined; + }; + + for (var property in b) { + if (!hasKey(a, property) && hasKey(b, property)) { + mismatchKeys.push("expected has key '" + property + "', but missing from actual."); + } + } + for (property in a) { + if (!hasKey(b, property) && hasKey(a, property)) { + mismatchKeys.push("expected missing key '" + property + "', but present in actual."); + } + } + for (property in b) { + if (property == '__Jasmine_been_here_before__') continue; + if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { + mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); + } + } + + if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { + mismatchValues.push("arrays were not the same length"); + } + + delete a.__Jasmine_been_here_before__; + delete b.__Jasmine_been_here_before__; + return (mismatchKeys.length == 0 && mismatchValues.length == 0); +}; + +jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { + mismatchKeys = mismatchKeys || []; + mismatchValues = mismatchValues || []; + + for (var i = 0; i < this.equalityTesters_.length; i++) { + var equalityTester = this.equalityTesters_[i]; + var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); + if (result !== jasmine.undefined) return result; + } + + if (a === b) return true; + + if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { + return (a == jasmine.undefined && b == jasmine.undefined); + } + + if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { + return a === b; + } + + if (a instanceof Date && b instanceof Date) { + return a.getTime() == b.getTime(); + } + + if (a instanceof jasmine.Matchers.Any) { + return a.matches(b); + } + + if (b instanceof jasmine.Matchers.Any) { + return b.matches(a); + } + + if (jasmine.isString_(a) && jasmine.isString_(b)) { + return (a == b); + } + + if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { + return (a == b); + } + + if (typeof a === "object" && typeof b === "object") { + return this.compareObjects_(a, b, mismatchKeys, mismatchValues); + } + + //Straight check + return (a === b); +}; + +jasmine.Env.prototype.contains_ = function(haystack, needle) { + if (jasmine.isArray_(haystack)) { + for (var i = 0; i < haystack.length; i++) { + if (this.equals_(haystack[i], needle)) return true; + } + return false; + } + return haystack.indexOf(needle) >= 0; +}; + +jasmine.Env.prototype.addEqualityTester = function(equalityTester) { + this.equalityTesters_.push(equalityTester); +}; +/** No-op base class for Jasmine reporters. + * + * @constructor + */ +jasmine.Reporter = function() { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportRunnerResults = function(runner) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSuiteResults = function(suite) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSpecStarting = function(spec) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSpecResults = function(spec) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.log = function(str) { +}; + +/** + * Blocks are functions with executable code that make up a spec. + * + * @constructor + * @param {jasmine.Env} env + * @param {Function} func + * @param {jasmine.Spec} spec + */ +jasmine.Block = function(env, func, spec) { + this.env = env; + this.func = func; + this.spec = spec; +}; + +jasmine.Block.prototype.execute = function(onComplete) { + try { + this.func.apply(this.spec); + } catch (e) { + this.spec.fail(e); + } + onComplete(); +}; +/** JavaScript API reporter. + * + * @constructor + */ +jasmine.JsApiReporter = function() { + this.started = false; + this.finished = false; + this.suites_ = []; + this.results_ = {}; +}; + +jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { + this.started = true; + var suites = runner.topLevelSuites(); + for (var i = 0; i < suites.length; i++) { + var suite = suites[i]; + this.suites_.push(this.summarize_(suite)); + } +}; + +jasmine.JsApiReporter.prototype.suites = function() { + return this.suites_; +}; + +jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { + var isSuite = suiteOrSpec instanceof jasmine.Suite; + var summary = { + id: suiteOrSpec.id, + name: suiteOrSpec.description, + type: isSuite ? 'suite' : 'spec', + children: [] + }; + + if (isSuite) { + var children = suiteOrSpec.children(); + for (var i = 0; i < children.length; i++) { + summary.children.push(this.summarize_(children[i])); + } + } + return summary; +}; + +jasmine.JsApiReporter.prototype.results = function() { + return this.results_; +}; + +jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { + return this.results_[specId]; +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { + this.finished = true; +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { + this.results_[spec.id] = { + messages: spec.results().getItems(), + result: spec.results().failedCount > 0 ? "failed" : "passed" + }; +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.log = function(str) { +}; + +jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ + var results = {}; + for (var i = 0; i < specIds.length; i++) { + var specId = specIds[i]; + results[specId] = this.summarizeResult_(this.results_[specId]); + } + return results; +}; + +jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ + var summaryMessages = []; + var messagesLength = result.messages.length; + for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { + var resultMessage = result.messages[messageIndex]; + summaryMessages.push({ + text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, + passed: resultMessage.passed ? resultMessage.passed() : true, + type: resultMessage.type, + message: resultMessage.message, + trace: { + stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined + } + }); + } + + return { + result : result.result, + messages : summaryMessages + }; +}; + +/** + * @constructor + * @param {jasmine.Env} env + * @param actual + * @param {jasmine.Spec} spec + */ +jasmine.Matchers = function(env, actual, spec, opt_isNot) { + this.env = env; + this.actual = actual; + this.spec = spec; + this.isNot = opt_isNot || false; + this.reportWasCalled_ = false; +}; + +// todo: @deprecated as of Jasmine 0.11, remove soon [xw] +jasmine.Matchers.pp = function(str) { + throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); +}; + +// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] +jasmine.Matchers.prototype.report = function(result, failing_message, details) { + throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); +}; + +jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { + for (var methodName in prototype) { + if (methodName == 'report') continue; + var orig = prototype[methodName]; + matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); + } +}; + +jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { + return function() { + var matcherArgs = jasmine.util.argsToArray(arguments); + var result = matcherFunction.apply(this, arguments); + + if (this.isNot) { + result = !result; + } + + if (this.reportWasCalled_) return result; + + var message; + if (!result) { + if (this.message) { + message = this.message.apply(this, arguments); + if (jasmine.isArray_(message)) { + message = message[this.isNot ? 1 : 0]; + } + } else { + var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); + message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; + if (matcherArgs.length > 0) { + for (var i = 0; i < matcherArgs.length; i++) { + if (i > 0) message += ","; + message += " " + jasmine.pp(matcherArgs[i]); + } + } + message += "."; + } + } + var expectationResult = new jasmine.ExpectationResult({ + matcherName: matcherName, + passed: result, + expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], + actual: this.actual, + message: message + }); + this.spec.addMatcherResult(expectationResult); + return jasmine.undefined; + }; +}; + + + + +/** + * toBe: compares the actual to the expected using === + * @param expected + */ +jasmine.Matchers.prototype.toBe = function(expected) { + return this.actual === expected; +}; + +/** + * toNotBe: compares the actual to the expected using !== + * @param expected + * @deprecated as of 1.0. Use not.toBe() instead. + */ +jasmine.Matchers.prototype.toNotBe = function(expected) { + return this.actual !== expected; +}; + +/** + * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. + * + * @param expected + */ +jasmine.Matchers.prototype.toEqual = function(expected) { + return this.env.equals_(this.actual, expected); +}; + +/** + * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual + * @param expected + * @deprecated as of 1.0. Use not.toNotEqual() instead. + */ +jasmine.Matchers.prototype.toNotEqual = function(expected) { + return !this.env.equals_(this.actual, expected); +}; + +/** + * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes + * a pattern or a String. + * + * @param expected + */ +jasmine.Matchers.prototype.toMatch = function(expected) { + return new RegExp(expected).test(this.actual); +}; + +/** + * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch + * @param expected + * @deprecated as of 1.0. Use not.toMatch() instead. + */ +jasmine.Matchers.prototype.toNotMatch = function(expected) { + return !(new RegExp(expected).test(this.actual)); +}; + +/** + * Matcher that compares the actual to jasmine.undefined. + */ +jasmine.Matchers.prototype.toBeDefined = function() { + return (this.actual !== jasmine.undefined); +}; + +/** + * Matcher that compares the actual to jasmine.undefined. + */ +jasmine.Matchers.prototype.toBeUndefined = function() { + return (this.actual === jasmine.undefined); +}; + +/** + * Matcher that compares the actual to null. + */ +jasmine.Matchers.prototype.toBeNull = function() { + return (this.actual === null); +}; + +/** + * Matcher that boolean not-nots the actual. + */ +jasmine.Matchers.prototype.toBeTruthy = function() { + return !!this.actual; +}; + + +/** + * Matcher that boolean nots the actual. + */ +jasmine.Matchers.prototype.toBeFalsy = function() { + return !this.actual; +}; + + +/** + * Matcher that checks to see if the actual, a Jasmine spy, was called. + */ +jasmine.Matchers.prototype.toHaveBeenCalled = function() { + if (arguments.length > 0) { + throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); + } + + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + + this.message = function() { + return [ + "Expected spy " + this.actual.identity + " to have been called.", + "Expected spy " + this.actual.identity + " not to have been called." + ]; + }; + + return this.actual.wasCalled; +}; + +/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ +jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; + +/** + * Matcher that checks to see if the actual, a Jasmine spy, was not called. + * + * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead + */ +jasmine.Matchers.prototype.wasNotCalled = function() { + if (arguments.length > 0) { + throw new Error('wasNotCalled does not take arguments'); + } + + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + + this.message = function() { + return [ + "Expected spy " + this.actual.identity + " to not have been called.", + "Expected spy " + this.actual.identity + " to have been called." + ]; + }; + + return !this.actual.wasCalled; +}; + +/** + * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. + * + * @example + * + */ +jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { + var expectedArgs = jasmine.util.argsToArray(arguments); + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + this.message = function() { + if (this.actual.callCount == 0) { + // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw] + return [ + "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.", + "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was." + ]; + } else { + return [ + "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall), + "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall) + ]; + } + }; + + return this.env.contains_(this.actual.argsForCall, expectedArgs); +}; + +/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ +jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; + +/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ +jasmine.Matchers.prototype.wasNotCalledWith = function() { + var expectedArgs = jasmine.util.argsToArray(arguments); + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + + this.message = function() { + return [ + "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", + "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" + ] + }; + + return !this.env.contains_(this.actual.argsForCall, expectedArgs); +}; + +/** + * Matcher that checks that the expected item is an element in the actual Array. + * + * @param {Object} expected + */ +jasmine.Matchers.prototype.toContain = function(expected) { + return this.env.contains_(this.actual, expected); +}; + +/** + * Matcher that checks that the expected item is NOT an element in the actual Array. + * + * @param {Object} expected + * @deprecated as of 1.0. Use not.toNotContain() instead. + */ +jasmine.Matchers.prototype.toNotContain = function(expected) { + return !this.env.contains_(this.actual, expected); +}; + +jasmine.Matchers.prototype.toBeLessThan = function(expected) { + return this.actual < expected; +}; + +jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { + return this.actual > expected; +}; + +/** + * Matcher that checks that the expected exception was thrown by the actual. + * + * @param {String} expected + */ +jasmine.Matchers.prototype.toThrow = function(expected) { + var result = false; + var exception; + if (typeof this.actual != 'function') { + throw new Error('Actual is not a function'); + } + try { + this.actual(); + } catch (e) { + exception = e; + } + if (exception) { + result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); + } + + var not = this.isNot ? "not " : ""; + + this.message = function() { + if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { + return ["Expected function " + not + "to throw", expected ? expected.message || expected : " an exception", ", but it threw", exception.message || exception].join(' '); + } else { + return "Expected function to throw an exception."; + } + }; + + return result; +}; + +jasmine.Matchers.Any = function(expectedClass) { + this.expectedClass = expectedClass; +}; + +jasmine.Matchers.Any.prototype.matches = function(other) { + if (this.expectedClass == String) { + return typeof other == 'string' || other instanceof String; + } + + if (this.expectedClass == Number) { + return typeof other == 'number' || other instanceof Number; + } + + if (this.expectedClass == Function) { + return typeof other == 'function' || other instanceof Function; + } + + if (this.expectedClass == Object) { + return typeof other == 'object'; + } + + return other instanceof this.expectedClass; +}; + +jasmine.Matchers.Any.prototype.toString = function() { + return ''; +}; + +/** + * @constructor + */ +jasmine.MultiReporter = function() { + this.subReporters_ = []; +}; +jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); + +jasmine.MultiReporter.prototype.addReporter = function(reporter) { + this.subReporters_.push(reporter); +}; + +(function() { + var functionNames = [ + "reportRunnerStarting", + "reportRunnerResults", + "reportSuiteResults", + "reportSpecStarting", + "reportSpecResults", + "log" + ]; + for (var i = 0; i < functionNames.length; i++) { + var functionName = functionNames[i]; + jasmine.MultiReporter.prototype[functionName] = (function(functionName) { + return function() { + for (var j = 0; j < this.subReporters_.length; j++) { + var subReporter = this.subReporters_[j]; + if (subReporter[functionName]) { + subReporter[functionName].apply(subReporter, arguments); + } + } + }; + })(functionName); + } +})(); +/** + * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults + * + * @constructor + */ +jasmine.NestedResults = function() { + /** + * The total count of results + */ + this.totalCount = 0; + /** + * Number of passed results + */ + this.passedCount = 0; + /** + * Number of failed results + */ + this.failedCount = 0; + /** + * Was this suite/spec skipped? + */ + this.skipped = false; + /** + * @ignore + */ + this.items_ = []; +}; + +/** + * Roll up the result counts. + * + * @param result + */ +jasmine.NestedResults.prototype.rollupCounts = function(result) { + this.totalCount += result.totalCount; + this.passedCount += result.passedCount; + this.failedCount += result.failedCount; +}; + +/** + * Adds a log message. + * @param values Array of message parts which will be concatenated later. + */ +jasmine.NestedResults.prototype.log = function(values) { + this.items_.push(new jasmine.MessageResult(values)); +}; + +/** + * Getter for the results: message & results. + */ +jasmine.NestedResults.prototype.getItems = function() { + return this.items_; +}; + +/** + * Adds a result, tracking counts (total, passed, & failed) + * @param {jasmine.ExpectationResult|jasmine.NestedResults} result + */ +jasmine.NestedResults.prototype.addResult = function(result) { + if (result.type != 'log') { + if (result.items_) { + this.rollupCounts(result); + } else { + this.totalCount++; + if (result.passed()) { + this.passedCount++; + } else { + this.failedCount++; + } + } + } + this.items_.push(result); +}; + +/** + * @returns {Boolean} True if everything below passed + */ +jasmine.NestedResults.prototype.passed = function() { + return this.passedCount === this.totalCount; +}; +/** + * Base class for pretty printing for expectation results. + */ +jasmine.PrettyPrinter = function() { + this.ppNestLevel_ = 0; +}; + +/** + * Formats a value in a nice, human-readable string. + * + * @param value + */ +jasmine.PrettyPrinter.prototype.format = function(value) { + if (this.ppNestLevel_ > 40) { + throw new Error('jasmine.PrettyPrinter: format() nested too deeply!'); + } + + this.ppNestLevel_++; + try { + if (value === jasmine.undefined) { + this.emitScalar('undefined'); + } else if (value === null) { + this.emitScalar('null'); + } else if (value === jasmine.getGlobal()) { + this.emitScalar(''); + } else if (value instanceof jasmine.Matchers.Any) { + this.emitScalar(value.toString()); + } else if (typeof value === 'string') { + this.emitString(value); + } else if (jasmine.isSpy(value)) { + this.emitScalar("spy on " + value.identity); + } else if (value instanceof RegExp) { + this.emitScalar(value.toString()); + } else if (typeof value === 'function') { + this.emitScalar('Function'); + } else if (typeof value.nodeType === 'number') { + this.emitScalar('HTMLNode'); + } else if (value instanceof Date) { + this.emitScalar('Date(' + value + ')'); + } else if (value.__Jasmine_been_here_before__) { + this.emitScalar(''); + } else if (jasmine.isArray_(value) || typeof value == 'object') { + value.__Jasmine_been_here_before__ = true; + if (jasmine.isArray_(value)) { + this.emitArray(value); + } else { + this.emitObject(value); + } + delete value.__Jasmine_been_here_before__; + } else { + this.emitScalar(value.toString()); + } + } finally { + this.ppNestLevel_--; + } +}; + +jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { + for (var property in obj) { + if (property == '__Jasmine_been_here_before__') continue; + fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) != null) : false); + } +}; + +jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; + +jasmine.StringPrettyPrinter = function() { + jasmine.PrettyPrinter.call(this); + + this.string = ''; +}; +jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); + +jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { + this.append(value); +}; + +jasmine.StringPrettyPrinter.prototype.emitString = function(value) { + this.append("'" + value + "'"); +}; + +jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { + this.append('[ '); + for (var i = 0; i < array.length; i++) { + if (i > 0) { + this.append(', '); + } + this.format(array[i]); + } + this.append(' ]'); +}; + +jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { + var self = this; + this.append('{ '); + var first = true; + + this.iterateObject(obj, function(property, isGetter) { + if (first) { + first = false; + } else { + self.append(', '); + } + + self.append(property); + self.append(' : '); + if (isGetter) { + self.append(''); + } else { + self.format(obj[property]); + } + }); + + this.append(' }'); +}; + +jasmine.StringPrettyPrinter.prototype.append = function(value) { + this.string += value; +}; +jasmine.Queue = function(env) { + this.env = env; + this.blocks = []; + this.running = false; + this.index = 0; + this.offset = 0; + this.abort = false; +}; + +jasmine.Queue.prototype.addBefore = function(block) { + this.blocks.unshift(block); +}; + +jasmine.Queue.prototype.add = function(block) { + this.blocks.push(block); +}; + +jasmine.Queue.prototype.insertNext = function(block) { + this.blocks.splice((this.index + this.offset + 1), 0, block); + this.offset++; +}; + +jasmine.Queue.prototype.start = function(onComplete) { + this.running = true; + this.onComplete = onComplete; + this.next_(); +}; + +jasmine.Queue.prototype.isRunning = function() { + return this.running; +}; + +jasmine.Queue.LOOP_DONT_RECURSE = true; + +jasmine.Queue.prototype.next_ = function() { + var self = this; + var goAgain = true; + + while (goAgain) { + goAgain = false; + + if (self.index < self.blocks.length && !this.abort) { + var calledSynchronously = true; + var completedSynchronously = false; + + var onComplete = function () { + if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { + completedSynchronously = true; + return; + } + + if (self.blocks[self.index].abort) { + self.abort = true; + } + + self.offset = 0; + self.index++; + + var now = new Date().getTime(); + if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { + self.env.lastUpdate = now; + self.env.setTimeout(function() { + self.next_(); + }, 0); + } else { + if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { + goAgain = true; + } else { + self.next_(); + } + } + }; + self.blocks[self.index].execute(onComplete); + + calledSynchronously = false; + if (completedSynchronously) { + onComplete(); + } + + } else { + self.running = false; + if (self.onComplete) { + self.onComplete(); + } + } + } +}; + +jasmine.Queue.prototype.results = function() { + var results = new jasmine.NestedResults(); + for (var i = 0; i < this.blocks.length; i++) { + if (this.blocks[i].results) { + results.addResult(this.blocks[i].results()); + } + } + return results; +}; + + +/** + * Runner + * + * @constructor + * @param {jasmine.Env} env + */ +jasmine.Runner = function(env) { + var self = this; + self.env = env; + self.queue = new jasmine.Queue(env); + self.before_ = []; + self.after_ = []; + self.suites_ = []; +}; + +jasmine.Runner.prototype.execute = function() { + var self = this; + if (self.env.reporter.reportRunnerStarting) { + self.env.reporter.reportRunnerStarting(this); + } + self.queue.start(function () { + self.finishCallback(); + }); +}; + +jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { + beforeEachFunction.typeName = 'beforeEach'; + this.before_.splice(0,0,beforeEachFunction); +}; + +jasmine.Runner.prototype.afterEach = function(afterEachFunction) { + afterEachFunction.typeName = 'afterEach'; + this.after_.splice(0,0,afterEachFunction); +}; + + +jasmine.Runner.prototype.finishCallback = function() { + this.env.reporter.reportRunnerResults(this); +}; + +jasmine.Runner.prototype.addSuite = function(suite) { + this.suites_.push(suite); +}; + +jasmine.Runner.prototype.add = function(block) { + if (block instanceof jasmine.Suite) { + this.addSuite(block); + } + this.queue.add(block); +}; + +jasmine.Runner.prototype.specs = function () { + var suites = this.suites(); + var specs = []; + for (var i = 0; i < suites.length; i++) { + specs = specs.concat(suites[i].specs()); + } + return specs; +}; + +jasmine.Runner.prototype.suites = function() { + return this.suites_; +}; + +jasmine.Runner.prototype.topLevelSuites = function() { + var topLevelSuites = []; + for (var i = 0; i < this.suites_.length; i++) { + if (!this.suites_[i].parentSuite) { + topLevelSuites.push(this.suites_[i]); + } + } + return topLevelSuites; +}; + +jasmine.Runner.prototype.results = function() { + return this.queue.results(); +}; +/** + * Internal representation of a Jasmine specification, or test. + * + * @constructor + * @param {jasmine.Env} env + * @param {jasmine.Suite} suite + * @param {String} description + */ +jasmine.Spec = function(env, suite, description) { + if (!env) { + throw new Error('jasmine.Env() required'); + } + if (!suite) { + throw new Error('jasmine.Suite() required'); + } + var spec = this; + spec.id = env.nextSpecId ? env.nextSpecId() : null; + spec.env = env; + spec.suite = suite; + spec.description = description; + spec.queue = new jasmine.Queue(env); + + spec.afterCallbacks = []; + spec.spies_ = []; + + spec.results_ = new jasmine.NestedResults(); + spec.results_.description = description; + spec.matchersClass = null; +}; + +jasmine.Spec.prototype.getFullName = function() { + return this.suite.getFullName() + ' ' + this.description + '.'; +}; + + +jasmine.Spec.prototype.results = function() { + return this.results_; +}; + +/** + * All parameters are pretty-printed and concatenated together, then written to the spec's output. + * + * Be careful not to leave calls to jasmine.log in production code. + */ +jasmine.Spec.prototype.log = function() { + return this.results_.log(arguments); +}; + +jasmine.Spec.prototype.runs = function (func) { + var block = new jasmine.Block(this.env, func, this); + this.addToQueue(block); + return this; +}; + +jasmine.Spec.prototype.addToQueue = function (block) { + if (this.queue.isRunning()) { + this.queue.insertNext(block); + } else { + this.queue.add(block); + } +}; + +/** + * @param {jasmine.ExpectationResult} result + */ +jasmine.Spec.prototype.addMatcherResult = function(result) { + this.results_.addResult(result); +}; + +jasmine.Spec.prototype.expect = function(actual) { + var positive = new (this.getMatchersClass_())(this.env, actual, this); + positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); + return positive; +}; + +/** + * Waits a fixed time period before moving to the next block. + * + * @deprecated Use waitsFor() instead + * @param {Number} timeout milliseconds to wait + */ +jasmine.Spec.prototype.waits = function(timeout) { + var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); + this.addToQueue(waitsFunc); + return this; +}; + +/** + * Waits for the latchFunction to return true before proceeding to the next block. + * + * @param {Function} latchFunction + * @param {String} optional_timeoutMessage + * @param {Number} optional_timeout + */ +jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { + var latchFunction_ = null; + var optional_timeoutMessage_ = null; + var optional_timeout_ = null; + + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + switch (typeof arg) { + case 'function': + latchFunction_ = arg; + break; + case 'string': + optional_timeoutMessage_ = arg; + break; + case 'number': + optional_timeout_ = arg; + break; + } + } + + var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); + this.addToQueue(waitsForFunc); + return this; +}; + +jasmine.Spec.prototype.fail = function (e) { + var expectationResult = new jasmine.ExpectationResult({ + passed: false, + message: e ? jasmine.util.formatException(e) : 'Exception' + }); + this.results_.addResult(expectationResult); +}; + +jasmine.Spec.prototype.getMatchersClass_ = function() { + return this.matchersClass || this.env.matchersClass; +}; + +jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { + var parent = this.getMatchersClass_(); + var newMatchersClass = function() { + parent.apply(this, arguments); + }; + jasmine.util.inherit(newMatchersClass, parent); + jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); + this.matchersClass = newMatchersClass; +}; + +jasmine.Spec.prototype.finishCallback = function() { + this.env.reporter.reportSpecResults(this); +}; + +jasmine.Spec.prototype.finish = function(onComplete) { + this.removeAllSpies(); + this.finishCallback(); + if (onComplete) { + onComplete(); + } +}; + +jasmine.Spec.prototype.after = function(doAfter) { + if (this.queue.isRunning()) { + this.queue.add(new jasmine.Block(this.env, doAfter, this)); + } else { + this.afterCallbacks.unshift(doAfter); + } +}; + +jasmine.Spec.prototype.execute = function(onComplete) { + var spec = this; + if (!spec.env.specFilter(spec)) { + spec.results_.skipped = true; + spec.finish(onComplete); + return; + } + + this.env.reporter.reportSpecStarting(this); + + spec.env.currentSpec = spec; + + spec.addBeforesAndAftersToQueue(); + + spec.queue.start(function () { + spec.finish(onComplete); + }); +}; + +jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { + var runner = this.env.currentRunner(); + var i; + + for (var suite = this.suite; suite; suite = suite.parentSuite) { + for (i = 0; i < suite.before_.length; i++) { + this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); + } + } + for (i = 0; i < runner.before_.length; i++) { + this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); + } + for (i = 0; i < this.afterCallbacks.length; i++) { + this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this)); + } + for (suite = this.suite; suite; suite = suite.parentSuite) { + for (i = 0; i < suite.after_.length; i++) { + this.queue.add(new jasmine.Block(this.env, suite.after_[i], this)); + } + } + for (i = 0; i < runner.after_.length; i++) { + this.queue.add(new jasmine.Block(this.env, runner.after_[i], this)); + } +}; + +jasmine.Spec.prototype.explodes = function() { + throw 'explodes function should not have been called'; +}; + +jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { + if (obj == jasmine.undefined) { + throw "spyOn could not find an object to spy upon for " + methodName + "()"; + } + + if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { + throw methodName + '() method does not exist'; + } + + if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { + throw new Error(methodName + ' has already been spied upon'); + } + + var spyObj = jasmine.createSpy(methodName); + + this.spies_.push(spyObj); + spyObj.baseObj = obj; + spyObj.methodName = methodName; + spyObj.originalValue = obj[methodName]; + + obj[methodName] = spyObj; + + return spyObj; +}; + +jasmine.Spec.prototype.removeAllSpies = function() { + for (var i = 0; i < this.spies_.length; i++) { + var spy = this.spies_[i]; + spy.baseObj[spy.methodName] = spy.originalValue; + } + this.spies_ = []; +}; + +/** + * Internal representation of a Jasmine suite. + * + * @constructor + * @param {jasmine.Env} env + * @param {String} description + * @param {Function} specDefinitions + * @param {jasmine.Suite} parentSuite + */ +jasmine.Suite = function(env, description, specDefinitions, parentSuite) { + var self = this; + self.id = env.nextSuiteId ? env.nextSuiteId() : null; + self.description = description; + self.queue = new jasmine.Queue(env); + self.parentSuite = parentSuite; + self.env = env; + self.before_ = []; + self.after_ = []; + self.children_ = []; + self.suites_ = []; + self.specs_ = []; +}; + +jasmine.Suite.prototype.getFullName = function() { + var fullName = this.description; + for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { + fullName = parentSuite.description + ' ' + fullName; + } + return fullName; +}; + +jasmine.Suite.prototype.finish = function(onComplete) { + this.env.reporter.reportSuiteResults(this); + this.finished = true; + if (typeof(onComplete) == 'function') { + onComplete(); + } +}; + +jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { + beforeEachFunction.typeName = 'beforeEach'; + this.before_.unshift(beforeEachFunction); +}; + +jasmine.Suite.prototype.afterEach = function(afterEachFunction) { + afterEachFunction.typeName = 'afterEach'; + this.after_.unshift(afterEachFunction); +}; + +jasmine.Suite.prototype.results = function() { + return this.queue.results(); +}; + +jasmine.Suite.prototype.add = function(suiteOrSpec) { + this.children_.push(suiteOrSpec); + if (suiteOrSpec instanceof jasmine.Suite) { + this.suites_.push(suiteOrSpec); + this.env.currentRunner().addSuite(suiteOrSpec); + } else { + this.specs_.push(suiteOrSpec); + } + this.queue.add(suiteOrSpec); +}; + +jasmine.Suite.prototype.specs = function() { + return this.specs_; +}; + +jasmine.Suite.prototype.suites = function() { + return this.suites_; +}; + +jasmine.Suite.prototype.children = function() { + return this.children_; +}; + +jasmine.Suite.prototype.execute = function(onComplete) { + var self = this; + this.queue.start(function () { + self.finish(onComplete); + }); +}; +jasmine.WaitsBlock = function(env, timeout, spec) { + this.timeout = timeout; + jasmine.Block.call(this, env, null, spec); +}; + +jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); + +jasmine.WaitsBlock.prototype.execute = function (onComplete) { + this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); + this.env.setTimeout(function () { + onComplete(); + }, this.timeout); +}; +/** + * A block which waits for some condition to become true, with timeout. + * + * @constructor + * @extends jasmine.Block + * @param {jasmine.Env} env The Jasmine environment. + * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. + * @param {Function} latchFunction A function which returns true when the desired condition has been met. + * @param {String} message The message to display if the desired condition hasn't been met within the given time period. + * @param {jasmine.Spec} spec The Jasmine spec. + */ +jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { + this.timeout = timeout || env.defaultTimeoutInterval; + this.latchFunction = latchFunction; + this.message = message; + this.totalTimeSpentWaitingForLatch = 0; + jasmine.Block.call(this, env, null, spec); +}; +jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); + +jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; + +jasmine.WaitsForBlock.prototype.execute = function(onComplete) { + this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); + var latchFunctionResult; + try { + latchFunctionResult = this.latchFunction.apply(this.spec); + } catch (e) { + this.spec.fail(e); + onComplete(); + return; + } + + if (latchFunctionResult) { + onComplete(); + } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { + var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); + this.spec.fail({ + name: 'timeout', + message: message + }); + + this.abort = true; + onComplete(); + } else { + this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; + var self = this; + this.env.setTimeout(function() { + self.execute(onComplete); + }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); + } +}; +// Mock setTimeout, clearTimeout +// Contributed by Pivotal Computer Systems, www.pivotalsf.com + +jasmine.FakeTimer = function() { + this.reset(); + + var self = this; + self.setTimeout = function(funcToCall, millis) { + self.timeoutsMade++; + self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); + return self.timeoutsMade; + }; + + self.setInterval = function(funcToCall, millis) { + self.timeoutsMade++; + self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); + return self.timeoutsMade; + }; + + self.clearTimeout = function(timeoutKey) { + self.scheduledFunctions[timeoutKey] = jasmine.undefined; + }; + + self.clearInterval = function(timeoutKey) { + self.scheduledFunctions[timeoutKey] = jasmine.undefined; + }; + +}; + +jasmine.FakeTimer.prototype.reset = function() { + this.timeoutsMade = 0; + this.scheduledFunctions = {}; + this.nowMillis = 0; +}; + +jasmine.FakeTimer.prototype.tick = function(millis) { + var oldMillis = this.nowMillis; + var newMillis = oldMillis + millis; + this.runFunctionsWithinRange(oldMillis, newMillis); + this.nowMillis = newMillis; +}; + +jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { + var scheduledFunc; + var funcsToRun = []; + for (var timeoutKey in this.scheduledFunctions) { + scheduledFunc = this.scheduledFunctions[timeoutKey]; + if (scheduledFunc != jasmine.undefined && + scheduledFunc.runAtMillis >= oldMillis && + scheduledFunc.runAtMillis <= nowMillis) { + funcsToRun.push(scheduledFunc); + this.scheduledFunctions[timeoutKey] = jasmine.undefined; + } + } + + if (funcsToRun.length > 0) { + funcsToRun.sort(function(a, b) { + return a.runAtMillis - b.runAtMillis; + }); + for (var i = 0; i < funcsToRun.length; ++i) { + try { + var funcToRun = funcsToRun[i]; + this.nowMillis = funcToRun.runAtMillis; + funcToRun.funcToCall(); + if (funcToRun.recurring) { + this.scheduleFunction(funcToRun.timeoutKey, + funcToRun.funcToCall, + funcToRun.millis, + true); + } + } catch(e) { + } + } + this.runFunctionsWithinRange(oldMillis, nowMillis); + } +}; + +jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { + this.scheduledFunctions[timeoutKey] = { + runAtMillis: this.nowMillis + millis, + funcToCall: funcToCall, + recurring: recurring, + timeoutKey: timeoutKey, + millis: millis + }; +}; + +/** + * @namespace + */ +jasmine.Clock = { + defaultFakeTimer: new jasmine.FakeTimer(), + + reset: function() { + jasmine.Clock.assertInstalled(); + jasmine.Clock.defaultFakeTimer.reset(); + }, + + tick: function(millis) { + jasmine.Clock.assertInstalled(); + jasmine.Clock.defaultFakeTimer.tick(millis); + }, + + runFunctionsWithinRange: function(oldMillis, nowMillis) { + jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); + }, + + scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { + jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); + }, + + useMock: function() { + if (!jasmine.Clock.isInstalled()) { + var spec = jasmine.getEnv().currentSpec; + spec.after(jasmine.Clock.uninstallMock); + + jasmine.Clock.installMock(); + } + }, + + installMock: function() { + jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; + }, + + uninstallMock: function() { + jasmine.Clock.assertInstalled(); + jasmine.Clock.installed = jasmine.Clock.real; + }, + + real: { + setTimeout: jasmine.getGlobal().setTimeout, + clearTimeout: jasmine.getGlobal().clearTimeout, + setInterval: jasmine.getGlobal().setInterval, + clearInterval: jasmine.getGlobal().clearInterval + }, + + assertInstalled: function() { + if (!jasmine.Clock.isInstalled()) { + throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); + } + }, + + isInstalled: function() { + return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; + }, + + installed: null +}; +jasmine.Clock.installed = jasmine.Clock.real; + +//else for IE support +jasmine.getGlobal().setTimeout = function(funcToCall, millis) { + if (jasmine.Clock.installed.setTimeout.apply) { + return jasmine.Clock.installed.setTimeout.apply(this, arguments); + } else { + return jasmine.Clock.installed.setTimeout(funcToCall, millis); + } +}; + +jasmine.getGlobal().setInterval = function(funcToCall, millis) { + if (jasmine.Clock.installed.setInterval.apply) { + return jasmine.Clock.installed.setInterval.apply(this, arguments); + } else { + return jasmine.Clock.installed.setInterval(funcToCall, millis); + } +}; + +jasmine.getGlobal().clearTimeout = function(timeoutKey) { + if (jasmine.Clock.installed.clearTimeout.apply) { + return jasmine.Clock.installed.clearTimeout.apply(this, arguments); + } else { + return jasmine.Clock.installed.clearTimeout(timeoutKey); + } +}; + +jasmine.getGlobal().clearInterval = function(timeoutKey) { + if (jasmine.Clock.installed.clearTimeout.apply) { + return jasmine.Clock.installed.clearInterval.apply(this, arguments); + } else { + return jasmine.Clock.installed.clearInterval(timeoutKey); + } +}; + + +jasmine.version_= { + "major": 1, + "minor": 0, + "build": 0, + "revision": 1284494074 +}; diff --git a/spec/infrastructure/jasmine-standalone-1.0.0/spec/PlayerSpec.js b/spec/infrastructure/jasmine-standalone-1.0.0/spec/PlayerSpec.js new file mode 100644 index 0000000..79f1022 --- /dev/null +++ b/spec/infrastructure/jasmine-standalone-1.0.0/spec/PlayerSpec.js @@ -0,0 +1,58 @@ +describe("Player", function() { + var player; + var song; + + beforeEach(function() { + player = new Player(); + song = new Song(); + }); + + it("should be able to play a Song", function() { + player.play(song); + expect(player.currentlyPlayingSong).toEqual(song); + + //demonstrates use of custom matcher + expect(player).toBePlaying(song); + }); + + describe("when song has been paused", function() { + beforeEach(function() { + player.play(song); + player.pause(); + }); + + it("should indicate that the song is currently paused", function() { + expect(player.isPlaying).toBeFalsy(); + + // demonstrates use of 'not' with a custom matcher + expect(player).not.toBePlaying(song); + }); + + it("should be possible to resume", function() { + player.resume(); + expect(player.isPlaying).toBeTruthy(); + expect(player.currentlyPlayingSong).toEqual(song); + }); + }); + + // demonstrates use of spies to intercept and test method calls + it("tells the current song if the user has made it a favorite", function() { + spyOn(song, 'persistFavoriteStatus'); + + player.play(song); + player.makeFavorite(); + + expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true); + }); + + //demonstrates use of expected exceptions + describe("#resume", function() { + it("should throw an exception if song is already playing", function() { + player.play(song); + + expect(function() { + player.resume(); + }).toThrow("song is already playing"); + }); + }); +}); \ No newline at end of file diff --git a/spec/infrastructure/jasmine-standalone-1.0.0/spec/SpecHelper.js b/spec/infrastructure/jasmine-standalone-1.0.0/spec/SpecHelper.js new file mode 100644 index 0000000..4919c87 --- /dev/null +++ b/spec/infrastructure/jasmine-standalone-1.0.0/spec/SpecHelper.js @@ -0,0 +1,9 @@ +beforeEach(function() { + this.addMatchers({ + toBePlaying: function(expectedSong) { + var player = this.actual; + return player.currentlyPlayingSong === expectedSong + && player.isPlaying; + } + }) +}); diff --git a/spec/infrastructure/jasmine-standalone-1.0.0/src/Player.js b/spec/infrastructure/jasmine-standalone-1.0.0/src/Player.js new file mode 100644 index 0000000..fcce826 --- /dev/null +++ b/spec/infrastructure/jasmine-standalone-1.0.0/src/Player.js @@ -0,0 +1,22 @@ +function Player() { +} +Player.prototype.play = function(song) { + this.currentlyPlayingSong = song; + this.isPlaying = true; +}; + +Player.prototype.pause = function() { + this.isPlaying = false; +}; + +Player.prototype.resume = function() { + if (this.isPlaying) { + throw new Error("song is already playing"); + } + + this.isPlaying = true; +}; + +Player.prototype.makeFavorite = function() { + this.currentlyPlayingSong.persistFavoriteStatus(true); +}; \ No newline at end of file diff --git a/spec/infrastructure/jasmine-standalone-1.0.0/src/Song.js b/spec/infrastructure/jasmine-standalone-1.0.0/src/Song.js new file mode 100644 index 0000000..a8a3f2d --- /dev/null +++ b/spec/infrastructure/jasmine-standalone-1.0.0/src/Song.js @@ -0,0 +1,7 @@ +function Song() { +} + +Song.prototype.persistFavoriteStatus = function(value) { + // something complicated + throw new Error("not yet implemented"); +}; \ No newline at end of file