Skip to content

Commit

Permalink
Add blake2_256 function and its tests to auto-utils
Browse files Browse the repository at this point in the history
  • Loading branch information
abhi3700 committed Jun 10, 2024
1 parent 0252e96 commit 642b19b
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/auto-utils/__test__/crypto.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { blake2b_256, stringToUint8Array } from '../src/crypto'

describe('Verify crypto functions', () => {
test('Check blake2b_256 return the hash of the data', async () => {
const message = 'Alice transfer money to Bob'
const data = stringToUint8Array(message)
const hash = blake2b_256(data)
expect(hash).toMatch('0x')
})

test('Check stringToUint8Array return the byte array of the string', async () => {
const message = 'Hello, world!'
const byteArray = stringToUint8Array(message)
expect(byteArray).toBeInstanceOf(Uint8Array)
})
})
31 changes: 31 additions & 0 deletions packages/auto-utils/src/crypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { blake2AsHex } from '@polkadot/util-crypto'

/**
* Hashes the given data using BLAKE2b-256.
*
* @param data Uint8Array - The data to be hashed.
* @returns string - The BLAKE2b-256 hash of the data as a hex string.
*/
export function blake2b_256(data: Uint8Array): string {
return blake2AsHex(data, 256)
}

/**
* Converts a string to a Uint8Array using UTF-8 encoding.
*
* This function uses the TextEncoder API to convert a plain string into its equivalent byte array
* representation in UTF-8 format. It is useful for scenarios where string data needs to be processed
* in a binary format, such as hashing or cryptographic operations.
*
* @param text The string to be converted into a byte array.
* @returns Uint8Array - The UTF-8 encoded byte array representation of the input string.
*
* @example
* const text = "Hello, world!";
* const byteArray = stringToUint8Array(text);
* console.log(byteArray); // Outputs the byte array of the string
*/
export function stringToUint8Array(text: string): Uint8Array {
const encoder = new TextEncoder() // Create a new TextEncoder instance
return encoder.encode(text) // Encode the string to a Uint8Array using UTF-8 encoding
}
1 change: 1 addition & 0 deletions packages/auto-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './api'
export * from './crypto'
export * from './network'
export * from './read'
export * from './save'

0 comments on commit 642b19b

Please sign in to comment.