Skip to content

perf(IDEA): implementation #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
6 changes: 6 additions & 0 deletions .eslintrc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

---
root: true
extends: plugin:coremail/standard
env:
jasmine: true
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,6 @@ dist

# IDEA
.idea

# locked dependencies
package-lock.json
3 changes: 3 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/*
!/dist
!/lib
45 changes: 43 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,46 @@
## IDEA
# IDEA

![npm](https://badges.aleen42.com/src/npm.svg) ![javascript](https://badges.aleen42.com/src/javascript.svg)

The IDEA cypher implementation in JavaScript
It is about the IDEA cypher which is implemented in JavaScript within ~10 KiB. If you want better compatibility, you may need the polyfill version `dist/idea.all.js`, which has shimmed [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) for you.

## Compatibility

- IE6+ (polyfills required for ES7- browsers)
- NodeJS

## Install

```bash
npm install @cormeail/idea
```

## Usage

- without padding:

```js
function paddingToBytes(str) {
typeof str !== 'string' && (str = JSON.stringify(str));

const blockSize = 8;
const srcBytes = encoder.encode(str);
const len = Math.ceil(srcBytes.length / blockSize) * blockSize; // padding with \x00
const src = new Int8Array(len);
src.set(srcBytes);
return src;
}

const IDEA = require('@coremail/idea');
const idea = new IDEA(str2bytes('private key'), /* no padding */-1);
idea.encrypt(paddingToBytes('message')); // => Int8Array[]
```

- with xor padding (ENC3 by default):

```js
const encoder = new TextEncoder();
const IDEA = require('@coremail/idea');
const idea = new IDEA(str2bytes('private key'), /* ENC3 by default */197);
idea.encrypt(encoder.encode('message')); // => Int8Array[]
```
21 changes: 21 additions & 0 deletions build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const webpack = require('webpack');
const config = require('./webpack.config');

// build uncompressed
webpack(config(0)).run(webpackCallback);
// build minimized
webpack(config(1)).run(webpackCallback);

function log(msg) {
log.logged ? console.log('') : (log.logged = true); // add blank line
console.log(msg);
}

function webpackCallback(err, stats) {
if (err) {
process.exit(1);
}
log(stats.toString({
colors : true,
}));
}
68 changes: 68 additions & 0 deletions build/ES3HarmonyPlugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright (c) 2018 Coremail.cn, Ltd. All Rights Reserved.
*/

// see https://github.com/inferpse/es3-harmony-webpack-plugin

const name = 'ES3HarmonyPlugin';

module.exports = class ES3HarmonyPlugin {
apply({hooks, webpack : {javascript : {JavascriptModulesPlugin}}}) {
// noinspection JSUnresolvedVariable
hooks.compilation.tap({name}, compilation => {
// noinspection JSUnresolvedVariable, JSUnresolvedFunction
JavascriptModulesPlugin.getCompilationHooks(compilation).renderMain.tap({name}, replaceSource)
});
}
};

function replaceSource(source) {
source = source['original'] ? source['original']() : source;
if (source['getChildren']) {
source['getChildren']().forEach(replaceSource);
} else {
// pattern: RegExp|substr, replacement: newSubstr|function
replacements.forEach(([pattern, replacement]) => {
if (pattern.test(source.source())) {
source._value = source.source().replace(pattern, replacement);
}
});
}
}

const toReplace = (pattern, replacement) => [
new RegExp(pattern.trim().replace(/.*noinspection.*\n/g, '').replace(/[?.[\]()]/g, '\\$&').replace(/\s+/g, '\\s*'), 'g'),
// trimIndent
replacement.trim().replace(/^ {8}/mg, ''),
];

/* global __webpack_require__ */// eslint-disable-line no-unused-vars
// language=JS
const replacements = [
// @formatter:off
toReplace(`
__webpack_require__.d = function (exports, definition) {
for (var key in definition) {
// noinspection JSUnfilteredForInLoop, JSUnresolvedFunction
if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
// noinspection JSUnfilteredForInLoop
Object.defineProperty(exports, key, { enumerable : true, get : definition[key] });
}
}
};
`, `
__webpack_require__.d = function (exports, definition) {
for (var key in definition) {
// noinspection JSUnfilteredForInLoop, JSUnresolvedFunction
if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
// noinspection JSUnfilteredForInLoop
exports[key] = definition[key](); // patched by ${name}
}
}
};
`),
// @formatter:on

// remove "use strict"
[/(['"])use\s+strict(['"]);?/gm, ''],
];
38 changes: 38 additions & 0 deletions karma.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 Coremail.cn, Ltd. All Rights Reserved.
*/

const webpackConfig = Object.assign({}, require('./webpack.config')(1));
delete webpackConfig.entry;
delete webpackConfig.output;

module.exports = config => {
config.set({
webpack : webpackConfig,
files : ['test/index.js'],
preprocessors : {'test/index.js' : ['webpack', 'sourcemap']},
frameworks : ['jasmine', 'webpack', 'detectBrowsers'],
reporters : ['mocha'],
singleRun : true,
plugins : [
'karma-jasmine',
'karma-mocha-reporter',
'karma-sourcemap-loader',
'karma-webpack',
'karma-chrome-launcher',
'karma-safari-launcher',
'karma-firefox-launcher',
'karma-ie-launcher',
'karma-edge-launcher',
'karma-detect-browsers',
],

client : {jasmine : {random : false}},

detectBrowsers : {
usePhantomJS : false,
// ref: https://github.com/karma-runner/karma-safari-launcher/issues/12
'postDetection' : availableBrowser => availableBrowser.filter(name => name !== 'Safari'),
},
});
};
Loading