Skip to content

Commit

Permalink
💥 ⚡ use wasm, resolves #2
Browse files Browse the repository at this point in the history
BREAKING CHANGE: replace typescript implementation with a web assembly one based on rust-crypto. Removes scryptSync and all scrypt helper functions from lib/scrypt.ts
  • Loading branch information
oplik0 committed Jun 21, 2020
1 parent eba1e3a commit 77993bd
Show file tree
Hide file tree
Showing 7 changed files with 238 additions and 246 deletions.
12 changes: 12 additions & 0 deletions lib/_wasm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "scrypt-wasm"
version = "0.1.1"
authors = ["Kosala Hemachandra <kvhnuke@aol.com>", "oplik0"]

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2"
rust-crypto-wasm = "^0.3"
hex = "^0.3"
22 changes: 22 additions & 0 deletions lib/_wasm/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2018 MyEtherWallet
Copyright (c) 2018 oplik0

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
20 changes: 20 additions & 0 deletions lib/_wasm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# scrypt-wasm

Scrypt crypto library in Web Assembly

# Prerequisities

- This project requires Rust 1.30.0 or later.
- `wasm-pack` is required.
```sh
cargo install wasm-pack
```
### Build

```sh
deno run --allow-read --allow-write --allow-run ./build.ts
```

### acknowledgement

