Skip to content

Commit

Permalink
Improved performance, JSDocs, README and added Prettifier
Browse files Browse the repository at this point in the history
  • Loading branch information
zigazajc007 committed Aug 12, 2024
1 parent 2d030b3 commit 5498091
Show file tree
Hide file tree
Showing 14 changed files with 431 additions and 331 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Publish
on:
push:
branches:
- main

jobs:
publish:
runs-on: ubuntu-latest

permissions:
contents: read
id-token: write

steps:
- uses: actions/checkout@v4

- name: Publish package
run: npx jsr publish
5 changes: 5 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"tabWidth": 2,
"useTabs": true,
"printWidth": 160
}
49 changes: 33 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,34 @@
# Blake2b-JS

Blake2b-512 implementation in JavaScript (ES6).
A JavaScript (ES6) implementation of the Blake2b-512 cryptographic hash function.

## Usage

### 1. Download library
### 1. Download the library

```bash
npm i --save @rabbit-company/blake2b
```

### 2. Import library
### 2. Import the library

```js
import Blake2b from "@rabbit-company/blake2b";
```

### 3. Hash
```js
/*
Parameters:
1. Message (String or Uint8Array)
2. Secret (String or Uint8Array | undefined) <>
3. Length (Int) <64> (Min = 0 and Max = 64)
4. Salt (String or Uint8Array) <> (String with length 16 or Uint8Array)
5. Personal (String or Uint8Array) <> (String with length 16 or Uint8Array)
### 3. Generate a Hash

*/
```ts
/**
* Generate a Blake2b hash.
*
* @param {string | Uint8Array} message - The input message to hash (required).
* @param {string | Uint8Array | undefined} secret - An optional secret key for HMAC mode.
* @param {number} [length=64] - The length of the hash output in bytes (default is 64, max is 64).
* @param {string | Uint8Array} [salt] - An optional salt value for the hash (must be 16 bytes long).
* @param {string | Uint8Array} [personal] - An optional personalization value (must be 16 bytes long).
* @returns {string} - The hexadecimal representation of the hash.
*/

// Generate hash from the provided message
Blake2b.hash("message");
Expand All @@ -40,5 +43,19 @@ Blake2b.hash("message", "secretKey", 32);
Blake2b.hash("message", "secretKey", 32, "c32df5f2f3c77a03");

// Generate hash from the provided message, secret key, length, salt and personal
Blake2b.hash("message", "secretKey", 32, "c32df5f2f3c77a03", "4862f0260a9803da");
```
Blake2b.hash(
"message",
"secretKey",
32,
"c32df5f2f3c77a03",
"4862f0260a9803da"
);
```

### Parameters

- **message**: The input to be hashed. Can be a string or a Uint8Array.
- **secret**: (Optional) A secret key for HMAC mode. Can be a string or Uint8Array. If not provided, a standard Blake2b hash will be generated.
- **length**: (Optional) The length of the output hash in bytes. Defaults to 64. Must be between 1 and 64.
- **salt**: (Optional) A salt value for the hash. Must be a 16-byte string or Uint8Array.
- **personal**: (Optional) A personalization string for the hash. Must be a 16-byte string or Uint8Array.
58 changes: 28 additions & 30 deletions build.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,41 @@
import dts from 'bun-plugin-dts';
import Logger from '@rabbit-company/logger';
import fs from 'fs/promises';
import dts from "bun-plugin-dts";
import Logger from "@rabbit-company/logger";
import fs from "fs/promises";

await fs.rm('./module', {recursive: true, force: true});
await fs.rm('./dist', {recursive: true, force: true});
await fs.rm("./module", { recursive: true, force: true });
await fs.rm("./dist", { recursive: true, force: true });

Logger.info('Start bulding module...');
Logger.info("Start bulding module...");
let moduleBuild = await Bun.build({
entrypoints: ['./src/blake2b.ts'],
outdir: './module',
target: 'browser',
format: 'esm',
plugins: [
dts({output: {noBanner: true}})
],
entrypoints: ["./src/blake2b.ts"],
outdir: "./module",
target: "browser",
format: "esm",
plugins: [dts({ output: { noBanner: true } })],
});

if(moduleBuild.success){
Logger.info('Bulding module complete');
}else{
Logger.error('Bulding module failed');
if (moduleBuild.success) {
Logger.info("Bulding module complete");
} else {
Logger.error("Bulding module failed");
}

fs.cp('./src/index.html', './dist/index.html', {recursive: true, force: true});
fs.cp("./src/index.html", "./dist/index.html", { recursive: true, force: true });

Logger.info('Start bundling dist...');
Logger.info("Start bundling dist...");
let distBuild = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser',
format: 'esm',
entrypoints: ["./src/index.ts"],
outdir: "./dist",
target: "browser",
format: "esm",
minify: true,
sourcemap: 'none', // Bun still generates incorrect sourcemaps
plugins: [],
sourcemap: "none",
plugins: [],
});

if(distBuild.success){
Logger.info('Bundling dist complete');
}else{
Logger.error('Bundling dist failed');
if (distBuild.success) {
Logger.info("Bundling dist complete");
} else {
Logger.error("Bundling dist failed");
Logger.error(distBuild.logs);
}
}
Binary file modified bun.lockb
Binary file not shown.
2 changes: 1 addition & 1 deletion dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ <h1><a href="https://github.com/Rabbit-Company/Blake2b-JS" target="_blank">Blake

