diff --git a/dev/Common/Utils.js b/dev/Common/Utils.js index 55c9237b1..4cc2059fa 100644 --- a/dev/Common/Utils.js +++ b/dev/Common/Utils.js @@ -73,6 +73,31 @@ Utils.isNonEmptyArray = function (aValue) return Utils.isArray(aValue) && 0 < aValue.length; }; +/** + * @param {string} aValue + * @param {string} sKey + * @param {string} sLongKey + * @return {string|boolean} + */ +Utils.rsaEncode = function (sValue, sHash, sKey, sLongKey) +{ + if (window.crypto && window.crypto.getRandomValues && window.RSAKey && sHash && sKey && sLongKey) + { + var oRsa = new window.RSAKey(); + oRsa.setPublic(sLongKey, sKey); + + sValue = oRsa.encrypt(Utils.fakeMd5() + ':' + sValue + ':' + Utils.fakeMd5()); + if (false !== sValue) + { + return 'rsa:' + sHash + ':' + sValue; + } + } + + return false; +}; + +Utils.rsaEncode.supported = !!(window.crypto && window.crypto.getRandomValues && window.RSAKey); + /** * @param {string} sPath * @param {*=} oObject @@ -462,7 +487,7 @@ Utils.replySubjectAdd = function (sPrefix, sSubject) for (iIndex = 0; iIndex < aParts.length; iIndex++) { sTrimmedPart = Utils.trim(aParts[iIndex]); - if (!bDrop && + if (!bDrop && (/^(RE|FWD)$/i.test(sTrimmedPart) || /^(RE|FWD)[\[\(][\d]+[\]\)]$/i.test(sTrimmedPart)) ) { @@ -470,7 +495,7 @@ Utils.replySubjectAdd = function (sPrefix, sSubject) { bRe = !!(/^RE/i.test(sTrimmedPart)); } - + if (!bFwd) { bFwd = !!(/^FWD/i.test(sTrimmedPart)); diff --git a/dev/ViewModels/LoginViewModel.js b/dev/ViewModels/LoginViewModel.js index c11a954b4..de9213d94 100644 --- a/dev/ViewModels/LoginViewModel.js +++ b/dev/ViewModels/LoginViewModel.js @@ -70,7 +70,7 @@ function LoginViewModel() this.signMeVisibility = ko.computed(function () { return Enums.LoginSignMeType.Unused !== this.signMeType(); }, this); - + this.submitCommand = Utils.createCommand(this, function () { this.emailError('' === Utils.trim(this.email())); @@ -90,7 +90,7 @@ function LoginViewModel() var sPassword = this.password(), - + fLoginRequest = _.bind(function (sPassword) { RL.remote().login(_.bind(function (sResult, oData) { @@ -138,43 +138,33 @@ function LoginViewModel() this.additionalCode.visibility() ? this.additionalCode() : '', this.additionalCode.visibility() ? !!this.additionalCodeSignMe() : false ); - + }, this) ; - if (!!RL.settingsGet('UseRsaEncryption')) + if (!!RL.settingsGet('UseRsaEncryption') && Utils.rsaEncode.supported) { - if (window.cryptico) - { - RL.remote().getPublicKey(function (sResult, oData) { + RL.remote().getPublicKey(_.bind(function (sResult, oData) { - var - bRequest = false, - oEncryptionResult = null - ; - - if (Enums.StorageResultType.Success === sResult && oData && oData.Result) + var bRequest = false; + if (Enums.StorageResultType.Success === sResult && oData && oData.Result && + Utils.isArray(oData.Result) && oData.Result[0] && oData.Result[1] && oData.Result[2]) + { + var sEncryptedPassword = Utils.rsaEncode(sPassword, oData.Result[0], oData.Result[1], oData.Result[2]); + if (sEncryptedPassword) { - oEncryptionResult = window.cryptico.encrypt(sPassword, oData.Result); - if (oEncryptionResult && oEncryptionResult.cipher) - { - bRequest = false; - fLoginRequest('cipher:' + oEncryptionResult.cipher); - } + fLoginRequest(sEncryptedPassword); + bRequest = true; } + } - if (bRequest) - { - this.submitRequest(false); - this.submitError(Utils.getNotification(Enums.Notification.UnknownError)); - } - }); - } - else - { - this.submitRequest(false); - this.submitError(Utils.getNotification(Enums.Notification.UnknownError)); - } + if (!bRequest) + { + this.submitRequest(false); + this.submitError(Utils.getNotification(Enums.Notification.UnknownError)); + } + + }, this)); } else { @@ -188,7 +178,7 @@ function LoginViewModel() }); this.facebookLoginEnabled = ko.observable(false); - + this.facebookCommand = Utils.createCommand(this, function () { window.open(RL.link().socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes'); @@ -208,7 +198,7 @@ function LoginViewModel() }, function () { return !this.submitRequest() && this.googleLoginEnabled(); }); - + this.twitterLoginEnabled = ko.observable(false); this.twitterCommand = Utils.createCommand(this, function () { @@ -221,8 +211,8 @@ function LoginViewModel() }); this.socialLoginEnabled = ko.computed(function () { - - var + + var bF = this.facebookLoginEnabled(), bG = this.googleLoginEnabled(), bT = this.twitterLoginEnabled() @@ -282,7 +272,7 @@ LoginViewModel.prototype.onBuild = function () } } ; - + this.facebookLoginEnabled(!!RL.settingsGet('AllowFacebookSocial')); this.twitterLoginEnabled(!!RL.settingsGet('AllowTwitterSocial')); this.googleLoginEnabled(!!RL.settingsGet('AllowGoogleSocial')); @@ -308,7 +298,7 @@ LoginViewModel.prototype.onBuild = function () { window['rl_' + sJsHash + '_google_login_service'] = fSocial; } - + if (this.facebookLoginEnabled()) { window['rl_' + sJsHash + '_facebook_login_service'] = fSocial; diff --git a/gulpfile.js b/gulpfile.js index c8117a76f..c03529861 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -118,10 +118,17 @@ cfg.paths.js = { 'vendors/openpgp/openpgp-0.5.1.min.js' ] }, - cryptico: { - name: 'cryptico.min.js', + encrypt: { + name: '_encrypt.min.js', + header: '(function (window) {', + footer: '}(window));', + dest: 'vendors/jsbn/', src: [ - 'vendors/cryptico/cryptico.min.js' + 'vendors/jsbn/jsbn.js', + 'vendors/jsbn/prng4.js', + 'vendors/jsbn/rng.js', + 'vendors/jsbn/rsa.js', + 'vendors/jsbn/_fix.js' ] }, libs: { @@ -148,6 +155,7 @@ cfg.paths.js = { 'vendors/knockout-projections/knockout-projections-1.0.0.min.js', 'vendors/ssm/ssm.min.js', 'vendors/jua/jua.min.js', + 'vendors/jsbn/_encrypt.min.js', 'vendors/keymaster/keymaster.js', 'vendors/ifvisible/ifvisible.min.js', 'vendors/jquery-magnific-popup/jquery.magnific-popup.min.js', @@ -367,10 +375,14 @@ gulp.task('js:boot', function() { .pipe(gulp.dest(cfg.paths.staticJS)); }); -gulp.task('js:cryptico', function() { - return gulp.src(cfg.paths.js.cryptico.src) - .pipe(rename(cfg.paths.js.cryptico.name)) - .pipe(gulp.dest(cfg.paths.staticJS)); +gulp.task('js:encrypt', function() { + return gulp.src(cfg.paths.js.encrypt.src) + .pipe(concat(cfg.paths.js.encrypt.name)) + .pipe(header(cfg.paths.js.encrypt.header || '')) + .pipe(footer(cfg.paths.js.encrypt.footer || '')) + .pipe(uglify(cfg.uglify)) + .pipe(gulp.dest(cfg.paths.js.encrypt.dest || cfg.paths.staticJS)) + .on('error', gutil.log); }); gulp.task('js:openpgp', function() { diff --git a/rainloop/v/0.0.0/app/libraries/RainLoop/Actions.php b/rainloop/v/0.0.0/app/libraries/RainLoop/Actions.php index 371dc897e..61a38277f 100644 --- a/rainloop/v/0.0.0/app/libraries/RainLoop/Actions.php +++ b/rainloop/v/0.0.0/app/libraries/RainLoop/Actions.php @@ -345,7 +345,7 @@ class Actions { $sFileName = \str_replace('{user:ip}', $this->Http()->GetClientIp(), $sFileName); } - + if (\preg_match('/\{user:(email|login|domain)\}/i', $sFileName)) { $this->ParseQueryAuthString(); @@ -1338,12 +1338,6 @@ class Actions { $sPluginsLink = './?/Plugins/0/'.($bAdmin ? 'Admin' : 'User').'/'.$sStaticCache.'/'; } - - $sCrypticoLink = ''; - if ($aResult['UseRsaEncryption']) - { - $sCrypticoLink = APP_WEB_STATIC_PATH.'js/cryptico.min.js'; - } $aResult['Theme'] = $sTheme; $aResult['NewThemeLink'] = $sNewThemeLink; @@ -1352,7 +1346,6 @@ class Actions $aResult['LangLink'] = './?/Lang/0/'.($bAdmin ? 'en' : $aResult['Language']).'/'.$sStaticCache.'/'; $aResult['TemplatesLink'] = './?/Templates/0/'.($bAdmin ? 'Admin' : 'App').'/'.$sStaticCache.'/'; $aResult['PluginsLink'] = $sPluginsLink; - $aResult['CrypticoLink'] = $sCrypticoLink; $aResult['EditorDefaultType'] = 'Html' === $aResult['EditorDefaultType'] ? 'Html' : 'Plain'; // IDN @@ -1466,7 +1459,7 @@ class Actions if (false === \strpos($sEmail, '@')) { $this->Logger()->Write('The email address "'.$sEmail.'" is not complete', \MailSo\Log\Enumerations\Type::INFO, 'LOGIN'); - + if (false === \strpos($sEmail, '@') && 0 < \strlen(\trim($this->Config()->Get('login', 'determine_user_domain', false)))) { $sUserHost = \trim($this->Http()->GetHost(false, true, true)); @@ -1613,19 +1606,100 @@ class Actions return $oAccount; } + /** + * @param string $sEncryptedData + * + * @return string + */ + private function clientRsaDecryptHelper($sEncryptedData) + { + $aMatch = array(); + if (\preg_match('/^rsa:([a-z0-9]{32}):/', $sEncryptedData, $aMatch) && !empty($aMatch[1]) && + $this->Config()->Get('security', 'use_rsa_encryption', false)) + { + $oLogger = $this->Logger(); + $oLogger->Write('Trying to decode encrypted data', \MailSo\Log\Enumerations\Type::INFO, 'RSA'); + + $sPrivateKey = $this->Cacher()->Get('/Key/RSA/'.$aMatch[1].'/'); + if (!empty($sPrivateKey)) + { + $this->Cacher()->Delete('/Key/RSA/'.$aMatch[1].'/'); + + $sData = \trim(\substr($sEncryptedData, 37)); + + if (!\class_exists('Crypt_RSA')) + { + \set_include_path(\get_include_path().PATH_SEPARATOR.APP_VERSION_ROOT_PATH.'app/libraries/phpseclib'); + include_once 'Crypt/RSA.php'; + \defined('CRYPT_RSA_MODE') || \define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); + } + + \RainLoop\Service::$__HIDE_ERROR_NOTICES = true; + + $oRsa = new \Crypt_RSA(); + $oRsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); + $oRsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1); + $oRsa->setPrivateKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1); + $oRsa->loadKey($sPrivateKey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1); + + $oMsg = new \Math_BigInteger($sData, 16); + + $sData = $oRsa->decrypt($oMsg->toBytes()); + if (\preg_match('/^[a-z0-9]{32}:(.+):[a-z0-9]{32}$/', $sData, $aMatch) && isset($aMatch[1])) + { + $sEncryptedData = $aMatch[1]; + } + else + { + $oLogger->Write('Invalid decrypted data', \MailSo\Log\Enumerations\Type::WARNING, 'RSA'); + } + + \RainLoop\Service::$__HIDE_ERROR_NOTICES = false; + } + else + { + $oLogger->Write('Private key is not found', \MailSo\Log\Enumerations\Type::WARNING, 'RSA'); + } + } + + return $sEncryptedData; + } + /** * @return array */ public function DoGetPublicKey() { - \set_include_path(\get_include_path().PATH_SEPARATOR.APP_VERSION_ROOT_PATH.'app/libraries/phpseclib'); + if ($this->Config()->Get('security', 'use_rsa_encryption', false)) + { + \RainLoop\Service::$__HIDE_ERROR_NOTICES = true; - include_once 'Crypt/RSA.php'; + if (!\class_exists('Crypt_RSA')) + { + \set_include_path(\get_include_path().PATH_SEPARATOR.APP_VERSION_ROOT_PATH.'app/libraries/phpseclib'); + include_once 'Crypt/RSA.php'; + \defined('CRYPT_RSA_MODE') || \define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); + } - $oRsa = new \Crypt_RSA(); - $aKeys = $oRsa->createKey(1024); + $oRsa = new \Crypt_RSA(); + $oRsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_RAW); + $aKeys = $oRsa->createKey(1024); - return $this->DefaultResponse(__FUNCTION__, empty($aKeys['publickey']) ? false : $aKeys['publickey']); + if (!empty($aKeys['privatekey']) && !empty($aKeys['publickey']['e']) && !empty($aKeys['publickey']['n'])) + { + $e = new \Math_BigInteger($aKeys['publickey']['e'], 10); + $n = new \Math_BigInteger($aKeys['publickey']['n'], 10); + + $sHash = \md5($e->toHex().$n->toHex()); + + \RainLoop\Service::$__HIDE_ERROR_NOTICES = false; + return $this->DefaultResponse(__FUNCTION__, + $this->Cacher()->Set('/Key/RSA/'.$sHash.'/', $aKeys['privatekey']) ? array($sHash, $e->toHex(), $n->toHex()) : false); + } + } + + \RainLoop\Service::$__HIDE_ERROR_NOTICES = false; + return $this->FalseResponse(__FUNCTION__); } /** @@ -1645,6 +1719,8 @@ class Actions $oAccount = null; + $sPassword = $this->clientRsaDecryptHelper($sPassword); + try { $oAccount = $this->LoginProcess($sEmail, $sPassword, @@ -6001,7 +6077,7 @@ class Actions $sFile = \stream_get_contents($rFile); if (\is_resource($rFile)) { - @\fclose($rFile); + \fclose($rFile); } if (is_string($sFile) && 5 < \strlen($sFile)) diff --git a/rainloop/v/0.0.0/app/libraries/RainLoop/Config/Application.php b/rainloop/v/0.0.0/app/libraries/RainLoop/Config/Application.php index 9c6366a05..37358e62e 100644 --- a/rainloop/v/0.0.0/app/libraries/RainLoop/Config/Application.php +++ b/rainloop/v/0.0.0/app/libraries/RainLoop/Config/Application.php @@ -101,7 +101,8 @@ class Application extends \RainLoop\Config\AbstractConfig 'Enable CSRF protection (http://en.wikipedia.org/wiki/Cross-site_request_forgery)'), 'custom_server_signature' => array('RainLoop'), - 'openpgp' => array(false), + 'openpgp' => array(false), + 'use_rsa_encryption' => array(false), 'admin_login' => array('admin', 'Login and password for web admin panel'), 'admin_password' => array('12345'), 'allow_admin_panel' => array(true, 'Access settings'), @@ -141,7 +142,7 @@ Values: 'write_on_error_only' => array(false, 'Logs entire request only if error occured'), 'write_on_timeout_only' => array(0, 'Logs entire request only if request timeout (in seconds) occured.'), - + 'hide_passwords' => array(true, 'Required for development purposes only. Disabling this option is not recommended.'), diff --git a/rainloop/v/0.0.0/app/libraries/RainLoop/Service.php b/rainloop/v/0.0.0/app/libraries/RainLoop/Service.php index 9d206a115..7b54afc30 100644 --- a/rainloop/v/0.0.0/app/libraries/RainLoop/Service.php +++ b/rainloop/v/0.0.0/app/libraries/RainLoop/Service.php @@ -4,6 +4,11 @@ namespace RainLoop; class Service { + /** + * @var bool + */ + static $__HIDE_ERROR_NOTICES = false; + /** * @var \MailSo\Base\Http */ @@ -88,7 +93,7 @@ class Service $this->oActions->Logger()->Write($sErrFile.' [line:'.$iErrLine.', code:'.$iErrNo.']', $iType, 'PHP'); $this->oActions->Logger()->Write('Error: '.$sErrStr, $iType, 'PHP'); - return false; + return !!(\MailSo\Log\Enumerations\Type::NOTICE === $iType && \RainLoop\Service::$__HIDE_ERROR_NOTICES); } /** diff --git a/rainloop/v/0.0.0/app/templates/Index.html b/rainloop/v/0.0.0/app/templates/Index.html index e5f27c025..575d65f89 100644 --- a/rainloop/v/0.0.0/app/templates/Index.html +++ b/rainloop/v/0.0.0/app/templates/Index.html @@ -89,11 +89,6 @@ __fIncludeScr(window.rainloopAppData['PluginsLink']); } - -// -// Math.seedrandom('yipee'); Sets Math.random to a function that is -// initialized using the given explicit seed. -// -// Math.seedrandom(); Sets Math.random to a function that is -// seeded using the current time, dom state, -// and other accumulated local entropy. -// The generated seed string is returned. -// -// Math.seedrandom('yowza', true); -// Seeds using the given explicit seed mixed -// together with accumulated entropy. -// -// -// Seeds using physical random bits downloaded -// from random.org. -// -// Seeds using urandom bits from call.jsonlib.com, -// which is faster than random.org. -// -// Examples: -// -// Math.seedrandom("hello"); // Use "hello" as the seed. -// document.write(Math.random()); // Always 0.5463663768140734 -// document.write(Math.random()); // Always 0.43973793770592234 -// var rng1 = Math.random; // Remember the current prng. -// -// var autoseed = Math.seedrandom(); // New prng with an automatic seed. -// document.write(Math.random()); // Pretty much unpredictable. -// -// Math.random = rng1; // Continue "hello" prng sequence. -// document.write(Math.random()); // Always 0.554769432473455 -// -// Math.seedrandom(autoseed); // Restart at the previous seed. -// document.write(Math.random()); // Repeat the 'unpredictable' value. -// -// Notes: -// -// Each time seedrandom('arg') is called, entropy from the passed seed -// is accumulated in a pool to help generate future seeds for the -// zero-argument form of Math.seedrandom, so entropy can be injected over -// time by calling seedrandom with explicit data repeatedly. -// -// On speed - This javascript implementation of Math.random() is about -// 3-10x slower than the built-in Math.random() because it is not native -// code, but this is typically fast enough anyway. Seeding is more expensive, -// especially if you use auto-seeding. Some details (timings on Chrome 4): -// -// Our Math.random() - avg less than 0.002 milliseconds per call -// seedrandom('explicit') - avg less than 0.5 milliseconds per call -// seedrandom('explicit', true) - avg less than 2 milliseconds per call -// seedrandom() - avg about 38 milliseconds per call -// -// LICENSE (BSD): -// -// Copyright 2010 David Bau, 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. -// -// 3. Neither the name of this module nor the names of its contributors may -// be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER 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. -// -/** - * All code is in an anonymous closure to keep the global namespace clean. - * - * @param {number=} overflow - * @param {number=} startdenom - */ -(function (pool, math, width, chunks, significance, overflow, startdenom) -{ - - - // - // seedrandom() - // This is the seedrandom function described above. - // - math['seedrandom'] = function seedrandom(seed, use_entropy) - { - var key = []; - var arc4; - - // Flatten the seed string or build one from local entropy if needed. - seed = mixkey(flatten( - use_entropy ? [seed, pool] : arguments.length ? seed : [new Date().getTime(), pool, window], 3), key); - - // Use the seed to initialize an ARC4 generator. - arc4 = new ARC4(key); - - // Mix the randomness into accumulated entropy. - mixkey(arc4.S, pool); - - // Override Math.random - // This function returns a random double in [0, 1) that contains - // randomness in every bit of the mantissa of the IEEE 754 value. - math['random'] = function random() - { // Closure to return a random double: - var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48 - var d = startdenom; // and denominator d = 2 ^ 48. - var x = 0; // and no 'extra last byte'. - while (n < significance) - { // Fill up all significant digits by - n = (n + x) * width; // shifting numerator and - d *= width; // denominator and generating a - x = arc4.g(1); // new least-significant-byte. - } - while (n >= overflow) - { // To avoid rounding up, before adding - n /= 2; // last byte, shift everything - d /= 2; // right using integer math until - x >>>= 1; // we have exactly the desired bits. - } - return (n + x) / d; // Form the number within [0, 1). - }; - - // Return the seed that was used - return seed; - }; - - // - // ARC4 - // - // An ARC4 implementation. The constructor takes a key in the form of - // an array of at most (width) integers that should be 0 <= x < (width). - // - // The g(count) method returns a pseudorandom integer that concatenates - // the next (count) outputs from ARC4. Its return value is a number x - // that is in the range 0 <= x < (width ^ count). - // - /** @constructor */ - - function ARC4(key) - { - var t, u, me = this, - keylen = key.length; - var i = 0, - j = me.i = me.j = me.m = 0; - me.S = []; - me.c = []; - - // The empty key [] is treated as [0]. - if (!keylen) - { - key = [keylen++]; - } - - // Set up S using the standard key scheduling algorithm. - while (i < width) - { - me.S[i] = i++; - } - for (i = 0; i < width; i++) - { - t = me.S[i]; - j = lowbits(j + t + key[i % keylen]); - u = me.S[j]; - me.S[i] = u; - me.S[j] = t; - } - - // The "g" method returns the next (count) outputs as one number. - me.g = function getnext(count) - { - var s = me.S; - var i = lowbits(me.i + 1); - var t = s[i]; - var j = lowbits(me.j + t); - var u = s[j]; - s[i] = u; - s[j] = t; - var r = s[lowbits(t + u)]; - while (--count) - { - i = lowbits(i + 1); - t = s[i]; - j = lowbits(j + t); - u = s[j]; - s[i] = u; - s[j] = t; - r = r * width + s[lowbits(t + u)]; - } - me.i = i; - me.j = j; - return r; - }; - // For robust unpredictability discard an initial batch of values. - // See http://www.rsa.com/rsalabs/node.asp?id=2009 - me.g(width); - } - - // - // flatten() - // Converts an object tree to nested arrays of strings. - // - /** @param {Object=} result - * @param {string=} prop - * @param {string=} typ */ - - function flatten(obj, depth, result, prop, typ) - { - result = []; - typ = typeof (obj); - if (depth && typ == 'object') - { - for (prop in obj) - { - if (prop.indexOf('S') < 5) - { // Avoid FF3 bug (local/sessionStorage) - try - { - result.push(flatten(obj[prop], depth - 1)); - } - catch (e) - {} - } - } - } - return (result.length ? result : obj + (typ != 'string' ? '\0' : '')); - } - - // - // mixkey() - // Mixes a string seed into a key that is an array of integers, and - // returns a shortened string seed that is equivalent to the result key. - // - /** @param {number=} smear - * @param {number=} j */ - - function mixkey(seed, key, smear, j) - { - seed += ''; // Ensure the seed is a string - smear = 0; - for (j = 0; j < seed.length; j++) - { - key[lowbits(j)] = lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j)); - } - seed = ''; - for (j in key) - { - seed += String.fromCharCode(key[j]); - } - return seed; - } - - // - // lowbits() - // A quick "n mod width" for width a power of 2. - // - - - function lowbits(n) - { - return n & (width - 1); - } - - // - // The following constants are related to IEEE 754 limits. - // - startdenom = math.pow(width, chunks); - significance = math.pow(2, significance); - overflow = significance * 2; - - // - // When seedrandom.js is loaded, we immediately mix a few bits - // from the built-in RNG into the entropy pool. Because we do - // not want to intefere with determinstic PRNG state later, - // seedrandom will not call math.random on its own again after - // initialization. - // - mixkey(math.random(), pool); - - // End anonymous scope, and pass initial values. -})([], // pool: entropy pool starts empty -Math, // math: package containing random, pow, and seedrandom -256, // width: each RC4 output is 0 <= x < 256 -6, // chunks: at least six RC4 outputs for each double -52 // significance: there are 52 significant digits in a double -); - - -// This is not really a random number generator object, and two SeededRandom -// objects will conflict with one another, but it's good enough for generating -// the rsa key. -function SeededRandom(){} - -function SRnextBytes(ba) -{ - var i; - for(i = 0; i < ba.length; i++) - { - ba[i] = Math.floor(Math.random() * 256); - } -} - -SeededRandom.prototype.nextBytes = SRnextBytes; - -// prng4.js - uses Arcfour as a PRNG - -function Arcfour() { - this.i = 0; - this.j = 0; - this.S = new Array(); -} - -// Initialize arcfour context from key, an array of ints, each from [0..255] -function ARC4init(key) { - var i, j, t; - for(i = 0; i < 256; ++i) - this.S[i] = i; - j = 0; - for(i = 0; i < 256; ++i) { - j = (j + this.S[i] + key[i % key.length]) & 255; - t = this.S[i]; - this.S[i] = this.S[j]; - this.S[j] = t; - } - this.i = 0; - this.j = 0; -} - -function ARC4next() { - var t; - this.i = (this.i + 1) & 255; - this.j = (this.j + this.S[this.i]) & 255; - t = this.S[this.i]; - this.S[this.i] = this.S[this.j]; - this.S[this.j] = t; - return this.S[(t + this.S[this.i]) & 255]; -} - -Arcfour.prototype.init = ARC4init; -Arcfour.prototype.next = ARC4next; - -// Plug in your RNG constructor here -function prng_newstate() { - return new Arcfour(); -} - -// Pool size must be a multiple of 4 and greater than 32. -// An array of bytes the size of the pool will be passed to init() -var rng_psize = 256; - -// Random number generator - requires a PRNG backend, e.g. prng4.js - -// For best results, put code like -//
-// in your main HTML document. - -var rng_state; -var rng_pool; -var rng_pptr; - -// Mix in a 32-bit integer into the pool -function rng_seed_int(x) { - rng_pool[rng_pptr++] ^= x & 255; - rng_pool[rng_pptr++] ^= (x >> 8) & 255; - rng_pool[rng_pptr++] ^= (x >> 16) & 255; - rng_pool[rng_pptr++] ^= (x >> 24) & 255; - if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; -} - -// Mix in the current time (w/milliseconds) into the pool -function rng_seed_time() { - rng_seed_int(new Date().getTime()); -} - -// Initialize the pool with junk if needed. -if(rng_pool == null) { - rng_pool = new Array(); - 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) - rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; - } - while(rng_pptr < rng_psize) { // extract some randomness from Math.random() - t = Math.floor(65536 * Math.random()); - rng_pool[rng_pptr++] = t >>> 8; - rng_pool[rng_pptr++] = t & 255; - } - rng_pptr = 0; - rng_seed_time(); - //rng_seed_int(window.screenX); - //rng_seed_int(window.screenY); -} - -function rng_get_byte() { - if(rng_state == null) { - rng_seed_time(); - rng_state = prng_newstate(); - rng_state.init(rng_pool); - for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) - rng_pool[rng_pptr] = 0; - rng_pptr = 0; - //rng_pool = null; - } - // TODO: allow reseeding after first request - return rng_state.next(); -} - -function rng_get_bytes(ba) { - var i; - for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); -} - -function SecureRandom() {} - -SecureRandom.prototype.nextBytes = rng_get_bytes; - - - - - - - -/** -* -* Secure Hash Algorithm (SHA256) -* http://www.webtoolkit.info/ -* -* Original code by Angel Marin, Paul Johnston. -* -**/ - -function SHA256(s){ - - var chrsz = 8; - var hexcase = 0; - - function safe_add (x, y) { - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 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; - - m[l >> 5] |= 0x80 << (24 - l % 32); - m[((l + 64 >> 9) << 4) + 15] = l; - - for ( var i = 0; i=0;){var S=s[--d]==l?this.DM:Math.floor(s[d]*v+(s[d-1]+y)*m);if((s[d]+=e.am(0,S,s,D,0,p)) >(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 (this.s<0)?-r: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< >(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<0&&s.rShiftTo(a,s),0>u&&i.ZERO.subTo(s,s)}}}function R(t){var o=r();return this.abs().divRemTo(t,null,o),this.s<0&&o.compareTo(i.ZERO)>0&&t.subTo(o,o),o}function A(t){this.m=t}function V(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function x(t){return t}function O(t){t.divRemTo(this.m,null,t)}function q(t,i,r){t.multiplyTo(i,r),this.reduce(r)}function F(t,i){t.squareTo(i),this.reduce(i)}function I(){if(this.t<1)return 0;var t=this[0];if(0==(1&t))return 0;var i=3&t;return i=i*(2-(15&t)*i)&15,i=i*(2-(255&t)*i)&255,i=i*(2-((65535&t)*i&65535))&65535,i=i*(2-t*i%this.DV)%this.DV,i>0?this.DV-i:-i}function Z(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<