This implementation is a modified version of [this repository](https://github.com/MyEtherWallet/scrypt-wasm/)
47 changes: 47 additions & 0 deletions lib/_wasm/build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// adopted from https://deno.land/std/hash/_wasm/build.ts
import { encode as base64Encode } from "https://deno.land/std/encoding/base64.ts";

// 1. build wasm
async function buildWasm(path: string): Promise<void> {
const cmd = [
"wasm-pack",
"build",
"--target",
"web",
"--release",
"-d",
path,
];
const builder = Deno.run({ cmd });
const status = await builder.status();

if (!status.success) {
console.error(`Failed to build wasm: ${status.code}`);
Deno.exit(1);
}
}

// 2. encode wasm
async function encodeWasm(wasmPath: string): Promise<string> {
const wasm = await Deno.readFile(`${wasmPath}/scrypt_wasm_bg.wasm`);
return base64Encode(wasm);
}

// 3. generate script
async function generate(wasm: string, output: string): Promise<void> {
const initScript = await Deno.readTextFile(`${output}/scrypt_wasm.js`);
const denoHashScript = "/* eslint-disable */\n" +
"//deno-fmt-ignore-file\n" +
`import * as base64 from "https://deno.land/std/encoding/base64.ts";` +
`export const source = base64.decode("${wasm}");` +
initScript;

await Deno.writeFile("wasm.js", new TextEncoder().encode(denoHashScript));
}

const OUTPUT_DIR = "./out";

await buildWasm(OUTPUT_DIR);
const wasm = await encodeWasm(OUTPUT_DIR);
await generate(wasm, OUTPUT_DIR);
17 changes: 17 additions & 0 deletions lib/_wasm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
extern crate wasm_bindgen;
extern crate hex;
extern crate crypto;

use crypto::{ scrypt };
use wasm_bindgen::prelude::*;
use std::iter::repeat;

#[wasm_bindgen]
pub fn scrypt(password: &[u8], salt: &[u8], n: u32, r: u32, p: u32, dklen: usize) -> Vec<u8> {
let log_n = (32 - n.leading_zeros() - 1) as u8;
let mut result: Vec<u8> = repeat(0).take(dklen).collect();
let params = scrypt::ScryptParams::new(log_n,r,p);

scrypt::scrypt(&password, &salt, &params, &mut result);
result
}
116 changes: 116 additions & 0 deletions lib/_wasm/wasm.js

Large diffs are not rendered by default.

250 changes: 4 additions & 246 deletions lib/scrypt.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { pbkdf2 } from "https://denopkg.com/chiefbiiko/pbkdf2/mod.ts";
import init, { source, scrypt as scryptWASM } from "./_wasm/wasm.js";
import { encode as base64encode } from "https://deno.land/std/encoding/base64.ts";
import { encodeToString as hexencode } from "https://deno.land/std/encoding/hex.ts";
const encoder: TextEncoder = new TextEncoder();
const decoder: TextDecoder = new TextDecoder("utf-8");
await init(source);
export type encoding = ("utf-8" | "base64" | "hex");
/**
* Scrypt implementation in TypeScript
* Scrypt implementation using web assembly
* @param {string|Uint8Array} password - string to hash
* @param {string|Uint8Array} salt -
* @param {number} N - CPU/Memory cost parameter. Must be a power of 2 smaller than 2^(128*r/8)
Expand All @@ -27,42 +28,7 @@ export async function scrypt(
dklen = dklen ?? 64;
password = typeof password === "string" ? encoder.encode(password) : password;
salt = typeof salt === "string" ? encoder.encode(salt) : salt;
const blockSize: number = 128 * r;
const hashResult: Uint8Array = pbkdf2(
"sha256",
password,
salt,
undefined,
undefined,
blockSize * p,
1,
) as Uint8Array;
const blockPromises: Array<Promise<Uint8Array>> = [];
for (let i: number = 0; i < p; i++) {
blockPromises.push(
ROMix(
hashResult.subarray(i * blockSize, (i + 1) * blockSize),
N,
blockSize,
),
);
}
const expensiveSalt: Uint8Array = (await Promise.all(blockPromises)).reduce(
(result: Uint8Array, item: Uint8Array, index: number) => {
result.set(item, index * blockSize);
return result;
},
new Uint8Array(p * blockSize),
);
const result: Uint8Array = pbkdf2(
"sha256",
password,
expensiveSalt,
undefined,
undefined,
dklen,
1,
) as Uint8Array;
const result: Uint8Array = scryptWASM(password, salt, N, r, p, dklen);
switch (outputEncoding) {
case "base64":
return base64encode(result);
Expand All @@ -74,211 +40,3 @@ export async function scrypt(
return result;
}
}
/**
* Synchronous Scrypt implementation in TypeScript.
* Might be a little faster than the async one, but benchmark results are mostly similar
* @param {string|Uint8Array} password - string to hash
* @param {string|Uint8Array} salt -
* @param {number} N - CPU/Memory cost parameter. Must be a power of 2 smaller than 2^(128*r/8)
* @param {number} r - block size
* @param {number} p - parallelism factor
* @param {number} [dklen] - length (in bytes) of the output. Defaults to 32.
* @param {encoding} [outputEncoding] - encoding used, defaults to null (Uint8Array)
* @returns {Promise<string|Uint8Array>} - the resulting hash encoded according to outputEncoding
*/
export function scryptSync(
password: (string | Uint8Array),
salt: (string | Uint8Array),
N: number,
r: number,
p: number,
dklen?: number,
outputEncoding?: encoding,
): (Uint8Array | string) {
dklen = dklen ?? 64;
password = typeof password === "string" ? encoder.encode(password) : password;
salt = typeof salt === "string" ? encoder.encode(salt) : salt;
const blockSize: number = 128 * r;
let hashResult: Uint8Array = pbkdf2(
"sha256",
password,
salt,
undefined,
undefined,
blockSize * p,
1,
) as Uint8Array;
let expensiveSalt: Uint8Array = new Uint8Array(p * blockSize);
for (let i: number = 0; i < p; i++) {
expensiveSalt.set(
ROMixSync(
hashResult.subarray(i * blockSize, (i + 1) * blockSize),
N,
blockSize,
),
i * blockSize,
);
}
return pbkdf2(
"sha256",
password,
expensiveSalt,
undefined,
outputEncoding ? outputEncoding : undefined,
dklen,
1,
);
}
/**
* scryptROMix asynchronous implementation based on RFC7914
* @param {Uint8Array} block
* @param {number} iterations - N parameter of scrypt
* @returns {Promise<Uint8Array>} - ROMixed data
*/
export async function ROMix(
block: Uint8Array,
iterations: number,
blockSize?: number,
): Promise<Uint8Array> {
blockSize = blockSize ? blockSize : block.length;
const V: Uint8Array = new Uint8Array(iterations * blockSize);
const temp: Uint32Array = new Uint32Array(16);
for (let i: number = 0; i < iterations; i++) {
V.set(block, i * blockSize);
block = BlockMix(block, temp);
}
let j: number;
for (let i: number = 0; i < iterations; i++) {
j = (integrify(block) & (iterations - 1)) >>> 0;
block = BlockMix(
xor(block, V.subarray(j * blockSize, (j + 1) * blockSize)),
temp,
);
}
return block;
}
/**
* scryptROMix synchronous implementation based on RFC7914
* @param {Uint8Array} block
* @param {number} iterations - N parameter of scrypt
* @returns {Promise<Uint8Array>} - ROMixed data
*/
export function ROMixSync(
block: Uint8Array,
iterations: number,
blockSize?: number,
): Uint8Array {
blockSize = blockSize ? blockSize : block.length;
const V: Uint8Array = new Uint8Array(iterations * blockSize);
for (let i: number = 0; i < iterations; i++) {
V.set(block, i * blockSize);
block = BlockMix(block);
}
let j: number;
for (let i: number = 0; i < iterations; i++) {
j = (integrify(block) & (iterations - 1)) >>> 0;
block = BlockMix(
xor(block, V.subarray(j * blockSize, (j + 1) * blockSize)),
);
}
return block;
}
/**
* turn last 64 bytes of input into a little-endian integer
* @param {Uint8Array} input - Uint8Array that will be "integrified"
* @returns {number} - the resulting integer
*/
function integrify(input: Uint8Array): number {
const dataview = new DataView(input.buffer);
return dataview.getUint32(input.length - 64, true);
}
/**
* scryptBlockMix implementation based on RFC7914
* @param {Uint8Array} block
* @param {Uint32Array} [temp] Temporary array that can be used to avoid creating new arraybuffers
* @returns {Uint8Array}
*/
export function BlockMix(block: Uint8Array, temp?: Uint32Array): Uint8Array {
const r2: number = Math.floor(block.length / 64);
let X: Uint8Array = block.subarray(block.length - 64);
let Y: Uint8Array = block.slice();
temp = temp ?? new Uint32Array(16);
for (let i: number = 0; i < r2; i++) {
X = salsa20_8(xor(X, block.subarray(i * 64, (i + 1) * 64)), temp);
Y.set(X, (i + (i % 2 * (r2 - 1))) * 32);
}
return Y;
}
/**
* R function used by salsa20 core implementation in RFC7914
* @param {number} data
* @param {number} shift
* @returns {number}
*/
function R(data: number, shift: number): number {
//">>>0" is a hack to make js bitwise operations work with unsigned representations of 32 bit ints
return ((data << shift) | (data >>> (32 - shift)));
}
/**
* Salsa20/8 core implementation based on RFC7914 and js-salsa20
* @param {Uint8Array} input
* @param {Uint32Array} x temporary array that's used to avoid creating new arraybuffers
* @returns {Uint8Array}
*/
export function salsa20_8(input: Uint8Array, x: Uint32Array): Uint8Array {
//B32 is a Uint32 representation of the buffer provided on input
const B32 = new Uint32Array(input.buffer);
x.set(B32);
for (let i: number = 0; i < 8; i += 2) {
x[4] ^= R(x[0] + x[12], 7);
x[8] ^= R(x[4] + x[0], 9);
x[12] ^= R(x[8] + x[4], 13);
x[0] ^= R(x[12] + x[8], 18);
x[9] ^= R(x[5] + x[1], 7);
x[13] ^= R(x[9] + x[5], 9);
x[1] ^= R(x[13] + x[9], 13);
x[5] ^= R(x[1] + x[13], 18);
x[14] ^= R(x[10] + x[6], 7);
x[2] ^= R(x[14] + x[10], 9);
x[6] ^= R(x[2] + x[14], 13);
x[10] ^= R(x[6] + x[2], 18);
x[3] ^= R(x[15] + x[11], 7);
x[7] ^= R(x[3] + x[15], 9);
x[11] ^= R(x[7] + x[3], 13);
x[15] ^= R(x[11] + x[7], 18);
x[1] ^= R(x[0] + x[3], 7);
x[2] ^= R(x[1] + x[0], 9);
x[3] ^= R(x[2] + x[1], 13);
x[0] ^= R(x[3] + x[2], 18);
x[6] ^= R(x[5] + x[4], 7);
x[7] ^= R(x[6] + x[5], 9);
x[4] ^= R(x[7] + x[6], 13);
x[5] ^= R(x[4] + x[7], 18);
x[11] ^= R(x[10] + x[9], 7);
x[8] ^= R(x[11] + x[10], 9);
x[9] ^= R(x[8] + x[11], 13);
x[10] ^= R(x[9] + x[8], 18);
x[12] ^= R(x[15] + x[14], 7);
x[13] ^= R(x[12] + x[15], 9);
x[14] ^= R(x[13] + x[12], 13);
x[15] ^= R(x[14] + x[13], 18);
}
for (let i: number = 0; i < 16; ++i) {
B32[i] += x[i];
}
//since the underlying buffer was modified we don't need a new Uint8Array as a representation of it.
return input;
}
/**
* xor two Uint8Arrays
* @param {Uint8Array} a - first Uint8Array
* @param {Uint8Array} b - second Uint8Array
* @returns {Uint8Array} - xor result
*/
function xor(a: Uint8Array, b: Uint8Array): Uint8Array {
const buffer = new Uint8Array(a);
for (let i: number = a.length - 1; i >= 0; i--) {
buffer[i] ^= b[i];
}
return buffer;
}

0 comments on commit 77993bd

Please sign in to comment.