<h1>Performance Test</h1>
<div>
<label>Number of executions:</label>
<label for="amount">Number of executions:</label>
<input id="amount" type="number" min="1" max="100000" placeholder="Amount" value="1000" />
<button id="btn-start">Start</button>
</div>
Expand Down
2 changes: 1 addition & 1 deletion dist/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions jsr.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "@rabbit-company/blake2b",
"version": "2.1.0",
"exports": "./src/blake2b.ts"
}
79 changes: 46 additions & 33 deletions module/blake2b.d.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,52 @@
export interface CTX {
b: Uint8Array;
h: Uint32Array;
t: number;
c: number;
outlen: number;
}
export default class Blake2b {
v: Uint32Array;
m: Uint32Array;
BLAKE2B_IV32: Uint32Array;
SIGMA8: number[];
parameterBlock: Uint8Array;
SIGMA82: Uint8Array;
ADD64AA(v: Uint32Array, a: number, b: number): void;
ADD64AC(v: Uint32Array, a: number, b0: number, b1: number): void;
B2B_GET32(arr: Uint8Array, i: number): number;
B2B_G(a: number, b: number, c: number, d: number, ix: number, iy: number): void;
blake2bCompress(ctx: CTX, last: boolean): void;
blake2bInit(outlen: number, key: Uint8Array | undefined, salt: Uint8Array, personal: Uint8Array): CTX;
blake2bUpdate(ctx: CTX, input: Uint8Array): void;
blake2bFinal(ctx: CTX): Uint8Array;
blake2bStart(input: string | Uint8Array, key: Uint8Array | undefined, outlen: number, salt: string | Uint8Array, personal: string | Uint8Array): Uint8Array;
normalizeInput(input: string | Uint8Array): Uint8Array;
toHex(bytes: Uint8Array): string;
/**
* The `Blake2b` namespace provides functionality for generating Blake2b-512 cryptographic hashes.
* It includes methods for creating hashes with optional HMAC mode, specifying output length,
* and applying salt and personalization values.
*/
declare namespace Blake2b {
/**
* Calculates the Blake2b hash of the given message using the specified parameters.
* Computes the Blake2b hash of the provided message using the given parameters.
*
* @param {string | Uint8Array} message - The input message to be hashed.
* @param {string | Uint8Array | undefined} secret - The secret key for HMAC mode (optional).
* @param {number} [length=64] - The desired length of the hash output in bytes (default is 64).
* @param {string | Uint8Array} [salt=new Uint8Array(16)] - The salt value for the hash function (default is a new Uint8Array(16)).
* @param {string | Uint8Array} [personal=new Uint8Array(16)] - The personalization string for the hash function (default is a new Uint8Array(16)).
* @param {string | Uint8Array} message - The input data to be hashed. This can be a string or a Uint8Array.
* @param {string | Uint8Array | undefined} [secret] - An optional secret key for HMAC mode. This can be a string or a Uint8Array.
* If not provided, a standard Blake2b hash will be computed. If provided, it should be between 1 and 64 bytes in length.
* @param {number} [length=64] - The desired length of the hash output in bytes. The value should be between 1 and 64. Defaults to 64 bytes.
* @param {string | Uint8Array} [salt=new Uint8Array(16)] - An optional salt value for the hash function. This can be a string or a Uint8Array.
* The salt must be exactly 16 bytes long. Defaults to a zeroed 16-byte Uint8Array.
* @param {string | Uint8Array} [personal=new Uint8Array(16)] - An optional personalization string for the hash function. This can be a string or a Uint8Array.
* The personalization string must be exactly 16 bytes long. Defaults to a zeroed 16-byte Uint8Array.
* @returns {string} - The hexadecimal representation of the Blake2b hash output.
*/
static hash(message: string | Uint8Array | undefined, secret: string | Uint8Array | undefined, length?: number, salt?: string | Uint8Array, personal?: string | Uint8Array): string;
*
* @throws {Error} If the provided output length (`length`) is not within the range of 1 to 64 bytes.
* @throws {Error} If the provided secret key exceeds 64 bytes in length.
* @throws {Error} If the provided salt is not exactly 16 bytes long.
* @throws {Error} If the provided personalization string is not exactly 16 bytes long.
*
* @example
* // Simple usage with a message
* const hashValue = hash('Hello, world!');
* console.log(hashValue); // Outputs the Blake2b hash as a hex string
*
* @example
* // Using a secret key for HMAC mode
* const hashWithKey = hash('Hello, world!', 'my-secret-key');
* console.log(hashWithKey); // Outputs the Blake2b HMAC as a hex string
*
* @example
* // Custom output length
* const shortHash = hash('Hello, world!', '', 32);
* console.log(shortHash); // Outputs a 32-byte Blake2b hash as a hex string
*
* @example
* // Using salt and personalization
* const saltedHash = hash('Hello, world!', '', 64, 'my-salt', 'my-personal');
* console.log(saltedHash); // Outputs a Blake2b hash with salt and personalization as a hex string
*/
function hash(message?: string | Uint8Array, secret?: string | Uint8Array | undefined, length?: number, salt?: string | Uint8Array, personal?: string | Uint8Array): string;
}

export {
Blake2b as default,
};

export {};
Loading

0 comments on commit 5498091

Please sign in to comment.