Repository: fex-team/webuploader Branch: master Commit: ac93940c4c98 Files: 276 Total size: 3.9 MB Directory structure: gitextract_4gxwg5qi/ ├── .gitignore ├── .jshintrc ├── .travis.yml ├── Gruntfile.js ├── LICENSE ├── README.md ├── _draft/ │ ├── demo.html │ ├── demo.js │ ├── demo2.html │ ├── demo2.js │ ├── flash_cpp/ │ │ ├── Test.swc │ │ ├── as3api.cpp │ │ ├── exports.txt │ │ ├── hashlib/ │ │ │ ├── .hashlibpp.h.swp │ │ │ ├── .svn/ │ │ │ │ ├── all-wcprops │ │ │ │ ├── entries │ │ │ │ └── text-base/ │ │ │ │ ├── Makefile.svn-base │ │ │ │ ├── hashlibpp.h.svn-base │ │ │ │ ├── hl_exception.h.svn-base │ │ │ │ ├── hl_hashwrapper.h.svn-base │ │ │ │ ├── hl_md5.cpp.svn-base │ │ │ │ ├── hl_md5.h.svn-base │ │ │ │ ├── hl_md5wrapper.cpp.svn-base │ │ │ │ ├── hl_md5wrapper.h.svn-base │ │ │ │ ├── hl_sha1.cpp.svn-base │ │ │ │ ├── hl_sha1.h.svn-base │ │ │ │ ├── hl_sha1wrapper.cpp.svn-base │ │ │ │ ├── hl_sha1wrapper.h.svn-base │ │ │ │ ├── hl_sha256.cpp.svn-base │ │ │ │ ├── hl_sha256.h.svn-base │ │ │ │ ├── hl_sha256wrapper.cpp.svn-base │ │ │ │ ├── hl_sha256wrapper.h.svn-base │ │ │ │ ├── hl_sha2ext.cpp.svn-base │ │ │ │ ├── hl_sha2ext.h.svn-base │ │ │ │ ├── hl_sha2mac.h.svn-base │ │ │ │ ├── hl_sha384wrapper.cpp.svn-base │ │ │ │ ├── hl_sha384wrapper.h.svn-base │ │ │ │ ├── hl_sha512wrapper.cpp.svn-base │ │ │ │ ├── hl_sha512wrapper.h.svn-base │ │ │ │ ├── hl_types.h.svn-base │ │ │ │ ├── hl_wrapperfactory.cpp.svn-base │ │ │ │ └── hl_wrapperfactory.h.svn-base │ │ │ ├── Makefile │ │ │ ├── hashlibpp.h │ │ │ ├── hl_exception.h │ │ │ ├── hl_hashwrapper.h │ │ │ ├── hl_md5.cpp │ │ │ ├── hl_md5.h │ │ │ ├── hl_md5wrapper.cpp │ │ │ ├── hl_md5wrapper.h │ │ │ ├── hl_sha1.cpp │ │ │ ├── hl_sha1.h │ │ │ ├── hl_sha1wrapper.cpp │ │ │ ├── hl_sha1wrapper.h │ │ │ ├── hl_sha256.cpp │ │ │ ├── hl_sha256.h │ │ │ ├── hl_sha256wrapper.cpp │ │ │ ├── hl_sha256wrapper.h │ │ │ ├── hl_sha2ext.cpp │ │ │ ├── hl_sha2ext.h │ │ │ ├── hl_sha2mac.h │ │ │ ├── hl_sha384wrapper.cpp │ │ │ ├── hl_sha384wrapper.h │ │ │ ├── hl_sha512wrapper.cpp │ │ │ ├── hl_sha512wrapper.h │ │ │ ├── hl_types.h │ │ │ ├── hl_wrapperfactory.cpp │ │ │ └── hl_wrapperfactory.h │ │ ├── main.cpp │ │ └── makefile │ ├── hashFile.js │ ├── md5.js │ ├── md5File.js │ └── music/ │ ├── index.html │ ├── jquery.js │ ├── md5.js │ ├── server/ │ │ └── fileupload.php │ ├── style.css │ ├── upload.js │ └── webuploader.js ├── bower.json ├── build/ │ ├── docTpl/ │ │ ├── class.ejs │ │ ├── content.ejs │ │ ├── css/ │ │ │ └── doc.css │ │ ├── events.ejs │ │ ├── items.ejs │ │ ├── layout.ejs │ │ ├── module.ejs │ │ ├── options.ejs │ │ ├── plugins.ejs │ │ └── sidebar.ejs │ ├── fis/ │ │ ├── intro.js │ │ └── outro.js │ ├── intro.js │ ├── outro.js │ └── tasks/ │ ├── build.js │ ├── concat.js │ └── doc.js ├── css/ │ └── webuploader.css ├── dist/ │ ├── README.md │ ├── Uploader.swf │ ├── webuploader.css │ ├── webuploader.custom.js │ ├── webuploader.fis.js │ ├── webuploader.flashonly.js │ ├── webuploader.html5nodepend.js │ ├── webuploader.html5only.js │ ├── webuploader.js │ ├── webuploader.noimage.js │ ├── webuploader.nolog.js │ └── webuploader.withoutimage.js ├── examples/ │ ├── cropper/ │ │ ├── cropper.css │ │ ├── cropper.js │ │ ├── index.html │ │ ├── jquery.js │ │ ├── style.css │ │ └── uploader.js │ ├── image-upload/ │ │ ├── expressInstall.swf │ │ ├── icons.psd │ │ ├── index.html │ │ ├── jquery.js │ │ ├── progress.psd │ │ ├── style.css │ │ └── upload.js │ ├── md5-demo/ │ │ ├── index.html │ │ └── script.js │ └── requirejs/ │ ├── app.js │ ├── index.html │ └── require.js ├── flash/ │ ├── .actionScriptProperties │ ├── .project │ ├── .settings/ │ │ └── org.eclipse.core.resources.prefs │ ├── Uploader.iml │ ├── lib/ │ │ ├── Test.swc │ │ ├── as3corelib.swc │ │ ├── lib.swc │ │ └── stringecho.swc │ ├── lib.fla │ └── src/ │ ├── ComponentFactory.as │ ├── Uploader.as │ └── com/ │ ├── Blob.as │ ├── File.as │ ├── FilePicker.as │ ├── FileReader.as │ ├── FileReaderSync.as │ ├── Image.as │ ├── Md5.as │ ├── XMLHttpRequest.as │ ├── errors/ │ │ ├── DOMError.as │ │ ├── ImageError.as │ │ └── RuntimeError.as │ ├── events/ │ │ ├── FilePickerEvent.as │ │ ├── ImageEvent.as │ │ ├── ODataEvent.as │ │ ├── OErrorEvent.as │ │ ├── OProgressEvent.as │ │ └── URLStreamProgressEvent.as │ ├── image/ │ │ ├── BMP.as │ │ ├── ExifParser.as │ │ ├── GIF.as │ │ ├── ImageEditor.as │ │ ├── JPEG.as │ │ ├── JPEGEncoder.as │ │ ├── PNG.as │ │ ├── ascb/ │ │ │ └── filters/ │ │ │ ├── ColorMatrixArrays.as │ │ │ └── ConvolutionMatrixArrays.as │ │ ├── events/ │ │ │ └── ExifParserEvent.as │ │ └── formatlos/ │ │ ├── BitmapDataUnlimited.as │ │ ├── Gif.as │ │ └── events/ │ │ └── BitmapDataUnlimitedEvent.as │ └── utils/ │ ├── BMPDecoder.as │ ├── Base64.as │ ├── BinaryReader.as │ ├── Buffer.as │ ├── OEventDispatcher.as │ ├── URLStreamProgress.as │ ├── Utils.as │ └── Zhenpin.as ├── jekyll/ │ ├── _config.yml │ ├── _includes/ │ │ ├── comments.html │ │ ├── footer.html │ │ └── header.html │ ├── _layouts/ │ │ ├── default.html │ │ └── post.html │ ├── _plugins/ │ │ └── fancytoc.rb │ ├── css/ │ │ ├── bootstrap-theme.css │ │ ├── bootstrap.css │ │ ├── demo.css │ │ ├── font-awesome.css │ │ ├── style.css │ │ ├── syntax.css │ │ └── webuploader.css │ ├── demo.md │ ├── doc/ │ │ ├── css/ │ │ │ └── doc.css │ │ └── index.html │ ├── document.md │ ├── download.md │ ├── fonts/ │ │ └── FontAwesome.otf │ ├── getting-started.md │ ├── images/ │ │ └── logo.psd │ ├── index.md │ └── js/ │ ├── Uploader.swf │ ├── bootstrap.js │ ├── demo.js │ ├── getting-started.js │ ├── global.js │ └── webuploader.js ├── package.json ├── server/ │ ├── crossdomain.xml │ ├── fileupload.php │ ├── fileupload2.php │ └── preview.php ├── src/ │ ├── base.js │ ├── dollar-builtin.js │ ├── dollar-third.js │ ├── dollar.js │ ├── file.js │ ├── lib/ │ │ ├── blob.js │ │ ├── dnd.js │ │ ├── file.js │ │ ├── filepaste.js │ │ ├── filepicker.js │ │ ├── image.js │ │ ├── md5.js │ │ └── transport.js │ ├── mediator.js │ ├── preset/ │ │ ├── all.js │ │ ├── flashonly.js │ │ ├── html5only.js │ │ └── withoutimage.js │ ├── promise-builtin.js │ ├── promise-third.js │ ├── promise.js │ ├── queue.js │ ├── runtime/ │ │ ├── client.js │ │ ├── compbase.js │ │ ├── flash/ │ │ │ ├── blob.js │ │ │ ├── filepicker.js │ │ │ ├── image.js │ │ │ ├── md5.js │ │ │ ├── runtime.js │ │ │ └── transport.js │ │ ├── html5/ │ │ │ ├── androidpatch.js │ │ │ ├── blob.js │ │ │ ├── dnd.js │ │ │ ├── filepaste.js │ │ │ ├── filepicker.js │ │ │ ├── image.js │ │ │ ├── imagemeta/ │ │ │ │ └── exif.js │ │ │ ├── imagemeta.js │ │ │ ├── jpegencoder.js │ │ │ ├── md5.js │ │ │ ├── runtime.js │ │ │ ├── transport.js │ │ │ └── util.js │ │ └── runtime.js │ ├── uploader.js │ ├── webuploader.js │ └── widgets/ │ ├── filednd.js │ ├── filepaste.js │ ├── filepicker.js │ ├── image.js │ ├── log.js │ ├── md5.js │ ├── queue.js │ ├── runtime.js │ ├── upload.js │ ├── validator.js │ └── widget.js └── test/ ├── Qunit/ │ ├── qunit-1.14.0.css │ └── qunit-1.14.0.js ├── index.html ├── require.js ├── testDesign/ │ └── webuploader.xmind └── units/ ├── base.js └── filepicker.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store .idea /pages /node_modules /doc server/* !server/preview.php !server/fileupload.php !server/fileupload2.php !server/crossdomain.xml .tags .tags_sorted_by_file /flash/bin-debug /flash/html-template /.grunt /jekyll/_site/ /dist/*.zip ================================================ FILE: .jshintrc ================================================ { "maxerr" : 50, "bitwise" : false, "camelcase" : true, "curly" : true, "eqeqeq" : true, "forin" : false, "immed" : false, "indent" : 4, "latedef" : false, "newcap" : false, "noarg" : false, "noempty" : true, "nonew" : false, "plusplus" : false, "quotmark" : "single", "undef" : true, "unused" : true, "strict" : false, "trailing" : false, "maxparams" : false, "maxdepth" : false, "maxstatements" : false, "maxcomplexity" : false, "maxlen" : 80, "asi" : false, "boss" : false, "debug" : false, "eqnull" : true, "es5" : false, "esnext" : false, "evil" : false, "expr" : true, "funcscope" : false, "globalstrict" : false, "iterator" : false, "lastsemic" : false, "laxbreak" : false, "laxcomma" : false, "loopfunc" : false, "multistr" : false, "proto" : false, "scripturl" : false, "smarttabs" : false, "shadow" : false, "sub" : false, "supernew" : false, "validthis" : false, "browser" : true, "couch" : false, "devel" : true, "dojo" : false, "jquery" : false, "mootools" : false, "node" : false, "nonstandard" : false, "prototypejs" : false, "rhino" : false, "worker" : false, "wsh" : false, "yui" : false, "nomen" : false, "onevar" : true, "passfail" : false, "white" : true, "predef" : [ "require", "define", "module", "URL", "XDomainRequest", "ActiveXObject" ], "withstmt" : false, "zepto" : true, "assignvarfirst" : true, "varnewline": true, "strictchain": true, "strictindent": true, "operatorend": true, "strictlinebreak": false, "assignthisto" : false, "assignexceptionto" : false, "strictcomment" : true, "fileoverview" : true, "novoid" : true } ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - 0.10 before_script: - npm install -g grunt-cli script: - grunt test ================================================ FILE: Gruntfile.js ================================================ module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), build: { options: { banner: '/*! WebUploader <%= pkg.version %> */\n' }, all: { name: 'webuploader', dest: "dist/webuploader.js", // 在没有jquery类似的库的前提下可以设置builtin,去除强行依赖。 builtin: { dollar: false, promise: false } }, nolog: { preset: 'all', dest: "dist/webuploader.nolog.js", // 在没有jquery类似的库的前提下可以设置builtin,去除强行依赖。 builtin: { dollar: false, promise: false } }, flashonly: { preset: 'flashonly', dest: "dist/webuploader.flashonly.js", }, html5only: { preset: 'html5only', dest: "dist/webuploader.html5only.js", }, html5nodepend: { preset: 'html5only', dest: "dist/webuploader.html5nodepend.js", builtin: { dollar: true, promise: true }, }, withoutimage: { preset: 'withoutimage', dest: "dist/webuploader.noimage.js", }, // 自己配置的实例 // glob语法。 // 移动端方案,请搭配 zepto 使用。 custom: { preset: "custom", cwd: "src", builtin: { promise: true }, src: [ 'widgets/filepicker.js', 'widgets/image.js', 'widgets/queue.js', 'widgets/runtime.js', 'widgets/upload.js', 'widgets/log.js', 'runtime/html5/blob.js', 'runtime/html5/filepicker.js', 'runtime/html5/imagemeta/exif.js', 'runtime/html5/image.js', 'runtime/html5/androidpatch.js', 'runtime/html5/transport.js' ], dest: "dist/webuploader.custom.js" }, fis: { name: 'webuploader', dest: "dist/webuploader.fis.js", fis: true, // 在没有jquery类似的库的前提下可以设置builtin,去除强行依赖。 builtin: { dollar: false, promise: false } } }, uglify: { options: { mangle: true, banner: '/* WebUploader <%= pkg.version %> */' }, static_mapping: { files: [ { src: 'dist/webuploader.js', dest: 'dist/webuploader.min.js' }, { src: 'dist/webuploader.nolog.js', dest: 'dist/webuploader.nolog.min.js' }, { src: 'dist/webuploader.flashonly.js', dest: 'dist/webuploader.flashonly.min.js' }, { src: 'dist/webuploader.html5only.js', dest: 'dist/webuploader.html5only.min.js' }, { src: 'dist/webuploader.html5nodepend.js', dest: 'dist/webuploader.html5nodepend.min.js' }, { src: 'dist/webuploader.noimage.js', dest: 'dist/webuploader.noimage.min.js' }, { src: 'dist/webuploader.custom.js', dest: 'dist/webuploader.custom.min.js' } ] } }, copy: { jekyll: { src: 'dist/webuploader.js', dest: 'jekyll/js/webuploader.js', }, css: { src: 'css/webuploader.css', dest: 'dist/webuploader.css' }, css2: { src: 'css/webuploader.css', dest: 'jekyll/css/webuploader.css' } }, watch: { options: { debounceDelay: 250 }, all: { files: ['src/**/*.js', 'Gruntfile.js'], tasks: ['default'], }, dist: { files: ['src/**/*.js', 'Gruntfile.js'], tasks: ['dist'], }, doc: { files: ['src/**/*.js', 'Gruntfile.js', 'build/docTpl/**/*'], tasks: ['doc'], }, dev: { files: 'src/**/*.js', tasks: 'build:all' }, flashonly: { files: 'src/**/*.js', tasks: 'build:flashonly' } }, jsbint: { options: { jshintrc: '.jshintrc' }, all: [ 'src/**/*.js', '!src/runtime/html5/jpegencoder.js' ] }, size: { dist: { cwd: 'dist/', src: '*.js' }, src: { src: 'src/**/*.js' } }, doc: { options: { cwd: './src/', files: [ 'uploader.js', 'base.js', 'mediator.js', '**/*.js' ], tplDir: './build/docTpl', theme: 'gmu', outputDir: './jekyll/doc', title: 'WebUploader API文档' } }, jekyll: { options: { // Universal options src: 'jekyll' }, dist: { // Target options: { // Target options dest: 'pages', config: 'jekyll/_config.yml' } } }, 'gh-pages': { options: { message: '程序自动提交,源码请查看tree/master/jekyll目录', base: 'pages', repo: 'https://github.com/fex-team/webuploader.git' }, src: ['**/*'] }, qunit: { all: { options: { urls: [ 'http://0.0.0.0:8000/test/index.html' ] } } }, connect: { server: { options: { port: 8000, base: '.' } } /*, keepalive: { options: { port: 8000, base: '.', keepalive: true } }*/ }, }); require('load-grunt-tasks')(grunt); grunt.loadTasks('build/tasks'); // 加载build目录下的所有task // Default task(s). grunt.registerTask('default', ['jsbint:all', 'dist']); grunt.registerTask('dist', ['build', 'uglify', 'copy']); grunt.registerTask('deploy', ['doc', 'jekyll', 'gh-pages']); grunt.registerTask('test', ['connect', 'qunit']); }; ================================================ FILE: LICENSE ================================================ Copyright (c) 2014, FEX@Baidu Inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Baidu Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Baidu Inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: README.md ================================================ 不再对使用问题进行答复,如果有希望的功能改进或者bugfix可以提交PR ================================================== # WebUploader 文件上传 [![Build Status](https://secure.travis-ci.org/fex-team/webuploader.png?branch=master)](http://travis-ci.org/fex-team/webuploader) [![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/) WebUploader是一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览器,延用原来的FLASH运行时,兼容IE6+,Andorid 4+,IOS 6+。两套运行时,同样的调用方式,可供用户任意选用。 支持大文件分片并发上传,极大的提高了文件上传效率。 - 官网: http://fex.baidu.com/webuploader/ - ISSUES:https://github.com/fex-team/webuploader/issues ## 支持 **代码肯定存在很多不足和需要优化的地方,欢迎大家提交 [pr](https://help.github.com/articles/using-pull-requests)。**感谢**以下代码贡献者, 排名不分先后。** [@zensh](https://github.com/zensh),[@ushelp](https://github.com/ushelp),[@duanlixin](https://github.com/duanlixin)。 ## 特性 ### 分片、并发 分片与并发结合,将一个大文件分割成多块,并发上传,极大地提高大文件的上传速度。 当网络问题导致传输错误时,只需要重传出错分片,而不是整个文件。另外分片传输能够更加实时的跟踪上传进度。 ### 预览、压缩 支持常用图片格式jpg,jpeg,gif,bmp,png预览与压缩,节省网络数据传输。 解析jpeg中的meta信息,对于各种orientation做了正确的处理,同时压缩后上传保留图片的所有原始meta数据。 ### 多途径添加文件 支持文件多选,类型过滤,拖拽(文件&文件夹),图片粘贴功能。 粘贴功能主要体现在当有图片数据在剪切板中时(截屏工具如QQ(Ctrl + ALT + A), 网页中右击图片点击复制),Ctrl + V便可添加此图片文件。 ### HTML5 & FLASH 兼容主流浏览器,接口一致,实现了两套运行时支持,用户无需关心内部用了什么内核。 同时Flash部分没有做任何UI相关的工作,方便不关心flash的用户扩展和自定义业务需求。 ### MD5秒传 当文件体积大、量比较多时,支持上传前做文件md5值验证,一致则可直接跳过。 如果服务端与前端统一修改算法,取段md5,可大大提升验证性能,耗时在20ms左右。 ### 易扩展、可拆分 采用可拆分机制, 将各个功能独立成了小组件,可自由搭配。 采用AMD规范组织代码,清晰明了,方便高级玩家扩展。 ================================================ FILE: _draft/demo.html ================================================ WebUploader演示 - 秒传
点击选择文件

或将照片拖到这里,单次最多可选300张

