зеркало из
1
0
Форкнуть 0
This commit is contained in:
Braintree 2011-06-07 16:46:50 -05:00
Коммит 46261b467e
64 изменённых файлов: 14858 добавлений и 0 удалений

2
.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,2 @@
/target
/spec/SpecRunner.html

61
README.md Normal file
Просмотреть файл

@ -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
<head>
<script src="/javascripts/braintree-0.1.0.min.js" type="text/javascript"></script>
</head>
```
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.

95
Rakefile Normal file
Просмотреть файл

@ -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"]

3
build/bundle_footer.js Normal file
Просмотреть файл

@ -0,0 +1,3 @@
return Braintree;
})();

1
build/bundle_header.js Normal file
Просмотреть файл

@ -0,0 +1 @@
Braintree = (function () {

205
build/jsmin.rb Normal file
Просмотреть файл

@ -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

14
build/minified_header.js Normal file
Просмотреть файл

@ -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 <www.pidder.com>
* 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.
*/

54
lib/braintree.js Normal file
Просмотреть файл

@ -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'
};
};

417
lib/pidCrypt/aes_cbc.js Normal file
Просмотреть файл

@ -0,0 +1,417 @@
/*----------------------------------------------------------------------------*/
// Copyright (c) 2009 pidder <www.pidder.com>
// 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<miter; j++){
if(j == 0)
result = data00; //initialize
else {
hashtarget = pidCryptUtil.convertFromHex(result);
hashtarget += data00;
result = hashtarget;
}
for(var c=0; c<count; c++){
result = pidCrypt.MD5(result);
}
keymaterial[loop++] = result;
}
switch(pObj.bits){
case 128://128 bit
retObj.key = keymaterial[1];
retObj.iv = keymaterial[2];
break;
case 192://192 bit
retObj.key = keymaterial[1] + keymaterial[2].substr(0,16);
retObj.iv = keymaterial[3];
break;
case 256://256 bit
retObj.key = keymaterial[1] + keymaterial[2];
retObj.iv = keymaterial[3];
break;
default:
pidcrypt.appendError('pidCrypt.AES.CBC.createKeyAndIv: Sorry, only 128, 192 and 256 bits are supported.\nBits('+typeof(pObj.bits)+') = '+pObj.bits);
}
return retObj;
}
/**
* Encrypt a text using AES encryption in CBC mode of operation
* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
*
* one of the pidCrypt.AES.CBC init funtions must be called before execution
*
* @param byteArray: text to encrypt as array of bytes
*
* @return aes-cbc encrypted text
*/
pidCrypt.AES.CBC.prototype.encryptRaw = function(byteArray) {
var pidcrypt = this.pidcrypt;
var aes = this.aes;
var p = pidcrypt.getParams(); //get parameters for operation set by init
if(!byteArray)
byteArray = p.encryptIn;
pidcrypt.setParams({encryptIn: byteArray});
if(!p.dataIn) pidcrypt.setParams({dataIn:byteArray});
var iv = pidCryptUtil.convertFromHex(p.iv);
//PKCS5 paddding
var charDiv = p.blockSize - ((byteArray.length+1) % p.blockSize);
if(p.A0_PAD) {
byteArray[byteArray.length] = 10
} else {
// charDiv += 1;
}
for(var c=0;c<charDiv;c++) byteArray[byteArray.length] = charDiv;
var nBytes = Math.floor(p.nBits/8); // nr of bytes in key
var keyBytes = new Array(nBytes);
var key = pidCryptUtil.convertFromHex(p.key);
for (var i=0; i<nBytes; i++) {
keyBytes[i] = isNaN(key.charCodeAt(i)) ? 0 : key.charCodeAt(i);
}
// generate key schedule
var keySchedule = aes.expandKey(keyBytes);
var blockCount = Math.ceil(byteArray.length/p.blockSize);
var ciphertxt = new Array(blockCount); // ciphertext as array of strings
var textBlock = [];
var state = pidCryptUtil.toByteArray(iv);
for (var b=0; b<blockCount; b++) {
// XOR last block and next data block, then encrypt that
textBlock = byteArray.slice(b*p.blockSize, b*p.blockSize+p.blockSize);
state = aes.xOr_Array(state, textBlock);
state = aes.encrypt(state.slice(), keySchedule); // -- encrypt block --
ciphertxt[b] = pidCryptUtil.byteArray2String(state);
}
var ciphertext = ciphertxt.join('');
pidcrypt.setParams({dataOut:ciphertext, encryptOut:ciphertext});
//remove all parameters from enviroment for more security is debug off
if(!pidcrypt.isDebug() && pidcrypt.clear) pidcrypt.clearParams();
return ciphertext || '';
}
/**
* Encrypt a text using AES encryption in CBC mode of operation
* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
*
* Unicode multi-byte character safe
*
* one of the pidCrypt.AES.CBC init funtions must be called before execution
*
* @param plaintext: text to encrypt
*
* @return aes-cbc encrypted text openssl compatible
*/
pidCrypt.AES.CBC.prototype.encrypt = function(plaintext) {
var pidcrypt = this.pidcrypt;
var salt = '';
var p = pidcrypt.getParams(); //get parameters for operation set by init
if(!plaintext)
plaintext = p.dataIn;
if(p.UTF8)
plaintext = pidCryptUtil.encodeUTF8(plaintext);
pidcrypt.setParams({dataIn:plaintext, encryptIn: pidCryptUtil.toByteArray(plaintext)});
var ciphertext = this.encryptRaw()
salt = 'Salted__' + pidCryptUtil.convertFromHex(p.salt);
ciphertext = salt + ciphertext;
ciphertext = pidCryptUtil.encodeBase64(ciphertext); // encode in base64
pidcrypt.setParams({dataOut:ciphertext});
//remove all parameters from enviroment for more security is debug off
if(!pidcrypt.isDebug() && pidcrypt.clear) pidcrypt.clearParams();
return ciphertext || '';
}
/**
* Encrypt a text using AES encryption in CBC mode of operation
* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
*
* Unicode multi-byte character safe
*
* @param dataIn: plain text
* @param password: String
* @param options {
* nBits: aes bit size (128, 192 or 256)
* }
*
* @param plaintext: text to encrypt
*
* @return aes-cbc encrypted text openssl compatible
*
*/
pidCrypt.AES.CBC.prototype.encryptText = function(dataIn,password,options) {
this.initEncrypt(dataIn, password, options);
return this.encrypt();
}
/**
* Decrypt a text encrypted by AES in CBC mode of operation
*
* one of the pidCrypt.AES.CBC init funtions must be called before execution
*
* @param byteArray: aes-cbc encrypted text as array of bytes
*
* @return decrypted text as String
*/
pidCrypt.AES.CBC.prototype.decryptRaw = 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.decryptIn;
pidcrypt.setParams({decryptIn: byteArray});
if(!p.dataIn) pidcrypt.setParams({dataIn:byteArray});
if((p.iv.length/2)<p.blockSize)
return pidcrypt.appendError('pidCrypt.AES.CBC.decrypt: Sorry, can not decrypt without complete set of parameters.\n Length of key,iv:'+p.key.length+','+p.iv.length);
var iv = pidCryptUtil.convertFromHex(p.iv);
if(byteArray.length%p.blockSize != 0)
return pidcrypt.appendError('pidCrypt.AES.CBC.decrypt: Sorry, the encrypted text has the wrong length for aes-cbc mode\n Length of ciphertext:'+byteArray.length+byteArray.length%p.blockSize);
var nBytes = Math.floor(p.nBits/8); // nr of bytes in key
var keyBytes = new Array(nBytes);
var key = pidCryptUtil.convertFromHex(p.key);
for (var i=0; i<nBytes; i++) {
keyBytes[i] = isNaN(key.charCodeAt(i)) ? 0 : key.charCodeAt(i);
}
// generate key schedule
var keySchedule = aes.expandKey(keyBytes);
// separate byteArray into blocks
var nBlocks = Math.ceil((byteArray.length) / p.blockSize);
// plaintext will get generated block-by-block into array of block-length strings
var plaintxt = new Array(nBlocks.length);
var state = pidCryptUtil.toByteArray(iv);
var ciphertextBlock = [];
var dec_state = [];
for (var b=0; b<nBlocks; b++) {
ciphertextBlock = byteArray.slice(b*p.blockSize, b*p.blockSize+p.blockSize);
dec_state = aes.decrypt(ciphertextBlock, keySchedule); // decrypt ciphertext block
plaintxt[b] = pidCryptUtil.byteArray2String(aes.xOr_Array(state, dec_state));
state = ciphertextBlock.slice(); //save old ciphertext for next round
}
// join array of blocks into single plaintext string and return it
var plaintext = plaintxt.join('');
if(pidcrypt.isDebug()) pidcrypt.appendDebug('Padding after decryption:'+ pidCryptUtil.convertToHex(plaintext) + ':' + plaintext.length + '\n');
var endByte = plaintext.charCodeAt(plaintext.length-1);
//remove oppenssl A0 padding eg. 0A05050505
if(p.A0_PAD){
plaintext = plaintext.substr(0,plaintext.length-(endByte+1));
}
else {
var div = plaintext.length - (plaintext.length-endByte);
var firstPadByte = plaintext.charCodeAt(plaintext.length-endByte);
if(endByte == firstPadByte && endByte == div)
plaintext = plaintext.substr(0,plaintext.length-endByte);
}
pidcrypt.setParams({dataOut: plaintext,decryptOut: plaintext});
//remove all parameters from enviroment for more security is debug off
if(!pidcrypt.isDebug() && pidcrypt.clear) pidcrypt.clearParams();
return plaintext || '';
}
/**
* Decrypt a base64 encoded text encrypted by AES in CBC mode of operation
* and removes padding from decrypted text
*
* one of the pidCrypt.AES.CBC init funtions must be called before execution
*
* @param ciphertext: base64 encoded and aes-cbc encrypted text
*
* @return decrypted text as String
*/
pidCrypt.AES.CBC.prototype.decrypt = function(ciphertext) {
var pidcrypt = this.pidcrypt;
var p = pidcrypt.getParams(); //get parameters for operation set by init
if(ciphertext)
pidcrypt.setParams({dataIn:ciphertext});
if(!p.decryptIn) {
var decryptIn = pidCryptUtil.decodeBase64(p.dataIn);
if(decryptIn.indexOf('Salted__') == 0) decryptIn = decryptIn.substr(16);
pidcrypt.setParams({decryptIn: pidCryptUtil.toByteArray(decryptIn)});
}
var plaintext = this.decryptRaw();
if(p.UTF8)
plaintext = pidCryptUtil.decodeUTF8(plaintext); // decode from UTF8 back to Unicode multi-byte chars
if(pidcrypt.isDebug()) pidcrypt.appendDebug('Removed Padding after decryption:'+ pidCryptUtil.convertToHex(plaintext) + ':' + plaintext.length + '\n');
pidcrypt.setParams({dataOut:plaintext});
//remove all parameters from enviroment for more security is debug off
if(!pidcrypt.isDebug() && pidcrypt.clear) pidcrypt.clearParams();
return plaintext || '';
}
/**
* Decrypt a base64 encoded text encrypted by AES in CBC mode of operation
* and removes padding from decrypted text
*
* one of the pidCrypt.AES.CBC init funtions must be called before execution
*
* @param dataIn: base64 encoded aes encrypted text
* @param password: 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
* }
*
* @return decrypted text as String
*/
pidCrypt.AES.CBC.prototype.decryptText = function(dataIn, password, options) {
this.initDecrypt(dataIn, password, options);
return this.decrypt();
}
}

239
lib/pidCrypt/aes_core.js Normal file
Просмотреть файл

@ -0,0 +1,239 @@
/*!Copyright (c) 2009 pidder <www.pidder.com>*/
/*----------------------------------------------------------------------------*/
// 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<a1.length; i++ )
res[i] = a1[i] ^ a2[i];
return res;
}
pidCrypt.AES.prototype.getCounterBlock = function(){
// 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(this.blockSize);
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 (var i=0; i<4; i++) ctrBlk[i+4] = nonceMs & 0xff;
return ctrBlk.slice();
}
}

335
lib/pidCrypt/aes_ctr.js Normal file
Просмотреть файл

@ -0,0 +1,335 @@
/*----------------------------------------------------------------------------*/
// Copyright (c) 2009 pidder <www.pidder.com>
// 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<nBytes; i++)
pwBytes[i] = isNaN(password.charCodeAt(i)) ? 0 : password.charCodeAt(i);
var key = aes.encrypt(pwBytes.slice(0,16), aes.expandKey(pwBytes)); // gives us 16-byte key
key = key.concat(key.slice(0, nBytes-16)); // expand key to 16/24/32 bytes long
var counterBlock = this.getCounterBlock(p.blockSize);
// and convert it to a string to go on the front of the ciphertext
var ctrTxt = pidCryptUtil.byteArray2String(counterBlock.slice(0,8));
pidcrypt.setParams({salt:pidCryptUtil.convertToHex(ctrTxt)});
// generate key schedule - an expansion of the key into distinct Key Rounds
// for each round
var keySchedule = aes.expandKey(key);
var blockCount = Math.ceil(byteArray.length/p.blockSize);
var ciphertxt = new Array(blockCount); // ciphertext as array of strings
for (var b=0; b<blockCount; b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
// done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB)
for (var c=0; c<4; c++) counterBlock[15-c] = (b >>> 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<blockCount-1 ? p.blockSize : (byteArray.length-1)%p.blockSize+1;
var cipherChar = new Array(blockLength);
for (var i=0; i<blockLength; i++) { // -- xor plaintext with ciphered counter char-by-char --
cipherChar[i] = cipherCntr[i] ^ byteArray[b*p.blockSize+i];
cipherChar[i] = String.fromCharCode(cipherChar[i]);
}
ciphertxt[b] = cipherChar.join('');
}
// alert(pidCryptUtil.encodeBase64(ciphertxt.join('')));
// Array.join is more efficient than repeated string concatenation
var ciphertext = ctrTxt + ciphertxt.join('');
pidcrypt.setParams({dataOut:ciphertext, encryptOut:ciphertext});
//remove all parameters from enviroment for more security is debug off
if(!pidcrypt.isDebug() && pidcrypt.clear) pidcrypt.clearParams();
return ciphertext;
}
/**
* 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
*
* Unicode multi-byte character safe
*
*
* @param plaintext: text to encrypt
*
*
* @return encrypted text
*/
pidCrypt.AES.CTR.prototype.encrypt = function(plaintext) {
var pidcrypt = this.pidcrypt;
var p = pidcrypt.getParams(); //get parameters for operation set by init
if(!plaintext)
plaintext = p.dataIn;
if(p.UTF8){
plaintext = pidCryptUtil.encodeUTF8(plaintext);
pidcrypt.setParams({key:pidCryptUtil.encodeUTF8(pidcrypt.getParam('key'))});
}
pidcrypt.setParams({dataIn:plaintext, encryptIn: pidCryptUtil.toByteArray(plaintext)});
var ciphertext = this.encryptRaw();
ciphertext = pidCryptUtil.encodeBase64(ciphertext); // encode in base64
pidcrypt.setParams({dataOut:ciphertext});
//remove all parameters from enviroment for more security is debug off
if(!pidcrypt.isDebug() && pidcrypt.clear) pidcrypt.clearParams();
return ciphertext;
}
/**
* 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
*
* Unicode multi-byte character safe
*
* @param dataIn: plain text
* @param password: String
* @param options {
* nBits: aes bit size (128, 192 or 256)
* }
*
* @return encrypted text
*/
pidCrypt.AES.CTR.prototype.encryptText = function(dataIn, password, options) {
this.initEncrypt(dataIn, password, options);
return this.encrypt();
}
/**
* Decrypt a text encrypted by AES in CTR mode of operation
*
* one of the pidCrypt.AES.CTR init funtions must be called before execution
*
* @param ciphertext: text to decrypt
*
* @return decrypted text as String
*/
pidCrypt.AES.CTR.prototype.decryptRaw = function(byteArray) {
var pidcrypt = this.pidcrypt;
var aes = this.aes;
var p = pidcrypt.getParams(); //get parameters for operation set by init
if(!byteArray)
byteArray = p.decryptIn;
pidcrypt.setParams({decryptIn:byteArray});
if(!p.dataIn) pidcrypt.setParams({dataIn:byteArray});
// use AES to encrypt password (mirroring encrypt routine)
var nBytes = Math.floor(p.nBits/8); // no bytes in key
var pwBytes = new Array(nBytes);
for (var i=0; i<nBytes; i++) {
pwBytes[i] = isNaN(p.key.charCodeAt(i)) ? 0 : p.key.charCodeAt(i);
}
var key = aes.encrypt(pwBytes.slice(0,16), aes.expandKey(pwBytes)); // gives us 16-byte key
key = key.concat(key.slice(0, nBytes-16)); // expand key to 16/24/32 bytes long
var counterBlock = new Array(8);
var ctrTxt = pidCryptUtil.convertFromHex(p.salt);
for (i=0; i<8; i++) counterBlock[i] = ctrTxt.charCodeAt(i);
// generate key schedule
var keySchedule = aes.expandKey(key);
// separate ciphertext into blocks (skipping past initial 8 bytes)
var nBlocks = Math.ceil((byteArray.length) / p.blockSize);
var blockArray = new Array(nBlocks);
for (var b=0; b<nBlocks; b++) blockArray[b] = byteArray.slice(b*p.blockSize, b*p.blockSize+p.blockSize);
// plaintext will get generated block-by-block into array of block-length
// strings
var plaintxt = new Array(blockArray.length);
var cipherCntr = [];
var plaintxtByte = [];
for (b=0; b<nBlocks; b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
for (var c=0; c<4; c++) counterBlock[15-c] = ((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<blockArray[b].length; i++) {
// -- xor plaintxt with ciphered counter byte-by-byte --
plaintxtByte[i] = cipherCntr[i] ^ blockArray[b][i];
plaintxtByte[i] = String.fromCharCode(plaintxtByte[i]);
}
plaintxt[b] = plaintxtByte.join('');
}
// join array of blocks into single plaintext string
var plaintext = plaintxt.join('');
pidcrypt.setParams({dataOut:plaintext});
//remove all parameters from enviroment for more security is debug off
if(!pidcrypt.isDebug() && pidcrypt.clear) pidcrypt.clearParams();
return plaintext;
}
/**
* Decrypt a text encrypted by AES in CTR mode of operation
*
* one of the pidCrypt.AES.CTR init funtions must be called before execution
*
* @param ciphertext: text to decrypt
*
* @return decrypted text as String
*/
pidCrypt.AES.CTR.prototype.decrypt = function(ciphertext) {
var pidcrypt = this.pidcrypt;
var p = pidcrypt.getParams(); //get parameters for operation set by init
if(ciphertext)
pidcrypt.setParams({dataIn:ciphertext, decryptIn: pidCryptUtil.toByteArray(ciphertext)});
if(p.UTF8){
pidcrypt.setParams({key:pidCryptUtil.encodeUTF8(pidcrypt.getParam('key'))});
}
var plaintext = this.decryptRaw();
plaintext = pidCryptUtil.decodeUTF8(plaintext); // decode from UTF8 back to Unicode multi-byte chars
pidcrypt.setParams({dataOut:plaintext});
//remove all parameters from enviroment for more security is debug off
if(!pidcrypt.isDebug() && pidcrypt.clear) pidcrypt.clearParams();
return plaintext;
}
/**
* Decrypt a text encrypted by AES in CTR mode of operation
*
* one of the pidCrypt.AES.CTR init funtions must be called before execution
*
* @param crypted: base64 encrypted text
* @param password: String
* @param options {
*
* @return decrypted text as String
*/
pidCrypt.AES.CTR.prototype.decryptText = function(crypted, password, options) {
this.initDecrypt(crypted, password, options);
return this.decrypt();
}
}

494
lib/pidCrypt/asn1.js Normal file
Просмотреть файл

@ -0,0 +1,494 @@
/*----------------------------------------------------------------------------*/
// Copyright (c) 2009 pidder <www.pidder.com>
// 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 <lapo@lapo.it>
// 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 + "<br/>";
s += "Length: " + this.header + "+";
if (this.length >= 0)
s += this.length;
else
s += (-this.length) + " (undefined)";
if (this.tag & 0x20)
s += "<br/>(constructed)";
else if (((this.tag == 0x03) || (this.tag == 0x04)) && (this.sub != null))
s += "<br/>(encapsulates)";
var content = this.content();
if (content != null) {
s += "<br/>Value:<br/><b>" + content + "</b>";
if ((typeof(oids) == 'object') && (this.tag == 0x06)) {
var oid = oids[content];
if (oid) {
if (oid.d) s += "<br/>" + oid.d;
if (oid.c) s += "<br/>" + oid.c;
if (oid.w) s += "<br/>(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");
}
}
}

675
lib/pidCrypt/gpl-3.0.txt Normal file
Просмотреть файл

@ -0,0 +1,675 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

119
lib/pidCrypt/history.txt Normal file
Просмотреть файл

@ -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

1232
lib/pidCrypt/jsbn.js Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

185
lib/pidCrypt/md5.js Normal file
Просмотреть файл

@ -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<<iShiftBits) | (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)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>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<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=GG(d,a,b,c,x[k+10],S22,0x2441453);
c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=II(a,b,c,d,x[k+0], S41,0xF4292244);
d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=II(c,d,a,b,x[k+6], S43,0xA3014314);
b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
a=AddUnsigned(a,AA);
b=AddUnsigned(b,BB);
c=AddUnsigned(c,CC);
d=AddUnsigned(d,DD);
}
var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
return temp.toLowerCase();
}
}

1578
lib/pidCrypt/oids.js Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

212
lib/pidCrypt/pidcrypt.js Normal file
Просмотреть файл

@ -0,0 +1,212 @@
/*!Copyright (c) 2009 pidder <www.pidder.com>*/
// 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;i<bytes.length;i++)
bytes[i] = field[Math.floor(Math.random()*field.length)];
return bytes
}
this.setDefaults = function(){
this.params.nBits = 256;
//salt should always be a Hex String e.g. AD0E76FF6535AD...
this.params.salt = getRandomBytes(8);
this.params.salt = pidCryptUtil.byteArray2String(this.params.salt);
this.params.salt = pidCryptUtil.convertToHex(this.params.salt);
this.params.blockSize = 16;
this.params.UTF8 = true;
this.params.A0_PAD = true;
}
this.debug = true;
this.params = {};
//setting default values for params
this.params.dataIn = '';
this.params.dataOut = '';
this.params.decryptIn = '';
this.params.decryptOut = '';
this.params.encryptIn = '';
this.params.encryptOut = '';
//key should always be a Hex String e.g. AD0E76FF6535AD...
this.params.key = '';
//iv should always be a Hex String e.g. AD0E76FF6535AD...
this.params.iv = '';
this.params.clear = true;
this.setDefaults();
this.errors = '';
this.warnings = '';
this.infos = '';
this.debugMsg = '';
//set and get methods for base class
this.setParams = function(pObj){
if(!pObj) pObj = {};
for(var p in pObj)
this.params[p] = pObj[p];
}
this.getParams = function(){
return this.params;
}
this.getParam = function(p){
return this.params[p] || '';
}
this.clearParams = function(){
this.params= {};
}
this.getNBits = function(){
return this.params.nBits;
}
this.getOutput = function(){
return this.params.dataOut;
}
this.setError = function(str){
this.error = str;
}
this.appendError = function(str){
this.errors += str;
return '';
}
this.getErrors = function(){
return this.errors;
}
this.isError = function(){
if(this.errors.length>0)
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><b>'+p+'</b>:<pre>' + tmp + '</pre></p>';
}
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
}

Просмотреть файл

@ -0,0 +1,347 @@
/*----------------------------------------------------------------------------*/
// Copyright (c) 2009 pidder <www.pidder.com>
// 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<plain.length; c+=3) { // pack three octets into four hexets
o1 = plain.charCodeAt(c);
o2 = plain.charCodeAt(c+1);
o3 = plain.charCodeAt(c+2);
bits = o1<<16 | o2<<8 | o3;
h1 = bits>>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<coded.length; c+=4) { // unpack four hexets into three octets
h1 = b64.indexOf(coded.charAt(c));
h2 = b64.indexOf(coded.charAt(c+1));
h3 = b64.indexOf(coded.charAt(c+2));
h4 = b64.indexOf(coded.charAt(c+3));
bits = h1<<18 | h2<<12 | h3<<6 | h4;
o1 = bits>>>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<str.length; i++) {
hv = str.charCodeAt(i).toString(16);
hs += (hv.length == 1) ? '0'+hv : hv;
}
return hs;
}
/**
* Converts a hex string into a string
* returns the characters of a hex string to their char of charcode
*
* @return hex string e.g. "68656c6c6f20776f726c64" => "hello world"
*/
pidCryptUtil.convertFromHex = function(str){
if(!str) str = "";
var s = "";
for(var i= 0;i<str.length;i+=2){
s += String.fromCharCode(parseInt(str.substring(i,i+2),16));
}
return s
}
/**
* strips off all linefeeds from a string
* returns the the strong without line feeds
*
* @return string
*/
pidCryptUtil.stripLineFeeds = function(str){
if(!str) str = "";
// var re = RegExp(String.fromCharCode(13),'g');//\r
// var re = RegExp(String.fromCharCode(10),'g');//\n
var s = '';
s = str.replace(/\n/g,'');
s = s.replace(/\r/g,'');
return s;
}
/**
* Converts a string into an array of char code bytes
* returns the characters of a hex string to their char of charcode
*
* @return hex string e.g. "68656c6c6f20776f726c64" => "hello world"
*/
pidCryptUtil.toByteArray = function(str){
if(!str) str = "";
var ba = [];
for(var i=0;i<str.length;i++)
ba[i] = str.charCodeAt(i);
return ba;
}
/**
* Fragmentize a string into lines adding a line feed (lf) every length
* characters
*
* @return string e.g. length=3 "abcdefghi" => "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<str.length;i+=length)
tmp += str.substr(i,length) + lf;
return tmp;
}
/**
* Formats a hex string in two lower case chars + : and lines of given length
* characters
*
* @return string e.g. "68656C6C6F20" => "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<hex.length;i+=2)
str_new += hex.substr(i,2) +':';
hex = this.fragment(str_new,length);
return hex;
}
/*----------------------------------------------------------------------------*/
/* End of intance methods of the String object */
/*----------------------------------------------------------------------------*/
pidCryptUtil.byteArray2String = function(b){
// var out ='';
var s = '';
for(var i=0;i<b.length;i++){
s += String.fromCharCode(b[i]);
// out += b[i]+':';
}
// alert(out);
return s;
}

47
lib/pidCrypt/prng4.js Normal file
Просмотреть файл

@ -0,0 +1,47 @@
// Author: Tom Wu
// tjw@cs.Stanford.EDU
// 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;

73
lib/pidCrypt/rng.js Normal file
Просмотреть файл

@ -0,0 +1,73 @@
// Author: Tom Wu
// tjw@cs.Stanford.EDU
// Random number generator - requires a PRNG backend, e.g. prng4.js
// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// 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();
}
}

373
lib/pidCrypt/rsa.js Normal file
Просмотреть файл

@ -0,0 +1,373 @@
/*----------------------------------------------------------------------------*/
// Copyright (c) 2009 pidder <www.pidder.com>
// 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 +'<BR>');
}
// 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<tree.sub.length;i++)
data = data.concat(this.getASNData(tree.sub[i]));
return data;
}
//
//
//get parameters from ASN1 structure object created from pidCrypt.ASN1.toHexTree
//e.g. A RSA Public Key gives the ASN structure object:
// {
// SEQUENCE:
// {
// INTEGER: modulus,
// INTEGER: public exponent
// }
//}
pidCrypt.RSA.prototype.setKeyFromASN = function(key,asntree) {
var keys = ['N','E','D','P','Q','DP','DQ','C'];
var params = {};
var asnData = this.getASNData(asntree);
switch(key){
case 'Public':
case 'public':
for(var i=0;i<asnData.length;i++)
params[keys[i]] = asnData[i].toLowerCase();
this.setPublic(params.N,params.E,16);
break;
case 'Private':
case 'private':
for(var i=1;i<asnData.length;i++)
params[keys[i-1]] = asnData[i].toLowerCase();
this.setPrivateEx(params.N,params.E,params.D,params.P,params.Q,params.DP,params.DQ,params.C,16);
// this.setPrivate(params.N,params.E,params.D);
break;
}
}
/**
* Init RSA Encryption with public key.
* @param asntree: ASN1 structure object created from pidCrypt.ASN1.toHexTree
*/
pidCrypt.RSA.prototype.setPublicKeyFromASN = function(asntree) {
this.setKeyFromASN('public',asntree);
}
/**
* Init RSA Encryption with private key.
* @param asntree: ASN1 structure object created from pidCrypt.ASN1.toHexTree
*/
pidCrypt.RSA.prototype.setPrivateKeyFromASN = function(asntree) {
this.setKeyFromASN('private',asntree);
}
/**
* gets the current paramters as object.
* @return params: object with RSA parameters
*/
pidCrypt.RSA.prototype.getParameters = function() {
var params = {}
if(this.n != null) params.n = this.n;
params.e = this.e;
if(this.d != null) params.d = this.d;
if(this.p != null) params.p = this.p;
if(this.q != null) params.q = this.q;
if(this.dmp1 != null) params.dmp1 = this.dmp1;
if(this.dmq1 != null) params.dmq1 = this.dmq1;
if(this.coeff != null) params.c = this.coeff;
return params;
}
//pidCrypt extensions end
}

152
lib/pidCrypt/sha1.js Normal file
Просмотреть файл

@ -0,0 +1,152 @@
/**
*
* SHA1 (Secure Hash Algorithm) for use in pidCrypt Library
* Depends on pidCrypt (pidcrypt.js, pidcrypt_util.js)
*
* For original source see http://www.webtoolkit.info/
* Download: 02.03.2009 from http://www.webtoolkit.info/javascript-sha1.html
**/
if(typeof(pidCrypt) != 'undefined') {
pidCrypt.SHA1 = function(msg) {
function rotate_left(n,s) {
var t4 = ( n<<s ) | (n>>>(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<msg_len-3; i+=4 ) {
j = msg.charCodeAt(i)<<24 | msg.charCodeAt(i+1)<<16 |
msg.charCodeAt(i+2)<<8 | msg.charCodeAt(i+3);
word_array.push( j );
}
switch( msg_len % 4 ) {
case 0:
i = 0x080000000;
break;
case 1:
i = msg.charCodeAt(msg_len-1)<<24 | 0x0800000;
break;
case 2:
i = msg.charCodeAt(msg_len-2)<<24 | msg.charCodeAt(msg_len-1)<<16 | 0x08000;
break;
case 3:
i = msg.charCodeAt(msg_len-3)<<24 | msg.charCodeAt(msg_len-2)<<16 | msg.charCodeAt(msg_len-1)<<8 | 0x80;
break;
}
word_array.push( i );
while( (word_array.length % 16) != 14 ) word_array.push( 0 );
word_array.push( msg_len>>>29 );
word_array.push( (msg_len<<3)&0x0ffffffff );
for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {
for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
A = H0;
B = H1;
C = H2;
D = H3;
E = H4;
for( i= 0; i<=19; i++ ) {
temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=20; i<=39; i++ ) {
temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=40; i<=59; i++ ) {
temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=60; i<=79; i++ ) {
temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
H0 = (H0 + A) & 0x0ffffffff;
H1 = (H1 + B) & 0x0ffffffff;
H2 = (H2 + C) & 0x0ffffffff;
H3 = (H3 + D) & 0x0ffffffff;
H4 = (H4 + E) & 0x0ffffffff;
}
var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
return temp.toLowerCase();
}
}

81
lib/pidCrypt/sha256.js Normal file
Просмотреть файл

@ -0,0 +1,81 @@
/**
*
* SHA256 (Secure Hash Algorithm) for use in pidCrypt Library
* Depends on pidCrypt (pidcrypt.js, pidcrypt_util.js)
*
* For original source see http://anmar.eu.org/projects/jssha2/
* Download: 09.06.2009 from http://anmar.eu.org/projects/jssha2/
*
**/
/* A JavaScript implementation of the Secure Hash Algorithm, SHA-256
* Version 0.3 Copyright Angel Marin 2003-2004 - http://anmar.eu.org/
* Distributed under the BSD License
* Some bits taken from Paul Johnston's SHA-1 implementation
*/
if(typeof(pidCrypt) != 'undefined') {
pidCrypt.SHA256 = function(s) {
/* A JavaScript implementation of the Secure Hash Algorithm, SHA-256
* Version 0.3 Copyright Angel Marin 2003-2004 - http://anmar.eu.org/
* Distributed under the BSD License
* Some bits taken from Paul Johnston's SHA-1 implementation
*/
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
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;
/* append padding */
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >> 9) << 4) + 15] = l;
for ( var i = 0; i<m.length; i+=16 ) {
a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7];
for ( var j = 0; j<64; j++) {
if (j < 16) W[j] = m[j + i];
else W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
T2 = safe_add(Sigma0256(a), Maj(a, b, c));
h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2);
}
HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]); HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]);
}
return HASH;
}
function str2binb (str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[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));
}
}

276
lib/pidCrypt/sha512.js Normal file
Просмотреть файл

@ -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<length;i += jsSHA.charSize)
{
bin[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<length;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;
};
var binb2b64=function(binarray)
{
var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str="";
var length=binarray.length*4;
for(var i=0;i<length;i += 3)
{
var triplet =(((binarray[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<appendedMessageLength;i += 32)
{
a=H[0];
b=H[1];
c=H[2];
d=H[3];
e=H[4];
f=H[5];
g=H[6];
h=H[7];
for(var t=0;t<80;t++)
{
if(t<16)
{
W[t]=new Int_64(message[t*2+i],message[t*2+i+1]);
}
else
{
W[t]=safeAdd(safeAdd(safeAdd(gamma1(W[t-2]),W[t-7]),gamma0(W[t-15])),W[t-16]);
}
T1=safeAdd(safeAdd(safeAdd(safeAdd(h,sigma1(e)),ch(e,f,g)),K[t]),W[t]);
T2=safeAdd(sigma0(a),maj(a,b,c));
h=g;
g=f;
f=e;
e=safeAdd(d,T1);
d=c;
c=b;
b=a;
a=safeAdd(T1,T2);
}
H[0]=safeAdd(a,H[0]);
H[1]=safeAdd(b,H[1]);
H[2]=safeAdd(c,H[2]);
H[3]=safeAdd(d,H[3]);
H[4]=safeAdd(e,H[4]);
H[5]=safeAdd(f,H[5]);
H[6]=safeAdd(g,H[6]);
H[7]=safeAdd(h,H[7]);
}
switch(variant)
{
case "SHA-384":
return[H[0].highOrder,H[0].lowOrder,H[1].highOrder,H[1].lowOrder,H[2].highOrder,H[2].lowOrder,H[3].highOrder,H[3].lowOrder,H[4].highOrder,H[4].lowOrder,H[5].highOrder,H[5].lowOrder];
case "SHA-512":
return[H[0].highOrder,H[0].lowOrder,H[1].highOrder,H[1].lowOrder,H[2].highOrder,H[2].lowOrder,H[3].highOrder,H[3].lowOrder,H[4].highOrder,H[4].lowOrder,H[5].highOrder,H[5].lowOrder,H[6].highOrder,H[6].lowOrder,H[7].highOrder,H[7].lowOrder];
default:return [];
}
};
this.getHash=function(variant,format)
{
var formatFunc=null;
switch(format)
{
case "HEX":
formatFunc=binb2hex;
break;
case "B64":
formatFunc=binb2b64;
break;
default:
return "FORMAT NOT RECOGNIZED";
}
switch(variant)
{
case "SHA-384":
if(sha384===null)
{
sha384=coreSHA2(variant);
}
return formatFunc(sha384);
case "SHA-512":
if(sha512===null)
{
sha512=coreSHA2(variant);
}
return formatFunc(sha512);
default:
return "HASH NOT RECOGNIZED";
}
};
}
pidCrypt.SHA512 = function(str,format)
{
if(!format) format = 'HEX';
var sha = new jsSHA(str);
return sha.getHash('SHA-512', format);
}
pidCrypt.SHA384 = function(str,format)
{
if(!format) format = 'HEX';
var sha = new jsSHA(str);
return sha.getHash('SHA-384', format);
}
}

Просмотреть файл

@ -0,0 +1,60 @@
/*----------------------------------------------------------------------------*/
// Copyright (c) 2010 pidder <www.pidder.com>
// 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);
}

32
lib/sjcl/README/COPYRIGHT Normal file
Просмотреть файл

@ -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.

36
lib/sjcl/README/INSTALL Normal file
Просмотреть файл

@ -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.

30
lib/sjcl/README/bsd.txt Normal file
Просмотреть файл

@ -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 <COPYRIGHT HOLDER> 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.

339
lib/sjcl/README/gpl-2.0.txt Normal file
Просмотреть файл

@ -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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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.
<signature of Ty Coon>, 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.

674
lib/sjcl/README/gpl-3.0.txt Normal file
Просмотреть файл

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

2
lib/sjcl/config.mk Normal file
Просмотреть файл

@ -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

141
lib/sjcl/configure поставляемый Executable file
Просмотреть файл

@ -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 <<EOT;
Usage: $0 arguments...
Valid arguments are:
--with-all: by default, include all targets
--without-all: by default, include no targets
--compress=none|closure|yui
--with-TARGET: require TARGET
--without-TARGET: forbid TARGET
--help: show this message
Valid targets are:
$targets
EOT
exit 1 unless $arg =~ /^--?help$/;
exit 0;
}
}
my $config = '';
my $pconfig;
# dependency analysis: forbidden
foreach $i (@targets) {
if ($enabled{$i} > 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";

208
lib/sjcl/core/aes.js Normal file
Просмотреть файл

@ -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;
}
};

187
lib/sjcl/core/bitArray.js Normal file
Просмотреть файл

@ -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
* <p>
* These objects are the currency accepted by SJCL's crypto functions.
* </p>
*
* <p>
* 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.
* </p>
*
* <p>
* Because bitwise ops clear this out-of-band data, these arrays can be passed
* to ciphers like AES which want arrays of words.
* </p>
*/
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<<blength) - 1);
},
/**
* Concatenate two bit arrays.
* @param {bitArray} a1 The first array.
* @param {bitArray} a2 The second array.
* @return {bitArray} The concatenation of a1 and a2.
*/
concat: function (a1, a2) {
if (a1.length === 0 || a2.length === 0) {
return a1.concat(a2);
}
var out, i, last = a1[a1.length-1], shift = sjcl.bitArray.getPartial(last);
if (shift === 32) {
return a1.concat(a2);
} else {
return sjcl.bitArray._shiftRight(a2, shift, last|0, a1.slice(0,a1.length-1));
}
},
/**
* Find the length of an array of bits.
* @param {bitArray} a The array.
* @return {Number} The length of a, in bits.
*/
bitLength: function (a) {
var l = a.length, x;
if (l === 0) { return 0; }
x = a[l - 1];
return (l-1) * 32 + sjcl.bitArray.getPartial(x);
},
/**
* Truncate an array.
* @param {bitArray} a The array.
* @param {Number} len The length to truncate to, in bits.
* @return {bitArray} A new array, truncated to len bits.
*/
clamp: function (a, len) {
if (a.length * 32 < len) { return a; }
a = a.slice(0, Math.ceil(len / 32));
var l = a.length;
len = len & 31;
if (l > 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<a.length; i++) {
x |= a[i]^b[i];
}
return (x === 0);
},
/** Shift an array right.
* @param {bitArray} a The array to shift.
* @param {Number} shift The number of bits to shift.
* @param {Number} [carry=0] A byte to carry in
* @param {bitArray} [out=[]] An array to prepend to the output.
* @private
*/
_shiftRight: function (a, shift, carry, out) {
var i, last2=0, shift2;
if (out === undefined) { out = []; }
for (; shift >= 32; shift -= 32) {
out.push(carry);
carry = 0;
}
if (shift === 0) {
return out.concat(a);
}
for (i=0; i<a.length; i++) {
out.push(carry | a[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]];
}
};

534
lib/sjcl/core/bn.js Normal file
Просмотреть файл

@ -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<ll.length; i++) {
l[i] = 0;
}
for (i=0; i<ll.length; i++) {
l[i] += ll[i];
}
return this;
},
/** this *= 2. Requires normalized; ends up normalized. */
doubleM: function() {
var i, carry=0, tmp, r=this.radix, m=this.radixMask, l=this.limbs;
for (i=0; i<l.length; i++) {
tmp = l[i];
tmp = tmp+tmp+carry;
l[i] = tmp & m;
carry = tmp >> 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<ll.length; i++) {
l[i] = 0;
}
for (i=0; i<ll.length; i++) {
l[i] -= ll[i];
}
return this;
},
mod: function(that) {
that = new sjcl.bn(that).normalize(); // copy before we begin
var out = new sjcl.bn(this).normalize(), ci=0;
for (; out.greaterEquals(that); ci++) {
that.doubleM();
}
for (; ci > 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<x.limbs.length; i++) {
nz |= x.limbs[i];
}
} while(nz);
if (!y.equals(1)) {
throw (new sjcl.exception.invalid("inverseMod: p and x must be relatively prime"));
}
return b;
},
/** this + that. Does not normalize. */
add: function(that) {
return this.copy().addM(that);
},
/** this - that. Does not normalize. */
sub: function(that) {
return this.copy().subM(that);
},
/** this * that. Normalizes and reduces. */
mul: function(that) {
if (typeof(that) === "number") { that = new this._class(that); }
var i, j, a = this.limbs, b = that.limbs, al = a.length, bl = b.length, out = new this._class(), c = out.limbs, ai, ii=this.maxMul;
for (i=0; i < this.limbs.length + that.limbs.length + 1; i++) {
c[i] = 0;
}
for (i=0; i<al; i++) {
ai = a[i];
for (j=0; j<bl; j++) {
c[i+j] += ai * b[j];
}
if (!--ii) {
ii = this.maxMul;
out.cnormalize();
}
}
return out.cnormalize().reduce();
},
/** this ^ 2. Normalizes and reduces. */
square: function() {
return this.mul(this);
},
/** this ^ n. Uses square-and-multiply. Normalizes and reduces. */
power: function(l) {
if (typeof(l) === "number") {
l = [l];
} else if (l.limbs !== undefined) {
l = l.normalize().limbs;
}
var i, j, out = new this._class(1), pow = this;
for (i=0; i<l.length; i++) {
for (j=0; j<this.radix; j++) {
if (l[i] & (1<<j)) {
out = out.mul(pow);
}
pow = pow.square();
}
}
return out;
},
/** this * that mod N */
mulmod: function(that, N) {
return this.mod(N).mul(that.mod(N)).mod(N);
},
/** this ^ x mod N */
powermod: function(x, N) {
var result = new sjcl.bn(1), a = new sjcl.bn(this), k = new sjcl.bn(x);
while (true) {
if (k.limbs[0] & 1) { result = result.mulmod(a, N); }
k.halveM();
if (k.equals(0)) { break; }
a = a.mulmod(a, N);
}
return result.normalize().reduce();
},
trim: function() {
var l = this.limbs, p;
do {
p = l.pop();
} while (l.length && p === 0);
l.push(p);
return this;
},
/** Reduce mod a modulus. Stubbed for subclassing. */
reduce: function() {
return this;
},
/** Reduce and normalize. */
fullReduce: function() {
return this.normalize();
},
/** Propagate carries. */
normalize: function() {
var carry=0, i, pv = this.placeVal, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;
for (i=0; i < ll || (carry !== 0 && carry !== -1); i++) {
l = (limbs[i]||0) + carry;
m = limbs[i] = l & mask;
carry = (l-m)*ipv;
}
if (carry === -1) {
limbs[i-1] -= this.placeVal;
}
return this;
},
/** Constant-time normalize. Does not allocate additional space. */
cnormalize: function() {
var carry=0, i, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;
for (i=0; i < ll-1; i++) {
l = limbs[i] + carry;
m = limbs[i] = l & mask;
carry = (l-m)*ipv;
}
limbs[i] += carry;
return this;
},
/** Serialize to a bit array */
toBits: function(len) {
this.fullReduce();
len = len || this.exponent || this.limbs.length * this.radix;
var i = Math.floor((len-1)/24), w=sjcl.bitArray, e = (len + 7 & -8) % this.radix || this.radix,
out = [w.partial(e, this.getLimb(i))];
for (i--; 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<coeff.length; i++) {
ppr.offset[i] = Math.floor(coeff[i][0] / ppr.radix - tmp);
ppr.fullOffset[i] = Math.ceil(coeff[i][0] / ppr.radix - tmp);
ppr.factor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.offset[i] * ppr.radix);
ppr.fullFactor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.fullOffset[i] * ppr.radix);
ppr.modulus.addM(new sjcl.bn(Math.pow(2,coeff[i][0])*coeff[i][1]));
ppr.minOffset = Math.min(ppr.minOffset, -ppr.offset[i]); // conservative
}
ppr._class = p;
ppr.modulus.cnormalize();
/** Approximate reduction mod p. May leave a number which is negative or slightly larger than p. */
ppr.reduce = function() {
var i, k, l, mo = this.modOffset, limbs = this.limbs, aff, off = this.offset, ol = this.offset.length, fac = this.factor, ll;
i = this.minOffset;
while (limbs.length > mo) {
l = limbs.pop();
ll = limbs.length;
for (k=0; k<ol; k++) {
limbs[ll+off[k]] -= fac[k] * l;
}
i--;
if (!i) {
limbs.push(0);
this.cnormalize();
i = this.minOffset;
}
}
this.cnormalize();
return this;
};
ppr._strongReduce = (ppr.fullMask === -1) ? ppr.reduce : function() {
var limbs = this.limbs, i = limbs.length - 1, k, l;
this.reduce();
if (i === this.modOffset - 1) {
l = limbs[i] & this.fullMask;
limbs[i] -= l;
for (k=0; k<this.fullOffset.length; k++) {
limbs[i+this.fullOffset[k]] -= this.fullFactor[k] * l;
}
this.normalize();
}
};
/** mostly constant-time, very expensive full reduction. */
ppr.fullReduce = function() {
var greater, i;
// massively above the modulus, may be negative
this._strongReduce();
// less than twice the modulus, may be negative
this.addM(this.modulus);
this.addM(this.modulus);
this.normalize();
// probably 2-3x the modulus
this._strongReduce();
// less than the power of 2. still may be more than
// the modulus
// HACK: pad out to this length
for (i=this.limbs.length; i<this.modOffset; i++) {
this.limbs[i] = 0;
}
// constant-time subtract modulus
greater = this.greaterEquals(this.modulus);
for (i=0; i<this.limbs.length; i++) {
this.limbs[i] -= this.modulus.limbs[i] * greater;
}
this.cnormalize();
return this;
};
ppr.inverse = function() {
return (this.power(this.modulus.sub(2)));
};
p.fromBits = sjcl.bn.fromBits;
return p;
};
// a small Mersenne prime
sjcl.bn.prime = {
p127: sjcl.bn.pseudoMersennePrime(127, [[0,-1]]),
// Bernstein's prime for Curve25519
p25519: sjcl.bn.pseudoMersennePrime(255, [[0,-19]]),
// NIST primes
p192: sjcl.bn.pseudoMersennePrime(192, [[0,-1],[64,-1]]),
p224: sjcl.bn.pseudoMersennePrime(224, [[0,1],[96,-1]]),
p256: sjcl.bn.pseudoMersennePrime(256, [[0,-1],[96,1],[192,1],[224,-1]]),
p384: sjcl.bn.pseudoMersennePrime(384, [[0,-1],[32,1],[96,-1],[128,-1]]),
p521: sjcl.bn.pseudoMersennePrime(521, [[0,-1]])
};
sjcl.bn.random = function(modulus, paranoia) {
if (typeof modulus !== "object") { modulus = new sjcl.bn(modulus); }
var words, i, l = modulus.limbs.length, m = modulus.limbs[l-1]+1, out = new sjcl.bn();
while (true) {
// get a sequence whose first digits make sense
do {
words = sjcl.random.randomWords(l, paranoia);
if (words[l-1] < 0) { words[l-1] += 0x100000000; }
} while (Math.floor(words[l-1] / m) === Math.floor(0x100000000 / m));
words[l-1] %= m;
// mask off all the limbs
for (i=0; i<l-1; i++) {
words[i] &= modulus.radixMask;
}
// check the rest of the digitssj
out.limbs = words;
if (!out.greaterEquals(modulus)) {
return out;
}
}
};

115
lib/sjcl/core/cbc.js Normal file
Просмотреть файл

@ -0,0 +1,115 @@
/** @fileOverview CBC mode implementation
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/** @namespace
* Dangerous: CBC mode with PKCS#5 padding.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
if (sjcl.beware === undefined) {
sjcl.beware = {};
}
sjcl.beware["CBC mode is dangerous because it doesn't protect message integrity."
] = function() {
sjcl.mode.cbc = {
/** The name of the mode.
* @constant
*/
name: "cbc",
/** Encrypt in CBC mode with PKCS#5 padding.
* @param {Object} prp The block cipher. 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. Must be empty.
* @return The encrypted data, an array of bytes.
* @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits, or if any adata is specified.
*/
encrypt: function(prp, plaintext, 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");
}
var i,
w = sjcl.bitArray,
xor = w._xor4,
bl = w.bitLength(plaintext),
bp = 0,
output = [];
if (bl&7) {
throw new sjcl.exception.invalid("pkcs#5 padding only works for multiples of a byte");
}
for (i=0; bp+128 <= bl; i+=4, bp+=128) {
/* Encrypt a non-final block */
iv = prp.encrypt(xor(iv, plaintext.slice(i,i+4)));
output.splice(i,0,iv[0],iv[1],iv[2],iv[3]);
}
/* Construct the pad. */
bl = (16 - ((bl >> 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<ciphertext.length; i+=4) {
bi = ciphertext.slice(i,i+4);
bo = xor(iv,prp.decrypt(bi));
output.splice(i,0,bo[0],bo[1],bo[2],bo[3]);
iv = bi;
}
/* check and remove the pad */
bi = output[i-1] & 255;
if (bi == 0 || bi > 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);
}
};
};

185
lib/sjcl/core/ccm.js Normal file
Просмотреть файл

@ -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<macData.length; i += 4) {
mac = prf.encrypt(xor(mac, macData.slice(i,i+4).concat([0,0,0])));
}
}
// mac the plaintext
for (i=0; i<plaintext.length; i+=4) {
mac = prf.encrypt(xor(mac, plaintext.slice(i,i+4).concat([0,0,0])));
}
return w.clamp(mac, tlen * 8);
},
/** CCM CTR mode.
* Encrypt or decrypt data and tag with the prf in CCM-style CTR mode.
* May mutate its arguments.
* @param {Object} prf The PRF.
* @param {bitArray} data The data to be encrypted or decrypted.
* @param {bitArray} iv The initialization vector.
* @param {bitArray} tag The authentication tag.
* @param {Number} tlen The length of th etag, in bits.
* @param {Number} L The CCM L value.
* @return {Object} An object with data and tag, the en/decryption of data and tag values.
* @private
*/
_ctrMode: function(prf, data, iv, tag, tlen, L) {
var enc, i, w=sjcl.bitArray, xor = w._xor4, ctr, b, l = data.length, bl=w.bitLength(data);
// start the ctr
ctr = w.concat([w.partial(8,L-1)],iv).concat([0,0,0]).slice(0,4);
// en/decrypt the tag
tag = w.bitSlice(xor(tag,prf.encrypt(ctr)), 0, tlen);
// en/decrypt the data
if (!l) { return {tag:tag, data:[]}; }
for (i=0; i<l; i+=4) {
ctr[3]++;
enc = prf.encrypt(ctr);
data[i] ^= enc[0];
data[i+1] ^= enc[1];
data[i+2] ^= enc[2];
data[i+3] ^= enc[3];
}
return { tag:tag, data:w.clamp(data,bl) };
}
};

Просмотреть файл

@ -0,0 +1,56 @@
/** @fileOverview Bit array codec implementations.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/** @namespace Base64 encoding/decoding */
sjcl.codec.base64 = {
/** The base64 alphabet.
* @private
*/
_chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
/** Convert from a bitArray to a base64 string. */
fromBits: function (arr, _noEquals) {
var out = "", i, bits=0, c = sjcl.codec.base64._chars, ta=0, bl = sjcl.bitArray.bitLength(arr);
for (i=0; out.length * 6 < bl; ) {
out += c.charAt((ta ^ arr[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<str.length; i++) {
x = c.indexOf(str.charAt(i));
if (x < 0) {
throw new sjcl.exception.invalid("this isn't base64!");
}
if (bits > 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;
}
};

Просмотреть файл

@ -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<bl/8; i++) {
if ((i&3) === 0) {
tmp = arr[i/4];
}
out.push(tmp >>> 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<bytes.length; i++) {
tmp = tmp << 8 | bytes[i];
if ((i&3) === 3) {
out.push(tmp);
tmp = 0;
}
}
if (i&3) {
out.push(sjcl.bitArray.partial(8*(i&3), tmp));
}
return out;
}
};

30
lib/sjcl/core/codecHex.js Normal file
Просмотреть файл

@ -0,0 +1,30 @@
/** @fileOverview Bit array codec implementations.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/** @namespace Hexadecimal */
sjcl.codec.hex = {
/** Convert from a bitArray to a hex string. */
fromBits: function (arr) {
var out = "", i, x;
for (i=0; i<arr.length; i++) {
out += ((arr[i]|0)+0xF00000000000).toString(16).substr(4);
}
return out.substr(0, sjcl.bitArray.bitLength(arr)/4);//.replace(/(.{8})/g, "$1 ");
},
/** Convert from a hex string to a bitArray. */
toBits: function (str) {
var i, out=[], len;
str = str.replace(/\s|0x/g, "");
len = str.length;
str = str + "00000000";
for (i=0; i<str.length; i+=8) {
out.push(parseInt(str.substr(i,8),16)^0);
}
return sjcl.bitArray.clamp(out, len*4);
}
};

Просмотреть файл

@ -0,0 +1,39 @@
/** @fileOverview Bit array codec implementations.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/** @namespace UTF-8 strings */
sjcl.codec.utf8String = {
/** Convert from a bitArray to a UTF-8 string. */
fromBits: function (arr) {
var out = "", bl = sjcl.bitArray.bitLength(arr), i, tmp;
for (i=0; i<bl/8; i++) {
if ((i&3) === 0) {
tmp = arr[i/4];
}
out += String.fromCharCode(tmp >>> 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<str.length; i++) {
tmp = tmp << 8 | str.charCodeAt(i);
if ((i&3) === 3) {
out.push(tmp);
tmp = 0;
}
}
if (i&3) {
out.push(sjcl.bitArray.partial(8*(i&3), tmp));
}
return out;
}
};

Просмотреть файл

@ -0,0 +1,271 @@
/** @fileOverview Convenince functions centered around JSON encapsulation.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/** @namespace JSON encapsulation */
sjcl.json = {
/** Default values for encryption */
defaults: { v:1, iter:1000, ks:128, ts:64, mode:"ccm", adata:"", cipher:"aes" },
/** Simple encryption function.
* @param {String|bitArray} password The password or key.
* @param {String} plaintext The data to encrypt.
* @param {Object} [params] The parameters including tag, iv and salt.
* @param {Object} [rp] A returned version with filled-in parameters.
* @return {String} The ciphertext.
* @throws {sjcl.exception.invalid} if a parameter is invalid.
*/
encrypt: function (password, plaintext, params, rp) {
params = params || {};
rp = rp || {};
var j = sjcl.json, p = j._add({ iv: sjcl.random.randomWords(4,0) },
j.defaults), tmp, prp;
j._add(p, params);
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.length < 2 || p.iv.length > 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<a.length; i++) {
if (!(m=a[i].match(/^([a-z][a-z0-9]*):(?:(\d+)|"([a-z0-9+\/%*_.@=\-]*)")$/i))) {
throw new sjcl.exception.invalid("json decode: this isn't json!");
}
if (m[2]) {
out[m[1]] = parseInt(m[2],10);
} else {
out[m[1]] = m[1].match(/^(ct|salt|iv)$/) ? sjcl.codec.base64.toBits(m[3]) : unescape(m[3]);
}
}
return out;
},
/** Insert all elements of src into target, modifying and returning target.
* @param {Object} target The object to be modified.
* @param {Object} src The object to pull data from.
* @param {boolean} [requireSame=false] If true, throw an exception if any field of target differs from corresponding field of src.
* @return {Object} target.
* @private
*/
_add: function (target, src, requireSame) {
if (target === undefined) { target = {}; }
if (src === undefined) { return target; }
var i;
for (i in src) {
if (src.hasOwnProperty(i)) {
if (requireSame && target[i] !== undefined && target[i] !== src[i]) {
throw new sjcl.exception.invalid("required parameter overridden");
}
target[i] = src[i];
}
}
return target;
},
/** Remove all elements of minus from plus. Does not modify plus.
* @private
*/
_subtract: function (plus, minus) {
var out = {}, i;
for (i in plus) {
if (plus.hasOwnProperty(i) && plus[i] !== minus[i]) {
out[i] = plus[i];
}
}
return out;
},
/** Return only the specified elements of src.
* @private
*/
_filter: function (src, filter) {
var out = {}, i;
for (i=0; i<filter.length; i++) {
if (src[filter[i]] !== undefined) {
out[filter[i]] = src[filter[i]];
}
}
return out;
}
};
/** Simple encryption function; convenient shorthand for sjcl.json.encrypt.
* @param {String|bitArray} password The password or key.
* @param {String} plaintext The data to encrypt.
* @param {Object} [params] The parameters including tag, iv and salt.
* @param {Object} [rp] A returned version with filled-in parameters.
* @return {String} The ciphertext.
*/
sjcl.encrypt = sjcl.json.encrypt;
/** Simple decryption function; convenient shorthand for sjcl.json.decrypt.
* @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.
*/
sjcl.decrypt = sjcl.json.decrypt;
/** The cache for cachedPbkdf2.
* @private
*/
sjcl.misc._pbkdf2Cache = {};
/** Cached PBKDF2 key derivation.
* @param {String} The password.
* @param {Object} The derivation params (iteration count and optional salt).
* @return {Object} The derived data in key, the salt in salt.
*/
sjcl.misc.cachedPbkdf2 = function (password, obj) {
var cache = sjcl.misc._pbkdf2Cache, c, cp, str, salt, iter;
obj = obj || {};
iter = obj.iter || 1000;
/* open the cache for this password and iteration count */
cp = cache[password] = cache[password] || {};
c = cp[iter] = cp[iter] || { firstSalt: (obj.salt && obj.salt.length) ?
obj.salt.slice(0) : sjcl.random.randomWords(2,0) };
salt = (obj.salt === undefined) ? c.firstSalt : obj.salt;
c[salt] = c[salt] || sjcl.misc.pbkdf2(password, salt, obj.iter);
return { key: c[salt].slice(0), salt:salt.slice(0) };
};

380
lib/sjcl/core/ecc.js Normal file
Просмотреть файл

@ -0,0 +1,380 @@
sjcl.ecc = {};
/**
* Represents a point on a curve in affine coordinates.
* @constructor
* @param {sjcl.ecc.curve} curve The curve that this point lies on.
* @param {bigInt} x The x coordinate.
* @param {bigInt} y The y coordinate.
*/
sjcl.ecc.point = function(curve,x,y) {
if (x === undefined) {
this.isIdentity = true;
} else {
this.x = x;
this.y = y;
this.isIdentity = false;
}
this.curve = curve;
};
sjcl.ecc.point.prototype = {
toJac: function() {
return new sjcl.ecc.pointJac(this.curve, this.x, this.y, new this.curve.field(1));
},
mult: function(k) {
return this.toJac().mult(k, this).toAffine();
},
/**
* 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 {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(k, k2, affine2) {
return this.toJac().mult2(k, this, k2, affine2).toAffine();
},
multiples: function() {
var m, i, j;
if (this._multiples === undefined) {
j = this.toJac().doubl();
m = this._multiples = [new sjcl.ecc.point(this.curve), this, j.toAffine()];
for (i=3; i<16; i++) {
j = j.add(this);
m.push(j.toAffine());
}
}
return this._multiples;
},
isValid: function() {
return this.y.square().equals(this.curve.b.add(this.x.mul(this.curve.a.add(this.x.square()))));
},
toBits: function() {
return sjcl.bitArray.concat(this.x.toBits(), this.y.toBits());
}
};
/**
* Represents a point on a curve in Jacobian coordinates. Coordinates can be specified as bigInts or strings (which
* will be converted to bigInts).
*
* @constructor
* @param {bigInt/string} x The x coordinate.
* @param {bigInt/string} y The y coordinate.
* @param {bigInt/string} z The z coordinate.
* @param {sjcl.ecc.curve} curve The curve that this point lies on.
*/
sjcl.ecc.pointJac = function(curve, x, y, z) {
if (x === undefined) {
this.isIdentity = true;
} else {
this.x = x;
this.y = y;
this.z = z;
this.isIdentity = false;
}
this.curve = curve;
};
sjcl.ecc.pointJac.prototype = {
/**
* Adds S and T and returns the result in Jacobian coordinates. Note that S must be in Jacobian coordinates and T must be in affine coordinates.
* @param {sjcl.ecc.pointJac} S One of the points to add, in Jacobian coordinates.
* @param {sjcl.ecc.point} T The other point to add, in affine coordinates.
* @return {sjcl.ecc.pointJac} The sum of the two points, in Jacobian coordinates.
*/
add: function(T) {
var S = this, sz2, c, d, c2, x1, x2, x, y1, y2, y, z;
if (S.curve !== T.curve) {
throw("sjcl.ecc.add(): Points must be on the same curve to add them!");
}
if (S.isIdentity) {
return T.toJac();
} else if (T.isIdentity) {
return S;
}
sz2 = S.z.square();
c = T.x.mul(sz2).subM(S.x);
if (c.equals(0)) {
if (S.y.equals(T.y.mul(sz2.mul(S.z)))) {
// same point
return S.doubl();
} else {
// inverses
return new sjcl.ecc.pointJac(S.curve);
}
}
d = T.y.mul(sz2.mul(S.z)).subM(S.y);
c2 = c.square();
x1 = d.square();
x2 = c.square().mul(c).addM( S.x.add(S.x).mul(c2) );
x = x1.subM(x2);
y1 = S.x.mul(c2).subM(x).mul(d);
y2 = S.y.mul(c.square().mul(c));
y = y1.subM(y2);
z = S.z.mul(c);
return new sjcl.ecc.pointJac(this.curve,x,y,z);
},
/**
* doubles this point.
* @return {sjcl.ecc.pointJac} The doubled point.
*/
doubl: function() {
if (this.isIdentity) { return this; }
var
y2 = this.y.square(),
a = y2.mul(this.x.mul(4)),
b = y2.square().mul(8),
z2 = this.z.square(),
c = this.x.sub(z2).mul(3).mul(this.x.add(z2)),
x = c.square().subM(a).subM(a),
y = a.sub(x).mul(c).subM(b),
z = this.y.add(this.y).mul(this.z);
return new sjcl.ecc.pointJac(this.curve, x, y, z);
},
/**
* Returns a copy of this point converted to affine coordinates.
* @return {sjcl.ecc.point} The converted point.
*/
toAffine: function() {
if (this.isIdentity || this.z.equals(0)) {
return new sjcl.ecc.point(this.curve);
}
var zi = this.z.inverse(), zi2 = zi.square();
return new sjcl.ecc.point(this.curve, this.x.mul(zi2).fullReduce(), this.y.mul(zi2.mul(zi)).fullReduce());
},
/**
* Multiply this point by k and return the answer in Jacobian coordinates.
* @param {bigInt} k The coefficient to multiply by.
* @param {sjcl.ecc.point} affine This point in affine coordinates.
* @return {sjcl.ecc.pointJac} The result of the multiplication, in Jacobian coordinates.
*/
mult: function(k, affine) {
if (typeof(k) === "number") {
k = [k];
} else if (k.limbs !== undefined) {
k = k.normalize().limbs;
}
var i, j, out = new sjcl.ecc.point(this.curve).toJac(), multiples = affine.multiples();
for (i=k.length-1; 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;
}
};

40
lib/sjcl/core/hmac.js Normal file
Просмотреть файл

@ -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<bs; i++) {
exKey[0][i] = key[i]^0x36363636;
exKey[1][i] = key[i]^0x5C5C5C5C;
}
this._baseHash[0].update(exKey[0]);
this._baseHash[1].update(exKey[1]);
};
/** HMAC with the specified hash function. Also called encrypt since it's a prf.
* @param {bitArray|String} data The data to mac.
* @param {Codec} [encoding] the encoding function to use.
*/
sjcl.misc.hmac.prototype.encrypt = sjcl.misc.hmac.prototype.mac = function (data, encoding) {
var w = new (this._hash)(this._baseHash[0]).update(data, encoding).finalize();
return new (this._hash)(this._baseHash[1]).update(w).finalize();
};

171
lib/sjcl/core/ocb2.js Normal file
Просмотреть файл

@ -0,0 +1,171 @@
/** @fileOverview OCB 2.0 implementation
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/** @namespace
* Phil Rogaway's Offset CodeBook mode, version 2.0.
* May be covered by US and international patents.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
sjcl.mode.ocb2 = {
/** The name of the mode.
* @constant
*/
name: "ocb2",
/** Encrypt in OCB mode, version 2.0.
* @param {Object} prp The block cipher. 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.
* @param [false] premac 1 if the authentication data is pre-macced with PMAC.
* @return The encrypted data, an array of bytes.
* @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits.
*/
encrypt: function(prp, plaintext, iv, adata, tlen, premac) {
if (sjcl.bitArray.bitLength(iv) !== 128) {
throw new sjcl.exception.invalid("ocb iv must be 128 bits");
}
var i,
times2 = sjcl.mode.ocb2._times2,
w = sjcl.bitArray,
xor = w._xor4,
checksum = [0,0,0,0],
delta = times2(prp.encrypt(iv)),
bi, bl,
output = [],
pad;
adata = adata || [];
tlen = tlen || 64;
for (i=0; i+4 < plaintext.length; i+=4) {
/* Encrypt a non-final block */
bi = plaintext.slice(i,i+4);
checksum = xor(checksum, bi);
output = output.concat(xor(delta,prp.encrypt(xor(delta, bi))));
delta = times2(delta);
}
/* Chop out the final block */
bi = plaintext.slice(i);
bl = w.bitLength(bi);
pad = prp.encrypt(xor(delta,[0,0,0,bl]));
bi = w.clamp(xor(bi.concat([0,0,0]),pad), bl);
/* Checksum the final block, and finalize the checksum */
checksum = xor(checksum,xor(bi.concat([0,0,0]),pad));
checksum = prp.encrypt(xor(checksum,xor(delta,times2(delta))));
/* MAC the header */
if (adata.length) {
checksum = xor(checksum, premac ? adata : sjcl.mode.ocb2.pmac(prp, adata));
}
return output.concat(w.concat(bi, w.clamp(checksum, tlen)));
},
/** Decrypt in OCB 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.
* @param {Number} [tlen=64] the desired tag length, in bits.
* @param {boolean} [premac=false] true if the authentication data is pre-macced with PMAC.
* @return The decrypted data, an array of bytes.
* @throws {sjcl.exception.invalid} if the IV isn't exactly 128 bits.
* @throws {sjcl.exception.corrupt} if if the message is corrupt.
*/
decrypt: function(prp, ciphertext, iv, adata, tlen, premac) {
if (sjcl.bitArray.bitLength(iv) !== 128) {
throw new sjcl.exception.invalid("ocb iv must be 128 bits");
}
tlen = tlen || 64;
var i,
times2 = sjcl.mode.ocb2._times2,
w = sjcl.bitArray,
xor = w._xor4,
checksum = [0,0,0,0],
delta = times2(prp.encrypt(iv)),
bi, bl,
len = sjcl.bitArray.bitLength(ciphertext) - tlen,
output = [],
pad;
adata = adata || [];
for (i=0; i+4 < len/32; i+=4) {
/* Decrypt a non-final block */
bi = xor(delta, prp.decrypt(xor(delta, ciphertext.slice(i,i+4))));
checksum = xor(checksum, bi);
output = output.concat(bi);
delta = times2(delta);
}
/* Chop out and decrypt the final block */
bl = len-i*32;
pad = prp.encrypt(xor(delta,[0,0,0,bl]));
bi = xor(pad, w.clamp(ciphertext.slice(i),bl).concat([0,0,0]));
/* Checksum the final block, and finalize the checksum */
checksum = xor(checksum, bi);
checksum = prp.encrypt(xor(checksum, xor(delta, times2(delta))));
/* MAC the header */
if (adata.length) {
checksum = xor(checksum, premac ? adata : sjcl.mode.ocb2.pmac(prp, adata));
}
if (!w.equal(w.clamp(checksum, tlen), w.bitSlice(ciphertext, len))) {
throw new sjcl.exception.corrupt("ocb: tag doesn't match");
}
return output.concat(w.clamp(bi,bl));
},
/** PMAC authentication for OCB associated data.
* @param {Object} prp The block cipher. It must have a block size of 16 bytes.
* @param {bitArray} adata The authenticated data.
*/
pmac: function(prp, adata) {
var i,
times2 = sjcl.mode.ocb2._times2,
w = sjcl.bitArray,
xor = w._xor4,
checksum = [0,0,0,0],
delta = prp.encrypt([0,0,0,0]),
bi;
delta = xor(delta,times2(times2(delta)));
for (i=0; i+4<adata.length; i+=4) {
delta = times2(delta);
checksum = xor(checksum, prp.encrypt(xor(delta, adata.slice(i,i+4))));
}
bi = adata.slice(i);
if (w.bitLength(bi) < 128) {
delta = xor(delta,times2(delta));
bi = w.concat(bi,[0x80000000|0,0,0,0]);
}
checksum = xor(checksum, bi);
return prp.encrypt(xor(times2(xor(delta,times2(delta))), checksum));
},
/** Double a block of words, OCB style.
* @private
*/
_times2: function(x) {
return [x[0]<<1 ^ x[1]>>>31,
x[1]<<1 ^ x[2]>>>31,
x[2]<<1 ^ x[3]>>>31,
x[3]<<1 ^ (x[0]>>>31)*0x87];
}
};

54
lib/sjcl/core/pbkdf2.js Normal file
Просмотреть файл

@ -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<count; i++) {
ui = prf.encrypt(ui);
for (j=0; j<ui.length; j++) {
u[j] ^= ui[j];
}
}
out = out.concat(u);
}
if (length) { out = b.clamp(out, length); }
return out;
};

368
lib/sjcl/core/random.js Normal file
Просмотреть файл

@ -0,0 +1,368 @@
/** @fileOverview Random number generator.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/** @namespace Random number generator
*
* @description
* <p>
* 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.
* </p>
*
* <p>
* 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.
* </p>
*
* <p>
* 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.
* </p>
*
* <p>
* 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.
* </p>
*/
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; i<nwords; i+= 4) {
if ((i+1) % this._MAX_WORDS_PER_BURST === 0) {
this._gate();
}
g = this._gen4words();
out.push(g[0],g[1],g[2],g[3]);
}
this._gate();
return out.slice(0,nwords);
},
setDefaultParanoia: function (paranoia) {
this._defaultParanoia = paranoia;
},
/**
* Add entropy to the pools.
* @param data The entropic value. Should be a 32-bit integer, array of 32-bit integers, or string
* @param {Number} estimatedEntropy The estimated entropy of data, in bits
* @param {String} source The source of the entropy, eg "mouse"
*/
addEntropy: function (data, estimatedEntropy, source) {
source = source || "user";
var id,
i, ty = 0, tmp,
t = (new Date()).valueOf(),
robin = this._robins[source],
oldReady = this.isReady();
id = this._collectorIds[source];
if (id === undefined) { id = this._collectorIds[source] = this._collectorIdNext ++; }
if (robin === undefined) { robin = this._robins[source] = 0; }
this._robins[source] = ( this._robins[source] + 1 ) % this._pools.length;
switch(typeof(data)) {
case "number":
data=[data];
ty=1;
break;
case "object":
if (estimatedEntropy === undefined) {
/* horrible entropy estimator */
estimatedEntropy = 0;
for (i=0; i<data.length; i++) {
tmp= data[i];
while (tmp>0) {
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<jsTemp.length; i++) {
j = jsTemp[i];
delete cbs[j];
}
},
/* private */
_pools : [new sjcl.hash.sha256()],
_poolEntropy : [0],
_reseedCount : 0,
_robins : {},
_eventId : 0,
_collectorIds : {},
_collectorIdNext : 0,
_strength : 0,
_poolStrength : 0,
_nextReseed : 0,
_key : [0,0,0,0,0,0,0,0],
_counter : [0,0,0,0],
_cipher : undefined,
_defaultParanoia : 6,
/* event listener stuff */
_collectorsStarted : false,
_callbacks : {progress: {}, seeded: {}},
_callbackI : 0,
/* constants */
_NOT_READY : 0,
_READY : 1,
_REQUIRES_RESEED : 2,
_MAX_WORDS_PER_BURST : 65536,
_PARANOIA_LEVELS : [0,48,64,96,128,192,256,384,512,768,1024],
_MILLISECONDS_PER_RESEED : 30000,
_BITS_PER_RESEED : 80,
/** Generate 4 random words, no reseed, no gate.
* @private
*/
_gen4words: function () {
for (var i=0; i<4; i++) {
this._counter[i] = this._counter[i]+1 | 0;
if (this._counter[i]) { break; }
}
return this._cipher.encrypt(this._counter);
},
/* Rekey the AES instance with itself after a request, or every _MAX_WORDS_PER_BURST words.
* @private
*/
_gate: function () {
this._key = this._gen4words().concat(this._gen4words());
this._cipher = new sjcl.cipher.aes(this._key);
},
/** Reseed the generator with the given words
* @private
*/
_reseed: function (seedWords) {
this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords));
this._cipher = new sjcl.cipher.aes(this._key);
for (var i=0; i<4; i++) {
this._counter[i] = this._counter[i]+1 | 0;
if (this._counter[i]) { break; }
}
},
/** reseed the data from the entropy pools
* @param full If set, use all the entropy pools in the reseed.
*/
_reseedFromPools: function (full) {
var reseedData = [], strength = 0, i;
this._nextReseed = reseedData[0] =
(new Date()).valueOf() + this._MILLISECONDS_PER_RESEED;
for (i=0; i<16; i++) {
/* On some browsers, this is cryptographically random. So we might
* as well toss it in the pot and stir...
*/
reseedData.push(Math.random()*0x100000000|0);
}
for (i=0; i<this._pools.length; i++) {
reseedData = reseedData.concat(this._pools[i].finalize());
strength += this._poolEntropy[i];
this._poolEntropy[i] = 0;
if (!full && (this._reseedCount & (1<<i))) { break; }
}
/* if we used the last pool, push a new one onto the stack */
if (this._reseedCount >= 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<cbsTemp.length; j++) {
cbsTemp[j](arg);
}
}
};

165
lib/sjcl/core/sha1.js Normal file
Просмотреть файл

@ -0,0 +1,165 @@
/** @fileOverview Javascript SHA-1 implementation.
*
* Based on the implementation in RFC 3174, method 1, and on the SJCL
* SHA-256 implementation.
*
* @author Quinn Slack
*/
/**
* Context for a SHA-1 operation in progress.
* @constructor
* @class Secure Hash Algorithm, 160 bits.
*/
sjcl.hash.sha1 = function (hash) {
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 5 big-endian words.
*/
sjcl.hash.sha1.hash = function (data) {
return (new sjcl.hash.sha1()).update(data).finalize();
};
sjcl.hash.sha1.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 = this.blockSize+ol & -this.blockSize; i <= nl;
i+= this.blockSize) {
this._block(b.splice(0,16));
}
return this;
},
/**
* Complete hashing and output the hash value.
* @return {bitArray} The hash value, an array of 5 big-endian words. TODO
*/
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-1 initialization vector.
* @private
*/
_init:[0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0],
/**
* The SHA-1 hash key.
* @private
*/
_key:[0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6],
/**
* The SHA-1 logical functions f(0), f(1), ..., f(79).
* @private
*/
_f:function(t, b, c, d) {
if (t <= 19) {
return (b & c) | (~b & d);
} else if (t <= 39) {
return b ^ c ^ d;
} else if (t <= 59) {
return (b & c) | (b & d) | (c & d);
} else if (t <= 79) {
return b ^ c ^ d;
}
},
/**
* Circular left-shift operator.
* @private
*/
_S:function(n, x) {
return (x << n) | (x >>> 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;
}
};

216
lib/sjcl/core/sha256.js Normal file
Просмотреть файл

@ -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;
}
};

69
lib/sjcl/core/sjcl.js Normal file
Просмотреть файл

@ -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;
}
}
};

113
lib/sjcl/core/srp.js Normal file
Просмотреть файл

@ -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(<salt> | SHA(<username> | ":" | <raw password>)) [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
}
}
};

40
lib/sjcl/sjcl.js Normal file
Просмотреть файл

@ -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<k;j++){g=n[d>>>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<<c)-1},concat:function(a,b){if(a.length===0||b.length===0)return a.concat(b);var c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return d===32?a.concat(b):sjcl.bitArray.P(b,d,c|0,a.slice(0,a.length-1))},bitLength:function(a){var b=a.length;
if(b===0)return 0;return(b-1)*32+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(a.length*32<b)return a;a=a.slice(0,Math.ceil(b/32));var c=a.length;b&=31;if(c>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<a.length;d++)c|=
a[d]^b[d];return c===0},P:function(a,b,c,d){var e;e=0;if(d===undefined)d=[];for(;b>=32;b-=32){d.push(c);c=0}if(b===0)return d.concat(a);for(e=0;e<a.length;e++){d.push(c|a[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<c/8;d++){if((d&3)===0)e=a[d/4];b+=String.fromCharCode(e>>>24);e<<=8}return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++){d=d<<8|a.charCodeAt(c);if((c&3)===3){b.push(d);d=0}}c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a+="00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,d*4)}};
sjcl.codec.base64={D:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b){var c="",d,e=0,f=sjcl.codec.base64.D,g=0,h=sjcl.bitArray.bitLength(a);for(d=0;c.length*6<h;){c+=f.charAt((g^a[d]>>>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;c<a.length;c++){g=e.indexOf(a.charAt(c));if(g<0)throw new sjcl.exception.invalid("this isn't base64!");
if(d>26){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<g.length;d+=4)f=a.encrypt(i(f,g.slice(d,d+4).concat([0,0,0])))}for(d=0;d<b.length;d+=4)f=a.encrypt(i(f,b.slice(d,d+4).concat([0,0,0])));return h.clamp(f,e*8)},I:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.k;var i=b.length,k=h.bitLength(b);c=h.concat([h.partial(8,
f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!i)return{tag:d,data:[]};for(g=0;g<i;g+=4){c[3]++;e=a.encrypt(c);b[g]^=e[0];b[g+1]^=e[1];b[g+2]^=e[2];b[g+3]^=e[3]}return{tag:d,data:h.clamp(b,k)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(sjcl.bitArray.bitLength(c)!==128)throw new sjcl.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.A,i=sjcl.bitArray,k=i.k,j=[0,0,0,0];c=h(a.encrypt(c));var l,m=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4){l=b.slice(g,g+4);j=k(j,l);m=m.concat(k(c,a.encrypt(k(c,l))));c=h(c)}l=b.slice(g);b=i.bitLength(l);g=a.encrypt(k(c,[0,0,0,b]));l=i.clamp(k(l.concat([0,0,0]),g),b);j=k(j,k(l.concat([0,0,0]),g));j=a.encrypt(k(j,k(c,h(c))));
if(d.length)j=k(j,f?d:sjcl.mode.ocb2.pmac(a,d));return m.concat(i.concat(l,i.clamp(j,e)))},decrypt:function(a,b,c,d,e,f){if(sjcl.bitArray.bitLength(c)!==128)throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode.ocb2.A,h=sjcl.bitArray,i=h.k,k=[0,0,0,0],j=g(a.encrypt(c)),l,m,n=sjcl.bitArray.bitLength(b)-e,o=[];d=d||[];for(c=0;c+4<n/32;c+=4){l=i(j,a.decrypt(i(j,b.slice(c,c+4))));k=i(k,l);o=o.concat(l);j=g(j)}m=n-c*32;l=a.encrypt(i(j,[0,0,0,m]));l=i(l,h.clamp(b.slice(c),
m).concat([0,0,0]));k=i(k,l);k=a.encrypt(i(k,i(j,g(j))));if(d.length)k=i(k,f?d:sjcl.mode.ocb2.pmac(a,d));if(!h.equal(h.clamp(k,e),h.bitSlice(b,n)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return o.concat(h.clamp(l,m))},pmac:function(a,b){var c,d=sjcl.mode.ocb2.A,e=sjcl.bitArray,f=e.k,g=[0,0,0,0],h=a.encrypt([0,0,0,0]);h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4){h=d(h);g=f(g,a.encrypt(f(h,b.slice(c,c+4))))}b=b.slice(c);if(e.bitLength(b)<128){h=f(h,d(h));b=e.concat(b,[2147483648|0,0,
0,0])}g=f(g,b);return a.encrypt(f(d(f(h,d(h))),g))},A:function(a){return[a[0]<<1^a[1]>>>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;b<d;b++){c[0][b]=a[b]^909522486;c[1][b]=a[b]^1549556828}this.l[0].update(c[0]);this.l[1].update(c[1])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a,b){a=(new this.M(this.l[0])).update(a,b).finalize();return(new this.M(this.l[1])).update(a).finalize()};
sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E3;if(d<0||c<0)throw sjcl.exception.invalid("invalid params to pbkdf2");if(typeof a==="string")a=sjcl.codec.utf8String.toBits(a);e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,i,k=[],j=sjcl.bitArray;for(i=1;32*k.length<(d||1);i++){e=f=a.encrypt(j.concat(b,[i]));for(g=1;g<c;g++){f=a.encrypt(f);for(h=0;h<f.length;h++)e[h]^=f[h]}k=k.concat(e)}if(d)k=j.clamp(k,d);return k};
sjcl.random={randomWords:function(a,b){var c=[];b=this.isReady(b);var d;if(b===0)throw new sjcl.exception.notReady("generator isn't seeded");else b&2&&this.U(!(b&1));for(b=0;b<a;b+=4){(b+1)%0x10000===0&&this.L();d=this.u();c.push(d[0],d[1],d[2],d[3])}this.L();return c.slice(0,a)},setDefaultParanoia:function(a){this.t=a},addEntropy:function(a,b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.q[c],h=this.isReady();d=this.F[c];if(d===undefined)d=this.F[c]=this.R++;if(g===undefined)g=this.q[c]=0;this.q[c]=
(this.q[c]+1)%this.b.length;switch(typeof a){case "number":break;case "object":if(b===undefined)for(c=b=0;c<a.length;c++)for(e=a[c];e>0;){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<d.length;b++){c=d[b];delete a[c]}},b:[new sjcl.hash.sha256],j:[0],z:0,q:{},J:0,F:{},R:0,g:0,f:0,O:0,a:[0,0,0,0,0,0,0,0],d:[0,0,0,0],s:undefined,t:6,m:false,r:{progress:{},seeded:{}},Q:0,B:[0,48,64,96,128,192,0x100,384,512,768,1024],u:function(){for(var a=0;a<4;a++){this.d[a]=this.d[a]+1|0;if(this.d[a])break}return this.s.encrypt(this.d)},L:function(){this.a=this.u().concat(this.u());this.s=new sjcl.cipher.aes(this.a)},T:function(a){this.a=
sjcl.hash.sha256.hash(this.a.concat(a));this.s=new sjcl.cipher.aes(this.a);for(a=0;a<4;a++){this.d[a]=this.d[a]+1|0;if(this.d[a])break}},U:function(a){var b=[],c=0,d;this.O=b[0]=(new Date).valueOf()+3E4;for(d=0;d<16;d++)b.push(Math.random()*0x100000000|0);for(d=0;d<this.b.length;d++){b=b.concat(this.b[d].finalize());c+=this.j[d];this.j[d]=0;if(!a&&this.z&1<<d)break}if(this.z>=1<<this.b.length){this.b.push(new sjcl.hash.sha256);this.j.push(0)}this.f-=c;if(c>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<d.length;c++)d[c](b)}};
sjcl.json={defaults:{v:1,iter:1E3,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},encrypt:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.c({iv:sjcl.random.randomWords(4,0)},e.defaults);e.c(f,c);if(typeof f.salt==="string")f.salt=sjcl.codec.base64.toBits(f.salt);if(typeof f.iv==="string")f.iv=sjcl.codec.base64.toBits(f.iv);if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||typeof a==="string"&&f.iter<=100||f.ts!==64&&f.ts!==96&&f.ts!==128||f.ks!==128&&f.ks!==192&&f.ks!==0x100||f.iv.length<2||f.iv.length>
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<a.length;c++){if(!(d=a[c].match(/^([a-z][a-z0-9]*):(?:(\d+)|"([a-z0-9+\/%*_.@=\-]*)")$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!");b[d[1]]=d[2]?parseInt(d[2],10):d[1].match(/^(ct|salt|iv)$/)?sjcl.codec.base64.toBits(d[3]):unescape(d[3])}return b},c:function(a,b,c){if(a===
undefined)a={};if(b===undefined)return a;var d;for(d in b)if(b.hasOwnProperty(d)){if(c&&a[d]!==undefined&&a[d]!==b[d])throw new sjcl.exception.invalid("required parameter overridden");a[d]=b[d]}return a},V:function(a,b){var c={},d;for(d in a)if(a.hasOwnProperty(d)&&a[d]!==b[d])c[d]=a[d];return c},W:function(a,b){var c={},d;for(d=0;d<b.length;d++)if(a[b[d]]!==undefined)c[b[d]]=a[b[d]];return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl.decrypt=sjcl.json.decrypt;sjcl.misc.S={};
sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.S,d;b=b||{};d=b.iter||1E3;c=c[a]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=b.salt===undefined?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};

26
spec/SpecRunner.html.erb Normal file
Просмотреть файл

@ -0,0 +1,26 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Test Runner</title>
<link rel="stylesheet" type="text/css" href="infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.css">
<script type="text/javascript" src="infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine.js"></script>
<script type="text/javascript" src="infrastructure/jasmine-standalone-1.0.0/lib/jasmine-1.0.0/jasmine-html.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="../target/braintree-1.1.0.min.js"></script>
<!-- include spec files here... -->
<% spec_files.each do |source_file| %>
<script type="text/javascript" src="<%= source_file %>"></script>
<% end %>
</head>
<body>
<script type="text/javascript">
jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
jasmine.getEnv().execute();
</script>
</body>
</html>

58
spec/brainree_spec.js Normal file
Просмотреть файл

@ -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\$/);
});
});
});

Просмотреть файл

@ -0,0 +1,27 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Test Runner</title>
<link rel="stylesheet" type="text/css" href="lib/jasmine-1.0.0/jasmine.css">
<script type="text/javascript" src="lib/jasmine-1.0.0/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-1.0.0/jasmine-html.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="src/Player.js"></script>
<script type="text/javascript" src="src/Song.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="spec/SpecHelper.js"></script>
<script type="text/javascript" src="spec/PlayerSpec.js"></script>
</head>
<body>
<script type="text/javascript">
jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
jasmine.getEnv().execute();
</script>
</body>
</html>

Просмотреть файл

@ -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.

Просмотреть файл

@ -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;
};

Просмотреть файл

@ -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;
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -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");
});
});
});

Просмотреть файл

@ -0,0 +1,9 @@
beforeEach(function() {
this.addMatchers({
toBePlaying: function(expectedSong) {
var player = this.actual;
return player.currentlyPlayingSong === expectedSong
&& player.isPlaying;
}
})
});

Просмотреть файл

@ -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);
};

Просмотреть файл

@ -0,0 +1,7 @@
function Song() {
}
Song.prototype.persistFavoriteStatus = function(value) {
// something complicated
throw new Error("not yet implemented");
};