{"size": 1761, "ext": "js", "max_stars_repo_path": "src/utils/hash.js", "max_stars_repo_name": "digime/digime-sdk-react-native", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/hash.js", "max_issues_repo_name": "digime/digime-sdk-react-native", "max_issues_repo_issues_event_min_datetime": "2022-03-19T22:56:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:56:47.000Z", "max_forks_repo_path": "src/utils/hash.js", "max_forks_repo_name": "digime/digime-sdk-react-native", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 1, "max_forks_count": null, "avg_line_length": 24.8028169014, "max_line_length": 63, "alphanum_fraction": 0.6854060193}
import base64url from "base64url";
import { sha256, sha512 } from "hash.js";
import { randomBytes } from "react-native-randombytes";

const ALPHA_LOWER = "abcdefghijklmnopqrstuvwxyz";
const ALPHA_UPPER = ALPHA_LOWER.toUpperCase();
const NUMERIC = "0123456789";
const ALPHA_NUMERIC = `${ALPHA_LOWER}${ALPHA_UPPER}${NUMERIC}`;

/**
 * Create hash using SHA 256
 * @private
 * @function hashSHA256
 * @param {unknown} data data to hash
 * @returns {string} base64 result
 */
export const hashSHA256 = data => createHash(data, sha256);

/**
 * Create hash using SHA 512
 * @private
 * @function hashSHA512
 * @param {unknown} data data to hash
 * @returns {string} base64 result
 */
export const hashSHA512 = data => createHash(data, sha512);

/**
 * @function createHash
 * @private
 * @param {unknown} data data to hash
 * @param {function} hashFunction
 * @returns {string} base64 result
 */
const createHash = (data, hashFunction) => {
	const digest = hashFunction().update(data).digest();
	return base64url(digest);
};

/**
 * Returns a random hex of {@link size} characters
 * @private
 * @function getRandomAlphaNumeric
 * @param {number} size
 * @returns {string} result
 */
export const getRandomAlphaNumeric = size => {
	const charsLength = ALPHA_NUMERIC.length;
	return new Array(size)
		.fill(0)
		.map(random => {
			do {
				random = randomBytes(1).readUInt8(0);
			} while (random > (256 - (256 % charsLength)));
			return ALPHA_NUMERIC[random % charsLength];
		})
		.join("");
};

/**
 * Returns a random hex string
 * @private
 * @function getRandomHex
 * @param {number} size
 * @returns {string} random hex of {@link size}
 */
export const getRandomHex = size => {
	return randomBytes(Math.ceil(size / 2))
		.toString("hex")
		.slice(0, size);
};