================================================ FILE: _draft/demo.js ================================================ (function( $ ){ // 当domReady的时候开始初始化 $(function() { var $wrap = $('#uploader'), // 图片容器 $queue = $( '' ) .appendTo( $wrap.find( '.queueList' ) ), // 状态栏,包括进度和控制按钮 $statusBar = $wrap.find( '.statusBar' ), // 文件总体选择信息。 $info = $statusBar.find( '.info' ), // 上传按钮 $upload = $wrap.find( '.uploadBtn' ), // 没选择文件之前的内容。 $placeHolder = $wrap.find( '.placeholder' ), $progress = $statusBar.find( '.progress' ).hide(), // 添加的文件数量 fileCount = 0, // 添加的文件总大小 fileSize = 0, // 优化retina, 在retina下这个值是2 ratio = window.devicePixelRatio || 1, // 缩略图大小 thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio, // 可能有pedding, ready, uploading, confirm, done. state = 'pedding', // 所有文件的进度信息,key为file id percentages = {}, // WebUploader实例 uploader; // 实例化 uploader = WebUploader.create({ pick: '#filePicker', dnd: '#dndArea', paste: '#uploader', server: '../server/fileupload.php', accept: '', fileNumLimit: 300, fileSizeLimit: 0, fileSingleSizeLimit: 512 * 1024 * 1024 // 512 M }); // 添加“添加文件”的按钮, uploader.addButton('#filePicker2'); // 当有文件添加进来时执行,负责view的创建 function addFile( file ) { var $li = $( '
  • ' + '

    ' + file.name + '

    ' + '

    '+ '

    ' + '
  • ' ), $btns = $('
    ' + '删除' + '向右旋转' + '向左旋转
    ').appendTo( $li ), $prgress = $li.find('p.progress span'), $wrap = $li.find( 'p.imgWrap' ), $info = $('

    '), showError = function( code ) { switch( code ) { case 'exceed_size': text = '文件大小超出'; break; default: text = '上传失败,请重试'; break; } $info.text( text ).appendTo( $li ); }; if ( file.getStatus() === 'invalid' ) { showError( file.statusText ); } else { // @todo lazyload $wrap.text( '预览中' ); uploader.makeThumb( file, function( error, src ) { if ( error ) { $wrap.text( '不能预览' ); return; } var img = $(''); $wrap.empty().append( img ); }, thumbnailWidth, thumbnailHeight ); percentages[ file.id ] = [ file.size, 0 ]; file.ratation = 0; } file.on('statuschange', function( cur, prev ) { if ( prev === 'progress' ) { $prgress.hide().width(0); } else if ( prev === 'queued' ) { $li.off( 'mouseenter mouseleave' ); $btns.remove(); } // 成功 if ( cur === 'error' || cur === 'invalid' ) { showError( file.statusText ); percentages[ file.id ][ 1 ] = 1; } else if ( cur === 'queued' ) { percentages[ file.id ][ 1 ] = 0; } else if ( cur === 'progress' ) { $info.remove(); $prgress.css('display', 'block'); } $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur ); }); $li.on( 'mouseenter', function() { $btns.stop().animate({height: 30}); }); $li.on( 'mouseleave', function() { $btns.stop().animate({height: 0}); }); $btns.on( 'click', 'span', function() { var index = $(this).index(), deg; switch ( index ) { case 0: uploader.removeFile( file ); return; case 1: file.ratation += 90; break; case 2: file.ratation -= 90; break; } // -webkit-transform: rotate(90deg); index && (deg = 'rotate(' + file.ratation + 'deg)', $wrap.css({ '-webkit-transform': deg, '-mos-transform': deg, '-o-transform': deg, 'transform': deg })); }); $li.appendTo( $queue ); } // 负责view的销毁 function removeFile( file ) { var $li = $('#'+file.id); delete percentages[ file.id ]; updateTotalProgress(); $li.off().find('.file-panel').off().end().remove(); } function updateTotalProgress() { var loaded = 0, total = 0, spans = $progress.children(), percent; $.each( percentages, function( k, v ) { total += v[ 0 ]; loaded += v[ 0 ] * v[ 1 ]; } ); percent = total ? loaded / total : 0; spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' ); spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' ); updateStatus(); } function updateStatus() { var text = '', stats; if ( state === 'ready' ) { text = '选中' + fileCount + '张图片,共' + uploader.formatSize( fileSize ) + '。'; } else if ( state === 'confirm' ) { stats = uploader.getStats(); if ( stats.uploadFailNum ) { text = '已成功上传' + stats.successNum+ '张照片至XX相册,'+ stats.uploadFailNum + '张照片上传失败,重新上传失败图片或忽略' } } else { stats = uploader.getStats(); text = '共' + fileCount + '张(' + uploader.formatSize( fileSize ) + '),已上传' + stats.successNum + '张'; if ( stats.uploadFailNum ) { text += ',失败' + stats.uploadFailNum + '张'; } } $info.html( text ); } function setState( val ) { var file, stats; if ( val === state ) { return; } $upload.removeClass( 'state-' + state ); $upload.addClass( 'state-' + val ); state = val; switch ( state ) { case 'pedding': $placeHolder.show(); $queue.hide(); $statusBar.hide(); break; case 'ready': $placeHolder.hide(); $( '#filePicker2' ).show(); $queue.show(); $statusBar.show(); break; case 'uploading': $( '#filePicker2' ).hide(); $progress.show(); $upload.text( '暂停上传' ); break; case 'paused': $progress.show(); $upload.text( '继续上传' ); break; case 'confirm': $progress.hide(); $upload.text( '开始上传' ).addClass( 'disabled' ); stats = uploader.getStats(); if ( stats.successNum && !stats.uploadFailNum ) { setState( 'finish' ); return; } break; case 'finish': stats = uploader.getStats(); if ( stats.successNum ) { alert( '上传成功' ); } else { // 没有成功的图片,重设 state = 'done'; location.reload(); } break; } updateStatus(); } uploader.onUploadBeforeSend = function( file, data ) { data.md5 = file.md5 || ''; }; uploader.onUploadProgress = function( file, percentage ) { var $li = $('#'+file.id), $percent = $li.find('.progress span'); $percent.css( 'width', percentage * 100 + '%' ); percentages[ file.id ][ 1 ] = percentage; updateTotalProgress(); }; uploader.onFileQueued = function( file ) { var start = Date.now(); fileCount++; fileSize += file.size; if ( fileCount === 1 ) { $placeHolder.hide(); $statusBar.show(); } Md5File( file, function( value ) { var $li = $('#'+file.id); file.md5 = value; $li.append( '

    md5:' + ((Date.now() - start)/1000).toFixed(2) + '秒

    ') }); addFile( file ); setState( 'ready' ); updateTotalProgress(); }; uploader.onFileDequeued = function( file ) { fileCount--; fileSize -= file.size; if ( !fileCount ) { setState( 'pedding' ); } removeFile( file ); updateTotalProgress(); }; uploader.on( 'all', function( type ) { var stats; switch( type ) { case 'uploadFinished': setState( 'confirm' ); break; case 'startUpload': setState( 'uploading' ); break; case 'stopUpload': setState( 'paused' ); break; } }); uploader.onError = function( code ) { alert( 'Eroor: ' + code ); }; uploader.onUploadChunkcontinue = function( file, ret ) { if ( ret.exist ) { var $li = $( '#'+file.id ); $li.append( '

    跳过' + uploader.formatSize( file.size - file.loaded ) + '

    ' ); return false; } }; $upload.on('click', function() { if ( $(this).hasClass( 'disabled' ) ) { return false; } if ( state === 'ready' ) { uploader.upload(); } else if ( state === 'paused' ) { uploader.upload(); } else if ( state === 'uploading' ) { uploader.stop(); } }); $info.on( 'click', '.retry', function() { uploader.retry(); } ); $info.on( 'click', '.ignore', function() { alert( 'todo' ); } ); $upload.addClass( 'state-' + state ); updateTotalProgress(); var Md5File = (function(){ return function( file, cb ) { var worker = new Worker( 'md5File.js' ); worker.onmessage = function( e ) { cb( e.data, file ); worker.terminate(); }; worker.postMessage( file.source ); } })(); }); })( jQuery ); ================================================ FILE: _draft/demo2.html ================================================ WebUploader演示 - 秒传
    点击选择文件

    或将照片拖到这里,单次最多可选300张

    ================================================ FILE: _draft/demo2.js ================================================ (function( $ ){ // 当domReady的时候开始初始化 $(function() { var $wrap = $('#uploader'), // 图片容器 $queue = $( '' ) .appendTo( $wrap.find( '.queueList' ) ), // 状态栏,包括进度和控制按钮 $statusBar = $wrap.find( '.statusBar' ), // 文件总体选择信息。 $info = $statusBar.find( '.info' ), // 上传按钮 $upload = $wrap.find( '.uploadBtn' ), // 没选择文件之前的内容。 $placeHolder = $wrap.find( '.placeholder' ), $progress = $statusBar.find( '.progress' ).hide(), // 添加的文件数量 fileCount = 0, // 添加的文件总大小 fileSize = 0, // 优化retina, 在retina下这个值是2 ratio = window.devicePixelRatio || 1, // 缩略图大小 thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio, // 可能有pedding, ready, uploading, confirm, done. state = 'pedding', // 所有文件的进度信息,key为file id percentages = {}, // WebUploader实例 uploader; // 实例化 uploader = WebUploader.create({ pick: '#filePicker', dnd: '#dndArea', paste: '#uploader', server: '../server/fileupload2.php', accept: '', fileNumLimit: 300, fileSizeLimit: 0, fileSingleSizeLimit: 512 * 1024 * 1024 // 512 M }); // 添加“添加文件”的按钮, uploader.addButton('#filePicker2'); // 当有文件添加进来时执行,负责view的创建 function addFile( file ) { var $li = $( '
  • ' + '

    ' + file.name + '

    ' + '

    '+ '

    ' + '
  • ' ), $btns = $('
    ' + '删除' + '向右旋转' + '向左旋转
    ').appendTo( $li ), $prgress = $li.find('p.progress span'), $wrap = $li.find( 'p.imgWrap' ), $info = $('

    '), showError = function( code ) { switch( code ) { case 'exceed_size': text = '文件大小超出'; break; default: text = '上传失败,请重试'; break; } $info.text( text ).appendTo( $li ); }; if ( file.getStatus() === 'invalid' ) { showError( file.statusText ); } else { // @todo lazyload $wrap.text( '预览中' ); uploader.makeThumb( file, function( error, src ) { if ( error ) { $wrap.text( '不能预览' ); return; } var img = $(''); $wrap.empty().append( img ); }, thumbnailWidth, thumbnailHeight ); percentages[ file.id ] = [ file.size, 0 ]; file.ratation = 0; } file.on('statuschange', function( cur, prev ) { if ( prev === 'progress' ) { $prgress.hide().width(0); } else if ( prev === 'queued' ) { $li.off( 'mouseenter mouseleave' ); $btns.remove(); } // 成功 if ( cur === 'error' || cur === 'invalid' ) { showError( file.statusText ); percentages[ file.id ][ 1 ] = 1; } else if ( cur === 'queued' ) { percentages[ file.id ][ 1 ] = 0; } else if ( cur === 'progress' ) { $info.remove(); $prgress.css('display', 'block'); } $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur ); }); $li.on( 'mouseenter', function() { $btns.stop().animate({height: 30}); }); $li.on( 'mouseleave', function() { $btns.stop().animate({height: 0}); }); $btns.on( 'click', 'span', function() { var index = $(this).index(), deg; switch ( index ) { case 0: uploader.removeFile( file ); return; case 1: file.ratation += 90; break; case 2: file.ratation -= 90; break; } // -webkit-transform: rotate(90deg); index && (deg = 'rotate(' + file.ratation + 'deg)', $wrap.css({ '-webkit-transform': deg, '-mos-transform': deg, '-o-transform': deg, 'transform': deg })); }); $li.appendTo( $queue ); } // 负责view的销毁 function removeFile( file ) { var $li = $('#'+file.id); delete percentages[ file.id ]; updateTotalProgress(); $li.off().find('.file-panel').off().end().remove(); } function updateTotalProgress() { var loaded = 0, total = 0, spans = $progress.children(), percent; $.each( percentages, function( k, v ) { total += v[ 0 ]; loaded += v[ 0 ] * v[ 1 ]; } ); percent = total ? loaded / total : 0; spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' ); spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' ); updateStatus(); } function updateStatus() { var text = '', stats; if ( state === 'ready' ) { text = '选中' + fileCount + '张图片,共' + uploader.formatSize( fileSize ) + '。'; } else if ( state === 'confirm' ) { stats = uploader.getStats(); if ( stats.uploadFailNum ) { text = '已成功上传' + stats.successNum+ '张照片至XX相册,'+ stats.uploadFailNum + '张照片上传失败,重新上传失败图片或忽略' } } else { stats = uploader.getStats(); text = '共' + fileCount + '张(' + uploader.formatSize( fileSize ) + '),已上传' + stats.successNum + '张'; if ( stats.uploadFailNum ) { text += ',失败' + stats.uploadFailNum + '张'; } } $info.html( text ); } function setState( val ) { var file, stats; if ( val === state ) { return; } $upload.removeClass( 'state-' + state ); $upload.addClass( 'state-' + val ); state = val; switch ( state ) { case 'pedding': $placeHolder.show(); $queue.hide(); $statusBar.hide(); break; case 'ready': $placeHolder.hide(); $( '#filePicker2' ).show(); $queue.show(); $statusBar.show(); break; case 'uploading': $( '#filePicker2' ).hide(); $progress.show(); $upload.text( '暂停上传' ); break; case 'paused': $progress.show(); $upload.text( '继续上传' ); break; case 'confirm': $progress.hide(); $upload.text( '开始上传' ).addClass( 'disabled' ); stats = uploader.getStats(); if ( stats.successNum && !stats.uploadFailNum ) { setState( 'finish' ); return; } break; case 'finish': stats = uploader.getStats(); if ( stats.successNum ) { alert( '上传成功' ); } else { // 没有成功的图片,重设 state = 'done'; location.reload(); } break; } updateStatus(); } uploader.onUploadBeforeSend = function( file, data ) { data.md5 = file.md5 || ''; }; uploader.onUploadProgress = function( file, percentage ) { var $li = $('#'+file.id), $percent = $li.find('.progress span'); $percent.css( 'width', percentage * 100 + '%' ); percentages[ file.id ][ 1 ] = percentage; updateTotalProgress(); }; uploader.onFileQueued = function( file ) { var start = Date.now(); fileCount++; fileSize += file.size; if ( fileCount === 1 ) { $placeHolder.hide(); $statusBar.show(); } Md5File( file, function( value ) { var $li = $('#'+file.id); file.md5 = value; console.log( value ); $li.append( '

    md5:' + ((Date.now() - start)/1000).toFixed(2) + '秒

    ') }); addFile( file ); setState( 'ready' ); updateTotalProgress(); }; uploader.onFileDequeued = function( file ) { fileCount--; fileSize -= file.size; if ( !fileCount ) { setState( 'pedding' ); } removeFile( file ); updateTotalProgress(); }; uploader.on( 'all', function( type ) { var stats; switch( type ) { case 'uploadFinished': setState( 'confirm' ); break; case 'startUpload': setState( 'uploading' ); break; case 'stopUpload': setState( 'paused' ); break; } }); uploader.onError = function( code ) { alert( 'Eroor: ' + code ); }; uploader.onUploadChunkcontinue = function( file, ret ) { if ( ret.exist ) { var $li = $( '#'+file.id ); $li.append( '

    跳过' + uploader.formatSize( file.size - file.loaded ) + '

    ' ); return false; } }; $upload.on('click', function() { if ( $(this).hasClass( 'disabled' ) ) { return false; } if ( state === 'ready' ) { uploader.upload(); } else if ( state === 'paused' ) { uploader.upload(); } else if ( state === 'uploading' ) { uploader.stop(); } }); $info.on( 'click', '.retry', function() { uploader.retry(); } ); $info.on( 'click', '.ignore', function() { alert( 'todo' ); } ); $upload.addClass( 'state-' + state ); updateTotalProgress(); var Md5File = (function(){ return function( file, cb ) { var worker = new Worker( 'hashFile.js' ); worker.onmessage = function( e ) { cb( e.data, file ); worker.terminate(); }; worker.postMessage( file.source ); } })(); }); })( jQuery ); ================================================ FILE: _draft/flash_cpp/as3api.cpp ================================================ #include #include #include "AS3/AS3.h" #include "hashlib/hl_hashwrapper.h" #include "hashlib/hl_md5wrapper.h" void md5String() __attribute__((used, annotate("as3sig:public function md5String(input:String):String"), annotate("as3package:com.webuploader"))); /** * MD5 ("") = d41d8cd98f00b204e9800998ecf8427e * MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661 * MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72 * MD5 ("message digest") = f96b697d7cb7938d525a2f31aaf161d0 * MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b * MD5 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = * d174ab98d277d9f5a5611c2c9f419d9f * MD5 ("123456789012345678901234567890123456789012345678901234567890123456 * 78901234567890") = 57edf4a22be3c955ac49da2e2107b67a */ void md5String(){ const char *src = NULL; AS3_MallocString(src, input); std::string srcString(src); const char *result; hashwrapper *wrapper; wrapper = new md5wrapper(); std::string md5 = wrapper->getHashFromString(srcString); result = md5.c_str(); delete wrapper; // We can't just call AS3_Return(s) because s is not a scalar. // Instead we need to marshall the C string into AS3 and use // AS3_ReturnAS3Var(). AS3_DeclareVar(myString, String); AS3_CopyCStringToVar(myString, result, 32); AS3_ReturnAS3Var(myString); } ================================================ FILE: _draft/flash_cpp/exports.txt ================================================ # built in symbols that must always be preserved _start1 malloc free memcpy memmove flascc_uiTickProc _sync_synchronize # symbols for C++ exception handling _Unwind_SjLj_Register _Unwind_SjLj_Resume _Unwind_SjLj_Unregister _Unwind_SjLj_RaiseException # symbols from libm.a __muldi3 # symbols for the GLUT based examples _avm2_glut_keyhandler glutMainLoopBody ================================================ FILE: _draft/flash_cpp/hashlib/.svn/all-wcprops ================================================ K 25 svn:wc:ra_dav:version-url V 43 /svnroot/hashlib2plus/!svn/ver/77/trunk/src END hl_sha384wrapper.cpp K 25 svn:wc:ra_dav:version-url V 64 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha384wrapper.cpp END hl_sha256.h K 25 svn:wc:ra_dav:version-url V 55 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha256.h END hl_wrapperfactory.h K 25 svn:wc:ra_dav:version-url V 63 /svnroot/hashlib2plus/!svn/ver/78/trunk/src/hl_wrapperfactory.h END hl_sha2ext.cpp K 25 svn:wc:ra_dav:version-url V 58 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha2ext.cpp END hl_sha256wrapper.h K 25 svn:wc:ra_dav:version-url V 62 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha256wrapper.h END hl_sha384wrapper.h K 25 svn:wc:ra_dav:version-url V 62 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha384wrapper.h END hl_sha2mac.h K 25 svn:wc:ra_dav:version-url V 56 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha2mac.h END hl_sha2ext.h K 25 svn:wc:ra_dav:version-url V 56 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha2ext.h END hl_md5.cpp K 25 svn:wc:ra_dav:version-url V 54 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_md5.cpp END hl_md5wrapper.cpp K 25 svn:wc:ra_dav:version-url V 61 /svnroot/hashlib2plus/!svn/ver/71/trunk/src/hl_md5wrapper.cpp END hl_hashwrapper.h K 25 svn:wc:ra_dav:version-url V 60 /svnroot/hashlib2plus/!svn/ver/78/trunk/src/hl_hashwrapper.h END hl_md5.h K 25 svn:wc:ra_dav:version-url V 52 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_md5.h END hl_md5wrapper.h K 25 svn:wc:ra_dav:version-url V 59 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_md5wrapper.h END hashlibpp.h K 25 svn:wc:ra_dav:version-url V 55 /svnroot/hashlib2plus/!svn/ver/78/trunk/src/hashlibpp.h END hl_sha1.cpp K 25 svn:wc:ra_dav:version-url V 55 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha1.cpp END hl_sha1wrapper.cpp K 25 svn:wc:ra_dav:version-url V 62 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha1wrapper.cpp END hl_sha1.h K 25 svn:wc:ra_dav:version-url V 53 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha1.h END hl_sha1wrapper.h K 25 svn:wc:ra_dav:version-url V 60 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha1wrapper.h END hl_exception.h K 25 svn:wc:ra_dav:version-url V 58 /svnroot/hashlib2plus/!svn/ver/78/trunk/src/hl_exception.h END hl_sha512wrapper.cpp K 25 svn:wc:ra_dav:version-url V 64 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha512wrapper.cpp END hl_sha256.cpp K 25 svn:wc:ra_dav:version-url V 57 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha256.cpp END hl_wrapperfactory.cpp K 25 svn:wc:ra_dav:version-url V 65 /svnroot/hashlib2plus/!svn/ver/78/trunk/src/hl_wrapperfactory.cpp END hl_sha256wrapper.cpp K 25 svn:wc:ra_dav:version-url V 64 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha256wrapper.cpp END Makefile K 25 svn:wc:ra_dav:version-url V 52 /svnroot/hashlib2plus/!svn/ver/78/trunk/src/Makefile END hl_sha512wrapper.h K 25 svn:wc:ra_dav:version-url V 62 /svnroot/hashlib2plus/!svn/ver/70/trunk/src/hl_sha512wrapper.h END hl_types.h K 25 svn:wc:ra_dav:version-url V 54 /svnroot/hashlib2plus/!svn/ver/71/trunk/src/hl_types.h END ================================================ FILE: _draft/flash_cpp/hashlib/.svn/entries ================================================ 10 dir 77 https://hashlib2plus.svn.sourceforge.net/svnroot/hashlib2plus/trunk/src https://hashlib2plus.svn.sourceforge.net/svnroot/hashlib2plus 2010-06-21T16:29:04.476273Z 77 bennygr 9fabf1d2-8a3a-0410-866c-cb411183c2a1 hl_sha384wrapper.cpp file 2011-10-13T17:29:23.000000Z 17f226c2a3e6270168d48504cd33e4c5 2010-01-24T14:59:38.128638Z 70 bennygr 3872 hl_wrapperfactory.h file 78 2011-10-13T17:38:25.000000Z 6c168d2d628100549c5f86aea00b5eb2 2011-10-13T17:45:28.472824Z 78 bennygr 3081 hl_sha256.h file 2011-10-13T15:33:07.000000Z ac167db3cab5eb2e27a8d41bd76f379e 2010-01-24T14:59:38.128638Z 70 bennygr 6439 hl_sha256wrapper.h file 2011-10-13T15:33:07.000000Z cff339a15b7b14a3ef48314245d91c2b 2010-01-24T14:59:38.128638Z 70 bennygr 4306 hl_sha2ext.cpp file 2011-10-13T17:29:23.000000Z 4cec161a0d4f59437da86e5f1f765bc4 2010-01-24T14:59:38.128638Z 70 bennygr 17404 hl_sha384wrapper.h file 2011-10-13T15:33:07.000000Z f005457935d9c2a049baa9fadd021c6d 2010-01-24T14:59:38.128638Z 70 bennygr 4328 hl_sha2ext.h file 2011-10-13T15:33:07.000000Z a4e096bb8f97a7e5a0660b869f9610da 2010-01-24T14:59:38.128638Z 70 bennygr 8066 hl_sha2mac.h file 2011-10-13T15:33:07.000000Z 28d51c6e7a66d1f27061b371e3faaae4 2010-01-24T14:59:38.128638Z 70 bennygr 7978 hl_md5.cpp file 2011-10-13T17:29:23.000000Z 51cc23699f77568796b7b999fc97bcb7 2010-01-24T14:59:38.128638Z 70 bennygr 13296 hl_md5wrapper.cpp file 2011-10-13T17:29:23.000000Z 15590646af0fbe840a7a97fccc341481 2010-02-21T19:02:17.752873Z 71 bennygr 4135 hl_hashwrapper.h file 78 2011-10-13T17:39:24.000000Z 1ea63f2f3d508eda466826372d671d8c 2011-10-13T17:45:28.472824Z 78 bennygr 8770 hl_md5.h file 2011-10-13T15:33:07.000000Z 28696d2f48d25b659f02c2ce961732ba 2010-01-24T14:59:38.128638Z 70 bennygr 6703 hl_md5wrapper.h file 2011-10-13T15:33:07.000000Z 1a195c7d60cc839cf3231467a2abbcd2 2010-01-24T14:59:38.128638Z 70 bennygr 4197 hl_sha1.cpp file 2011-10-13T17:29:23.000000Z d71e2ae594ad8ac3282d982729ae9c6a 2010-01-24T14:59:38.128638Z 70 bennygr 11049 hashlibpp.h file 78 2011-10-13T17:01:47.000000Z 286599faa35183c3ebe43a8d6cb9a6e8 2011-10-13T17:45:28.472824Z 78 bennygr 2353 hl_sha1wrapper.cpp file 2011-10-13T17:29:23.000000Z edb423e4747fa15007de22433493813d 2010-01-24T14:59:38.128638Z 70 bennygr 4008 hl_sha1.h file 2011-10-13T15:33:07.000000Z 6b43fa03d52be7252b40d2a394a8ef92 2010-01-24T14:59:38.128638Z 70 bennygr 7520 hl_sha1wrapper.h file 2011-10-13T15:33:07.000000Z 30060841e872c93ba4060d1ba3747501 2010-01-24T14:59:38.128638Z 70 bennygr 4169 hl_exception.h file 78 2011-10-13T16:21:12.000000Z d47e62e2482d07775926927f69b22c71 2011-10-13T17:45:28.472824Z 78 bennygr 3370 hl_sha512wrapper.cpp file 2011-10-13T17:29:23.000000Z 29019e1424ec4752f4451616dcd6c90b 2010-01-24T14:59:38.128638Z 70 bennygr 3905 hl_sha256.cpp file 2011-10-13T17:29:23.000000Z f1cb5fa1517094d1c02f8fa85a424241 2010-01-24T14:59:38.128638Z 70 bennygr 14722 hl_wrapperfactory.cpp file 78 2011-10-13T17:29:23.000000Z cb43b8485fa9189e7ca21e52262d25a8 2011-10-13T17:45:28.472824Z 78 bennygr 3251 hl_sha256wrapper.cpp file 2011-10-13T17:29:23.000000Z 19acf3f7d3c25d24b0633cb4a45bc8a9 2010-01-24T14:59:38.128638Z 70 bennygr 3948 Makefile file 78 2011-10-13T15:46:46.000000Z a6f58648331aa4856bfe65b6d5d66b60 2011-10-13T17:45:28.472824Z 78 bennygr 5644 hl_sha512wrapper.h file 2011-10-13T15:33:07.000000Z 629350ff78bd95a50fdd8eb563126da0 2010-01-24T14:59:38.128638Z 70 bennygr 4327 hl_types.h file 2011-10-13T15:33:07.000000Z 5d03e90911fa02c00fcbcda47c885794 2010-02-21T19:02:17.752873Z 71 bennygr 2584 ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/Makefile.svn-base ================================================ # # hashlib++ - a simple hash library for C++ # # Copyright (c) 2007-2010 Benjamin Grdelbach # # 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # #----------------------------------------------------------------------- # # This is the hashlib++ makefile. It builds and installs hashlib++ as a # static library. See the documentation for more information. # # Type 'make' to build the lib. # Type 'make install' to build and install the lib. # Type 'make clean' to clean the object files # # Note for FreeBSD users: # use gmake from "/usr/ports/devel/gmake" # # Benjamin Grdelbach # Mi 10 Okt 2007 # #----------------------------------------------------------------------- # Edit the following lines to meet your needs # Path to install the headerfiles INCLUDE_PATH = /usr/include/hashlib++ # Path to install the library LIB_PATH = /usr/local/lib/ # Compiler to use COMPILER = g++ # Global options for the compiler COPTIONS = -ansi -Wall -Wextra #----------------------------------------------------------------------- # DON'T CHANGE ANYTHING BELOW #----------------------------------------------------------------------- ifdef DEBUG COPTIONS += -g else COPTIONS += -O3 -fomit-frame-pointer endif GCC = $(COMPILER) $(COPTIONS) #----------------------------------------------------------------------- #Main-Target all: MD5 SHA1 SHA256 SHA2EXT CORE LIB #----------------------------------------------------------------------- #all header-files HEADER = hl_hashwrapper.h \ hl_wrapperfactory.h \ hl_exception.h \ hl_md5.h hl_md5wrapper.h \ hl_sha1.h hl_sha1wrapper.h \ hl_sha2mac.h \ hl_sha256.h hl_sha256wrapper.h \ hl_sha2ext.h hl_sha384wrapper.h hl_sha512wrapper.h \ hl_types.h \ hashlibpp.h #----------------------------------------------------------------------- CORE = hl_wrapperfactory.o CORE: hl_wrapperfactory.o hl_wrapperfactory.o: hl_wrapperfactory.cpp hl_wrapperfactory.h $(GCC) -c hl_wrapperfactory.cpp #----------------------------------------------------------------------- # MD5 Targets MD5 = hl_md5.o \ hl_md5wrapper.o MD5: hl_md5.o hl_md5wrapper.o hl_md5.o: hl_md5.cpp hl_md5.h $(GCC) -c hl_md5.cpp hl_md5wrapper.o: hl_md5wrapper.cpp hl_md5wrapper.h $(GCC) -c hl_md5wrapper.cpp #----------------------------------------------------------------------- # SHA1 Targets SHA1 = hl_sha1.o \ hl_sha1wrapper.o SHA1: hl_sha1.o hl_sha1wrapper.o hl_sha1.o: hl_sha1.cpp hl_sha1.h $(GCC) -c hl_sha1.cpp hl_sha1wrapper.o: hl_sha1wrapper.cpp hl_sha1wrapper.h $(GCC) -c hl_sha1wrapper.cpp #----------------------------------------------------------------------- # SHA256 Targets SHA256 = hl_sha256.o \ hl_sha256wrapper.o SHA256: hl_sha256.o hl_sha256wrapper.o hl_sha256.o: hl_sha256.cpp hl_sha256.h hl_sha2mac.h $(GCC) -c hl_sha256.cpp hl_sha256wrapper.o: hl_sha256wrapper.cpp hl_sha256wrapper.h $(GCC) -c hl_sha256wrapper.cpp #----------------------------------------------------------------------- # SHA2-ext Targets SHA2EXT = hl_sha2ext.o \ hl_sha384wrapper.o \ hl_sha512wrapper.o SHA2EXT: hl_sha2ext.o hl_sha384wrapper.o hl_sha512wrapper.o hl_sha2ext.o: hl_sha2ext.cpp hl_sha2ext.h hl_sha2mac.h $(GCC) -c hl_sha2ext.cpp hl_sha384wrapper.o: hl_sha384wrapper.cpp hl_sha384wrapper.h $(GCC) -c hl_sha384wrapper.cpp hl_sha512wrapper.o: hl_sha512wrapper.cpp hl_sha512wrapper.h $(GCC) -c hl_sha512wrapper.cpp #----------------------------------------------------------------------- # Creating a static lib using ar LIB: MD5 SHA1 SHA256 ar rs libhl++.a $(MD5) $(SHA1) $(SHA256) $(SHA2EXT) $(CORE) #----------------------------------------------------------------------- #Installing the lib install: all mkdir -p $(INCLUDE_PATH); \ mkdir -p $(LIB_PATH); \ cp libhl++.a $(LIB_PATH) && \ cp $(HEADER) $(INCLUDE_PATH) -@ echo "" -@ echo "" -@ echo "------------------------------" -@ echo "" -@ echo "hashlib++ has been installed to:" -@ echo "include files: $(INCLUDE_PATH)" -@ echo "library files: $(LIB_PATH)" -@ echo "" -@ echo "------------------------------" #----------------------------------------------------------------------- # Cleaning object-files clean: rm *.o -@ echo "cleaned up " -@ echo "" #----------------------------------------------------------------------- #EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hashlibpp.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hashlibpp.h * @brief This file is just an include wrapper * @date Sa 2 Feb */ //---------------------------------------------------------------------- #ifndef HASHLIBPP_H #define HASHLIBPP_H //---------------------------------------------------------------------- //current version of hashilb++ #define _HASHLIBPP_VERSION_ "0.3.4" //---------------------------------------------------------------------- #include "hl_exception.h" #include "hl_wrapperfactory.h" #include "hl_hashwrapper.h" #include "hl_md5wrapper.h" #include "hl_sha1wrapper.h" #include "hl_sha256wrapper.h" #include "hl_sha384wrapper.h" #include "hl_sha512wrapper.h" //---------------------------------------------------------------------- #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_exception.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_exception.h * @brief This file contains the hashlib++ exception class * @date Sa 24 Nov 2007 */ //---------------------------------------------------------------------- //include protection #ifndef HL_EXCEPTION_H #define HL_EXCEPTION_H //---------------------------------------------------------------------- //STL #include //---------------------------------------------------------------------- /** * definition of hashlib++ errornumbers */ typedef enum hlerrors { HL_NO_ERROR = 0, HL_FILE_READ_ERROR, HL_VERIFY_TEST_FAILED, HL_UNKNOWN_SEE_MSG, HL_UNKNOWN_HASH_TYPE } hlerror; //---------------------------------------------------------------------- /** * @brief This class represents a exception within the hashlib++ * project */ class hlException { private: /** * Error Number */ hlerror iError; /** * Error message as string */ std::string strMessge; public: /** * @brief constructor * @param er Error number * @param m Error message */ hlException(hlerror er, std::string m) { this->iError = er; this->strMessge = m; } /** * @brief constructor * @param m Error Message */ hlException(std::string m) { this->iError = HL_UNKNOWN_SEE_MSG; this->strMessge = m; } /** * @brief returns the error message * @return the error message */ std::string error_message(void) { return strMessge; } /** * @brief returns the error number * @return the error number */ hlerror error_number(void) { return iError; } }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_hashwrapper.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2011 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- //doxygen mainpage /** * @mainpage hashlib++ source documentation * *
    Version 0.3.4
    * * * @section intro Introduction * hashlib++ a simple hash library for C++ \n * Copyright (c) 2007-2011 Benjamin Grüdelbach * * * * hashlib++ is a simple and very easy to use library to create a * cryptographic checksum called "hash". hashlib++ is written in * plain C++ and should work with every compiler and platform. * hashlib++ is released under the BSD-license and * therefore free software. * * @section about About this document * * This is the documentation about the hashlib++ sourcecode. * Since it contains some internal information it its helpfull * but not necessary to read for the average user. * If you are new to hashlib++ you should start with reading * the README.TXT file which contains all relevant information * to start using this library. * */ //---------------------------------------------------------------------- /** * @file hl_hashwrapper.h * @brief This file contains the hashwrapper base class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef HASHWRAPPER_H #define HASHWRAPPER_H //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //C includes //#include #include //---------------------------------------------------------------------- //hashlib++ includes #include "hl_exception.h" //---------------------------------------------------------------------- /** * @brief This class represents the baseclass for all subwrappers * * hashwrapper is the abstract base class of all subwrappers like md5wrapper * or sha1wrapper. This class implements two simple and easy to use * memberfunctions to create a hash based on a string or a file. * ( getHashFromString() and getHashFromFile() ) * * getHashFromString() calls resetContext(), updateContext() and hashIt() * in this order. These three memberfunctions are pure virtual and have to * be implemented by the subclasses. * * getHashFromFile() calls resetContext() before reading the specified file * in 1024 byte blocks which are forwarded to the hash context by calling * updateContext(). Finaly hashIt() is called to return the hash. */ class hashwrapper { private: const std::string teststring; protected: /** * @brief This method finalizes the hash process * and returns the hash as std::string * * This memberfunction is pure virtual and * has to be implemented by the subclass * * @return the created hash as std::string */ virtual std::string hashIt(void) = 0; /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX) * * This memberfunction is pure virtual and * has to be implemented by the subclass * * @param data The hash-data to covert into HEX * @return The converted data as std::string */ virtual std::string convToString(unsigned char *data) = 0; /** * @brief This method adds the given data to the * current hash context * * This memberfunction is pure virtual and * has to be implemented by the subclass * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len) = 0; /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. * * This memberfunction is pure virtual and * has to be implemented by the subclass */ virtual void resetContext(void) = 0; /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void) = 0; public: /** * @brief Default Konstruktor */ hashwrapper( void ) : teststring("The quick brown fox jumps over the lazy dog") { } /** * @brief Default destructor */ virtual ~hashwrapper ( void ) { }; /** * @brief Method for testing the concrete implementation */ virtual void test( void ) { std::string hash = this->getHashFromString(teststring); std::string verify = this->getTestHash(); if(hash != verify) { throw hlException(HL_VERIFY_TEST_FAILED, "hashlib test-error: \"" + hash + "\" is not \"" + verify + "\" as supposed to be."); } } /** * @brief This method creates a hash based on the * given string * * This memberfunctions calls resetContext(), * updateContext() and hashIt() in this order. * These three memberfunctions are pure virtual and have to * be implemented by the subclasses. * * @param text The text to create a hash from. This * parameter is forwarded to updateContext() * @return the created hash as std::string */ virtual std::string getHashFromString(std::string text) { /* * reset the context so that we can start * with a new hash process */ resetContext(); /* * we update the context with the given text */ updateContext((unsigned char*) text.c_str(),text.length()); /* * now we can close the hash process * and return the created hash */ return this->hashIt(); } /** * @brief This method creates a hash from a given file * * First of all resetContext() is called before reading the * specified file in 1024 byte blocks which are forwarded * to the hash context by calling updateContext(). * Finaly hashIt() is called to return the hash. * These three memberfunctions are pure virtual and have to * be implemented by the subclasses. * * @param filename The file to created a hash from * * @return The created hash of the file or "-1" in case * the file could not be opened * @throw Throws a hlException if the specified file could not * be opened. */ virtual std::string getHashFromFile(std::string filename) { FILE *file; int len; unsigned char buffer[1024]; /* * reset the current hash context */ resetContext(); /* * open the specified file */ if((file = fopen(filename.c_str(), "rb")) == NULL) { throw hlException(HL_FILE_READ_ERROR, "Cannot read file \"" + filename + "\"."); } /* * read the file in 1024b blocks and * update the context for every block */ while( (len = fread(buffer,1,1024,file)) ) { updateContext(buffer, len); } //close the file and create the hash fclose(file); return(hashIt()); } }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_md5.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ MD5 implementation is derivative from the sourcecode * published in RFC 1321 * * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All * rights reserved. * * License to copy and use this software is granted provided that it * is identified as the "RSA Data Security, Inc. MD5 Message-Digest * Algorithm" in all material mentioning or referencing this software * or this function. * * License is also granted to make and use derivative works provided * that such works are identified as "derived from the RSA Data * Security, Inc. MD5 Message-Digest Algorithm" in all material * mentioning or referencing the derived work. * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. */ //---------------------------------------------------------------------- /** * @file hl_md5.cpp * @brief This file contains the implementation of the MD5 class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_md5.h" //---------------------------------------------------------------------- // defines // Constants for MD5Transform routine. #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 static unsigned char PADDING[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* F, G, H and I are basic MD5 functions. */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~z))) /* * ROTATE_LEFT rotates x left n bits. * cast to unsigned int to guarantee support for 64Bit System */ #define ROTATE_LEFT(x, n) (((x) << (n)) | (( (unsigned int) x) >> (32-(n)))) /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) { \ (a) += F ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define GG(a, b, c, d, x, s, ac) { \ (a) += G ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define HH(a, b, c, d, x, s, ac) { \ (a) += H ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define II(a, b, c, d, x, s, ac) { \ (a) += I ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } //---------------------------------------------------------------------- //private member-functions /** * @brief Basic transformation. Transforms state based on block. * @param state state to transform * @param block block to transform */ void MD5::MD5Transform (unsigned long int state[4], unsigned char block[64]) { unsigned long int a = state[0], b = state[1], c = state[2], d = state[3], x[16]; Decode (x, block, 64); /* Round 1 */ FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; /* * Zeroize sensitive information. */ MD5_memset ((POINTER)x, 0, sizeof (x)); } /** * @brief Encodes input data * @param output Encoded data as OUT parameter * @param input Input data * @param len The length of the input assuming it is a * multiple of 4 */ void MD5::Encode (unsigned char *output, unsigned long int *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) { output[j] = (unsigned char)(input[i] & 0xff); output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); } } /** * @brief Decodes input data into output * @param output Decoded data as OUT parameter * @param input Input data * @param len The length of the input assuming it is a * multiple of 4 */ void MD5::Decode (unsigned long int *output, unsigned char *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) output[i] = ((unsigned long int)input[j]) | (((unsigned long int)input[j+1]) << 8) | (((unsigned long int)input[j+2]) << 16) | (((unsigned long int)input[j+3]) << 24); } /** * @brief internal memory management * @param output OUT parameter where POINTER is a unsigned * char* * @param input Data to copy where POINTER is a unsigned char* * @param len The length of the data */ void MD5::MD5_memcpy (POINTER output, POINTER input, unsigned int len) { /* * TODO-Note: Replace "for loop" with standard memcpy if possible. */ unsigned int i; for (i = 0; i < len; i++) output[i] = input[i]; } /** * @brief internal memory management * @param output OUT parameter where POINTER is an unsigned * char* * @param value Value to fill the memory with * @param len The length of the data * */ void MD5::MD5_memset (POINTER output,int value,unsigned int len) { /* * TODO-Note: Replace "for loop" with standard memset if possible. */ unsigned int i; for (i = 0; i < len; i++) ((char *)output)[i] = (char)value; } //---------------------------------------------------------------------- //public member-functions /** * @brief Initialization begins an operation, * writing a new context * @param context The HL_MD5_CTX context to initialize */ void MD5::MD5Init (HL_MD5_CTX *context) { context->count[0] = context->count[1] = 0; context->state[0] = 0x67452301; context->state[1] = 0xefcdab89; context->state[2] = 0x98badcfe; context->state[3] = 0x10325476; } /** * @brief Block update operation. Continues an md5 * message-digest operation, processing another * message block, and updating the context. * @param context The HL_MD5_CTX context to update * @param input The data to write into the context * @param inputLen The length of the input data */ void MD5::MD5Update (HL_MD5_CTX *context, unsigned char *input, unsigned int inputLen) { unsigned int i, index, partLen; /* Compute number of bytes mod 64 */ index = (unsigned int)((context->count[0] >> 3) & 0x3F); /* Update number of bits */ if ( (context->count[0] += ((unsigned long int)inputLen << 3)) < ((unsigned long int)inputLen << 3)) context->count[1]++; context->count[1] += ((unsigned long int)inputLen >> 29); partLen = 64 - index; /* * Transform as many times as possible. */ if (inputLen >= partLen) { MD5_memcpy ((POINTER)&context->buffer[index], (POINTER)input, partLen); MD5Transform (context->state, context->buffer); for (i = partLen; i + 63 < inputLen; i += 64) MD5Transform (context->state, &input[i]); index = 0; } else i = 0; /* Buffer remaining input */ MD5_memcpy ((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i); } /** * @brief Finalization ends the md5 message-digest * operation, writing the the message digest and * zeroizing the context. * @param digest This is an OUT parameter which contains * the created hash after the method returns * @param context The context to finalize */ void MD5::MD5Final (unsigned char digest[16], HL_MD5_CTX *context) { unsigned char bits[8]; unsigned int index, padLen; /* Save number of bits */ Encode (bits, context->count, 8); /* * Pad out to 56 mod 64. */ index = (unsigned int)((context->count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); MD5Update (context, PADDING, padLen); /* Append length (before padding) */ MD5Update (context, bits, 8); /* Store state in digest */ Encode (digest, context->state, 16); /* * Zeroize sensitive information. */ MD5_memset ((POINTER)context, 0, sizeof (*context)); } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_md5.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ MD5 implementation is derivative from the sourcecode * published in RFC 1321 * * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All * rights reserved. * * License to copy and use this software is granted provided that it * is identified as the "RSA Data Security, Inc. MD5 Message-Digest * Algorithm" in all material mentioning or referencing this software * or this function. * * License is also granted to make and use derivative works provided * that such works are identified as "derived from the RSA Data * Security, Inc. MD5 Message-Digest Algorithm" in all material * mentioning or referencing the derived work. * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. */ //---------------------------------------------------------------------- /** * @file hl_md5.h * @brief This file contains the declaration of the MD5 class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef MD5_H #define MD5_H //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //hl includes #include "hl_types.h" //---------------------------------------------------------------------- //typedefs typedef hl_uint8 *POINTER; /** * @brief this struct represents a MD5-hash context. */ typedef struct { /** state (ABCD) */ unsigned long int state[4]; /** number of bits, modulo 2^64 (lsb first) */ unsigned long int count[2]; /** input buffer */ unsigned char buffer[64]; } HL_MD5_CTX; //---------------------------------------------------------------------- /** * @brief This class represents the implementation of * the md5 message digest algorithm. * * Basically the class provides three public member-functions * to create a hash: MD5Init(), MD5Update() and MD5Final(). * If you want to create a hash based on a string or file quickly * you should use the md5wrapper class instead of MD5. */ class MD5 { private: /** * @brief Basic transformation. Transforms state based on block. * @param state state to transform * @param block block to transform */ void MD5Transform (unsigned long int state[4], unsigned char block[64]); /** * @brief Encodes input data * @param output Encoded data as OUT parameter * @param input Input data * @param len The length of the input assuming it is a * multiple of 4 */ void Encode (unsigned char* output, unsigned long int *input, unsigned int len); /** * @brief Decodes input data into output * @param output Decoded data as OUT parameter * @param input Input data * @param len The length of the input assuming it is a * multiple of 4 */ void Decode (unsigned long int *output, unsigned char *input, unsigned int len); /** * @brief internal memory management * @param output OUT parameter where POINTER is an unsigned * char* * @param input Data to copy where POINTER is a unsigned char* * @param len The length of the data */ void MD5_memcpy (POINTER output, POINTER input, unsigned int len); /** * @brief internal memory management * @param output OUT parameter where POINTER is an unsigned * char* * @param value Value to fill the memory with * @param len The length of the data * */ void MD5_memset (POINTER output, int value, unsigned int len); public: /** * @brief Initialization begins an operation, * writing a new context * @param context The HL_MD5_CTX context to initialize */ void MD5Init (HL_MD5_CTX* context); /** * @brief Block update operation. Continues an md5 * message-digest operation, processing another * message block, and updating the context. * @param context The HL_MD5_CTX context to update * @param input The data to write into the context * @param inputLen The length of the input data */ void MD5Update (HL_MD5_CTX* context, unsigned char *input, unsigned int inputLen); /** * @brief Finalization ends the md5 message-digest * operation, writing the the message digest and * zeroizing the context. * @param digest This is an OUT parameter which contains * the created hash after the method returns * @param context The context to finalize */ void MD5Final (unsigned char digest[16], HL_MD5_CTX* context); /** * @brief default constructor */ MD5(){}; }; //---------------------------------------------------------------------- //End of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_md5wrapper.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_md5wrapper.cpp * @brief This file contains the implementation of the * md5wrapper class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //STL includes #include #include #include #include //---------------------------------------------------------------------- //hashlib++ includes #include "hl_md5wrapper.h" //---------------------------------------------------------------------- //private member functions /** * @brief This method ends the hash process * and returns the hash as string. * * @return the hash as std::string */ std::string md5wrapper::hashIt(void) { //create the hash unsigned char buff[16] = ""; md5->MD5Final((unsigned char*)buff,&ctx); //converte the hash to a string and return it return convToString(buff); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string md5wrapper::convToString(unsigned char *data) { /* * using a ostringstream to convert the hash in a * hex string */ std::ostringstream os; for(int i=0; i<16; ++i) { /* * set the width to 2 */ os.width(2); /* * fill with 0 */ os.fill('0'); /* * conv to hex */ os << std::hex << static_cast(data[i]); } /* * return as std::string */ return os.str(); } /** * @brief This method adds the given data to the * current hash context. * * @param data The data to add to the current context * @param len The length of the data to add */ void md5wrapper::updateContext(unsigned char *data, unsigned int len) { //update md5->MD5Update(&ctx, data, len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void md5wrapper::resetContext(void) { //init md5 md5->MD5Init(&ctx); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string md5wrapper::getTestHash(void) { return "9e107d9d372bb6826bd81d3542a419d6"; } //---------------------------------------------------------------------- //public member functions /** * @brief default constructor */ md5wrapper::md5wrapper() { md5 = new MD5(); } /** * @brief default destructor */ md5wrapper::~md5wrapper() { delete md5; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_md5wrapper.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_md5wrapper.h * @brief This file contains the definition of the md5wrapper * class. * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef MD5WRAPPER_H #define MD5WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_md5.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- /** * @brief This class represents the MD5 wrapper-class * * You can use this class to easily create a md5 hash. * Just create an instance of md5wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include md5example.cpp * * md5wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class md5wrapper : public hashwrapper { protected: /** * MD5 access */ MD5 *md5; /** * MD5 context */ HL_MD5_CTX ctx; /** * @brief This method ends the hash process * and returns the hash as string. * * @return the hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context. * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ md5wrapper(); /** * @brief default destructor */ virtual ~md5wrapper(); }; //---------------------------------------------------------------------- //include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha1.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA1 implementation is derivative from the sourcecode * published in RFC 3174 * * Copyright (C) The Internet Society (2001). All Rights Reserved. * * This document and translations of it may be copied and furnished to * others, and derivative works that comment on or otherwise explain it * or assist in its implementation may be prepared, copied, published * and distributed, in whole or in part, without restriction of any * kind, provided that the above copyright notice and this paragraph are * included on all such copies and derivative works. However, this * document itself may not be modified in any way, such as by removing * the copyright notice or references to the Internet Society or other * Internet organizations, except as needed for the purpose of * developing Internet standards in which case the procedures for * copyrights defined in the Internet Standards process must be * followed, or as required to translate it into languages other than * English. * * The limited permissions granted above are perpetual and will not be * revoked by the Internet Society or its successors or assigns. * * This document and the information contained herein is provided on an * "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING * TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION * HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */ //---------------------------------------------------------------------- /** * @file hl_sha1.cpp * @brief This file contains the implementation of the SHA1 class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha1.h" //---------------------------------------------------------------------- //defines /* * Define the SHA1 circular left shift macro */ #define SHA1CircularShift(bits,word) \ (((word) << (bits)) | ((word) >> (32-(bits)))) //---------------------------------------------------------------------- //private member-functions /** * @brief Internal method to padd the message * * According to the standard, the message must * be padded to an even 512 bits. The first * padding bit must be a '1'. The last 64 bits * represent the length of the original message. * All bits in between should be 0. * This function will pad the message according * to those rules by filling the Message_Block array * accordingly. It will also call the * ProcessMessageBlock function provided appropriately. * When it returns, it can be assumed that the message * digest has been computed. * * @param context The context to padd * */ void SHA1::SHA1PadMessage(HL_SHA1_CTX *context) { /* * Check to see if the current message block is too small to hold * the initial padding bits and length. If so, we will pad the * block, process it, and then continue padding into a second * block. */ if (context->Message_Block_Index > 55) { context->Message_Block[context->Message_Block_Index++] = 0x80; while(context->Message_Block_Index < 64) { context->Message_Block[context->Message_Block_Index++] = 0; } SHA1ProcessMessageBlock(context); while(context->Message_Block_Index < 56) { context->Message_Block[context->Message_Block_Index++] = 0; } } else { context->Message_Block[context->Message_Block_Index++] = 0x80; while(context->Message_Block_Index < 56) { context->Message_Block[context->Message_Block_Index++] = 0; } } /* * Store the message length as the last 8 octets */ context->Message_Block[56] = context->Length_High >> 24; context->Message_Block[57] = context->Length_High >> 16; context->Message_Block[58] = context->Length_High >> 8; context->Message_Block[59] = context->Length_High; context->Message_Block[60] = context->Length_Low >> 24; context->Message_Block[61] = context->Length_Low >> 16; context->Message_Block[62] = context->Length_Low >> 8; context->Message_Block[63] = context->Length_Low; SHA1ProcessMessageBlock(context); } /** * @brief This member-function will process the next 512 bits of the * message stored in the Message_Block array. * * Many of the variable names in this code, especially the * single character names, were used because those were the * names used in the publication. * * @param context The context to process */ void SHA1::SHA1ProcessMessageBlock(HL_SHA1_CTX *context) { const hl_uint32 K[] = { /* Constants defined in SHA-1 */ 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 }; int t; /* Loop counter */ hl_uint32 temp; /* Temporary word value */ hl_uint32 W[80]; /* Word sequence */ hl_uint32 A, B, C, D, E; /* Word buffers */ /* * Initialize the first 16 words in the array W */ for(t = 0; t < 16; t++) { W[t] = context->Message_Block[t * 4] << 24; W[t] |= context->Message_Block[t * 4 + 1] << 16; W[t] |= context->Message_Block[t * 4 + 2] << 8; W[t] |= context->Message_Block[t * 4 + 3]; } for(t = 16; t < 80; t++) { W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); } A = context->Intermediate_Hash[0]; B = context->Intermediate_Hash[1]; C = context->Intermediate_Hash[2]; D = context->Intermediate_Hash[3]; E = context->Intermediate_Hash[4]; for(t = 0; t < 20; t++) { temp = SHA1CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 20; t < 40; t++) { temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 40; t < 60; t++) { temp = SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 60; t < 80; t++) { temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } context->Intermediate_Hash[0] += A; context->Intermediate_Hash[1] += B; context->Intermediate_Hash[2] += C; context->Intermediate_Hash[3] += D; context->Intermediate_Hash[4] += E; context->Message_Block_Index = 0; } //---------------------------------------------------------------------- //public member-functions /** * @brief Resets the sha1 context and starts a new * hashprocess * @param context The context to reset * @return 0 on succes an error number otherwise */ int SHA1::SHA1Reset(HL_SHA1_CTX *context) { if (!context) { return shaNull; } context->Length_Low = 0; context->Length_High = 0; context->Message_Block_Index = 0; context->Intermediate_Hash[0] = 0x67452301; context->Intermediate_Hash[1] = 0xEFCDAB89; context->Intermediate_Hash[2] = 0x98BADCFE; context->Intermediate_Hash[3] = 0x10325476; context->Intermediate_Hash[4] = 0xC3D2E1F0; context->Computed = 0; context->Corrupted = 0; return shaSuccess; } /** * @brief Data input. * * This memberfunction add data to the specified * context. * * @param context The context to add data to * @param message_array The data to add * @param length The length of the data to add */ int SHA1::SHA1Input( HL_SHA1_CTX *context, const hl_uint8 *message_array, unsigned int length) { if (!length) { return shaSuccess; } if (!context || !message_array) { return shaNull; } if (context->Computed) { context->Corrupted = shaStateError; return shaStateError; } if (context->Corrupted) { return context->Corrupted; } while(length-- && !context->Corrupted) { context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF); context->Length_Low += 8; if (context->Length_Low == 0) { context->Length_High++; if (context->Length_High == 0) { /* Message is too long */ context->Corrupted = 1; } } if (context->Message_Block_Index == 64) { SHA1ProcessMessageBlock(context); } message_array++; } return shaSuccess; } /** * @brief This ends the sha operation, zeroizing the context * and returning the computed hash. * * @param context The context to get the hash from * @param Message_Digest This is an OUT parameter which * contains the hash after the menberfunction returns * @return 0 on succes, an error-code otherwise */ int SHA1::SHA1Result( HL_SHA1_CTX *context, hl_uint8 Message_Digest[SHA1HashSize]) { int i; if (!context || !Message_Digest) { return shaNull; } if (context->Corrupted) { return context->Corrupted; } if (!context->Computed) { SHA1PadMessage(context); for(i=0; i<64; ++i) { /* message may be sensitive, clear it out */ context->Message_Block[i] = 0; } context->Length_Low = 0; /* and clear length */ context->Length_High = 0; context->Computed = 1; } for(i = 0; i < SHA1HashSize; ++i) { Message_Digest[i] = context->Intermediate_Hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) ); } return shaSuccess; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha1.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA1 implementation is derivative from the sourcecode * published in RFC 3174 * * Copyright (C) The Internet Society (2001). All Rights Reserved. * * This document and translations of it may be copied and furnished to * others, and derivative works that comment on or otherwise explain it * or assist in its implementation may be prepared, copied, published * and distributed, in whole or in part, without restriction of any * kind, provided that the above copyright notice and this paragraph are * included on all such copies and derivative works. However, this * document itself may not be modified in any way, such as by removing * the copyright notice or references to the Internet Society or other * Internet organizations, except as needed for the purpose of * developing Internet standards in which case the procedures for * copyrights defined in the Internet Standards process must be * followed, or as required to translate it into languages other than * English. * * The limited permissions granted above are perpetual and will not be * revoked by the Internet Society or its successors or assigns. * * This document and the information contained herein is provided on an * "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING * TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION * HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */ //---------------------------------------------------------------------- /** * @file hl_sha1.h * @brief This file contains the declaration of the SHA1 class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA1_H #define SHA1_H //---------------------------------------------------------------------- //hl includes #include "hl_types.h" //---------------------------------------------------------------------- //enums #ifndef _SHA_enum_ #define _SHA_enum_ enum { shaSuccess = 0, shaNull, /* Null pointer parameter */ shaInputTooLong, /* input data too long */ shaStateError /* called Input after Result */ }; #endif //---------------------------------------------------------------------- //defines #define SHA1HashSize 20 //---------------------------------------------------------------------- //structs /** * @brief this struct represents a SHA1-hash context. */ typedef struct HL_SHA1_CTX { /** Message Digest */ hl_uint32 Intermediate_Hash[SHA1HashSize/4]; /** Message length in bits */ hl_uint32 Length_Low; /** Message length in bits */ hl_uint32 Length_High; /** Index into message block array */ hl_uint16 Message_Block_Index; /** 512-bit message blocks */ hl_uint8 Message_Block[64]; /** Is the digest computed? */ int Computed; /** Is the message digest corrupted? */ int Corrupted; } HL_SHA1_CTX; //---------------------------------------------------------------------- //class definition /** * @brief This class represents the implementation of * the sha1 algorithm. * * Basically the class provides three public member-functions * to create a hash: SHA1Reset(), SHA1Input() and SHA1Result(). * If you want to create a hash based on a string or file quickly * you should use the sha1wrapper class instead of SHA1. */ class SHA1 { private: /** * @brief Internal method to padd the message * * According to the standard, the message must * be padded to an even 512 bits. The first * padding bit must be a '1'. The last 64 bits * represent the length of the original message. * All bits in between should be 0. * This function will pad the message according * to those rules by filling the Message_Block array * accordingly. It will also call the * ProcessMessageBlock function provided appropriately. * When it returns, it can be assumed that the message * digest has been computed. * * @param context The context to padd * */ void SHA1PadMessage(HL_SHA1_CTX *context); /** * @brief This member-function will process the next 512 bits of the * message stored in the Message_Block array. * * Many of the variable names in this code, especially the * single character names, were used because those were the * names used in the publication. * * @param context The context to process */ void SHA1ProcessMessageBlock(HL_SHA1_CTX *context); public: /** * @brief Resets the sha1 context and starts a new * hashprocess * @param context The context to reset * @return 0 on succes an error number otherwise */ int SHA1Reset( HL_SHA1_CTX *context); /** * @brief Data input. * * This memberfunction add data to the specified * context. * * @param context The context to add data to * @param message_array The data to add * @param length The length of the data to add */ int SHA1Input( HL_SHA1_CTX *context, const hl_uint8 *message_array, unsigned int length); /** * @brief This ends the sha operation, zeroizing the context * and returning the computed hash. * * @param context The context to get the hash from * @param Message_Digest This is an OUT parameter which * contains the hash after the menberfunction returns * @return 0 on succes, an error-code otherwise */ int SHA1Result( HL_SHA1_CTX *context, hl_uint8 Message_Digest[SHA1HashSize]); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha1wrapper.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha1wrapper.cpp * @brief This file contains the implementation of the * sha1wrapper class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha1wrapper.h" #include "hl_sha1.h" #include "hl_types.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //private memberfunctions /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ std::string sha1wrapper::hashIt(void) { hl_uint8 Message_Digest[20]; sha1->SHA1Result(&context, Message_Digest); return convToString(Message_Digest); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string sha1wrapper::convToString(unsigned char *data) { std::ostringstream os; for(int i=0; i<20; ++i) { /* * set the width to 2 */ os.width(2); /* * fill with 0 */ os.fill('0'); /* * conv to hex */ os << std::hex << static_cast(data[i]); } /* * return as std::string */ return os.str(); } /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ void sha1wrapper::updateContext(unsigned char *data, unsigned int len) { sha1->SHA1Input(&context, data, len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void sha1wrapper::resetContext(void) { sha1->SHA1Reset(&context); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string sha1wrapper::getTestHash(void) { return "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"; } //---------------------------------------------------------------------- //public memberfunctions /** * @brief default constructor */ sha1wrapper::sha1wrapper() { this->sha1 = new SHA1(); } /** * @brief default destructor */ sha1wrapper::~sha1wrapper() { delete this->sha1; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha1wrapper.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha1wrapper.h * @brief This file contains the definition of the sha1wrapper * class. * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA1WRAPPER_H #define SHA1WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_sha1.h" //---------------------------------------------------------------------- /** * @brief This class represents the SHA1 wrapper-class * * You can use this class to easily create a sha1 hash. * Just create an instance of sha1wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include sha1example.cpp * * sha1wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class sha1wrapper : public hashwrapper { protected: /** * SHA1 access */ SHA1 *sha1; /* * SHA1 context */ HL_SHA1_CTX context; /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ sha1wrapper(); /** * @brief default destructor */ virtual ~sha1wrapper(); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha256.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA256 implementation is derivative from the sourcecode * published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. * */ //---------------------------------------------------------------------- /** * @file hl_sha256.cpp * @brief This file contains the implementation of the SHA256 class * @date Di 25 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha256.h" //---------------------------------------------------------------------- /* * Standard C includes */ #include #include //---------------------------------------------------------------------- #include "hl_sha2mac.h" //---------------------------------------------------------------------- /* * Hash constant words K for SHA-256: */ const static sha2_word32 K256[64] = { 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL }; /* * Initial hash value H for SHA-256: */ const static sha2_word32 sha256_initial_hash_value[8] = { 0x6a09e667UL, 0xbb67ae85UL, 0x3c6ef372UL, 0xa54ff53aUL, 0x510e527fUL, 0x9b05688cUL, 0x1f83d9abUL, 0x5be0cd19UL }; /* * Constant used by End() functions for converting the * digest to a readable hexadecimal character string: */ static const char *sha2_hex_digits = "0123456789abcdef"; /*** SHA-256: *********************************************************/ /** * @brief Initialize the context * @param context The context to init. */ void SHA256::SHA256_Init(HL_SHA256_CTX* context) { if (context == (HL_SHA256_CTX*)0) { return; } MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH); context->bitcount = 0; } #ifdef SHA2_UNROLL_TRANSFORM /* Unrolled SHA-256 round macros: */ #if BYTE_ORDER == LITTLE_ENDIAN #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ REVERSE32(*data++, W256[j]); \ T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ K256[j] + W256[j]; \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ #else /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ K256[j] + (W256[j] = *data++); \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ #endif /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND256(a,b,c,d,e,f,g,h) \ s0 = W256[(j+1)&0x0f]; \ s0 = sigma0_256(s0); \ s1 = W256[(j+14)&0x0f]; \ s1 = sigma1_256(s1); \ T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \ (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA256::SHA256_Transform(HL_SHA256_CTX* context, const sha2_word32* data) { sha2_word32 a, b, c, d, e, f, g, h, s0, s1; sha2_word32 T1, *W256; int j; W256 = (sha2_word32*)context->buffer; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { /* Rounds 0 to 15 (unrolled): */ ROUND256_0_TO_15(a,b,c,d,e,f,g,h); ROUND256_0_TO_15(h,a,b,c,d,e,f,g); ROUND256_0_TO_15(g,h,a,b,c,d,e,f); ROUND256_0_TO_15(f,g,h,a,b,c,d,e); ROUND256_0_TO_15(e,f,g,h,a,b,c,d); ROUND256_0_TO_15(d,e,f,g,h,a,b,c); ROUND256_0_TO_15(c,d,e,f,g,h,a,b); ROUND256_0_TO_15(b,c,d,e,f,g,h,a); } while (j < 16); /* Now for the remaining rounds to 64: */ do { ROUND256(a,b,c,d,e,f,g,h); ROUND256(h,a,b,c,d,e,f,g); ROUND256(g,h,a,b,c,d,e,f); ROUND256(f,g,h,a,b,c,d,e); ROUND256(e,f,g,h,a,b,c,d); ROUND256(d,e,f,g,h,a,b,c); ROUND256(c,d,e,f,g,h,a,b); ROUND256(b,c,d,e,f,g,h,a); } while (j < 64); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = 0; } #else /* SHA2_UNROLL_TRANSFORM */ /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA256::SHA256_Transform(HL_SHA256_CTX* context, const sha2_word32* data) { sha2_word32 a, b, c, d, e, f, g, h, s0, s1; sha2_word32 T1, T2, *W256; int j; W256 = (sha2_word32*)context->buffer; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { #if BYTE_ORDER == LITTLE_ENDIAN /* Copy data while converting to host byte order */ REVERSE32(*data++,W256[j]); /* Apply the SHA-256 compression function to update a..h */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j]; #else /* BYTE_ORDER == LITTLE_ENDIAN */ /* Apply the SHA-256 compression function to update a..h with copy */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++); #endif /* BYTE_ORDER == LITTLE_ENDIAN */ T2 = Sigma0_256(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 16); do { /* Part of the message block expansion: */ s0 = W256[(j+1)&0x0f]; s0 = sigma0_256(s0); s1 = W256[(j+14)&0x0f]; s1 = sigma1_256(s1); /* Apply the SHA-256 compression function to update a..h */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); T2 = Sigma0_256(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 64); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = T2 = 0; } #endif /* SHA2_UNROLL_TRANSFORM */ /** * @brief Updates the context * @param context The context to update. * @param data The data for updating the context. * @param len The length of the given data. */ void SHA256::SHA256_Update(HL_SHA256_CTX* context, const sha2_byte *data, unsigned int len) { unsigned int freespace, usedspace; if (len == 0) { /* Calling with no data is valid - we do nothing */ return; } /* Sanity check: */ assert(context != (HL_SHA256_CTX*)0 && data != (sha2_byte*)0); usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; if (usedspace > 0) { /* Calculate how much free space is available in the buffer */ freespace = SHA256_BLOCK_LENGTH - usedspace; if (len >= freespace) { /* Fill the buffer completely and process it */ MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); context->bitcount += freespace << 3; len -= freespace; data += freespace; SHA256_Transform(context, (sha2_word32*)context->buffer); } else { /* The buffer is not yet full */ MEMCPY_BCOPY(&context->buffer[usedspace], data, len); context->bitcount += len << 3; /* Clean up: */ usedspace = freespace = 0; return; } } while (len >= SHA256_BLOCK_LENGTH) { /* Process as many complete blocks as we can */ SHA256_Transform(context, (sha2_word32*)data); context->bitcount += SHA256_BLOCK_LENGTH << 3; len -= SHA256_BLOCK_LENGTH; data += SHA256_BLOCK_LENGTH; } if (len > 0) { /* There's left-overs, so save 'em */ MEMCPY_BCOPY(context->buffer, data, len); context->bitcount += len << 3; } /* Clean up: */ usedspace = freespace = 0; } /** * @brief Finalize the sha256 operation * @param digest The digest to finalize the operation with. * @param context The context to finalize. */ void SHA256::SHA256_Final(sha2_byte digest[], HL_SHA256_CTX* context) { sha2_word32 *d = (sha2_word32*)digest; unsigned int usedspace; /* Sanity check: */ assert(context != (HL_SHA256_CTX*)0); /* If no digest buffer is passed, we don't bother doing this: */ if (digest != (sha2_byte*)0) { usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; #if BYTE_ORDER == LITTLE_ENDIAN /* Convert FROM host byte order */ REVERSE64(context->bitcount,context->bitcount); #endif if (usedspace > 0) { /* Begin padding with a 1 bit: */ context->buffer[usedspace++] = 0x80; if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) { /* Set-up for the last transform: */ MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace); } else { if (usedspace < SHA256_BLOCK_LENGTH) { MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace); } /* Do second-to-last transform: */ SHA256_Transform(context, (sha2_word32*)context->buffer); /* And set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); } } else { /* Set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); /* Begin padding with a 1 bit: */ *context->buffer = 0x80; } /* Set the bit count: */ *(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount; /* Final transform: */ SHA256_Transform(context, (sha2_word32*)context->buffer); #if BYTE_ORDER == LITTLE_ENDIAN { /* Convert TO host byte order */ int j; for (j = 0; j < 8; j++) { REVERSE32(context->state[j],context->state[j]); *d++ = context->state[j]; } } #else MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH); #endif } /* Clean up state data: */ MEMSET_BZERO(context, sizeof(context)); usedspace = 0; } /** * @brief Ends the sha256 operation and return the * created hash in the given buffer. * @param context The context to end. * @param buffer This OUT-Parameter contains the created * hash after ending the operation. */ char* SHA256::SHA256_End(HL_SHA256_CTX* context, char buffer[]) { sha2_byte digest[SHA256_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != (HL_SHA256_CTX*)0); if (buffer != (char*)0) { SHA256_Final(digest, context); for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = (char)0; } else { MEMSET_BZERO(context, sizeof(context)); } MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH); return buffer; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha256.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA256 implementation is derivative from the sourcecode * published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. */ //---------------------------------------------------------------------- /** * @file hl_sha256.h * @brief This file contains the declaration of the SHA256 class * @date Di 25 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA256_H #define SHA256_H //---------------------------------------------------------------------- //lenght defines #define SHA256_BLOCK_LENGTH 64 #define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8) #define SHA256_DIGEST_LENGTH 32 #define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1) //---------------------------------------------------------------------- //hl includes #include "hl_types.h" //---------------------------------------------------------------------- //typedefs /** * Exactly 1 byte */ typedef hl_uint8 sha2_byte; /** * Exactly 4 bytes */ typedef hl_uint32 sha2_word32; /** * Exactly 8 bytes */ typedef hl_uint64 sha2_word64; /** * @brief This struct represents a SHA256-hash context */ typedef struct HL_SHA256_CTX { /** * state */ hl_uint32 state[8]; /** * bitcount */ hl_uint64 bitcount; /** * message buffer */ hl_uint8 buffer[SHA256_BLOCK_LENGTH]; } HL_SHA256_CTX; //---------------------------------------------------------------------- /** * @brief This class represents the implementation of * the sha256 algorithm. * * Basically the class provides three public member-functions * to create a hash: SHA256_Init(), SHA256_Update() and SHA256_End(). * If you want to create a hash based on a string or file quickly * you should use the sha256wrapper class instead of SHA256. */ class SHA256 { private: /** * @brief Finalize the sha256 operation * @param digest The digest to finalize the operation with. * @param context The context to finalize. */ void SHA256_Final(hl_uint8 digest[SHA256_DIGEST_LENGTH], HL_SHA256_CTX* context); /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA256_Transform(HL_SHA256_CTX* context, const sha2_word32* data); public: /** * @brief Initialize the context * @param context The context to init. */ void SHA256_Init(HL_SHA256_CTX *context); /** * @brief Updates the context * @param context The context to update. * @param data The data for updating the context. * @param len The length of the given data. */ void SHA256_Update(HL_SHA256_CTX* context, const hl_uint8* data, unsigned int len); /** * @brief Ends the sha256 operation and return the * created hash in the given buffer. * @param context The context to end. * @param buffer This OUT-Parameter contains the created * hash after ending the operation. */ char* SHA256_End(HL_SHA256_CTX* context, char buffer[SHA256_DIGEST_STRING_LENGTH]); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha256wrapper.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha256wrapper.cpp * @brief This file contains the implementation of the sha256wrapper * class. * @date Di 25 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha256wrapper.h" #include "hl_sha256.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //private memberfunctions /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ std::string sha256wrapper::hashIt(void) { sha2_byte buff[SHA256_DIGEST_STRING_LENGTH]; sha256->SHA256_End(&context,(char*)buff); return convToString(buff); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string sha256wrapper::convToString(unsigned char *data) { /* * we can just copy data to a string, because * the transforming to hash is already done * within the sha256 implementation */ return std::string((const char*)data); } /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ void sha256wrapper::updateContext(unsigned char *data, unsigned int len) { this->sha256->SHA256_Update(&context,data,len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void sha256wrapper::resetContext(void) { sha256->SHA256_Init(&context); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string sha256wrapper::getTestHash(void) { return "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; } //---------------------------------------------------------------------- //public memberfunctions /** * @brief default constructor */ sha256wrapper::sha256wrapper() { this->sha256 = new SHA256(); } /** * @brief default destructor */ sha256wrapper::~sha256wrapper() { delete sha256; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha256wrapper.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha256wrapper.h * @brief This file contains the definition of the sha256wrapper * class. * @date Di 25 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA256WRAPPER_H #define SHA256WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_sha256.h" //---------------------------------------------------------------------- //STL #include //---------------------------------------------------------------------- /** * @brief This class represents the SHA256 wrapper-class * * You can use this class to easily create a sha256 hash. * Just create an instance of sha256wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include sha256example.cpp * * sha256wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class sha256wrapper : public hashwrapper { private: /** * SHA256 access */ SHA256 *sha256; /** * SHA256 context */ HL_SHA256_CTX context; /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ sha256wrapper(); /** * @brief default destructor */ virtual ~sha256wrapper(); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha2ext.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA384 and SHA512 implementations are derivative from * the sourcecode published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. * */ //---------------------------------------------------------------------- /** * @file sha2ext.cpp * @brief This file contains the implementation of the SHA2Ext class * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- // Standard C includes #include #include //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha2ext.h" #include "hl_sha2mac.h" //---------------------------------------------------------------------- /* Hash constant words K for SHA-384 and SHA-512: */ const static sha2_word64 K512[80] = { 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; /* Initial hash value H for SHA-384 */ const static sha2_word64 sha384_initial_hash_value[8] = { 0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL, 0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL, 0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL, 0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL }; /* Initial hash value H for SHA-512 */ const static sha2_word64 sha512_initial_hash_value[8] = { 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL }; /* * * Constant used by SHA256/384/512_End() functions for converting the * * digest to a readable hexadecimal character string: * */ static const char *sha2_hex_digits = "0123456789abcdef"; //---------------------------------------------------------------------- /** * @brief Initialize the SHA512 context * @param context The context to init. */ void SHA2ext::SHA512_Init(HL_SHA512_CTX* context) { if (context == (HL_SHA512_CTX*)0) { return; } MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH); context->bitcount[0] = context->bitcount[1] = 0; } #ifdef SHA2_UNROLL_TRANSFORM /* Unrolled SHA-512 round macros: */ #if BYTE_ORDER == LITTLE_ENDIAN #define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ REVERSE64(*data++, W512[j]); \ T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ K512[j] + W512[j]; \ (d) += T1, \ (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \ j++ #else /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ K512[j] + (W512[j] = *data++); \ (d) += T1; \ (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ j++ #endif /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND512(a,b,c,d,e,f,g,h) \ s0 = W512[(j+1)&0x0f]; \ s0 = sigma0_512(s0); \ s1 = W512[(j+14)&0x0f]; \ s1 = sigma1_512(s1); \ T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \ (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \ (d) += T1; \ (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ j++ /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA2ext::SHA512_Transform(HL_SHA512_CTX* context, const sha2_word64* data) { sha2_word64 a, b, c, d, e, f, g, h, s0, s1; sha2_word64 T1, *W512 = (sha2_word64*)context->buffer; int j; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { ROUND512_0_TO_15(a,b,c,d,e,f,g,h); ROUND512_0_TO_15(h,a,b,c,d,e,f,g); ROUND512_0_TO_15(g,h,a,b,c,d,e,f); ROUND512_0_TO_15(f,g,h,a,b,c,d,e); ROUND512_0_TO_15(e,f,g,h,a,b,c,d); ROUND512_0_TO_15(d,e,f,g,h,a,b,c); ROUND512_0_TO_15(c,d,e,f,g,h,a,b); ROUND512_0_TO_15(b,c,d,e,f,g,h,a); } while (j < 16); /* Now for the remaining rounds up to 79: */ do { ROUND512(a,b,c,d,e,f,g,h); ROUND512(h,a,b,c,d,e,f,g); ROUND512(g,h,a,b,c,d,e,f); ROUND512(f,g,h,a,b,c,d,e); ROUND512(e,f,g,h,a,b,c,d); ROUND512(d,e,f,g,h,a,b,c); ROUND512(c,d,e,f,g,h,a,b); ROUND512(b,c,d,e,f,g,h,a); } while (j < 80); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = 0; } #else /* SHA2_UNROLL_TRANSFORM */ /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA2ext::SHA512_Transform(HL_SHA512_CTX* context, const sha2_word64* data) { sha2_word64 a, b, c, d, e, f, g, h, s0, s1; sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer; int j; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { #if BYTE_ORDER == LITTLE_ENDIAN /* Convert TO host byte order */ REVERSE64(*data++, W512[j]); /* Apply the SHA-512 compression function to update a..h */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j]; #else /* BYTE_ORDER == LITTLE_ENDIAN */ /* Apply the SHA-512 compression function to update a..h with copy */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++); #endif /* BYTE_ORDER == LITTLE_ENDIAN */ T2 = Sigma0_512(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 16); do { /* Part of the message block expansion: */ s0 = W512[(j+1)&0x0f]; s0 = sigma0_512(s0); s1 = W512[(j+14)&0x0f]; s1 = sigma1_512(s1); /* Apply the SHA-512 compression function to update a..h */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); T2 = Sigma0_512(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 80); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = T2 = 0; } #endif /* SHA2_UNROLL_TRANSFORM */ void SHA2ext::SHA512_Update(HL_SHA512_CTX* context, const sha2_byte *data, unsigned int len) { unsigned int freespace, usedspace; if (len == 0) { /* Calling with no data is valid - we do nothing */ return; } /* Sanity check: */ assert(context != (HL_SHA512_CTX*)0 && data != (sha2_byte*)0); usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; if (usedspace > 0) { /* Calculate how much free space is available in the buffer */ freespace = SHA512_BLOCK_LENGTH - usedspace; if (len >= freespace) { /* Fill the buffer completely and process it */ MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); ADDINC128(context->bitcount, freespace << 3); len -= freespace; data += freespace; SHA512_Transform(context, (sha2_word64*)context->buffer); } else { /* The buffer is not yet full */ MEMCPY_BCOPY(&context->buffer[usedspace], data, len); ADDINC128(context->bitcount, len << 3); /* Clean up: */ usedspace = freespace = 0; return; } } while (len >= SHA512_BLOCK_LENGTH) { /* Process as many complete blocks as we can */ SHA512_Transform(context, (sha2_word64*)data); ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3); len -= SHA512_BLOCK_LENGTH; data += SHA512_BLOCK_LENGTH; } if (len > 0) { /* There's left-overs, so save 'em */ MEMCPY_BCOPY(context->buffer, data, len); ADDINC128(context->bitcount, len << 3); } /* Clean up: */ usedspace = freespace = 0; } void SHA2ext::SHA512_Last(HL_SHA512_CTX* context) { unsigned int usedspace; usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; #if BYTE_ORDER == LITTLE_ENDIAN /* Convert FROM host byte order */ REVERSE64(context->bitcount[0],context->bitcount[0]); REVERSE64(context->bitcount[1],context->bitcount[1]); #endif if (usedspace > 0) { /* Begin padding with a 1 bit: */ context->buffer[usedspace++] = 0x80; if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) { /* Set-up for the last transform: */ MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace); } else { if (usedspace < SHA512_BLOCK_LENGTH) { MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace); } /* Do second-to-last transform: */ SHA512_Transform(context, (sha2_word64*)context->buffer); /* And set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2); } } else { /* Prepare for final transform: */ MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH); /* Begin padding with a 1 bit: */ *context->buffer = 0x80; } /* Store the length of input data (in bits): */ *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1]; *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0]; /* Final transform: */ SHA512_Transform(context, (sha2_word64*)context->buffer); } void SHA2ext::SHA512_Final(sha2_byte digest[], HL_SHA512_CTX* context) { sha2_word64 *d = (sha2_word64*)digest; /* Sanity check: */ assert(context != (HL_SHA512_CTX*)0); /* If no digest buffer is passed, we don't bother doing this: */ if (digest != (sha2_byte*)0) { SHA512_Last(context); /* Save the hash data for output: */ #if BYTE_ORDER == LITTLE_ENDIAN { /* Convert TO host byte order */ int j; for (j = 0; j < 8; j++) { REVERSE64(context->state[j],context->state[j]); *d++ = context->state[j]; } } #else MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH); #endif } /* Zero out state data */ MEMSET_BZERO(context, sizeof(context)); } char* SHA2ext::SHA512_End(HL_SHA512_CTX* context, char buffer[]) { sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != (HL_SHA512_CTX*)0); if (buffer != (char*)0) { SHA512_Final(digest, context); for (i = 0; i < SHA512_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = (char)0; } else { MEMSET_BZERO(context, sizeof(context)); } MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH); return buffer; } void SHA2ext::SHA384_Init(HL_SHA_384_CTX* context) { if (context == (HL_SHA_384_CTX*)0) { return; } MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH); context->bitcount[0] = context->bitcount[1] = 0; } void SHA2ext::SHA384_Update(HL_SHA_384_CTX* context, const sha2_byte* data, unsigned int len) { SHA512_Update((HL_SHA512_CTX*)context, data, len); } void SHA2ext::SHA384_Final(sha2_byte digest[], HL_SHA_384_CTX* context) { sha2_word64 *d = (sha2_word64*)digest; /* Sanity check: */ assert(context != (HL_SHA_384_CTX*)0); /* If no digest buffer is passed, we don't bother doing this: */ if (digest != (sha2_byte*)0) { SHA512_Last((HL_SHA512_CTX*)context); /* Save the hash data for output: */ #if BYTE_ORDER == LITTLE_ENDIAN { /* Convert TO host byte order */ int j; for (j = 0; j < 6; j++) { REVERSE64(context->state[j],context->state[j]); *d++ = context->state[j]; } } #else MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH); #endif } /* Zero out state data */ MEMSET_BZERO(context, sizeof(context)); } char* SHA2ext::SHA384_End(HL_SHA_384_CTX* context, char buffer[]) { sha2_byte digest[SHA384_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != (HL_SHA_384_CTX*)0); if (buffer != (char*)0) { SHA384_Final(digest, context); for (i = 0; i < SHA384_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = (char)0; } else { MEMSET_BZERO(context, sizeof(context)); } MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH); return buffer; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha2ext.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA384 and SHA512 implementations are derivative from the * sourcecode published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. */ //---------------------------------------------------------------------- /** * @file hl_sha2ext.h * @brief This file contains the declaration of the SHA384 and * SHA512 classes * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA2ext_H #define SHA2ext_H //---------------------------------------------------------------------- //lenght defines #define SHA384_BLOCK_LENGTH 128 #define SHA384_DIGEST_LENGTH 48 #define SHA384_DIGEST_STRING_LENGTH (SHA384_DIGEST_LENGTH * 2 + 1) #define SHA512_BLOCK_LENGTH 128 #define SHA512_DIGEST_LENGTH 64 #define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1) #define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16) //---------------------------------------------------------------------- //hl includes #include "hl_types.h" //---------------------------------------------------------------------- //typedefs /** * Exactly 1 byte */ typedef hl_uint8 sha2_byte; /** * Exactly 4 bytes */ typedef hl_uint32 sha2_word32; /** * Exactly 8 bytes */ typedef hl_uint64 sha2_word64; /** * @brief This struct represents a SHA512-hash context */ typedef struct HL_SHA512_CTX { hl_uint64 state[8]; hl_uint64 bitcount[2]; hl_uint8 buffer[SHA512_BLOCK_LENGTH]; } HL_SHA512_CTX; /** * @brief This struct represents a SHA384-hash context */ typedef HL_SHA512_CTX HL_SHA_384_CTX; //---------------------------------------------------------------------- /** * @brief This class represents the implementation of * the SHA384 and SHA512 algorithm. * * Basically the class provides six public member-functions * to create a hash: SHA384_Init(), SHA384_Update(), SHA384_End(), * SHA512_Init(), SHA512_Update() and SHA512_End(). * If you want to create a hash based on a string or file quickly * you should use the sha384wrapper or sha512wrapper classes. */ class SHA2ext { private: /** * @brief Finalize the sha384 operation * @param digest The digest to finalize the operation with. * @param context The context to finalize. */ void SHA384_Final(hl_uint8 digest[SHA384_DIGEST_LENGTH], HL_SHA_384_CTX* context); /** * @brief Finalize the sha512 operation * @param digest The digest to finalize the operation with. * @param context The context to finalize. */ void SHA512_Final(hl_uint8 digest[SHA512_DIGEST_LENGTH], HL_SHA512_CTX* context); /** * @brief Internal method * * used by SHA512 and SHA384 * @author Benjamin Grdelbach * @param context The context of the operation */ void SHA512_Last(HL_SHA512_CTX* context); /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA512_Transform(HL_SHA512_CTX* context, const sha2_word64* data); public: /** * @brief Initialize the SHA384 context * @param context The context to init. */ void SHA384_Init(HL_SHA_384_CTX* context); /** * @brief Initialize the SHA512 context * @param context The context to init. */ void SHA512_Init(HL_SHA512_CTX* context); /** * @brief Updates the SHA512 context * @param context The context to update. * @param data The data for updating the context. * @param len The length of the given data. */ void SHA384_Update(HL_SHA_384_CTX* context, const hl_uint8* data, unsigned int len); /** * @brief Updates the SHA284 context * @param context The context to update. * @param data The data for updating the context. * @param len The length of the given data. */ void SHA512_Update(HL_SHA512_CTX* context, const hl_uint8* data, unsigned int len); /** * @brief Ends the SHA384 operation and return the * created hash in the given buffer. * @param context The context to end. * @param buffer This OUT-Parameter contains the created * hash after ending the operation. */ char* SHA384_End(HL_SHA_384_CTX* context, char buffer[SHA384_DIGEST_STRING_LENGTH]); /** * @brief Ends the SHA512 operation and return the * created hash in the given buffer. * @param context The context to end. * @param buffer This OUT-Parameter contains the created * hash after ending the operation. */ char* SHA512_End(HL_SHA512_CTX* context, char buffer[SHA512_DIGEST_STRING_LENGTH]); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha2mac.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA384 and SHA512 implementations are derivative from * the sourcecode published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. * */ //---------------------------------------------------------------------- /** * @file hl_sha2mac.h * @brief This file contains useful macros for use with SHA384 * and SHA512 * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- /* * SHA-256/384/512 Machine Architecture Definitions * BYTE_ORDER NOTE: * * Please make sure that your system defines BYTE_ORDER. If your * architecture is little-endian, make sure it also defines * LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are * equivilent. * * If your system does not define the above, then you can do so by * hand like this: * * #define LITTLE_ENDIAN 1234 * #define BIG_ENDIAN 4321 * * And for little-endian machines, add: * * #define BYTE_ORDER LITTLE_ENDIAN * * Or for big-endian machines: * * #define BYTE_ORDER BIG_ENDIAN * * The FreeBSD machine this was written on defines * BYTE_ORDER appropriately by including * (which in turn includes where the appropriate * definitions are actually made). */ #define LITTLE_ENDIAN 1234 #define BYTE_ORDER LITTLE_ENDIAN #if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN) #error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN #endif /*** ENDIAN REVERSAL MACROS *******************************************/ #if BYTE_ORDER == LITTLE_ENDIAN #define REVERSE32(w,x) { \ sha2_word32 tmp = (w); \ tmp = (tmp >> 16) | (tmp << 16); \ (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \ } #define REVERSE64(w,x) { \ sha2_word64 tmp = (w); \ tmp = (tmp >> 32) | (tmp << 32); \ tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) | \ ((tmp & 0x00ff00ff00ff00ffULL) << 8); \ (x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) | \ ((tmp & 0x0000ffff0000ffffULL) << 16); \ } #endif /* BYTE_ORDER == LITTLE_ENDIAN */ /* * Macro for incrementally adding the unsigned 64-bit integer n to the * unsigned 128-bit integer (represented using a two-element array of * 64-bit words): */ #define ADDINC128(w,n) { \ (w)[0] += (sha2_word64)(n); \ if ((w)[0] < (n)) { \ (w)[1]++; \ } \ } /* * Macros for copying blocks of memory and for zeroing out ranges * of memory. Using these macros makes it easy to switch from * using memset()/memcpy() and using bzero()/bcopy(). * * Please define either SHA2_USE_MEMSET_MEMCPY or define * SHA2_USE_BZERO_BCOPY depending on which function set you * choose to use: */ #if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY) /* Default to memset()/memcpy() if no option is specified */ #define SHA2_USE_MEMSET_MEMCPY 1 #endif #if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY) /* Abort with an error if BOTH options are defined */ #error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both! #endif #ifdef SHA2_USE_MEMSET_MEMCPY #define MEMSET_BZERO(p,l) memset((p), 0, (l)) #define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l)) #endif #ifdef SHA2_USE_BZERO_BCOPY #define MEMSET_BZERO(p,l) bzero((p), (l)) #define MEMCPY_BCOPY(d,s,l) bcopy((s), (d), (l)) #endif /*** THE SIX LOGICAL FUNCTIONS **************************************** * * Bit shifting and rotation (used by the six SHA-XYZ logical functions: * * NOTE: The naming of R and S appears backwards here (R is a SHIFT and * S is a ROTATION) because the SHA-256/384/512 description document * (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this * same "backwards" definition. */ /* Shift-right (used in SHA-256, SHA-384, and SHA-512): */ #define R(b,x) ((x) >> (b)) /* 32-bit Rotate-right (used in SHA-256): */ #define S32(b,x) (((x) >> (b)) | ((x) << (32 - (b)))) /* 64-bit Rotate-right (used in SHA-384 and SHA-512): */ #define S64(b,x) (((x) >> (b)) | ((x) << (64 - (b)))) /* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */ #define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) #define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) /* Four of six logical functions used in SHA-256: */ #define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x))) #define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x))) #define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3 , (x))) #define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x))) /* Four of six logical functions used in SHA-384 and SHA-512: */ #define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x))) #define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x))) #define sigma0_512(x) (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7, (x))) #define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R( 6, (x))) ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha384wrapper.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha384wrapper.cpp * @brief This file contains the implementation of the sha384wrapper * class. * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha384wrapper.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //private memberfunctions /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ std::string sha384wrapper::hashIt(void) { sha2_byte buff[SHA384_DIGEST_STRING_LENGTH]; sha384->SHA384_End(&context,(char*)buff); return convToString(buff); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string sha384wrapper::convToString(unsigned char *data) { /* * we can just copy data to a string, because * the transforming to hash is already done * within the sha384 implementation */ return std::string((const char*)data); } /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ void sha384wrapper::updateContext(unsigned char *data, unsigned int len) { this->sha384->SHA384_Update(&context,data,len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void sha384wrapper::resetContext(void) { sha384->SHA384_Init(&context); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string sha384wrapper::getTestHash(void) { return "ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1"; } //---------------------------------------------------------------------- //public memberfunctions /** * @brief default constructor */ sha384wrapper::sha384wrapper() { this->sha384 = new SHA2ext(); } /** * @brief default destructor */ sha384wrapper::~sha384wrapper() { delete sha384; } ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha384wrapper.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha384wrapper.h * @brief This file contains the definition of the sha384wrapper * class. * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA384WRAPPER_H #define SHA384WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_sha2ext.h" //---------------------------------------------------------------------- //STL #include //---------------------------------------------------------------------- /** * @brief This class represents the SHA384 wrapper-class * * You can use this class to easily create a sha384 hash. * Just create an instance of sha384wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include sha384example.cpp * * sha384wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class sha384wrapper : public hashwrapper { private: /** * SHA384 access * via extended SHA2 */ SHA2ext *sha384; /** * SHA384 context */ HL_SHA_384_CTX context; /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ sha384wrapper(); /** * @brief default destructor */ virtual ~sha384wrapper(); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha512wrapper.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha512wrapper.cpp * @brief This file contains the implementation of the sha512wrapper * class. * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha512wrapper.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //private memberfunctions /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ std::string sha512wrapper::hashIt(void) { sha2_byte buff[SHA512_DIGEST_STRING_LENGTH]; sha512->SHA512_End(&context,(char*)buff); return convToString(buff); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string sha512wrapper::convToString(unsigned char *data) { /* * we can just copy data to a string, because * the transforming to hash is already done * within the sha512 implementation */ return std::string((const char*)data); } /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ void sha512wrapper::updateContext(unsigned char *data, unsigned int len) { this->sha512->SHA512_Update(&context,data,len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void sha512wrapper::resetContext(void) { sha512->SHA512_Init(&context); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string sha512wrapper::getTestHash(void) { return "07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6"; } //---------------------------------------------------------------------- //public memberfunctions /** * @brief default constructor */ sha512wrapper::sha512wrapper() { this->sha512 = new SHA2ext(); } /** * @brief default destructor */ sha512wrapper::~sha512wrapper() { delete sha512; } ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_sha512wrapper.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha512wrapper.h * @brief This file contains the definition of the sha512wrapper * class. * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA512WRAPPER_H #define SHA512WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_sha2ext.h" //---------------------------------------------------------------------- //STL #include //---------------------------------------------------------------------- /** * @brief This class represents the SHA512 wrapper-class * * You can use this class to easily create a sha512 hash. * Just create an instance of sha512wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include sha512example.cpp * * sha512wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class sha512wrapper : public hashwrapper { private: /** * SHA512 access * via extended SHA2 */ SHA2ext *sha512; /** * SHA512 context */ HL_SHA512_CTX context; /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ sha512wrapper(); /** * @brief default destructor */ virtual ~sha512wrapper(); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_types.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_types.h * @brief This file defines some global types * @date So 13 Jan 2008 */ //---------------------------------------------------------------------- //include protection #ifndef HLTYPES_H #define HLTYPES_H //---------------------------------------------------------------------- /** * exactly 1 Byte */ typedef unsigned char hl_uint8; /** * at least 2 Byte */ typedef unsigned short int hl_uint16; /** * at least 4 Byte */ typedef unsigned int hl_uint32; /** * at least 8 Byte */ #ifdef __GNUC__ typedef unsigned long long int hl_uint64; #elif __MINGW32__ typedef unsigned long long int hl_uint64; #elif _MSC_VER typedef unsigned __int64 hl_uint64; #else #error "Unsuppported compiler." \ "Please use GCC,MINGW,MSVC " \ " or define hl_uint64 for your compiler in hl_types.h line 62" #endif //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_wrapperfactory.cpp.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grüdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_wrapperfactory.cpp * @brief This file contains the implementation of the * wrapperfactory class * @date DO 13 Oct 2011 */ //---------------------------------------------------------------------- #include #include "hl_wrapperfactory.h" #include "hashlibpp.h" //---------------------------------------------------------------------- //public member functions /** * @brief Simple factory-method to create a hashwrapper * * @param type The type of the hash algorithm to create a wrapper for * @return A hashwrapper for the fiven type */ hashwrapper* wrapperfactory::create(HL_Wrappertype type) { if(type == HL_MD5) { return new md5wrapper(); } else if(type == HL_SHA1) { return new sha1wrapper(); } else if(type == HL_SHA256) { return new sha256wrapper(); } else if(type == HL_SHA384) { return new sha384wrapper(); } else if(type == HL_SHA512) { return new sha512wrapper(); } throw hlException(HL_UNKNOWN_HASH_TYPE,"Unknown hashtype"); } /** * @brief Simple factory-method to create a hashwrapper * * @param type The type of the hash algorithm to create a wrapper for * @return A hashwrapper for the fiven type */ hashwrapper* wrapperfactory::create(std::string type) { std::transform(type.begin(), type.end(), type.begin(), ::toupper); if(type == "MD5") { return new md5wrapper(); } else if(type == "SHA1") { return new sha1wrapper(); } else if(type == "SHA256") { return new sha256wrapper(); } else if(type == "SHA384") { return new sha384wrapper(); } else if(type == "SHA512") { return new sha512wrapper(); } return NULL; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/.svn/text-base/hl_wrapperfactory.h.svn-base ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grüdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_wrapperfactory.h * @brief This file contains a simple hashwrapper factory * @date DO 13 Oct 2011 */ //---------------------------------------------------------------------- //include protection #ifndef WRAPPERFACTORY_H #define WRAPPERFACTORY_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" //---------------------------------------------------------------------- //enumeration /* * definition of the supported hashtypes */ enum HL_Wrappertype { HL_MD5, HL_SHA1, HL_SHA256, HL_SHA384, HL_SHA512 }; //---------------------------------------------------------------------- /** * @brief This class represents a simple factory for creating wrappers. * * U can use this class for dynamicly create wrappers of a given * type at runtime. */ class wrapperfactory { public: /** * @brief Simple factory-method to create a hashwrapper * * @param type The type of the hash algorithm to create a wrapper for * @return A hashwrapper for the fiven type */ hashwrapper* create(HL_Wrappertype type); /** * @brief Simple factory-method to create a hashwrapper * * @param type the simple name of the type for example "md5" * @return A hashwrapper for the fiven type */ hashwrapper* create(std::string type); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/Makefile ================================================ # # hashlib++ - a simple hash library for C++ # # Copyright (c) 2007-2010 Benjamin Grdelbach # # 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # #----------------------------------------------------------------------- # # This is the hashlib++ makefile. It builds and installs hashlib++ as a # static library. See the documentation for more information. # # Type 'make' to build the lib. # Type 'make install' to build and install the lib. # Type 'make clean' to clean the object files # # Note for FreeBSD users: # use gmake from "/usr/ports/devel/gmake" # # Benjamin Grdelbach # Mi 10 Okt 2007 # #----------------------------------------------------------------------- # Edit the following lines to meet your needs # Path to install the headerfiles INCLUDE_PATH = /usr/include/hashlib++ # Path to install the library LIB_PATH = /usr/local/lib/ # Compiler to use COMPILER = g++ # Global options for the compiler COPTIONS = -ansi -Wall -Wextra #----------------------------------------------------------------------- # DON'T CHANGE ANYTHING BELOW #----------------------------------------------------------------------- ifdef DEBUG COPTIONS += -g else COPTIONS += -O3 -fomit-frame-pointer endif GCC = $(COMPILER) $(COPTIONS) #----------------------------------------------------------------------- #Main-Target all: MD5 SHA1 SHA256 SHA2EXT CORE LIB #----------------------------------------------------------------------- #all header-files HEADER = hl_hashwrapper.h \ hl_wrapperfactory.h \ hl_exception.h \ hl_md5.h hl_md5wrapper.h \ hl_sha1.h hl_sha1wrapper.h \ hl_sha2mac.h \ hl_sha256.h hl_sha256wrapper.h \ hl_sha2ext.h hl_sha384wrapper.h hl_sha512wrapper.h \ hl_types.h \ hashlibpp.h #----------------------------------------------------------------------- CORE = hl_wrapperfactory.o CORE: hl_wrapperfactory.o hl_wrapperfactory.o: hl_wrapperfactory.cpp hl_wrapperfactory.h $(GCC) -c hl_wrapperfactory.cpp #----------------------------------------------------------------------- # MD5 Targets MD5 = hl_md5.o \ hl_md5wrapper.o MD5: hl_md5.o hl_md5wrapper.o hl_md5.o: hl_md5.cpp hl_md5.h $(GCC) -c hl_md5.cpp hl_md5wrapper.o: hl_md5wrapper.cpp hl_md5wrapper.h $(GCC) -c hl_md5wrapper.cpp #----------------------------------------------------------------------- # SHA1 Targets SHA1 = hl_sha1.o \ hl_sha1wrapper.o SHA1: hl_sha1.o hl_sha1wrapper.o hl_sha1.o: hl_sha1.cpp hl_sha1.h $(GCC) -c hl_sha1.cpp hl_sha1wrapper.o: hl_sha1wrapper.cpp hl_sha1wrapper.h $(GCC) -c hl_sha1wrapper.cpp #----------------------------------------------------------------------- # SHA256 Targets SHA256 = hl_sha256.o \ hl_sha256wrapper.o SHA256: hl_sha256.o hl_sha256wrapper.o hl_sha256.o: hl_sha256.cpp hl_sha256.h hl_sha2mac.h $(GCC) -c hl_sha256.cpp hl_sha256wrapper.o: hl_sha256wrapper.cpp hl_sha256wrapper.h $(GCC) -c hl_sha256wrapper.cpp #----------------------------------------------------------------------- # SHA2-ext Targets SHA2EXT = hl_sha2ext.o \ hl_sha384wrapper.o \ hl_sha512wrapper.o SHA2EXT: hl_sha2ext.o hl_sha384wrapper.o hl_sha512wrapper.o hl_sha2ext.o: hl_sha2ext.cpp hl_sha2ext.h hl_sha2mac.h $(GCC) -c hl_sha2ext.cpp hl_sha384wrapper.o: hl_sha384wrapper.cpp hl_sha384wrapper.h $(GCC) -c hl_sha384wrapper.cpp hl_sha512wrapper.o: hl_sha512wrapper.cpp hl_sha512wrapper.h $(GCC) -c hl_sha512wrapper.cpp #----------------------------------------------------------------------- # Creating a static lib using ar LIB: MD5 SHA1 SHA256 ar rs libhl++.a $(MD5) $(SHA1) $(SHA256) $(SHA2EXT) $(CORE) #----------------------------------------------------------------------- #Installing the lib install: all mkdir -p $(INCLUDE_PATH); \ mkdir -p $(LIB_PATH); \ cp libhl++.a $(LIB_PATH) && \ cp $(HEADER) $(INCLUDE_PATH) -@ echo "" -@ echo "" -@ echo "------------------------------" -@ echo "" -@ echo "hashlib++ has been installed to:" -@ echo "include files: $(INCLUDE_PATH)" -@ echo "library files: $(LIB_PATH)" -@ echo "" -@ echo "------------------------------" #----------------------------------------------------------------------- # Cleaning object-files clean: rm *.o -@ echo "cleaned up " -@ echo "" #----------------------------------------------------------------------- #EOF ================================================ FILE: _draft/flash_cpp/hashlib/hashlibpp.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hashlibpp.h * @brief This file is just an include wrapper * @date Sa 2 Feb */ //---------------------------------------------------------------------- #ifndef HASHLIBPP_H #define HASHLIBPP_H //---------------------------------------------------------------------- //current version of hashilb++ #define _HASHLIBPP_VERSION_ "0.3.4" //---------------------------------------------------------------------- #include "hl_exception.h" #include "hl_wrapperfactory.h" #include "hl_hashwrapper.h" #include "hl_md5wrapper.h" #include "hl_sha1wrapper.h" #include "hl_sha256wrapper.h" #include "hl_sha384wrapper.h" #include "hl_sha512wrapper.h" //---------------------------------------------------------------------- #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_exception.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_exception.h * @brief This file contains the hashlib++ exception class * @date Sa 24 Nov 2007 */ //---------------------------------------------------------------------- //include protection #ifndef HL_EXCEPTION_H #define HL_EXCEPTION_H //---------------------------------------------------------------------- //STL #include //---------------------------------------------------------------------- /** * definition of hashlib++ errornumbers */ typedef enum hlerrors { HL_NO_ERROR = 0, HL_FILE_READ_ERROR, HL_VERIFY_TEST_FAILED, HL_UNKNOWN_SEE_MSG, HL_UNKNOWN_HASH_TYPE } hlerror; //---------------------------------------------------------------------- /** * @brief This class represents a exception within the hashlib++ * project */ class hlException { private: /** * Error Number */ hlerror iError; /** * Error message as string */ std::string strMessge; public: /** * @brief constructor * @param er Error number * @param m Error message */ hlException(hlerror er, std::string m) { this->iError = er; this->strMessge = m; } /** * @brief constructor * @param m Error Message */ hlException(std::string m) { this->iError = HL_UNKNOWN_SEE_MSG; this->strMessge = m; } /** * @brief returns the error message * @return the error message */ std::string error_message(void) { return strMessge; } /** * @brief returns the error number * @return the error number */ hlerror error_number(void) { return iError; } }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_hashwrapper.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2011 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- //doxygen mainpage /** * @mainpage hashlib++ source documentation * *
    Version 0.3.4
    * * * @section intro Introduction * hashlib++ a simple hash library for C++ \n * Copyright (c) 2007-2011 Benjamin Grüdelbach * * * * hashlib++ is a simple and very easy to use library to create a * cryptographic checksum called "hash". hashlib++ is written in * plain C++ and should work with every compiler and platform. * hashlib++ is released under the BSD-license and * therefore free software. * * @section about About this document * * This is the documentation about the hashlib++ sourcecode. * Since it contains some internal information it its helpfull * but not necessary to read for the average user. * If you are new to hashlib++ you should start with reading * the README.TXT file which contains all relevant information * to start using this library. * */ //---------------------------------------------------------------------- /** * @file hl_hashwrapper.h * @brief This file contains the hashwrapper base class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef HASHWRAPPER_H #define HASHWRAPPER_H //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //C includes //#include #include //---------------------------------------------------------------------- //hashlib++ includes #include "hl_exception.h" //---------------------------------------------------------------------- /** * @brief This class represents the baseclass for all subwrappers * * hashwrapper is the abstract base class of all subwrappers like md5wrapper * or sha1wrapper. This class implements two simple and easy to use * memberfunctions to create a hash based on a string or a file. * ( getHashFromString() and getHashFromFile() ) * * getHashFromString() calls resetContext(), updateContext() and hashIt() * in this order. These three memberfunctions are pure virtual and have to * be implemented by the subclasses. * * getHashFromFile() calls resetContext() before reading the specified file * in 1024 byte blocks which are forwarded to the hash context by calling * updateContext(). Finaly hashIt() is called to return the hash. */ class hashwrapper { private: const std::string teststring; protected: /** * @brief This method finalizes the hash process * and returns the hash as std::string * * This memberfunction is pure virtual and * has to be implemented by the subclass * * @return the created hash as std::string */ virtual std::string hashIt(void) = 0; /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX) * * This memberfunction is pure virtual and * has to be implemented by the subclass * * @param data The hash-data to covert into HEX * @return The converted data as std::string */ virtual std::string convToString(unsigned char *data) = 0; /** * @brief This method adds the given data to the * current hash context * * This memberfunction is pure virtual and * has to be implemented by the subclass * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len) = 0; /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. * * This memberfunction is pure virtual and * has to be implemented by the subclass */ virtual void resetContext(void) = 0; /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void) = 0; public: /** * @brief Default Konstruktor */ hashwrapper( void ) : teststring("The quick brown fox jumps over the lazy dog") { } /** * @brief Default destructor */ virtual ~hashwrapper ( void ) { }; /** * @brief Method for testing the concrete implementation */ virtual void test( void ) { std::string hash = this->getHashFromString(teststring); std::string verify = this->getTestHash(); if(hash != verify) { throw hlException(HL_VERIFY_TEST_FAILED, "hashlib test-error: \"" + hash + "\" is not \"" + verify + "\" as supposed to be."); } } /** * @brief This method creates a hash based on the * given string * * This memberfunctions calls resetContext(), * updateContext() and hashIt() in this order. * These three memberfunctions are pure virtual and have to * be implemented by the subclasses. * * @param text The text to create a hash from. This * parameter is forwarded to updateContext() * @return the created hash as std::string */ virtual std::string getHashFromString(std::string text) { /* * reset the context so that we can start * with a new hash process */ resetContext(); /* * we update the context with the given text */ updateContext((unsigned char*) text.c_str(),text.length()); /* * now we can close the hash process * and return the created hash */ return this->hashIt(); } /** * @brief This method creates a hash from a given file * * First of all resetContext() is called before reading the * specified file in 1024 byte blocks which are forwarded * to the hash context by calling updateContext(). * Finaly hashIt() is called to return the hash. * These three memberfunctions are pure virtual and have to * be implemented by the subclasses. * * @param filename The file to created a hash from * * @return The created hash of the file or "-1" in case * the file could not be opened * @throw Throws a hlException if the specified file could not * be opened. */ virtual std::string getHashFromFile(std::string filename) { FILE *file; int len; unsigned char buffer[1024]; /* * reset the current hash context */ resetContext(); /* * open the specified file */ if((file = fopen(filename.c_str(), "rb")) == NULL) { throw hlException(HL_FILE_READ_ERROR, "Cannot read file \"" + filename + "\"."); } /* * read the file in 1024b blocks and * update the context for every block */ while( (len = fread(buffer,1,1024,file)) ) { updateContext(buffer, len); } //close the file and create the hash fclose(file); return(hashIt()); } }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_md5.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ MD5 implementation is derivative from the sourcecode * published in RFC 1321 * * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All * rights reserved. * * License to copy and use this software is granted provided that it * is identified as the "RSA Data Security, Inc. MD5 Message-Digest * Algorithm" in all material mentioning or referencing this software * or this function. * * License is also granted to make and use derivative works provided * that such works are identified as "derived from the RSA Data * Security, Inc. MD5 Message-Digest Algorithm" in all material * mentioning or referencing the derived work. * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. */ //---------------------------------------------------------------------- /** * @file hl_md5.cpp * @brief This file contains the implementation of the MD5 class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_md5.h" //---------------------------------------------------------------------- // defines // Constants for MD5Transform routine. #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 static unsigned char PADDING[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* F, G, H and I are basic MD5 functions. */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~z))) /* * ROTATE_LEFT rotates x left n bits. * cast to unsigned int to guarantee support for 64Bit System */ #define ROTATE_LEFT(x, n) (((x) << (n)) | (( (unsigned int) x) >> (32-(n)))) /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) { \ (a) += F ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define GG(a, b, c, d, x, s, ac) { \ (a) += G ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define HH(a, b, c, d, x, s, ac) { \ (a) += H ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define II(a, b, c, d, x, s, ac) { \ (a) += I ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } //---------------------------------------------------------------------- //private member-functions /** * @brief Basic transformation. Transforms state based on block. * @param state state to transform * @param block block to transform */ void MD5::MD5Transform (unsigned long int state[4], unsigned char block[64]) { unsigned long int a = state[0], b = state[1], c = state[2], d = state[3], x[16]; Decode (x, block, 64); /* Round 1 */ FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; /* * Zeroize sensitive information. */ MD5_memset ((POINTER)x, 0, sizeof (x)); } /** * @brief Encodes input data * @param output Encoded data as OUT parameter * @param input Input data * @param len The length of the input assuming it is a * multiple of 4 */ void MD5::Encode (unsigned char *output, unsigned long int *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) { output[j] = (unsigned char)(input[i] & 0xff); output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); } } /** * @brief Decodes input data into output * @param output Decoded data as OUT parameter * @param input Input data * @param len The length of the input assuming it is a * multiple of 4 */ void MD5::Decode (unsigned long int *output, unsigned char *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) output[i] = ((unsigned long int)input[j]) | (((unsigned long int)input[j+1]) << 8) | (((unsigned long int)input[j+2]) << 16) | (((unsigned long int)input[j+3]) << 24); } /** * @brief internal memory management * @param output OUT parameter where POINTER is a unsigned * char* * @param input Data to copy where POINTER is a unsigned char* * @param len The length of the data */ void MD5::MD5_memcpy (POINTER output, POINTER input, unsigned int len) { /* * TODO-Note: Replace "for loop" with standard memcpy if possible. */ unsigned int i; for (i = 0; i < len; i++) output[i] = input[i]; } /** * @brief internal memory management * @param output OUT parameter where POINTER is an unsigned * char* * @param value Value to fill the memory with * @param len The length of the data * */ void MD5::MD5_memset (POINTER output,int value,unsigned int len) { /* * TODO-Note: Replace "for loop" with standard memset if possible. */ unsigned int i; for (i = 0; i < len; i++) ((char *)output)[i] = (char)value; } //---------------------------------------------------------------------- //public member-functions /** * @brief Initialization begins an operation, * writing a new context * @param context The HL_MD5_CTX context to initialize */ void MD5::MD5Init (HL_MD5_CTX *context) { context->count[0] = context->count[1] = 0; context->state[0] = 0x67452301; context->state[1] = 0xefcdab89; context->state[2] = 0x98badcfe; context->state[3] = 0x10325476; } /** * @brief Block update operation. Continues an md5 * message-digest operation, processing another * message block, and updating the context. * @param context The HL_MD5_CTX context to update * @param input The data to write into the context * @param inputLen The length of the input data */ void MD5::MD5Update (HL_MD5_CTX *context, unsigned char *input, unsigned int inputLen) { unsigned int i, index, partLen; /* Compute number of bytes mod 64 */ index = (unsigned int)((context->count[0] >> 3) & 0x3F); /* Update number of bits */ if ( (context->count[0] += ((unsigned long int)inputLen << 3)) < ((unsigned long int)inputLen << 3)) context->count[1]++; context->count[1] += ((unsigned long int)inputLen >> 29); partLen = 64 - index; /* * Transform as many times as possible. */ if (inputLen >= partLen) { MD5_memcpy ((POINTER)&context->buffer[index], (POINTER)input, partLen); MD5Transform (context->state, context->buffer); for (i = partLen; i + 63 < inputLen; i += 64) MD5Transform (context->state, &input[i]); index = 0; } else i = 0; /* Buffer remaining input */ MD5_memcpy ((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i); } /** * @brief Finalization ends the md5 message-digest * operation, writing the the message digest and * zeroizing the context. * @param digest This is an OUT parameter which contains * the created hash after the method returns * @param context The context to finalize */ void MD5::MD5Final (unsigned char digest[16], HL_MD5_CTX *context) { unsigned char bits[8]; unsigned int index, padLen; /* Save number of bits */ Encode (bits, context->count, 8); /* * Pad out to 56 mod 64. */ index = (unsigned int)((context->count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); MD5Update (context, PADDING, padLen); /* Append length (before padding) */ MD5Update (context, bits, 8); /* Store state in digest */ Encode (digest, context->state, 16); /* * Zeroize sensitive information. */ MD5_memset ((POINTER)context, 0, sizeof (*context)); } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_md5.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ MD5 implementation is derivative from the sourcecode * published in RFC 1321 * * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All * rights reserved. * * License to copy and use this software is granted provided that it * is identified as the "RSA Data Security, Inc. MD5 Message-Digest * Algorithm" in all material mentioning or referencing this software * or this function. * * License is also granted to make and use derivative works provided * that such works are identified as "derived from the RSA Data * Security, Inc. MD5 Message-Digest Algorithm" in all material * mentioning or referencing the derived work. * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. */ //---------------------------------------------------------------------- /** * @file hl_md5.h * @brief This file contains the declaration of the MD5 class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef MD5_H #define MD5_H //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //hl includes #include "hl_types.h" //---------------------------------------------------------------------- //typedefs typedef hl_uint8 *POINTER; /** * @brief this struct represents a MD5-hash context. */ typedef struct { /** state (ABCD) */ unsigned long int state[4]; /** number of bits, modulo 2^64 (lsb first) */ unsigned long int count[2]; /** input buffer */ unsigned char buffer[64]; } HL_MD5_CTX; //---------------------------------------------------------------------- /** * @brief This class represents the implementation of * the md5 message digest algorithm. * * Basically the class provides three public member-functions * to create a hash: MD5Init(), MD5Update() and MD5Final(). * If you want to create a hash based on a string or file quickly * you should use the md5wrapper class instead of MD5. */ class MD5 { private: /** * @brief Basic transformation. Transforms state based on block. * @param state state to transform * @param block block to transform */ void MD5Transform (unsigned long int state[4], unsigned char block[64]); /** * @brief Encodes input data * @param output Encoded data as OUT parameter * @param input Input data * @param len The length of the input assuming it is a * multiple of 4 */ void Encode (unsigned char* output, unsigned long int *input, unsigned int len); /** * @brief Decodes input data into output * @param output Decoded data as OUT parameter * @param input Input data * @param len The length of the input assuming it is a * multiple of 4 */ void Decode (unsigned long int *output, unsigned char *input, unsigned int len); /** * @brief internal memory management * @param output OUT parameter where POINTER is an unsigned * char* * @param input Data to copy where POINTER is a unsigned char* * @param len The length of the data */ void MD5_memcpy (POINTER output, POINTER input, unsigned int len); /** * @brief internal memory management * @param output OUT parameter where POINTER is an unsigned * char* * @param value Value to fill the memory with * @param len The length of the data * */ void MD5_memset (POINTER output, int value, unsigned int len); public: /** * @brief Initialization begins an operation, * writing a new context * @param context The HL_MD5_CTX context to initialize */ void MD5Init (HL_MD5_CTX* context); /** * @brief Block update operation. Continues an md5 * message-digest operation, processing another * message block, and updating the context. * @param context The HL_MD5_CTX context to update * @param input The data to write into the context * @param inputLen The length of the input data */ void MD5Update (HL_MD5_CTX* context, unsigned char *input, unsigned int inputLen); /** * @brief Finalization ends the md5 message-digest * operation, writing the the message digest and * zeroizing the context. * @param digest This is an OUT parameter which contains * the created hash after the method returns * @param context The context to finalize */ void MD5Final (unsigned char digest[16], HL_MD5_CTX* context); /** * @brief default constructor */ MD5(){}; }; //---------------------------------------------------------------------- //End of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_md5wrapper.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_md5wrapper.cpp * @brief This file contains the implementation of the * md5wrapper class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //STL includes #include #include #include #include //---------------------------------------------------------------------- //hashlib++ includes #include "hl_md5wrapper.h" //---------------------------------------------------------------------- //private member functions /** * @brief This method ends the hash process * and returns the hash as string. * * @return the hash as std::string */ std::string md5wrapper::hashIt(void) { //create the hash unsigned char buff[16] = ""; md5->MD5Final((unsigned char*)buff,&ctx); //converte the hash to a string and return it return convToString(buff); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string md5wrapper::convToString(unsigned char *data) { /* * using a ostringstream to convert the hash in a * hex string */ std::ostringstream os; for(int i=0; i<16; ++i) { /* * set the width to 2 */ os.width(2); /* * fill with 0 */ os.fill('0'); /* * conv to hex */ os << std::hex << static_cast(data[i]); } /* * return as std::string */ return os.str(); } /** * @brief This method adds the given data to the * current hash context. * * @param data The data to add to the current context * @param len The length of the data to add */ void md5wrapper::updateContext(unsigned char *data, unsigned int len) { //update md5->MD5Update(&ctx, data, len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void md5wrapper::resetContext(void) { //init md5 md5->MD5Init(&ctx); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string md5wrapper::getTestHash(void) { return "9e107d9d372bb6826bd81d3542a419d6"; } //---------------------------------------------------------------------- //public member functions /** * @brief default constructor */ md5wrapper::md5wrapper() { md5 = new MD5(); } /** * @brief default destructor */ md5wrapper::~md5wrapper() { delete md5; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_md5wrapper.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_md5wrapper.h * @brief This file contains the definition of the md5wrapper * class. * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef MD5WRAPPER_H #define MD5WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_md5.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- /** * @brief This class represents the MD5 wrapper-class * * You can use this class to easily create a md5 hash. * Just create an instance of md5wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include md5example.cpp * * md5wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class md5wrapper : public hashwrapper { protected: /** * MD5 access */ MD5 *md5; /** * MD5 context */ HL_MD5_CTX ctx; /** * @brief This method ends the hash process * and returns the hash as string. * * @return the hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context. * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ md5wrapper(); /** * @brief default destructor */ virtual ~md5wrapper(); }; //---------------------------------------------------------------------- //include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha1.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA1 implementation is derivative from the sourcecode * published in RFC 3174 * * Copyright (C) The Internet Society (2001). All Rights Reserved. * * This document and translations of it may be copied and furnished to * others, and derivative works that comment on or otherwise explain it * or assist in its implementation may be prepared, copied, published * and distributed, in whole or in part, without restriction of any * kind, provided that the above copyright notice and this paragraph are * included on all such copies and derivative works. However, this * document itself may not be modified in any way, such as by removing * the copyright notice or references to the Internet Society or other * Internet organizations, except as needed for the purpose of * developing Internet standards in which case the procedures for * copyrights defined in the Internet Standards process must be * followed, or as required to translate it into languages other than * English. * * The limited permissions granted above are perpetual and will not be * revoked by the Internet Society or its successors or assigns. * * This document and the information contained herein is provided on an * "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING * TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION * HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */ //---------------------------------------------------------------------- /** * @file hl_sha1.cpp * @brief This file contains the implementation of the SHA1 class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha1.h" //---------------------------------------------------------------------- //defines /* * Define the SHA1 circular left shift macro */ #define SHA1CircularShift(bits,word) \ (((word) << (bits)) | ((word) >> (32-(bits)))) //---------------------------------------------------------------------- //private member-functions /** * @brief Internal method to padd the message * * According to the standard, the message must * be padded to an even 512 bits. The first * padding bit must be a '1'. The last 64 bits * represent the length of the original message. * All bits in between should be 0. * This function will pad the message according * to those rules by filling the Message_Block array * accordingly. It will also call the * ProcessMessageBlock function provided appropriately. * When it returns, it can be assumed that the message * digest has been computed. * * @param context The context to padd * */ void SHA1::SHA1PadMessage(HL_SHA1_CTX *context) { /* * Check to see if the current message block is too small to hold * the initial padding bits and length. If so, we will pad the * block, process it, and then continue padding into a second * block. */ if (context->Message_Block_Index > 55) { context->Message_Block[context->Message_Block_Index++] = 0x80; while(context->Message_Block_Index < 64) { context->Message_Block[context->Message_Block_Index++] = 0; } SHA1ProcessMessageBlock(context); while(context->Message_Block_Index < 56) { context->Message_Block[context->Message_Block_Index++] = 0; } } else { context->Message_Block[context->Message_Block_Index++] = 0x80; while(context->Message_Block_Index < 56) { context->Message_Block[context->Message_Block_Index++] = 0; } } /* * Store the message length as the last 8 octets */ context->Message_Block[56] = context->Length_High >> 24; context->Message_Block[57] = context->Length_High >> 16; context->Message_Block[58] = context->Length_High >> 8; context->Message_Block[59] = context->Length_High; context->Message_Block[60] = context->Length_Low >> 24; context->Message_Block[61] = context->Length_Low >> 16; context->Message_Block[62] = context->Length_Low >> 8; context->Message_Block[63] = context->Length_Low; SHA1ProcessMessageBlock(context); } /** * @brief This member-function will process the next 512 bits of the * message stored in the Message_Block array. * * Many of the variable names in this code, especially the * single character names, were used because those were the * names used in the publication. * * @param context The context to process */ void SHA1::SHA1ProcessMessageBlock(HL_SHA1_CTX *context) { const hl_uint32 K[] = { /* Constants defined in SHA-1 */ 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 }; int t; /* Loop counter */ hl_uint32 temp; /* Temporary word value */ hl_uint32 W[80]; /* Word sequence */ hl_uint32 A, B, C, D, E; /* Word buffers */ /* * Initialize the first 16 words in the array W */ for(t = 0; t < 16; t++) { W[t] = context->Message_Block[t * 4] << 24; W[t] |= context->Message_Block[t * 4 + 1] << 16; W[t] |= context->Message_Block[t * 4 + 2] << 8; W[t] |= context->Message_Block[t * 4 + 3]; } for(t = 16; t < 80; t++) { W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); } A = context->Intermediate_Hash[0]; B = context->Intermediate_Hash[1]; C = context->Intermediate_Hash[2]; D = context->Intermediate_Hash[3]; E = context->Intermediate_Hash[4]; for(t = 0; t < 20; t++) { temp = SHA1CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 20; t < 40; t++) { temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 40; t < 60; t++) { temp = SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 60; t < 80; t++) { temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } context->Intermediate_Hash[0] += A; context->Intermediate_Hash[1] += B; context->Intermediate_Hash[2] += C; context->Intermediate_Hash[3] += D; context->Intermediate_Hash[4] += E; context->Message_Block_Index = 0; } //---------------------------------------------------------------------- //public member-functions /** * @brief Resets the sha1 context and starts a new * hashprocess * @param context The context to reset * @return 0 on succes an error number otherwise */ int SHA1::SHA1Reset(HL_SHA1_CTX *context) { if (!context) { return shaNull; } context->Length_Low = 0; context->Length_High = 0; context->Message_Block_Index = 0; context->Intermediate_Hash[0] = 0x67452301; context->Intermediate_Hash[1] = 0xEFCDAB89; context->Intermediate_Hash[2] = 0x98BADCFE; context->Intermediate_Hash[3] = 0x10325476; context->Intermediate_Hash[4] = 0xC3D2E1F0; context->Computed = 0; context->Corrupted = 0; return shaSuccess; } /** * @brief Data input. * * This memberfunction add data to the specified * context. * * @param context The context to add data to * @param message_array The data to add * @param length The length of the data to add */ int SHA1::SHA1Input( HL_SHA1_CTX *context, const hl_uint8 *message_array, unsigned int length) { if (!length) { return shaSuccess; } if (!context || !message_array) { return shaNull; } if (context->Computed) { context->Corrupted = shaStateError; return shaStateError; } if (context->Corrupted) { return context->Corrupted; } while(length-- && !context->Corrupted) { context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF); context->Length_Low += 8; if (context->Length_Low == 0) { context->Length_High++; if (context->Length_High == 0) { /* Message is too long */ context->Corrupted = 1; } } if (context->Message_Block_Index == 64) { SHA1ProcessMessageBlock(context); } message_array++; } return shaSuccess; } /** * @brief This ends the sha operation, zeroizing the context * and returning the computed hash. * * @param context The context to get the hash from * @param Message_Digest This is an OUT parameter which * contains the hash after the menberfunction returns * @return 0 on succes, an error-code otherwise */ int SHA1::SHA1Result( HL_SHA1_CTX *context, hl_uint8 Message_Digest[SHA1HashSize]) { int i; if (!context || !Message_Digest) { return shaNull; } if (context->Corrupted) { return context->Corrupted; } if (!context->Computed) { SHA1PadMessage(context); for(i=0; i<64; ++i) { /* message may be sensitive, clear it out */ context->Message_Block[i] = 0; } context->Length_Low = 0; /* and clear length */ context->Length_High = 0; context->Computed = 1; } for(i = 0; i < SHA1HashSize; ++i) { Message_Digest[i] = context->Intermediate_Hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) ); } return shaSuccess; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha1.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA1 implementation is derivative from the sourcecode * published in RFC 3174 * * Copyright (C) The Internet Society (2001). All Rights Reserved. * * This document and translations of it may be copied and furnished to * others, and derivative works that comment on or otherwise explain it * or assist in its implementation may be prepared, copied, published * and distributed, in whole or in part, without restriction of any * kind, provided that the above copyright notice and this paragraph are * included on all such copies and derivative works. However, this * document itself may not be modified in any way, such as by removing * the copyright notice or references to the Internet Society or other * Internet organizations, except as needed for the purpose of * developing Internet standards in which case the procedures for * copyrights defined in the Internet Standards process must be * followed, or as required to translate it into languages other than * English. * * The limited permissions granted above are perpetual and will not be * revoked by the Internet Society or its successors or assigns. * * This document and the information contained herein is provided on an * "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING * TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION * HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */ //---------------------------------------------------------------------- /** * @file hl_sha1.h * @brief This file contains the declaration of the SHA1 class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA1_H #define SHA1_H //---------------------------------------------------------------------- //hl includes #include "hl_types.h" //---------------------------------------------------------------------- //enums #ifndef _SHA_enum_ #define _SHA_enum_ enum { shaSuccess = 0, shaNull, /* Null pointer parameter */ shaInputTooLong, /* input data too long */ shaStateError /* called Input after Result */ }; #endif //---------------------------------------------------------------------- //defines #define SHA1HashSize 20 //---------------------------------------------------------------------- //structs /** * @brief this struct represents a SHA1-hash context. */ typedef struct HL_SHA1_CTX { /** Message Digest */ hl_uint32 Intermediate_Hash[SHA1HashSize/4]; /** Message length in bits */ hl_uint32 Length_Low; /** Message length in bits */ hl_uint32 Length_High; /** Index into message block array */ hl_uint16 Message_Block_Index; /** 512-bit message blocks */ hl_uint8 Message_Block[64]; /** Is the digest computed? */ int Computed; /** Is the message digest corrupted? */ int Corrupted; } HL_SHA1_CTX; //---------------------------------------------------------------------- //class definition /** * @brief This class represents the implementation of * the sha1 algorithm. * * Basically the class provides three public member-functions * to create a hash: SHA1Reset(), SHA1Input() and SHA1Result(). * If you want to create a hash based on a string or file quickly * you should use the sha1wrapper class instead of SHA1. */ class SHA1 { private: /** * @brief Internal method to padd the message * * According to the standard, the message must * be padded to an even 512 bits. The first * padding bit must be a '1'. The last 64 bits * represent the length of the original message. * All bits in between should be 0. * This function will pad the message according * to those rules by filling the Message_Block array * accordingly. It will also call the * ProcessMessageBlock function provided appropriately. * When it returns, it can be assumed that the message * digest has been computed. * * @param context The context to padd * */ void SHA1PadMessage(HL_SHA1_CTX *context); /** * @brief This member-function will process the next 512 bits of the * message stored in the Message_Block array. * * Many of the variable names in this code, especially the * single character names, were used because those were the * names used in the publication. * * @param context The context to process */ void SHA1ProcessMessageBlock(HL_SHA1_CTX *context); public: /** * @brief Resets the sha1 context and starts a new * hashprocess * @param context The context to reset * @return 0 on succes an error number otherwise */ int SHA1Reset( HL_SHA1_CTX *context); /** * @brief Data input. * * This memberfunction add data to the specified * context. * * @param context The context to add data to * @param message_array The data to add * @param length The length of the data to add */ int SHA1Input( HL_SHA1_CTX *context, const hl_uint8 *message_array, unsigned int length); /** * @brief This ends the sha operation, zeroizing the context * and returning the computed hash. * * @param context The context to get the hash from * @param Message_Digest This is an OUT parameter which * contains the hash after the menberfunction returns * @return 0 on succes, an error-code otherwise */ int SHA1Result( HL_SHA1_CTX *context, hl_uint8 Message_Digest[SHA1HashSize]); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha1wrapper.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha1wrapper.cpp * @brief This file contains the implementation of the * sha1wrapper class * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha1wrapper.h" #include "hl_sha1.h" #include "hl_types.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //private memberfunctions /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ std::string sha1wrapper::hashIt(void) { hl_uint8 Message_Digest[20]; sha1->SHA1Result(&context, Message_Digest); return convToString(Message_Digest); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string sha1wrapper::convToString(unsigned char *data) { std::ostringstream os; for(int i=0; i<20; ++i) { /* * set the width to 2 */ os.width(2); /* * fill with 0 */ os.fill('0'); /* * conv to hex */ os << std::hex << static_cast(data[i]); } /* * return as std::string */ return os.str(); } /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ void sha1wrapper::updateContext(unsigned char *data, unsigned int len) { sha1->SHA1Input(&context, data, len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void sha1wrapper::resetContext(void) { sha1->SHA1Reset(&context); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string sha1wrapper::getTestHash(void) { return "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"; } //---------------------------------------------------------------------- //public memberfunctions /** * @brief default constructor */ sha1wrapper::sha1wrapper() { this->sha1 = new SHA1(); } /** * @brief default destructor */ sha1wrapper::~sha1wrapper() { delete this->sha1; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha1wrapper.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha1wrapper.h * @brief This file contains the definition of the sha1wrapper * class. * @date Mo 17 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA1WRAPPER_H #define SHA1WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_sha1.h" //---------------------------------------------------------------------- /** * @brief This class represents the SHA1 wrapper-class * * You can use this class to easily create a sha1 hash. * Just create an instance of sha1wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include sha1example.cpp * * sha1wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class sha1wrapper : public hashwrapper { protected: /** * SHA1 access */ SHA1 *sha1; /* * SHA1 context */ HL_SHA1_CTX context; /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ sha1wrapper(); /** * @brief default destructor */ virtual ~sha1wrapper(); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha256.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA256 implementation is derivative from the sourcecode * published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. * */ //---------------------------------------------------------------------- /** * @file hl_sha256.cpp * @brief This file contains the implementation of the SHA256 class * @date Di 25 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha256.h" //---------------------------------------------------------------------- /* * Standard C includes */ #include #include //---------------------------------------------------------------------- #include "hl_sha2mac.h" //---------------------------------------------------------------------- /* * Hash constant words K for SHA-256: */ const static sha2_word32 K256[64] = { 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL }; /* * Initial hash value H for SHA-256: */ const static sha2_word32 sha256_initial_hash_value[8] = { 0x6a09e667UL, 0xbb67ae85UL, 0x3c6ef372UL, 0xa54ff53aUL, 0x510e527fUL, 0x9b05688cUL, 0x1f83d9abUL, 0x5be0cd19UL }; /* * Constant used by End() functions for converting the * digest to a readable hexadecimal character string: */ static const char *sha2_hex_digits = "0123456789abcdef"; /*** SHA-256: *********************************************************/ /** * @brief Initialize the context * @param context The context to init. */ void SHA256::SHA256_Init(HL_SHA256_CTX* context) { if (context == (HL_SHA256_CTX*)0) { return; } MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH); context->bitcount = 0; } #ifdef SHA2_UNROLL_TRANSFORM /* Unrolled SHA-256 round macros: */ #if BYTE_ORDER == LITTLE_ENDIAN #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ REVERSE32(*data++, W256[j]); \ T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ K256[j] + W256[j]; \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ #else /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ K256[j] + (W256[j] = *data++); \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ #endif /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND256(a,b,c,d,e,f,g,h) \ s0 = W256[(j+1)&0x0f]; \ s0 = sigma0_256(s0); \ s1 = W256[(j+14)&0x0f]; \ s1 = sigma1_256(s1); \ T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \ (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA256::SHA256_Transform(HL_SHA256_CTX* context, const sha2_word32* data) { sha2_word32 a, b, c, d, e, f, g, h, s0, s1; sha2_word32 T1, *W256; int j; W256 = (sha2_word32*)context->buffer; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { /* Rounds 0 to 15 (unrolled): */ ROUND256_0_TO_15(a,b,c,d,e,f,g,h); ROUND256_0_TO_15(h,a,b,c,d,e,f,g); ROUND256_0_TO_15(g,h,a,b,c,d,e,f); ROUND256_0_TO_15(f,g,h,a,b,c,d,e); ROUND256_0_TO_15(e,f,g,h,a,b,c,d); ROUND256_0_TO_15(d,e,f,g,h,a,b,c); ROUND256_0_TO_15(c,d,e,f,g,h,a,b); ROUND256_0_TO_15(b,c,d,e,f,g,h,a); } while (j < 16); /* Now for the remaining rounds to 64: */ do { ROUND256(a,b,c,d,e,f,g,h); ROUND256(h,a,b,c,d,e,f,g); ROUND256(g,h,a,b,c,d,e,f); ROUND256(f,g,h,a,b,c,d,e); ROUND256(e,f,g,h,a,b,c,d); ROUND256(d,e,f,g,h,a,b,c); ROUND256(c,d,e,f,g,h,a,b); ROUND256(b,c,d,e,f,g,h,a); } while (j < 64); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = 0; } #else /* SHA2_UNROLL_TRANSFORM */ /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA256::SHA256_Transform(HL_SHA256_CTX* context, const sha2_word32* data) { sha2_word32 a, b, c, d, e, f, g, h, s0, s1; sha2_word32 T1, T2, *W256; int j; W256 = (sha2_word32*)context->buffer; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { #if BYTE_ORDER == LITTLE_ENDIAN /* Copy data while converting to host byte order */ REVERSE32(*data++,W256[j]); /* Apply the SHA-256 compression function to update a..h */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j]; #else /* BYTE_ORDER == LITTLE_ENDIAN */ /* Apply the SHA-256 compression function to update a..h with copy */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++); #endif /* BYTE_ORDER == LITTLE_ENDIAN */ T2 = Sigma0_256(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 16); do { /* Part of the message block expansion: */ s0 = W256[(j+1)&0x0f]; s0 = sigma0_256(s0); s1 = W256[(j+14)&0x0f]; s1 = sigma1_256(s1); /* Apply the SHA-256 compression function to update a..h */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); T2 = Sigma0_256(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 64); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = T2 = 0; } #endif /* SHA2_UNROLL_TRANSFORM */ /** * @brief Updates the context * @param context The context to update. * @param data The data for updating the context. * @param len The length of the given data. */ void SHA256::SHA256_Update(HL_SHA256_CTX* context, const sha2_byte *data, unsigned int len) { unsigned int freespace, usedspace; if (len == 0) { /* Calling with no data is valid - we do nothing */ return; } /* Sanity check: */ assert(context != (HL_SHA256_CTX*)0 && data != (sha2_byte*)0); usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; if (usedspace > 0) { /* Calculate how much free space is available in the buffer */ freespace = SHA256_BLOCK_LENGTH - usedspace; if (len >= freespace) { /* Fill the buffer completely and process it */ MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); context->bitcount += freespace << 3; len -= freespace; data += freespace; SHA256_Transform(context, (sha2_word32*)context->buffer); } else { /* The buffer is not yet full */ MEMCPY_BCOPY(&context->buffer[usedspace], data, len); context->bitcount += len << 3; /* Clean up: */ usedspace = freespace = 0; return; } } while (len >= SHA256_BLOCK_LENGTH) { /* Process as many complete blocks as we can */ SHA256_Transform(context, (sha2_word32*)data); context->bitcount += SHA256_BLOCK_LENGTH << 3; len -= SHA256_BLOCK_LENGTH; data += SHA256_BLOCK_LENGTH; } if (len > 0) { /* There's left-overs, so save 'em */ MEMCPY_BCOPY(context->buffer, data, len); context->bitcount += len << 3; } /* Clean up: */ usedspace = freespace = 0; } /** * @brief Finalize the sha256 operation * @param digest The digest to finalize the operation with. * @param context The context to finalize. */ void SHA256::SHA256_Final(sha2_byte digest[], HL_SHA256_CTX* context) { sha2_word32 *d = (sha2_word32*)digest; unsigned int usedspace; /* Sanity check: */ assert(context != (HL_SHA256_CTX*)0); /* If no digest buffer is passed, we don't bother doing this: */ if (digest != (sha2_byte*)0) { usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; #if BYTE_ORDER == LITTLE_ENDIAN /* Convert FROM host byte order */ REVERSE64(context->bitcount,context->bitcount); #endif if (usedspace > 0) { /* Begin padding with a 1 bit: */ context->buffer[usedspace++] = 0x80; if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) { /* Set-up for the last transform: */ MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace); } else { if (usedspace < SHA256_BLOCK_LENGTH) { MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace); } /* Do second-to-last transform: */ SHA256_Transform(context, (sha2_word32*)context->buffer); /* And set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); } } else { /* Set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); /* Begin padding with a 1 bit: */ *context->buffer = 0x80; } /* Set the bit count: */ *(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount; /* Final transform: */ SHA256_Transform(context, (sha2_word32*)context->buffer); #if BYTE_ORDER == LITTLE_ENDIAN { /* Convert TO host byte order */ int j; for (j = 0; j < 8; j++) { REVERSE32(context->state[j],context->state[j]); *d++ = context->state[j]; } } #else MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH); #endif } /* Clean up state data: */ MEMSET_BZERO(context, sizeof(context)); usedspace = 0; } /** * @brief Ends the sha256 operation and return the * created hash in the given buffer. * @param context The context to end. * @param buffer This OUT-Parameter contains the created * hash after ending the operation. */ char* SHA256::SHA256_End(HL_SHA256_CTX* context, char buffer[]) { sha2_byte digest[SHA256_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != (HL_SHA256_CTX*)0); if (buffer != (char*)0) { SHA256_Final(digest, context); for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = (char)0; } else { MEMSET_BZERO(context, sizeof(context)); } MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH); return buffer; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha256.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA256 implementation is derivative from the sourcecode * published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. */ //---------------------------------------------------------------------- /** * @file hl_sha256.h * @brief This file contains the declaration of the SHA256 class * @date Di 25 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA256_H #define SHA256_H //---------------------------------------------------------------------- //lenght defines #define SHA256_BLOCK_LENGTH 64 #define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8) #define SHA256_DIGEST_LENGTH 32 #define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1) //---------------------------------------------------------------------- //hl includes #include "hl_types.h" //---------------------------------------------------------------------- //typedefs /** * Exactly 1 byte */ typedef hl_uint8 sha2_byte; /** * Exactly 4 bytes */ typedef hl_uint32 sha2_word32; /** * Exactly 8 bytes */ typedef hl_uint64 sha2_word64; /** * @brief This struct represents a SHA256-hash context */ typedef struct HL_SHA256_CTX { /** * state */ hl_uint32 state[8]; /** * bitcount */ hl_uint64 bitcount; /** * message buffer */ hl_uint8 buffer[SHA256_BLOCK_LENGTH]; } HL_SHA256_CTX; //---------------------------------------------------------------------- /** * @brief This class represents the implementation of * the sha256 algorithm. * * Basically the class provides three public member-functions * to create a hash: SHA256_Init(), SHA256_Update() and SHA256_End(). * If you want to create a hash based on a string or file quickly * you should use the sha256wrapper class instead of SHA256. */ class SHA256 { private: /** * @brief Finalize the sha256 operation * @param digest The digest to finalize the operation with. * @param context The context to finalize. */ void SHA256_Final(hl_uint8 digest[SHA256_DIGEST_LENGTH], HL_SHA256_CTX* context); /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA256_Transform(HL_SHA256_CTX* context, const sha2_word32* data); public: /** * @brief Initialize the context * @param context The context to init. */ void SHA256_Init(HL_SHA256_CTX *context); /** * @brief Updates the context * @param context The context to update. * @param data The data for updating the context. * @param len The length of the given data. */ void SHA256_Update(HL_SHA256_CTX* context, const hl_uint8* data, unsigned int len); /** * @brief Ends the sha256 operation and return the * created hash in the given buffer. * @param context The context to end. * @param buffer This OUT-Parameter contains the created * hash after ending the operation. */ char* SHA256_End(HL_SHA256_CTX* context, char buffer[SHA256_DIGEST_STRING_LENGTH]); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha256wrapper.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha256wrapper.cpp * @brief This file contains the implementation of the sha256wrapper * class. * @date Di 25 Sep 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha256wrapper.h" #include "hl_sha256.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //private memberfunctions /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ std::string sha256wrapper::hashIt(void) { sha2_byte buff[SHA256_DIGEST_STRING_LENGTH]; sha256->SHA256_End(&context,(char*)buff); return convToString(buff); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string sha256wrapper::convToString(unsigned char *data) { /* * we can just copy data to a string, because * the transforming to hash is already done * within the sha256 implementation */ return std::string((const char*)data); } /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ void sha256wrapper::updateContext(unsigned char *data, unsigned int len) { this->sha256->SHA256_Update(&context,data,len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void sha256wrapper::resetContext(void) { sha256->SHA256_Init(&context); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string sha256wrapper::getTestHash(void) { return "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; } //---------------------------------------------------------------------- //public memberfunctions /** * @brief default constructor */ sha256wrapper::sha256wrapper() { this->sha256 = new SHA256(); } /** * @brief default destructor */ sha256wrapper::~sha256wrapper() { delete sha256; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha256wrapper.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha256wrapper.h * @brief This file contains the definition of the sha256wrapper * class. * @date Di 25 Sep 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA256WRAPPER_H #define SHA256WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_sha256.h" //---------------------------------------------------------------------- //STL #include //---------------------------------------------------------------------- /** * @brief This class represents the SHA256 wrapper-class * * You can use this class to easily create a sha256 hash. * Just create an instance of sha256wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include sha256example.cpp * * sha256wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class sha256wrapper : public hashwrapper { private: /** * SHA256 access */ SHA256 *sha256; /** * SHA256 context */ HL_SHA256_CTX context; /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ sha256wrapper(); /** * @brief default destructor */ virtual ~sha256wrapper(); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha2ext.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA384 and SHA512 implementations are derivative from * the sourcecode published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. * */ //---------------------------------------------------------------------- /** * @file sha2ext.cpp * @brief This file contains the implementation of the SHA2Ext class * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- // Standard C includes #include #include //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha2ext.h" #include "hl_sha2mac.h" //---------------------------------------------------------------------- /* Hash constant words K for SHA-384 and SHA-512: */ const static sha2_word64 K512[80] = { 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; /* Initial hash value H for SHA-384 */ const static sha2_word64 sha384_initial_hash_value[8] = { 0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL, 0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL, 0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL, 0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL }; /* Initial hash value H for SHA-512 */ const static sha2_word64 sha512_initial_hash_value[8] = { 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL }; /* * * Constant used by SHA256/384/512_End() functions for converting the * * digest to a readable hexadecimal character string: * */ static const char *sha2_hex_digits = "0123456789abcdef"; //---------------------------------------------------------------------- /** * @brief Initialize the SHA512 context * @param context The context to init. */ void SHA2ext::SHA512_Init(HL_SHA512_CTX* context) { if (context == (HL_SHA512_CTX*)0) { return; } MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH); context->bitcount[0] = context->bitcount[1] = 0; } #ifdef SHA2_UNROLL_TRANSFORM /* Unrolled SHA-512 round macros: */ #if BYTE_ORDER == LITTLE_ENDIAN #define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ REVERSE64(*data++, W512[j]); \ T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ K512[j] + W512[j]; \ (d) += T1, \ (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \ j++ #else /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ K512[j] + (W512[j] = *data++); \ (d) += T1; \ (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ j++ #endif /* BYTE_ORDER == LITTLE_ENDIAN */ #define ROUND512(a,b,c,d,e,f,g,h) \ s0 = W512[(j+1)&0x0f]; \ s0 = sigma0_512(s0); \ s1 = W512[(j+14)&0x0f]; \ s1 = sigma1_512(s1); \ T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \ (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \ (d) += T1; \ (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ j++ /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA2ext::SHA512_Transform(HL_SHA512_CTX* context, const sha2_word64* data) { sha2_word64 a, b, c, d, e, f, g, h, s0, s1; sha2_word64 T1, *W512 = (sha2_word64*)context->buffer; int j; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { ROUND512_0_TO_15(a,b,c,d,e,f,g,h); ROUND512_0_TO_15(h,a,b,c,d,e,f,g); ROUND512_0_TO_15(g,h,a,b,c,d,e,f); ROUND512_0_TO_15(f,g,h,a,b,c,d,e); ROUND512_0_TO_15(e,f,g,h,a,b,c,d); ROUND512_0_TO_15(d,e,f,g,h,a,b,c); ROUND512_0_TO_15(c,d,e,f,g,h,a,b); ROUND512_0_TO_15(b,c,d,e,f,g,h,a); } while (j < 16); /* Now for the remaining rounds up to 79: */ do { ROUND512(a,b,c,d,e,f,g,h); ROUND512(h,a,b,c,d,e,f,g); ROUND512(g,h,a,b,c,d,e,f); ROUND512(f,g,h,a,b,c,d,e); ROUND512(e,f,g,h,a,b,c,d); ROUND512(d,e,f,g,h,a,b,c); ROUND512(c,d,e,f,g,h,a,b); ROUND512(b,c,d,e,f,g,h,a); } while (j < 80); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = 0; } #else /* SHA2_UNROLL_TRANSFORM */ /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA2ext::SHA512_Transform(HL_SHA512_CTX* context, const sha2_word64* data) { sha2_word64 a, b, c, d, e, f, g, h, s0, s1; sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer; int j; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { #if BYTE_ORDER == LITTLE_ENDIAN /* Convert TO host byte order */ REVERSE64(*data++, W512[j]); /* Apply the SHA-512 compression function to update a..h */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j]; #else /* BYTE_ORDER == LITTLE_ENDIAN */ /* Apply the SHA-512 compression function to update a..h with copy */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++); #endif /* BYTE_ORDER == LITTLE_ENDIAN */ T2 = Sigma0_512(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 16); do { /* Part of the message block expansion: */ s0 = W512[(j+1)&0x0f]; s0 = sigma0_512(s0); s1 = W512[(j+14)&0x0f]; s1 = sigma1_512(s1); /* Apply the SHA-512 compression function to update a..h */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); T2 = Sigma0_512(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 80); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = T2 = 0; } #endif /* SHA2_UNROLL_TRANSFORM */ void SHA2ext::SHA512_Update(HL_SHA512_CTX* context, const sha2_byte *data, unsigned int len) { unsigned int freespace, usedspace; if (len == 0) { /* Calling with no data is valid - we do nothing */ return; } /* Sanity check: */ assert(context != (HL_SHA512_CTX*)0 && data != (sha2_byte*)0); usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; if (usedspace > 0) { /* Calculate how much free space is available in the buffer */ freespace = SHA512_BLOCK_LENGTH - usedspace; if (len >= freespace) { /* Fill the buffer completely and process it */ MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); ADDINC128(context->bitcount, freespace << 3); len -= freespace; data += freespace; SHA512_Transform(context, (sha2_word64*)context->buffer); } else { /* The buffer is not yet full */ MEMCPY_BCOPY(&context->buffer[usedspace], data, len); ADDINC128(context->bitcount, len << 3); /* Clean up: */ usedspace = freespace = 0; return; } } while (len >= SHA512_BLOCK_LENGTH) { /* Process as many complete blocks as we can */ SHA512_Transform(context, (sha2_word64*)data); ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3); len -= SHA512_BLOCK_LENGTH; data += SHA512_BLOCK_LENGTH; } if (len > 0) { /* There's left-overs, so save 'em */ MEMCPY_BCOPY(context->buffer, data, len); ADDINC128(context->bitcount, len << 3); } /* Clean up: */ usedspace = freespace = 0; } void SHA2ext::SHA512_Last(HL_SHA512_CTX* context) { unsigned int usedspace; usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; #if BYTE_ORDER == LITTLE_ENDIAN /* Convert FROM host byte order */ REVERSE64(context->bitcount[0],context->bitcount[0]); REVERSE64(context->bitcount[1],context->bitcount[1]); #endif if (usedspace > 0) { /* Begin padding with a 1 bit: */ context->buffer[usedspace++] = 0x80; if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) { /* Set-up for the last transform: */ MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace); } else { if (usedspace < SHA512_BLOCK_LENGTH) { MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace); } /* Do second-to-last transform: */ SHA512_Transform(context, (sha2_word64*)context->buffer); /* And set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2); } } else { /* Prepare for final transform: */ MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH); /* Begin padding with a 1 bit: */ *context->buffer = 0x80; } /* Store the length of input data (in bits): */ *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1]; *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0]; /* Final transform: */ SHA512_Transform(context, (sha2_word64*)context->buffer); } void SHA2ext::SHA512_Final(sha2_byte digest[], HL_SHA512_CTX* context) { sha2_word64 *d = (sha2_word64*)digest; /* Sanity check: */ assert(context != (HL_SHA512_CTX*)0); /* If no digest buffer is passed, we don't bother doing this: */ if (digest != (sha2_byte*)0) { SHA512_Last(context); /* Save the hash data for output: */ #if BYTE_ORDER == LITTLE_ENDIAN { /* Convert TO host byte order */ int j; for (j = 0; j < 8; j++) { REVERSE64(context->state[j],context->state[j]); *d++ = context->state[j]; } } #else MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH); #endif } /* Zero out state data */ MEMSET_BZERO(context, sizeof(context)); } char* SHA2ext::SHA512_End(HL_SHA512_CTX* context, char buffer[]) { sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != (HL_SHA512_CTX*)0); if (buffer != (char*)0) { SHA512_Final(digest, context); for (i = 0; i < SHA512_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = (char)0; } else { MEMSET_BZERO(context, sizeof(context)); } MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH); return buffer; } void SHA2ext::SHA384_Init(HL_SHA_384_CTX* context) { if (context == (HL_SHA_384_CTX*)0) { return; } MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH); context->bitcount[0] = context->bitcount[1] = 0; } void SHA2ext::SHA384_Update(HL_SHA_384_CTX* context, const sha2_byte* data, unsigned int len) { SHA512_Update((HL_SHA512_CTX*)context, data, len); } void SHA2ext::SHA384_Final(sha2_byte digest[], HL_SHA_384_CTX* context) { sha2_word64 *d = (sha2_word64*)digest; /* Sanity check: */ assert(context != (HL_SHA_384_CTX*)0); /* If no digest buffer is passed, we don't bother doing this: */ if (digest != (sha2_byte*)0) { SHA512_Last((HL_SHA512_CTX*)context); /* Save the hash data for output: */ #if BYTE_ORDER == LITTLE_ENDIAN { /* Convert TO host byte order */ int j; for (j = 0; j < 6; j++) { REVERSE64(context->state[j],context->state[j]); *d++ = context->state[j]; } } #else MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH); #endif } /* Zero out state data */ MEMSET_BZERO(context, sizeof(context)); } char* SHA2ext::SHA384_End(HL_SHA_384_CTX* context, char buffer[]) { sha2_byte digest[SHA384_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != (HL_SHA_384_CTX*)0); if (buffer != (char*)0) { SHA384_Final(digest, context); for (i = 0; i < SHA384_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = (char)0; } else { MEMSET_BZERO(context, sizeof(context)); } MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH); return buffer; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha2ext.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA384 and SHA512 implementations are derivative from the * sourcecode published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. */ //---------------------------------------------------------------------- /** * @file hl_sha2ext.h * @brief This file contains the declaration of the SHA384 and * SHA512 classes * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA2ext_H #define SHA2ext_H //---------------------------------------------------------------------- //lenght defines #define SHA384_BLOCK_LENGTH 128 #define SHA384_DIGEST_LENGTH 48 #define SHA384_DIGEST_STRING_LENGTH (SHA384_DIGEST_LENGTH * 2 + 1) #define SHA512_BLOCK_LENGTH 128 #define SHA512_DIGEST_LENGTH 64 #define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1) #define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16) //---------------------------------------------------------------------- //hl includes #include "hl_types.h" //---------------------------------------------------------------------- //typedefs /** * Exactly 1 byte */ typedef hl_uint8 sha2_byte; /** * Exactly 4 bytes */ typedef hl_uint32 sha2_word32; /** * Exactly 8 bytes */ typedef hl_uint64 sha2_word64; /** * @brief This struct represents a SHA512-hash context */ typedef struct HL_SHA512_CTX { hl_uint64 state[8]; hl_uint64 bitcount[2]; hl_uint8 buffer[SHA512_BLOCK_LENGTH]; } HL_SHA512_CTX; /** * @brief This struct represents a SHA384-hash context */ typedef HL_SHA512_CTX HL_SHA_384_CTX; //---------------------------------------------------------------------- /** * @brief This class represents the implementation of * the SHA384 and SHA512 algorithm. * * Basically the class provides six public member-functions * to create a hash: SHA384_Init(), SHA384_Update(), SHA384_End(), * SHA512_Init(), SHA512_Update() and SHA512_End(). * If you want to create a hash based on a string or file quickly * you should use the sha384wrapper or sha512wrapper classes. */ class SHA2ext { private: /** * @brief Finalize the sha384 operation * @param digest The digest to finalize the operation with. * @param context The context to finalize. */ void SHA384_Final(hl_uint8 digest[SHA384_DIGEST_LENGTH], HL_SHA_384_CTX* context); /** * @brief Finalize the sha512 operation * @param digest The digest to finalize the operation with. * @param context The context to finalize. */ void SHA512_Final(hl_uint8 digest[SHA512_DIGEST_LENGTH], HL_SHA512_CTX* context); /** * @brief Internal method * * used by SHA512 and SHA384 * @author Benjamin Grdelbach * @param context The context of the operation */ void SHA512_Last(HL_SHA512_CTX* context); /** * @brief Internal data transformation * @param context The context to use * @param data The data to transform */ void SHA512_Transform(HL_SHA512_CTX* context, const sha2_word64* data); public: /** * @brief Initialize the SHA384 context * @param context The context to init. */ void SHA384_Init(HL_SHA_384_CTX* context); /** * @brief Initialize the SHA512 context * @param context The context to init. */ void SHA512_Init(HL_SHA512_CTX* context); /** * @brief Updates the SHA512 context * @param context The context to update. * @param data The data for updating the context. * @param len The length of the given data. */ void SHA384_Update(HL_SHA_384_CTX* context, const hl_uint8* data, unsigned int len); /** * @brief Updates the SHA284 context * @param context The context to update. * @param data The data for updating the context. * @param len The length of the given data. */ void SHA512_Update(HL_SHA512_CTX* context, const hl_uint8* data, unsigned int len); /** * @brief Ends the SHA384 operation and return the * created hash in the given buffer. * @param context The context to end. * @param buffer This OUT-Parameter contains the created * hash after ending the operation. */ char* SHA384_End(HL_SHA_384_CTX* context, char buffer[SHA384_DIGEST_STRING_LENGTH]); /** * @brief Ends the SHA512 operation and return the * created hash in the given buffer. * @param context The context to end. * @param buffer This OUT-Parameter contains the created * hash after ending the operation. */ char* SHA512_End(HL_SHA512_CTX* context, char buffer[SHA512_DIGEST_STRING_LENGTH]); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha2mac.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /* * The hashlib++ SHA384 and SHA512 implementations are derivative from * the sourcecode published by Aaron D. Gifford * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) 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. * */ //---------------------------------------------------------------------- /** * @file hl_sha2mac.h * @brief This file contains useful macros for use with SHA384 * and SHA512 * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- /* * SHA-256/384/512 Machine Architecture Definitions * BYTE_ORDER NOTE: * * Please make sure that your system defines BYTE_ORDER. If your * architecture is little-endian, make sure it also defines * LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are * equivilent. * * If your system does not define the above, then you can do so by * hand like this: * * #define LITTLE_ENDIAN 1234 * #define BIG_ENDIAN 4321 * * And for little-endian machines, add: * * #define BYTE_ORDER LITTLE_ENDIAN * * Or for big-endian machines: * * #define BYTE_ORDER BIG_ENDIAN * * The FreeBSD machine this was written on defines * BYTE_ORDER appropriately by including * (which in turn includes where the appropriate * definitions are actually made). */ #define LITTLE_ENDIAN 1234 #define BYTE_ORDER LITTLE_ENDIAN #if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN) #error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN #endif /*** ENDIAN REVERSAL MACROS *******************************************/ #if BYTE_ORDER == LITTLE_ENDIAN #define REVERSE32(w,x) { \ sha2_word32 tmp = (w); \ tmp = (tmp >> 16) | (tmp << 16); \ (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \ } #define REVERSE64(w,x) { \ sha2_word64 tmp = (w); \ tmp = (tmp >> 32) | (tmp << 32); \ tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) | \ ((tmp & 0x00ff00ff00ff00ffULL) << 8); \ (x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) | \ ((tmp & 0x0000ffff0000ffffULL) << 16); \ } #endif /* BYTE_ORDER == LITTLE_ENDIAN */ /* * Macro for incrementally adding the unsigned 64-bit integer n to the * unsigned 128-bit integer (represented using a two-element array of * 64-bit words): */ #define ADDINC128(w,n) { \ (w)[0] += (sha2_word64)(n); \ if ((w)[0] < (n)) { \ (w)[1]++; \ } \ } /* * Macros for copying blocks of memory and for zeroing out ranges * of memory. Using these macros makes it easy to switch from * using memset()/memcpy() and using bzero()/bcopy(). * * Please define either SHA2_USE_MEMSET_MEMCPY or define * SHA2_USE_BZERO_BCOPY depending on which function set you * choose to use: */ #if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY) /* Default to memset()/memcpy() if no option is specified */ #define SHA2_USE_MEMSET_MEMCPY 1 #endif #if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY) /* Abort with an error if BOTH options are defined */ #error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both! #endif #ifdef SHA2_USE_MEMSET_MEMCPY #define MEMSET_BZERO(p,l) memset((p), 0, (l)) #define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l)) #endif #ifdef SHA2_USE_BZERO_BCOPY #define MEMSET_BZERO(p,l) bzero((p), (l)) #define MEMCPY_BCOPY(d,s,l) bcopy((s), (d), (l)) #endif /*** THE SIX LOGICAL FUNCTIONS **************************************** * * Bit shifting and rotation (used by the six SHA-XYZ logical functions: * * NOTE: The naming of R and S appears backwards here (R is a SHIFT and * S is a ROTATION) because the SHA-256/384/512 description document * (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this * same "backwards" definition. */ /* Shift-right (used in SHA-256, SHA-384, and SHA-512): */ #define R(b,x) ((x) >> (b)) /* 32-bit Rotate-right (used in SHA-256): */ #define S32(b,x) (((x) >> (b)) | ((x) << (32 - (b)))) /* 64-bit Rotate-right (used in SHA-384 and SHA-512): */ #define S64(b,x) (((x) >> (b)) | ((x) << (64 - (b)))) /* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */ #define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) #define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) /* Four of six logical functions used in SHA-256: */ #define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x))) #define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x))) #define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3 , (x))) #define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x))) /* Four of six logical functions used in SHA-384 and SHA-512: */ #define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x))) #define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x))) #define sigma0_512(x) (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7, (x))) #define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R( 6, (x))) ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha384wrapper.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha384wrapper.cpp * @brief This file contains the implementation of the sha384wrapper * class. * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha384wrapper.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //private memberfunctions /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ std::string sha384wrapper::hashIt(void) { sha2_byte buff[SHA384_DIGEST_STRING_LENGTH]; sha384->SHA384_End(&context,(char*)buff); return convToString(buff); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string sha384wrapper::convToString(unsigned char *data) { /* * we can just copy data to a string, because * the transforming to hash is already done * within the sha384 implementation */ return std::string((const char*)data); } /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ void sha384wrapper::updateContext(unsigned char *data, unsigned int len) { this->sha384->SHA384_Update(&context,data,len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void sha384wrapper::resetContext(void) { sha384->SHA384_Init(&context); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string sha384wrapper::getTestHash(void) { return "ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1"; } //---------------------------------------------------------------------- //public memberfunctions /** * @brief default constructor */ sha384wrapper::sha384wrapper() { this->sha384 = new SHA2ext(); } /** * @brief default destructor */ sha384wrapper::~sha384wrapper() { delete sha384; } ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha384wrapper.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha384wrapper.h * @brief This file contains the definition of the sha384wrapper * class. * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA384WRAPPER_H #define SHA384WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_sha2ext.h" //---------------------------------------------------------------------- //STL #include //---------------------------------------------------------------------- /** * @brief This class represents the SHA384 wrapper-class * * You can use this class to easily create a sha384 hash. * Just create an instance of sha384wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include sha384example.cpp * * sha384wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class sha384wrapper : public hashwrapper { private: /** * SHA384 access * via extended SHA2 */ SHA2ext *sha384; /** * SHA384 context */ HL_SHA_384_CTX context; /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ sha384wrapper(); /** * @brief default destructor */ virtual ~sha384wrapper(); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha512wrapper.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha512wrapper.cpp * @brief This file contains the implementation of the sha512wrapper * class. * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //hashlib++ includes #include "hl_sha512wrapper.h" //---------------------------------------------------------------------- //STL includes #include //---------------------------------------------------------------------- //private memberfunctions /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ std::string sha512wrapper::hashIt(void) { sha2_byte buff[SHA512_DIGEST_STRING_LENGTH]; sha512->SHA512_End(&context,(char*)buff); return convToString(buff); } /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ std::string sha512wrapper::convToString(unsigned char *data) { /* * we can just copy data to a string, because * the transforming to hash is already done * within the sha512 implementation */ return std::string((const char*)data); } /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ void sha512wrapper::updateContext(unsigned char *data, unsigned int len) { this->sha512->SHA512_Update(&context,data,len); } /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ void sha512wrapper::resetContext(void) { sha512->SHA512_Init(&context); } /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ std::string sha512wrapper::getTestHash(void) { return "07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6"; } //---------------------------------------------------------------------- //public memberfunctions /** * @brief default constructor */ sha512wrapper::sha512wrapper() { this->sha512 = new SHA2ext(); } /** * @brief default destructor */ sha512wrapper::~sha512wrapper() { delete sha512; } ================================================ FILE: _draft/flash_cpp/hashlib/hl_sha512wrapper.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_sha512wrapper.h * @brief This file contains the definition of the sha512wrapper * class. * @date Mo 12 Nov 2007 */ //---------------------------------------------------------------------- //include protection #ifndef SHA512WRAPPER_H #define SHA512WRAPPER_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" #include "hl_sha2ext.h" //---------------------------------------------------------------------- //STL #include //---------------------------------------------------------------------- /** * @brief This class represents the SHA512 wrapper-class * * You can use this class to easily create a sha512 hash. * Just create an instance of sha512wrapper and call the * inherited memberfunctions getHashFromString() * and getHashFromFile() to create a hash based on a * string or a file. * * Have a look at the following example: * * @include sha512example.cpp * * sha512wrapper implements resetContext(), updateContext() * and hashIt() to create a hash. */ class sha512wrapper : public hashwrapper { private: /** * SHA512 access * via extended SHA2 */ SHA2ext *sha512; /** * SHA512 context */ HL_SHA512_CTX context; /** * @brief This method ends the hash process * and returns the hash as string. * * @return a hash as std::string */ virtual std::string hashIt(void); /** * @brief This internal member-function * convertes the hash-data to a * std::string (HEX). * * @param data The hash-data to covert into HEX * @return the converted data as std::string */ virtual std::string convToString(unsigned char *data); /** * @brief This method adds the given data to the * current hash context * * @param data The data to add to the current context * @param len The length of the data to add */ virtual void updateContext(unsigned char *data, unsigned int len); /** * @brief This method resets the current hash context. * In other words: It starts a new hash process. */ virtual void resetContext(void); /** * @brief This method should return the hash of the * test-string "The quick brown fox jumps over the lazy * dog" */ virtual std::string getTestHash(void); public: /** * @brief default constructor */ sha512wrapper(); /** * @brief default destructor */ virtual ~sha512wrapper(); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_types.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_types.h * @brief This file defines some global types * @date So 13 Jan 2008 */ //---------------------------------------------------------------------- //include protection #ifndef HLTYPES_H #define HLTYPES_H //---------------------------------------------------------------------- /** * exactly 1 Byte */ typedef unsigned char hl_uint8; /** * at least 2 Byte */ typedef unsigned short int hl_uint16; /** * at least 4 Byte */ typedef unsigned int hl_uint32; /** * at least 8 Byte */ #ifdef __GNUC__ typedef unsigned long long int hl_uint64; #elif __MINGW32__ typedef unsigned long long int hl_uint64; #elif _MSC_VER typedef unsigned __int64 hl_uint64; #else #error "Unsuppported compiler." \ "Please use GCC,MINGW,MSVC " \ " or define hl_uint64 for your compiler in hl_types.h line 62" #endif //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_wrapperfactory.cpp ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grüdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_wrapperfactory.cpp * @brief This file contains the implementation of the * wrapperfactory class * @date DO 13 Oct 2011 */ //---------------------------------------------------------------------- #include #include "hl_wrapperfactory.h" #include "hashlibpp.h" //---------------------------------------------------------------------- //public member functions /** * @brief Simple factory-method to create a hashwrapper * * @param type The type of the hash algorithm to create a wrapper for * @return A hashwrapper for the fiven type */ hashwrapper* wrapperfactory::create(HL_Wrappertype type) { if(type == HL_MD5) { return new md5wrapper(); } else if(type == HL_SHA1) { return new sha1wrapper(); } else if(type == HL_SHA256) { return new sha256wrapper(); } else if(type == HL_SHA384) { return new sha384wrapper(); } else if(type == HL_SHA512) { return new sha512wrapper(); } throw hlException(HL_UNKNOWN_HASH_TYPE,"Unknown hashtype"); } /** * @brief Simple factory-method to create a hashwrapper * * @param type The type of the hash algorithm to create a wrapper for * @return A hashwrapper for the fiven type */ hashwrapper* wrapperfactory::create(std::string type) { std::transform(type.begin(), type.end(), type.begin(), ::toupper); if(type == "MD5") { return new md5wrapper(); } else if(type == "SHA1") { return new sha1wrapper(); } else if(type == "SHA256") { return new sha256wrapper(); } else if(type == "SHA384") { return new sha384wrapper(); } else if(type == "SHA512") { return new sha512wrapper(); } return NULL; } //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/hashlib/hl_wrapperfactory.h ================================================ /* * hashlib++ - a simple hash library for C++ * * Copyright (c) 2007-2010 Benjamin Grüdelbach * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- /** * @file hl_wrapperfactory.h * @brief This file contains a simple hashwrapper factory * @date DO 13 Oct 2011 */ //---------------------------------------------------------------------- //include protection #ifndef WRAPPERFACTORY_H #define WRAPPERFACTORY_H //---------------------------------------------------------------------- //hashlib++ includes #include "hl_hashwrapper.h" //---------------------------------------------------------------------- //enumeration /* * definition of the supported hashtypes */ enum HL_Wrappertype { HL_MD5, HL_SHA1, HL_SHA256, HL_SHA384, HL_SHA512 }; //---------------------------------------------------------------------- /** * @brief This class represents a simple factory for creating wrappers. * * U can use this class for dynamicly create wrappers of a given * type at runtime. */ class wrapperfactory { public: /** * @brief Simple factory-method to create a hashwrapper * * @param type The type of the hash algorithm to create a wrapper for * @return A hashwrapper for the fiven type */ hashwrapper* create(HL_Wrappertype type); /** * @brief Simple factory-method to create a hashwrapper * * @param type the simple name of the type for example "md5" * @return A hashwrapper for the fiven type */ hashwrapper* create(std::string type); }; //---------------------------------------------------------------------- //end of include protection #endif //---------------------------------------------------------------------- //EOF ================================================ FILE: _draft/flash_cpp/main.cpp ================================================ #include #include "AS3/AS3.h" int main() { AS3_GoAsync(); } ================================================ FILE: _draft/flash_cpp/makefile ================================================ T05: check @echo "-------- Sample 5 --------" @echo && echo "Now compile a SWC and demo SWF" "$(FLASCC)/usr/bin/g++" $(BASE_CFLAGS) \ main.cpp \ as3api.cpp \ hashlib/hl_md5.cpp \ hashlib/hl_md5wrapper.cpp \ -O4 -disable-telemetry -flto-api=exports.txt\ -emit-swc=com.webuploader -o Test.swc # "$(FLEX)/bin/mxmlc" -static-link-runtime-shared-libraries -compiler.omit-trace-statements=false -library-path=MurmurHash.swc -debug=false swcdemo.as -o swcdemo.swf FLASCC:=X FLEX:=X AS3COMPILER:=asc2.jar BASE_CFLAGS:=-Werror -Wno-write-strings -Wno-trigraphs $?UNAME=$(shell uname -s) ifneq (,$(findstring CYGWIN,$(UNAME))) $?nativepath=$(shell cygpath -at mixed $(1)) $?unixpath=$(shell cygpath -at unix $(1)) else $?nativepath=$(abspath $(1)) $?unixpath=$(abspath $(1)) endif ifneq (,$(findstring "asc2.jar","$(AS3COMPILER)")) $?AS3COMPILERARGS=java $(JVMARGS) -jar $(call nativepath,$(FLASCC)/usr/lib/$(AS3COMPILER)) -merge -md else echo "ASC is no longer supported" ; exit 1 ; endif check: @if [ -d $(FLASCC)/usr/bin ] ; then true ; \ else echo "Couldn't locate FLASCC sdk directory, please invoke make with \"make FLASCC=/path/to/FLASCC/sdk ...\"" ; exit 1 ; \ fi @if [ -d "$(FLEX)/bin" ] ; then true ; \ else echo "Couldn't locate Flex sdk directory, please invoke make with \"make FLEX=/path/to/flex ...\"" ; exit 1 ; \ fi clean: rm -f *.swf *.swc *.bc *.exe ================================================ FILE: _draft/hashFile.js ================================================ // 此文件在worker环境下运行。 importScripts('md5.js'); var hashMe = function(file, callbackFunction) { var thisObj = this, _binStart = "", _binEnd = "", callback = "", fileManager1 = new FileReader, fileManager2 = new FileReader; thisObj.setBinAndHash = function(startOrEnd, binData) { switch (startOrEnd) { case 0: thisObj._binStart = binData; break; case 1: thisObj._binEnd = binData; } thisObj._binStart && thisObj._binEnd && thisObj.md5sum(thisObj._binStart, thisObj._binEnd) }; thisObj.md5sum = function(start, end) { thisObj._hash = md5(start + end); callback(thisObj._hash); }; thisObj.getHash = function() { return thisObj._hash; }; thisObj.calculateHashOfFile = function(file) { fileManager1.onload = function(f) { thisObj.setBinAndHash(0, f.target.result); }; fileManager2.onload = function(f) { thisObj.setBinAndHash(1, f.target.result); }; var start = file.slice(0, 65536); var end = file.slice(file.size - 65536, file.size); fileManager1.readAsBinaryString(start); fileManager2.readAsBinaryString(end); }; thisObj.calculateHashOfFile(file); callback = callbackFunction; }; onmessage = function( e ) { var file = e.data; hashMe( file, function( ret ) { postMessage( ret ); }); } ================================================ FILE: _draft/md5.js ================================================ (function( window ){ function md5cycle(x, k) { var a = x[0], b = x[1], c = x[2], d = x[3]; a = ff(a, b, c, d, k[0], 7, -680876936); d = ff(d, a, b, c, k[1], 12, -389564586); c = ff(c, d, a, b, k[2], 17, 606105819); b = ff(b, c, d, a, k[3], 22, -1044525330); a = ff(a, b, c, d, k[4], 7, -176418897); d = ff(d, a, b, c, k[5], 12, 1200080426); c = ff(c, d, a, b, k[6], 17, -1473231341); b = ff(b, c, d, a, k[7], 22, -45705983); a = ff(a, b, c, d, k[8], 7, 1770035416); d = ff(d, a, b, c, k[9], 12, -1958414417); c = ff(c, d, a, b, k[10], 17, -42063); b = ff(b, c, d, a, k[11], 22, -1990404162); a = ff(a, b, c, d, k[12], 7, 1804603682); d = ff(d, a, b, c, k[13], 12, -40341101); c = ff(c, d, a, b, k[14], 17, -1502002290); b = ff(b, c, d, a, k[15], 22, 1236535329); a = gg(a, b, c, d, k[1], 5, -165796510); d = gg(d, a, b, c, k[6], 9, -1069501632); c = gg(c, d, a, b, k[11], 14, 643717713); b = gg(b, c, d, a, k[0], 20, -373897302); a = gg(a, b, c, d, k[5], 5, -701558691); d = gg(d, a, b, c, k[10], 9, 38016083); c = gg(c, d, a, b, k[15], 14, -660478335); b = gg(b, c, d, a, k[4], 20, -405537848); a = gg(a, b, c, d, k[9], 5, 568446438); d = gg(d, a, b, c, k[14], 9, -1019803690); c = gg(c, d, a, b, k[3], 14, -187363961); b = gg(b, c, d, a, k[8], 20, 1163531501); a = gg(a, b, c, d, k[13], 5, -1444681467); d = gg(d, a, b, c, k[2], 9, -51403784); c = gg(c, d, a, b, k[7], 14, 1735328473); b = gg(b, c, d, a, k[12], 20, -1926607734); a = hh(a, b, c, d, k[5], 4, -378558); d = hh(d, a, b, c, k[8], 11, -2022574463); c = hh(c, d, a, b, k[11], 16, 1839030562); b = hh(b, c, d, a, k[14], 23, -35309556); a = hh(a, b, c, d, k[1], 4, -1530992060); d = hh(d, a, b, c, k[4], 11, 1272893353); c = hh(c, d, a, b, k[7], 16, -155497632); b = hh(b, c, d, a, k[10], 23, -1094730640); a = hh(a, b, c, d, k[13], 4, 681279174); d = hh(d, a, b, c, k[0], 11, -358537222); c = hh(c, d, a, b, k[3], 16, -722521979); b = hh(b, c, d, a, k[6], 23, 76029189); a = hh(a, b, c, d, k[9], 4, -640364487); d = hh(d, a, b, c, k[12], 11, -421815835); c = hh(c, d, a, b, k[15], 16, 530742520); b = hh(b, c, d, a, k[2], 23, -995338651); a = ii(a, b, c, d, k[0], 6, -198630844); d = ii(d, a, b, c, k[7], 10, 1126891415); c = ii(c, d, a, b, k[14], 15, -1416354905); b = ii(b, c, d, a, k[5], 21, -57434055); a = ii(a, b, c, d, k[12], 6, 1700485571); d = ii(d, a, b, c, k[3], 10, -1894986606); c = ii(c, d, a, b, k[10], 15, -1051523); b = ii(b, c, d, a, k[1], 21, -2054922799); a = ii(a, b, c, d, k[8], 6, 1873313359); d = ii(d, a, b, c, k[15], 10, -30611744); c = ii(c, d, a, b, k[6], 15, -1560198380); b = ii(b, c, d, a, k[13], 21, 1309151649); a = ii(a, b, c, d, k[4], 6, -145523070); d = ii(d, a, b, c, k[11], 10, -1120210379); c = ii(c, d, a, b, k[2], 15, 718787259); b = ii(b, c, d, a, k[9], 21, -343485551); x[0] = add32(a, x[0]); x[1] = add32(b, x[1]); x[2] = add32(c, x[2]); x[3] = add32(d, x[3]); } function cmn(q, a, b, x, s, t) { a = add32(add32(a, q), add32(x, t)); return add32((a << s) | (a >>> (32 - s)), b); } function ff(a, b, c, d, x, s, t) { return cmn((b & c) | ((~b) & d), a, b, x, s, t); } function gg(a, b, c, d, x, s, t) { return cmn((b & d) | (c & (~d)), a, b, x, s, t); } function hh(a, b, c, d, x, s, t) { return cmn(b ^ c ^ d, a, b, x, s, t); } function ii(a, b, c, d, x, s, t) { return cmn(c ^ (b | (~d)), a, b, x, s, t); } function md51(s) { txt = ''; var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i; for (i = 64; i <= s.length; i += 64) { md5cycle(state, md5blk(s.substring(i - 64, i))); } s = s.substring(i - 64); var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (i = 0; i < s.length; i++) tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); tail[i >> 2] |= 0x80 << ((i % 4) << 3); if (i > 55) { md5cycle(state, tail); for (i = 0; i < 16; i++) tail[i] = 0; } tail[14] = n * 8; md5cycle(state, tail); return state; } /* there needs to be support for Unicode here, * unless we pretend that we can redefine the MD-5 * algorithm for multi-byte characters (perhaps * by adding every four 16-bit characters and * shortening the sum to 32 bits). Otherwise * I suggest performing MD-5 as if every character * was two bytes--e.g., 0040 0025 = @%--but then * how will an ordinary MD-5 sum be matched? * There is no way to standardize text to something * like UTF-8 before transformation; speed cost is * utterly prohibitive. The JavaScript standard * itself needs to look at this: it should start * providing access to strings as preformed UTF-8 * 8-bit unsigned value arrays. */ function md5blk(s) { /* I figured global was faster. */ var md5blks = [], i; /* Andy King said do it this way. */ for (i = 0; i < 64; i += 4) { md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24); } return md5blks; } var hex_chr = '0123456789abcdef'.split(''); function rhex(n) { var s = '', j = 0; for (; j < 4; j++) s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; return s; } function hex(x) { for (var i = 0; i < x.length; i++) x[i] = rhex(x[i]); return x.join(''); } function md5(s) { return hex(md51(s)); } /* this function is much faster, so if possible we use it. Some IEs are the only ones I know of that need the idiotic second function, generated by an if clause. */ var add32 = function(a, b) { return (a + b) & 0xFFFFFFFF; } if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') { add32 = function(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } } window.md5 = md5; })(this); ================================================ FILE: _draft/md5File.js ================================================ // 此文件在worker环境下运行。 importScripts('md5.js'); var fr = new FileReader(); var Md5File = (function() { /*var throttle = 3, pool = [], wating = []; function _tick() { var avaibles = [], i, fr, cb; for ( i = 0; i < throttle; i++ ) { fr = pool[ i ]; fr && fr.readyState === 2 && avaibles.push( fr ); } while ( avaibles.length && wating.length ) { fr = avaibles.shift(); cb = wating.shift(); fr.onload = fr.onerror = null; cb( fr ); fr.onloadend = _tick; } } function getReader( cb ) { var fr; if ( pool.length < throttle ) { fr = new FileReader(); pool.push( fr ); cb( fr ); fr.onloadend = _tick; return; } wating.push( cb ); _tick(); }*/ return function( file, cb ) { var reader = new FileReader(); reader.onload = function() { cb( md5( this.result ) ); reader.onload = reader.onerror = null; reader.readAsBinaryString( new Blob() ); reader = null; }; reader.onerror = function( e ) { reader = reader.onload = reader.onerror = null; }; reader.readAsBinaryString( file ); } })(); onmessage = function( e ) { var file = e.data; Md5File( file, function( ret ) { postMessage( ret ); }); } ================================================ FILE: _draft/music/index.html ================================================ WebUploader演示

    或将文件拖到这里

    ================================================ FILE: _draft/music/jquery.js ================================================ /*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML="
    a",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="
    t
    ",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="
    ",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="
    ",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&>(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/\s*$/g,At={option:[1,""],legend:[1,"
    ","
    "],area:[1,"",""],param:[1,"",""],thead:[1,"","
    "],tr:[2,"","
    "],col:[2,"","
    "],td:[3,"","
    "],_default:b.support.htmlSerialize?[0,"",""]:[1,"X
    ","
    "]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?""!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("

    分片、并发

    分片与并发结合,将一个大文件分割成多块,并发上传,极大地提高大文件的上传速度。

    当网络问题导致传输错误时,只需要重传出错分片,而不是整个文件。另外分片传输能够更加实时的跟踪上传进度。

    预览、压缩

    支持常用图片格式jpg,jpeg,gif,bmp,png预览与压缩,节省网络数据传输。

    解析jpeg中的meta信息,对于各种orientation做了正确的处理,同时压缩后上传保留图片的所有原始meta数据。

    多途径添加文件

    支持文件多选,类型过滤,拖拽(文件&文件夹),图片粘贴功能。

    粘贴功能主要体现在当有图片数据在剪切板中时(截屏工具如QQ(Ctrl + ALT + A), 网页中右击图片点击复制),Ctrl + V便可添加此图片文件。

    HTML5 & FLASH

    兼容主流浏览器,接口一致,实现了两套运行时支持,用户无需关心内部用了什么内核。

    同时Flash部分没有做任何UI相关的工作,方便不关心flash的用户扩展和自定义业务需求。

    MD5秒传

    当文件体积大、量比较多时,支持上传前做文件md5值验证,一致则可直接跳过。

    如果服务端与前端统一修改算法,取段md5,可大大提升验证性能,耗时在20ms左右。

    易扩展、可拆分

    采用可拆分机制, 将各个功能独立成了小组件,可自由搭配。

    采用AMD规范组织代码,清晰明了,方便高级玩家扩展。

    ================================================ FILE: jekyll/js/bootstrap.js ================================================ /*! * Bootstrap v3.0.3 (http://getbootstrap.com) * Copyright 2013 Twitter, Inc. * Licensed under http://www.apache.org/licenses/LICENSE-2.0 */ if (typeof jQuery === "undefined") { throw new Error("Bootstrap requires jQuery") } /* ======================================================================== * Bootstrap: transition.js v3.0.3 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false, $el = this $(this).one($.support.transition.end, function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.0.3 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one($.support.transition.end, removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.0.3 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) } Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (!data.resetText) $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d); }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-toggle="buttons"]') var changed = true if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') === 'radio') { // see if clicking on current one if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') e.preventDefault() }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.0.3 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.DEFAULTS = { interval: 5000 , pause: 'hover' , wrap: true } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getActiveIndex = function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getActiveIndex() if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } this.sliding = true isCycling && this.pause() var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid.bs.carousel', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0) }) .emulateTransitionEnd(600) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid.bs.carousel') } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) $carousel.carousel($carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.0.3 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.0.3 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle=dropdown]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('
    "; if ( actual !== expected ) { output += ""; output += ""; } source = sourceFromStacktrace(); if ( source ) { details.source = source; output += ""; } output += "
    Expected:
    " + expected + "
    Result:
    " + actual + "
    Diff:
    " + QUnit.diff( expected, actual ) + "
    Source:
    " + escapeText( source ) + "
    "; } runLoggingCallbacks( "log", QUnit, details ); config.current.assertions.push({ result: !!result, message: output }); }, pushFailure: function( message, source, actual ) { if ( !config.current ) { throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) ); } var output, details = { module: config.current.module, name: config.current.testName, result: false, message: message }; message = escapeText( message ) || "error"; message = "" + message + ""; output = message; output += ""; if ( actual ) { output += ""; } if ( source ) { details.source = source; output += ""; } output += "
    Result:
    " + escapeText( actual ) + "
    Source:
    " + escapeText( source ) + "
    "; runLoggingCallbacks( "log", QUnit, details ); config.current.assertions.push({ result: false, message: output }); }, url: function( params ) { params = extend( extend( {}, QUnit.urlParams ), params ); var key, querystring = "?"; for ( key in params ) { if ( hasOwn.call( params, key ) ) { querystring += encodeURIComponent( key ) + "=" + encodeURIComponent( params[ key ] ) + "&"; } } return window.location.protocol + "//" + window.location.host + window.location.pathname + querystring.slice( 0, -1 ); }, extend: extend, id: id, addEvent: addEvent, addClass: addClass, hasClass: hasClass, removeClass: removeClass // load, equiv, jsDump, diff: Attached later }); /** * @deprecated: Created for backwards compatibility with test runner that set the hook function * into QUnit.{hook}, instead of invoking it and passing the hook function. * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. * Doing this allows us to tell if the following methods have been overwritten on the actual * QUnit object. */ extend( QUnit.constructor.prototype, { // Logging callbacks; all receive a single argument with the listed properties // run test/logs.html for any related changes begin: registerLoggingCallback( "begin" ), // done: { failed, passed, total, runtime } done: registerLoggingCallback( "done" ), // log: { result, actual, expected, message } log: registerLoggingCallback( "log" ), // testStart: { name } testStart: registerLoggingCallback( "testStart" ), // testDone: { name, failed, passed, total, runtime } testDone: registerLoggingCallback( "testDone" ), // moduleStart: { name } moduleStart: registerLoggingCallback( "moduleStart" ), // moduleDone: { name, failed, passed, total } moduleDone: registerLoggingCallback( "moduleDone" ) }); if ( !defined.document || document.readyState === "complete" ) { config.autorun = true; } QUnit.load = function() { runLoggingCallbacks( "begin", QUnit, {} ); // Initialize the config, saving the execution queue var banner, filter, i, j, label, len, main, ol, toolbar, val, selection, urlConfigContainer, moduleFilter, userAgent, numModules = 0, moduleNames = [], moduleFilterHtml = "", urlConfigHtml = "", oldconfig = extend( {}, config ); QUnit.init(); extend(config, oldconfig); config.blocking = false; len = config.urlConfig.length; for ( i = 0; i < len; i++ ) { val = config.urlConfig[i]; if ( typeof val === "string" ) { val = { id: val, label: val }; } config[ val.id ] = QUnit.urlParams[ val.id ]; if ( !val.value || typeof val.value === "string" ) { urlConfigHtml += ""; } else { urlConfigHtml += ""; } } for ( i in config.modules ) { if ( config.modules.hasOwnProperty( i ) ) { moduleNames.push(i); } } numModules = moduleNames.length; moduleNames.sort( function( a, b ) { return a.localeCompare( b ); }); moduleFilterHtml += ""; // `userAgent` initialized at top of scope userAgent = id( "qunit-userAgent" ); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } // `banner` initialized at top of scope banner = id( "qunit-header" ); if ( banner ) { banner.innerHTML = "" + banner.innerHTML + " "; } // `toolbar` initialized at top of scope toolbar = id( "qunit-testrunner-toolbar" ); if ( toolbar ) { // `filter` initialized at top of scope filter = document.createElement( "input" ); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; addEvent( filter, "click", function() { var tmp, ol = id( "qunit-tests" ); if ( filter.checked ) { ol.className = ol.className + " hidepass"; } else { tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; ol.className = tmp.replace( / hidepass /, " " ); } if ( defined.sessionStorage ) { if (filter.checked) { sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); } else { sessionStorage.removeItem( "qunit-filter-passed-tests" ); } } }); if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { filter.checked = true; // `ol` initialized at top of scope ol = id( "qunit-tests" ); ol.className = ol.className + " hidepass"; } toolbar.appendChild( filter ); // `label` initialized at top of scope label = document.createElement( "label" ); label.setAttribute( "for", "qunit-filter-pass" ); label.setAttribute( "title", "Only show tests and assertions that fail. Stored in sessionStorage." ); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); urlConfigContainer = document.createElement("span"); urlConfigContainer.innerHTML = urlConfigHtml; // For oldIE support: // * Add handlers to the individual elements instead of the container // * Use "click" instead of "change" for checkboxes // * Fallback from event.target to event.srcElement addEvents( urlConfigContainer.getElementsByTagName("input"), "click", function( event ) { var params = {}, target = event.target || event.srcElement; params[ target.name ] = target.checked ? target.defaultValue || true : undefined; window.location = QUnit.url( params ); }); addEvents( urlConfigContainer.getElementsByTagName("select"), "change", function( event ) { var params = {}, target = event.target || event.srcElement; params[ target.name ] = target.options[ target.selectedIndex ].value || undefined; window.location = QUnit.url( params ); }); toolbar.appendChild( urlConfigContainer ); if (numModules > 1) { moduleFilter = document.createElement( "span" ); moduleFilter.setAttribute( "id", "qunit-modulefilter-container" ); moduleFilter.innerHTML = moduleFilterHtml; addEvent( moduleFilter.lastChild, "change", function() { var selectBox = moduleFilter.getElementsByTagName("select")[0], selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value); window.location = QUnit.url({ module: ( selectedModule === "" ) ? undefined : selectedModule, // Remove any existing filters filter: undefined, testNumber: undefined }); }); toolbar.appendChild(moduleFilter); } } // `main` initialized at top of scope main = id( "qunit-fixture" ); if ( main ) { config.fixture = main.innerHTML; } if ( config.autostart ) { QUnit.start(); } }; if ( defined.document ) { addEvent( window, "load", QUnit.load ); } // `onErrorFnPrev` initialized at top of scope // Preserve other handlers onErrorFnPrev = window.onerror; // Cover uncaught exceptions // Returning true will suppress the default browser handler, // returning false will let it run. window.onerror = function ( error, filePath, linerNr ) { var ret = false; if ( onErrorFnPrev ) { ret = onErrorFnPrev( error, filePath, linerNr ); } // Treat return value as window.onerror itself does, // Only do our handling if not suppressed. if ( ret !== true ) { if ( QUnit.config.current ) { if ( QUnit.config.current.ignoreGlobalErrors ) { return true; } QUnit.pushFailure( error, filePath + ":" + linerNr ); } else { QUnit.test( "global failure", extend( function() { QUnit.pushFailure( error, filePath + ":" + linerNr ); }, { validTest: validTest } ) ); } return false; } return ret; }; function done() { config.autorun = true; // Log the last module results if ( config.previousModule ) { runLoggingCallbacks( "moduleDone", QUnit, { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all }); } delete config.previousModule; var i, key, banner = id( "qunit-banner" ), tests = id( "qunit-tests" ), runtime = +new Date() - config.started, passed = config.stats.all - config.stats.bad, html = [ "Tests completed in ", runtime, " milliseconds.
    ", "", passed, " assertions of ", config.stats.all, " passed, ", config.stats.bad, " failed." ].join( "" ); if ( banner ) { banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" ); } if ( tests ) { id( "qunit-testresult" ).innerHTML = html; } if ( config.altertitle && defined.document && document.title ) { // show ✖ for good, ✔ for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document.title = [ ( config.stats.bad ? "\u2716" : "\u2714" ), document.title.replace( /^[\u2714\u2716] /i, "" ) ].join( " " ); } // clear own sessionStorage items if all tests passed if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { // `key` & `i` initialized at top of scope for ( i = 0; i < sessionStorage.length; i++ ) { key = sessionStorage.key( i++ ); if ( key.indexOf( "qunit-test-" ) === 0 ) { sessionStorage.removeItem( key ); } } } // scroll back to top to show results if ( config.scrolltop && window.scrollTo ) { window.scrollTo(0, 0); } runLoggingCallbacks( "done", QUnit, { failed: config.stats.bad, passed: passed, total: config.stats.all, runtime: runtime }); } /** @return Boolean: true if this test should be ran */ function validTest( test ) { var include, filter = config.filter && config.filter.toLowerCase(), module = config.module && config.module.toLowerCase(), fullName = ( test.module + ": " + test.testName ).toLowerCase(); // Internally-generated tests are always valid if ( test.callback && test.callback.validTest === validTest ) { delete test.callback.validTest; return true; } if ( config.testNumber.length > 0 ) { if ( inArray( test.testNumber, config.testNumber ) < 0 ) { return false; } } if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { return false; } if ( !filter ) { return true; } include = filter.charAt( 0 ) !== "!"; if ( !include ) { filter = filter.slice( 1 ); } // If the filter matches, we need to honour include if ( fullName.indexOf( filter ) !== -1 ) { return include; } // Otherwise, do the opposite return !include; } // so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions) // Later Safari and IE10 are supposed to support error.stack as well // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack function extractStacktrace( e, offset ) { offset = offset === undefined ? 3 : offset; var stack, include, i; if ( e.stacktrace ) { // Opera return e.stacktrace.split( "\n" )[ offset + 3 ]; } else if ( e.stack ) { // Firefox, Chrome stack = e.stack.split( "\n" ); if (/^error$/i.test( stack[0] ) ) { stack.shift(); } if ( fileName ) { include = []; for ( i = offset; i < stack.length; i++ ) { if ( stack[ i ].indexOf( fileName ) !== -1 ) { break; } include.push( stack[ i ] ); } if ( include.length ) { return include.join( "\n" ); } } return stack[ offset ]; } else if ( e.sourceURL ) { // Safari, PhantomJS // hopefully one day Safari provides actual stacktraces // exclude useless self-reference for generated Error objects if ( /qunit.js$/.test( e.sourceURL ) ) { return; } // for actual exceptions, this is useful return e.sourceURL + ":" + e.line; } } function sourceFromStacktrace( offset ) { try { throw new Error(); } catch ( e ) { return extractStacktrace( e, offset ); } } /** * Escape text for attribute or text content. */ function escapeText( s ) { if ( !s ) { return ""; } s = s + ""; // Both single quotes and double quotes (for attributes) return s.replace( /['"<>&]/g, function( s ) { switch( s ) { case "'": return "'"; case "\"": return """; case "<": return "<"; case ">": return ">"; case "&": return "&"; } }); } function synchronize( callback, last ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process( last ); } } function process( last ) { function next() { process( last ); } var start = new Date().getTime(); config.depth = config.depth ? config.depth + 1 : 1; while ( config.queue.length && !config.blocking ) { if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { config.queue.shift()(); } else { setTimeout( next, 13 ); break; } } config.depth--; if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { if ( hasOwn.call( window, key ) ) { // in Opera sometimes DOM element ids show up here, ignore them if ( /^qunit-test-output/.test( key ) ) { continue; } config.pollution.push( key ); } } } } function checkPollution() { var newGlobals, deletedGlobals, old = config.pollution; saveGlobal(); newGlobals = diff( config.pollution, old ); if ( newGlobals.length > 0 ) { QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); } deletedGlobals = diff( old, config.pollution ); if ( deletedGlobals.length > 0 ) { QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var i, j, result = a.slice(); for ( i = 0; i < result.length; i++ ) { for ( j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice( i, 1 ); i--; break; } } } return result; } function extend( a, b ) { for ( var prop in b ) { if ( hasOwn.call( b, prop ) ) { // Avoid "Member not found" error in IE8 caused by messing with window.constructor if ( !( prop === "constructor" && a === window ) ) { if ( b[ prop ] === undefined ) { delete a[ prop ]; } else { a[ prop ] = b[ prop ]; } } } } return a; } /** * @param {HTMLElement} elem * @param {string} type * @param {Function} fn */ function addEvent( elem, type, fn ) { if ( elem.addEventListener ) { // Standards-based browsers elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { // support: IE <9 elem.attachEvent( "on" + type, fn ); } else { // Caller must ensure support for event listeners is present throw new Error( "addEvent() was called in a context without event listener support" ); } } /** * @param {Array|NodeList} elems * @param {string} type * @param {Function} fn */ function addEvents( elems, type, fn ) { var i = elems.length; while ( i-- ) { addEvent( elems[i], type, fn ); } } function hasClass( elem, name ) { return (" " + elem.className + " ").indexOf(" " + name + " ") > -1; } function addClass( elem, name ) { if ( !hasClass( elem, name ) ) { elem.className += (elem.className ? " " : "") + name; } } function removeClass( elem, name ) { var set = " " + elem.className + " "; // Class name may appear multiple times while ( set.indexOf(" " + name + " ") > -1 ) { set = set.replace(" " + name + " " , " "); } // If possible, trim it for prettiness, but not necessarily elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, ""); } function id( name ) { return defined.document && document.getElementById && document.getElementById( name ); } function registerLoggingCallback( key ) { return function( callback ) { config[key].push( callback ); }; } // Supports deprecated method of completely overwriting logging callbacks function runLoggingCallbacks( key, scope, args ) { var i, callbacks; if ( QUnit.hasOwnProperty( key ) ) { QUnit[ key ].call(scope, args ); } else { callbacks = config[ key ]; for ( i = 0; i < callbacks.length; i++ ) { callbacks[ i ].call( scope, args ); } } } // from jquery.js function inArray( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; } function Test( settings ) { extend( this, settings ); this.assertions = []; this.testNumber = ++Test.count; } Test.count = 0; Test.prototype = { init: function() { var a, b, li, tests = id( "qunit-tests" ); if ( tests ) { b = document.createElement( "strong" ); b.innerHTML = this.nameHtml; // `a` initialized at top of scope a = document.createElement( "a" ); a.innerHTML = "Rerun"; a.href = QUnit.url({ testNumber: this.testNumber }); li = document.createElement( "li" ); li.appendChild( b ); li.appendChild( a ); li.className = "running"; li.id = this.id = "qunit-test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if ( // Emit moduleStart when we're switching from one module to another this.module !== config.previousModule || // They could be equal (both undefined) but if the previousModule property doesn't // yet exist it means this is the first test in a suite that isn't wrapped in a // module, in which case we'll just emit a moduleStart event for 'undefined'. // Without this, reporters can get testStart before moduleStart which is a problem. !hasOwn.call( config, "previousModule" ) ) { if ( hasOwn.call( config, "previousModule" ) ) { runLoggingCallbacks( "moduleDone", QUnit, { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all }); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; runLoggingCallbacks( "moduleStart", QUnit, { name: this.module }); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment ); this.started = +new Date(); runLoggingCallbacks( "testStart", QUnit, { name: this.testName, module: this.module }); /*jshint camelcase:false */ /** * Expose the current test environment. * * @deprecated since 1.12.0: Use QUnit.config.current.testEnvironment instead. */ QUnit.current_testEnvironment = this.testEnvironment; /*jshint camelcase:true */ if ( !config.pollution ) { saveGlobal(); } if ( config.notrycatch ) { this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert ); return; } try { this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert ); } catch( e ) { QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); } }, run: function() { config.current = this; var running = id( "qunit-testresult" ); if ( running ) { running.innerHTML = "Running:
    " + this.nameHtml; } if ( this.async ) { QUnit.stop(); } this.callbackStarted = +new Date(); if ( config.notrycatch ) { this.callback.call( this.testEnvironment, QUnit.assert ); this.callbackRuntime = +new Date() - this.callbackStarted; return; } try { this.callback.call( this.testEnvironment, QUnit.assert ); this.callbackRuntime = +new Date() - this.callbackStarted; } catch( e ) { this.callbackRuntime = +new Date() - this.callbackStarted; QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { QUnit.start(); } } }, teardown: function() { config.current = this; if ( config.notrycatch ) { if ( typeof this.callbackRuntime === "undefined" ) { this.callbackRuntime = +new Date() - this.callbackStarted; } this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert ); return; } else { try { this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert ); } catch( e ) { QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); } } checkPollution(); }, finish: function() { config.current = this; if ( config.requireExpects && this.expected === null ) { QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); } else if ( this.expected !== null && this.expected !== this.assertions.length ) { QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); } else if ( this.expected === null && !this.assertions.length ) { QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); } var i, assertion, a, b, time, li, ol, test = this, good = 0, bad = 0, tests = id( "qunit-tests" ); this.runtime = +new Date() - this.started; config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { ol = document.createElement( "ol" ); ol.className = "qunit-assert-list"; for ( i = 0; i < this.assertions.length; i++ ) { assertion = this.assertions[i]; li = document.createElement( "li" ); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" ); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible if ( QUnit.config.reorder && defined.sessionStorage ) { if ( bad ) { sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad ); } else { sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName ); } } if ( bad === 0 ) { addClass( ol, "qunit-collapsed" ); } // `b` initialized at top of scope b = document.createElement( "strong" ); b.innerHTML = this.nameHtml + " (" + bad + ", " + good + ", " + this.assertions.length + ")"; addEvent(b, "click", function() { var next = b.parentNode.lastChild, collapsed = hasClass( next, "qunit-collapsed" ); ( collapsed ? removeClass : addClass )( next, "qunit-collapsed" ); }); addEvent(b, "dblclick", function( e ) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() === "span" || target.nodeName.toLowerCase() === "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location = QUnit.url({ testNumber: test.testNumber }); } }); // `time` initialized at top of scope time = document.createElement( "span" ); time.className = "runtime"; time.innerHTML = this.runtime + " ms"; // `li` initialized at top of scope li = id( this.id ); li.className = bad ? "fail" : "pass"; li.removeChild( li.firstChild ); a = li.firstChild; li.appendChild( b ); li.appendChild( a ); li.appendChild( time ); li.appendChild( ol ); } else { for ( i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } runLoggingCallbacks( "testDone", QUnit, { name: this.testName, module: this.module, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length, runtime: this.runtime, // DEPRECATED: this property will be removed in 2.0.0, use runtime instead duration: this.runtime }); QUnit.reset(); config.current = undefined; }, queue: function() { var bad, test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // `bad` initialized at top of scope // defer when previous test run passed, if storage is available bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); if ( bad ) { run(); } else { synchronize( run, true ); } } }; // `assert` initialized at top of scope // Assert helpers // All of these must either call QUnit.push() or manually do: // - runLoggingCallbacks( "log", .. ); // - config.current.assertions.push({ .. }); assert = QUnit.assert = { /** * Asserts rough true-ish result. * @name ok * @function * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function( result, msg ) { if ( !config.current ) { throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) ); } result = !!result; msg = msg || ( result ? "okay" : "failed" ); var source, details = { module: config.current.module, name: config.current.testName, result: result, message: msg }; msg = "" + escapeText( msg ) + ""; if ( !result ) { source = sourceFromStacktrace( 2 ); if ( source ) { details.source = source; msg += "
    Source:
    " +
    					escapeText( source ) +
    					"
    "; } } runLoggingCallbacks( "log", QUnit, details ); config.current.assertions.push({ result: result, message: msg }); }, /** * Assert that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * @name equal * @function * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); */ equal: function( actual, expected, message ) { /*jshint eqeqeq:false */ QUnit.push( expected == actual, actual, expected, message ); }, /** * @name notEqual * @function */ notEqual: function( actual, expected, message ) { /*jshint eqeqeq:false */ QUnit.push( expected != actual, actual, expected, message ); }, /** * @name propEqual * @function */ propEqual: function( actual, expected, message ) { actual = objectValues(actual); expected = objectValues(expected); QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); }, /** * @name notPropEqual * @function */ notPropEqual: function( actual, expected, message ) { actual = objectValues(actual); expected = objectValues(expected); QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); }, /** * @name deepEqual * @function */ deepEqual: function( actual, expected, message ) { QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); }, /** * @name notDeepEqual * @function */ notDeepEqual: function( actual, expected, message ) { QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); }, /** * @name strictEqual * @function */ strictEqual: function( actual, expected, message ) { QUnit.push( expected === actual, actual, expected, message ); }, /** * @name notStrictEqual * @function */ notStrictEqual: function( actual, expected, message ) { QUnit.push( expected !== actual, actual, expected, message ); }, "throws": function( block, expected, message ) { var actual, expectedOutput = expected, ok = false; // 'expected' is optional if ( !message && typeof expected === "string" ) { message = expected; expected = null; } config.current.ignoreGlobalErrors = true; try { block.call( config.current.testEnvironment ); } catch (e) { actual = e; } config.current.ignoreGlobalErrors = false; if ( actual ) { // we don't want to validate thrown error if ( !expected ) { ok = true; expectedOutput = null; // expected is an Error object } else if ( expected instanceof Error ) { ok = actual instanceof Error && actual.name === expected.name && actual.message === expected.message; // expected is a regexp } else if ( QUnit.objectType( expected ) === "regexp" ) { ok = expected.test( errorString( actual ) ); // expected is a string } else if ( QUnit.objectType( expected ) === "string" ) { ok = expected === errorString( actual ); // expected is a constructor } else if ( actual instanceof expected ) { ok = true; // expected is a validation function which returns true is validation passed } else if ( expected.call( {}, actual ) === true ) { expectedOutput = null; ok = true; } QUnit.push( ok, actual, expectedOutput, message ); } else { QUnit.pushFailure( message, null, "No exception was thrown." ); } } }; /** * @deprecated since 1.8.0 * Kept assertion helpers in root for backwards compatibility. */ extend( QUnit.constructor.prototype, assert ); /** * @deprecated since 1.9.0 * Kept to avoid TypeErrors for undefined methods. */ QUnit.constructor.prototype.raises = function() { QUnit.push( false, false, false, "QUnit.raises has been deprecated since 2012 (fad3c1ea), use QUnit.throws instead" ); }; /** * @deprecated since 1.0.0, replaced with error pushes since 1.3.0 * Kept to avoid TypeErrors for undefined methods. */ QUnit.constructor.prototype.equals = function() { QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" ); }; QUnit.constructor.prototype.same = function() { QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" ); }; // Test for equality any JavaScript type. // Author: Philippe Rathé QUnit.equiv = (function() { // Call the o related callback with the given arguments. function bindCallbacks( o, callbacks, args ) { var prop = QUnit.objectType( o ); if ( prop ) { if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { return callbacks[ prop ].apply( callbacks, args ); } else { return callbacks[ prop ]; // or undefined } } } // the real equiv function var innerEquiv, // stack to decide between skip/abort functions callers = [], // stack to avoiding loops from circular referencing parents = [], parentsB = [], getProto = Object.getPrototypeOf || function ( obj ) { /*jshint camelcase:false */ return obj.__proto__; }, callbacks = (function () { // for string, boolean, number and null function useStrictEquality( b, a ) { /*jshint eqeqeq:false */ if ( b instanceof a.constructor || a instanceof b.constructor ) { // to catch short annotation VS 'new' annotation of a // declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function( b ) { return isNaN( b ); }, "date": function( b, a ) { return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function( b, a ) { return QUnit.objectType( b ) === "regexp" && // the regex itself a.source === b.source && // and its modifiers a.global === b.global && // (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function() { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function( b, a ) { var i, j, len, loop, aCircular, bCircular; // b could be an object literal here if ( QUnit.objectType( b ) !== "array" ) { return false; } len = a.length; if ( len !== b.length ) { // safe and faster return false; } // track reference to avoid circular references parents.push( a ); parentsB.push( b ); for ( i = 0; i < len; i++ ) { loop = false; for ( j = 0; j < parents.length; j++ ) { aCircular = parents[j] === a[i]; bCircular = parentsB[j] === b[i]; if ( aCircular || bCircular ) { if ( a[i] === b[i] || aCircular && bCircular ) { loop = true; } else { parents.pop(); parentsB.pop(); return false; } } } if ( !loop && !innerEquiv(a[i], b[i]) ) { parents.pop(); parentsB.pop(); return false; } } parents.pop(); parentsB.pop(); return true; }, "object": function( b, a ) { /*jshint forin:false */ var i, j, loop, aCircular, bCircular, // Default to true eq = true, aProperties = [], bProperties = []; // comparing constructors is more strict than using // instanceof if ( a.constructor !== b.constructor ) { // Allow objects with no prototype to be equivalent to // objects with Object as their constructor. if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) || ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) { return false; } } // stack constructor before traversing properties callers.push( a.constructor ); // track reference to avoid circular references parents.push( a ); parentsB.push( b ); // be strict: don't ensure hasOwnProperty and go deep for ( i in a ) { loop = false; for ( j = 0; j < parents.length; j++ ) { aCircular = parents[j] === a[i]; bCircular = parentsB[j] === b[i]; if ( aCircular || bCircular ) { if ( a[i] === b[i] || aCircular && bCircular ) { loop = true; } else { eq = false; break; } } } aProperties.push(i); if ( !loop && !innerEquiv(a[i], b[i]) ) { eq = false; break; } } parents.pop(); parentsB.pop(); callers.pop(); // unstack, we are done for ( i in b ) { bProperties.push( i ); // collect b's properties } // Ensures identical properties name return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); } }; }()); innerEquiv = function() { // can take multiple arguments var args = [].slice.apply( arguments ); if ( args.length < 2 ) { return true; // end transition } return (function( a, b ) { if ( a === b ) { return true; // catch the most you can } else if ( a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b) ) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [ b, a ]); } // apply transition with (1..n) arguments }( args[0], args[1] ) && innerEquiv.apply( this, args.splice(1, args.length - 1 )) ); }; return innerEquiv; }()); /** * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | * http://flesler.blogspot.com Licensed under BSD * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 * * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\""; } function literal( o ) { return o + ""; } function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) { arr = arr.join( "," + s + inner ); } if ( !arr ) { return pre + post; } return [ pre, inner + arr, base + post ].join(s); } function array( arr, stack ) { var i = arr.length, ret = new Array(i); this.up(); while ( i-- ) { ret[i] = this.parse( arr[i] , undefined , stack); } this.down(); return join( "[", ret, "]" ); } var reName = /^function (\w+)/, jsDump = { // type is used mostly internally, you can fix a (custom)type in advance parse: function( obj, type, stack ) { stack = stack || [ ]; var inStack, res, parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; inStack = inArray( obj, stack ); if ( inStack !== -1 ) { return "recursion(" + (inStack - stack.length) + ")"; } if ( type === "function" ) { stack.push( obj ); res = parser.call( this, obj, stack ); stack.pop(); return res; } return ( type === "string" ) ? parser : this.parsers.error; }, typeOf: function( obj ) { var type; if ( obj === null ) { type = "null"; } else if ( typeof obj === "undefined" ) { type = "undefined"; } else if ( QUnit.is( "regexp", obj) ) { type = "regexp"; } else if ( QUnit.is( "date", obj) ) { type = "date"; } else if ( QUnit.is( "function", obj) ) { type = "function"; } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { type = "window"; } else if ( obj.nodeType === 9 ) { type = "document"; } else if ( obj.nodeType ) { type = "node"; } else if ( // native arrays toString.call( obj ) === "[object Array]" || // NodeList objects ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) ) { type = "array"; } else if ( obj.constructor === Error.prototype.constructor ) { type = "error"; } else { type = typeof obj; } return type; }, separator: function() { return this.multiline ? this.HTML ? "
    " : "\n" : this.HTML ? " " : " "; }, // extra can be a number, shortcut for increasing-calling-decreasing indent: function( extra ) { if ( !this.multiline ) { return ""; } var chr = this.indentChar; if ( this.HTML ) { chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); } return new Array( this.depth + ( extra || 0 ) ).join(chr); }, up: function( a ) { this.depth += a || 1; }, down: function( a ) { this.depth -= a || 1; }, setParser: function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote: quote, literal: literal, join: join, // depth: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers: { window: "[Window]", document: "[Document]", error: function(error) { return "Error(\"" + error.message + "\")"; }, unknown: "[Unknown]", "null": "null", "undefined": "undefined", "function": function( fn ) { var ret = "function", // functions never have name in IE name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1]; if ( name ) { ret += " " + name; } ret += "( "; ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" ); return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" ); }, array: array, nodelist: array, "arguments": array, object: function( map, stack ) { /*jshint forin:false */ var ret = [ ], keys, key, val, i; QUnit.jsDump.up(); keys = []; for ( key in map ) { keys.push( key ); } keys.sort(); for ( i = 0; i < keys.length; i++ ) { key = keys[ i ]; val = map[ key ]; ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) ); } QUnit.jsDump.down(); return join( "{", ret, "}" ); }, node: function( node ) { var len, i, val, open = QUnit.jsDump.HTML ? "<" : "<", close = QUnit.jsDump.HTML ? ">" : ">", tag = node.nodeName.toLowerCase(), ret = open + tag, attrs = node.attributes; if ( attrs ) { for ( i = 0, len = attrs.length; i < len; i++ ) { val = attrs[i].nodeValue; // IE6 includes all attributes in .attributes, even ones not explicitly set. // Those have values like undefined, null, 0, false, "" or "inherit". if ( val && val !== "inherit" ) { ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" ); } } } ret += close; // Show content of TextNode or CDATASection if ( node.nodeType === 3 || node.nodeType === 4 ) { ret += node.nodeValue; } return ret + open + "/" + tag + close; }, // function calls it internally, it's the arguments part of the function functionArgs: function( fn ) { var args, l = fn.length; if ( !l ) { return ""; } args = new Array(l); while ( l-- ) { // 97 is 'a' args[l] = String.fromCharCode(97+l); } return " " + args.join( ", " ) + " "; }, // object calls it internally, the key part of an item in a map key: quote, // function calls it internally, it's the content of the function functionCode: "[code]", // node calls it internally, it's an html attribute value attribute: quote, string: quote, date: quote, regexp: literal, number: literal, "boolean": literal }, // if true, entities are escaped ( <, >, \t, space and \n ) HTML: false, // indentation unit indentChar: " ", // if true, items in a collection, are separated by a \n, else just a space. multiline: true }; return jsDump; }()); /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over" */ QUnit.diff = (function() { /*jshint eqeqeq:false, eqnull:true */ function diff( o, n ) { var i, ns = {}, os = {}; for ( i = 0; i < n.length; i++ ) { if ( !hasOwn.call( ns, n[i] ) ) { ns[ n[i] ] = { rows: [], o: null }; } ns[ n[i] ].rows.push( i ); } for ( i = 0; i < o.length; i++ ) { if ( !hasOwn.call( os, o[i] ) ) { os[ o[i] ] = { rows: [], n: null }; } os[ o[i] ].rows.push( i ); } for ( i in ns ) { if ( hasOwn.call( ns, i ) ) { if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) { n[ ns[i].rows[0] ] = { text: n[ ns[i].rows[0] ], row: os[i].rows[0] }; o[ os[i].rows[0] ] = { text: o[ os[i].rows[0] ], row: ns[i].rows[0] }; } } } for ( i = 0; i < n.length - 1; i++ ) { if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null && n[ i + 1 ] == o[ n[i].row + 1 ] ) { n[ i + 1 ] = { text: n[ i + 1 ], row: n[i].row + 1 }; o[ n[i].row + 1 ] = { text: o[ n[i].row + 1 ], row: i + 1 }; } } for ( i = n.length - 1; i > 0; i-- ) { if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null && n[ i - 1 ] == o[ n[i].row - 1 ]) { n[ i - 1 ] = { text: n[ i - 1 ], row: n[i].row - 1 }; o[ n[i].row - 1 ] = { text: o[ n[i].row - 1 ], row: i - 1 }; } } return { o: o, n: n }; } return function( o, n ) { o = o.replace( /\s+$/, "" ); n = n.replace( /\s+$/, "" ); var i, pre, str = "", out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ), oSpace = o.match(/\s+/g), nSpace = n.match(/\s+/g); if ( oSpace == null ) { oSpace = [ " " ]; } else { oSpace.push( " " ); } if ( nSpace == null ) { nSpace = [ " " ]; } else { nSpace.push( " " ); } if ( out.n.length === 0 ) { for ( i = 0; i < out.o.length; i++ ) { str += "" + out.o[i] + oSpace[i] + ""; } } else { if ( out.n[0].text == null ) { for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) { str += "" + out.o[n] + oSpace[n] + ""; } } for ( i = 0; i < out.n.length; i++ ) { if (out.n[i].text == null) { str += "" + out.n[i] + nSpace[i] + ""; } else { // `pre` initialized at top of scope pre = ""; for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) { pre += "" + out.o[n] + oSpace[n] + ""; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; }()); // For browser, export only select globals if ( typeof window !== "undefined" ) { extend( window, QUnit.constructor.prototype ); window.QUnit = QUnit; } // For CommonJS environments, export everything if ( typeof module !== "undefined" && module.exports ) { module.exports = QUnit; } // Get a reference to the global object, like window in browsers }( (function() { return this; })() )); ================================================ FILE: test/index.html ================================================ WebUploader test units.
    ================================================ FILE: test/require.js ================================================ /* RequireJS 2.1.10 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. Available via the MIT or new BSD license. see: http://github.com/jrburke/requirejs for details */ var requirejs,require,define; (function(ca){function G(b){return"[object Function]"===N.call(b)}function H(b){return"[object Array]"===N.call(b)}function v(b,c){if(b){var d;for(d=0;dthis.depCount&&!this.defined){if(G(c)){if(this.events.error&&this.map.isDefine||h.onError!==da)try{f=i.execCb(b,c,e,f)}catch(d){a=d}else f=i.execCb(b,c,e,f);this.map.isDefine&&void 0===f&&((e=this.module)?f=e.exports:this.usingExports&& (f=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else f=c;this.exports=f;if(this.map.isDefine&&!this.ignore&&(p[b]=f,h.onResourceLoad))h.onResourceLoad(i,this.map,this.depMaps);y(b);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a= this.map,b=a.id,d=m(a.prefix);this.depMaps.push(d);r(d,"defined",t(this,function(f){var d,g;g=j(ba,this.map.id);var J=this.map.name,u=this.map.parentMap?this.map.parentMap.name:null,p=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(J=f.normalize(J,function(a){return c(a,u,!0)})||""),f=m(a.prefix+"!"+J,this.map.parentMap),r(f,"defined",t(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),g=j(k,f.id)){this.depMaps.push(f); if(this.events.error)g.on("error",t(this,function(a){this.emit("error",a)}));g.enable()}}else g?(this.map.url=i.nameToUrl(g),this.load()):(d=t(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),d.error=t(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];B(k,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),d.fromText=t(this,function(f,c){var g=a.name,J=m(g),k=O;c&&(f=c);k&&(O=!1);q(J);s(l.config,b)&&(l.config[g]=l.config[b]);try{h.exec(f)}catch(j){return w(C("fromtexteval", "fromText eval for "+b+" failed: "+j,j,[b]))}k&&(O=!0);this.depMaps.push(J);i.completeLoad(g);p([g],d)}),f.load(a.name,p,d,l))}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){W[this.map.id]=this;this.enabling=this.enabled=!0;v(this.depMaps,t(this,function(a,b){var c,f;if("string"===typeof a){a=m(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=j(K,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;r(a,"defined",t(this,function(a){this.defineDep(b, a);this.check()}));this.errback&&r(a,"error",t(this,this.errback))}c=a.id;f=k[c];!s(K,c)&&(f&&!f.enabled)&&i.enable(a,this)}));B(this.pluginMaps,t(this,function(a){var b=j(k,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){v(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:l,contextName:b,registry:k,defined:p,urlFetched:T,defQueue:A,Module:$,makeModuleMap:m, nextTick:h.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=l.shim,c={paths:!0,bundles:!0,config:!0,map:!0};B(a,function(a,b){c[b]?(l[b]||(l[b]={}),V(l[b],a,!0,!0)):l[b]=a});a.bundles&&B(a.bundles,function(a,b){v(a,function(a){a!==b&&(ba[a]=b)})});a.shim&&(B(a.shim,function(a,c){H(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);b[c]=a}),l.shim=b);a.packages&&v(a.packages,function(a){var b, a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(l.paths[b]=a.location);l.pkgs[b]=a.name+"/"+(a.main||"main").replace(ja,"").replace(R,"")});B(k,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=m(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ca,arguments));return b||a.exports&&ea(a.exports)}},makeRequire:function(a,e){function g(f,c,d){var j,l;e.enableBuildCallback&&(c&&G(c))&&(c.__requireJsBuild= !0);if("string"===typeof f){if(G(c))return w(C("requireargs","Invalid require call"),d);if(a&&s(K,f))return K[f](k[a.id]);if(h.get)return h.get(i,f,a,g);j=m(f,a,!1,!0);j=j.id;return!s(p,j)?w(C("notloaded",'Module name "'+j+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):p[j]}M();i.nextTick(function(){M();l=q(m(null,a));l.skipMap=e.skipMap;l.init(f,c,d,{enabled:!0});D()});return g}e=e||{};V(g,{isBrowser:z,toUrl:function(b){var e,d=b.lastIndexOf("."),g=b.split("/")[0];if(-1!== d&&(!("."===g||".."===g)||1g.attachEvent.toString().indexOf("[native code"))&&!Z?(O=!0,g.attachEvent("onreadystatechange",b.onScriptLoad)): (g.addEventListener("load",b.onScriptLoad,!1),g.addEventListener("error",b.onScriptError,!1)),g.src=d,M=g,D?y.insertBefore(g,D):y.appendChild(g),M=null,g;if(fa)try{importScripts(d),b.completeLoad(c)}catch(j){b.onError(C("importscripts","importScripts failed for "+c+" at "+d,j,[c]))}};z&&!r.skipDataMain&&U(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(L=b.getAttribute("data-main"))return q=L,r.baseUrl||(E=q.split("/"),q=E.pop(),Q=E.length?E.join("/")+"/":"./",r.baseUrl= Q),q=q.replace(R,""),h.jsExtRegExp.test(q)&&(q=L),r.deps=r.deps?r.deps.concat(q):[q],!0});define=function(b,c,d){var g,h;"string"!==typeof b&&(d=c,c=b,b=null);H(c)||(d=c,c=null);!c&&G(d)&&(c=[],d.length&&(d.toString().replace(la,"").replace(ma,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(O){if(!(g=M))P&&"interactive"===P.readyState||U(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return P=b}),g=P;g&&(b|| (b=g.getAttribute("data-requiremodule")),h=F[g.getAttribute("data-requirecontext")])}(h?h.defQueue:S).push([b,c,d])};define.amd={jQuery:!0};h.exec=function(b){return eval(b)};h(r)}})(this); ================================================ FILE: test/units/base.js ================================================ define([ 'webuploader/base' ], function( Base ) { module('Base'); test( 'Test dollar', 1, function() { ok( Base.$, 'ok' ); }); test( 'Test bindFn', 2, function() { var obj = { name: '123' }, fn = function( arg1 ) { ok( this.name, '123', 'The name should be `123`,' ); ok( arg1, '456', 'The value of first arg should be `456`. '); }, proxyFn = Base.bindFn( fn, obj ); proxyFn('456'); }); }); ================================================ FILE: test/units/filepicker.js ================================================ define([ 'webuploader/preset/all' ], function( Base ) { var $fixture; module( 'FilePicker', { setup: function() { $fixture = $('#qunit-fixture'); }, teardown: function() { $fixture.empty(); $fixture = null; } }); test( 'Test initialize', 3, function() { var $btns, $pickers; $fixture.append('
    Button One
    Button Two
    '); $btns = $fixture.find('.btn').each(function( i ) { Base.create({ pick: this }); }); $pickers = $btns.find('.webuploader-pick'); equal( $pickers.length, 2, 'The length should be 2.' ); equal( $pickers.eq(0).text(), 'Button One', 'ok' ); equal( $pickers.eq(1).text(), 'Button Two', 'ok' ); }); });