Skip to content

Instantly share code, notes, and snippets.

View chrisveness's full-sized avatar

Chris Veness chrisveness

View GitHub Profile
@chrisveness
chrisveness / crypto-aes-gcm.js
Last active March 17, 2024 15:36
Uses the SubtleCrypto interface of the Web Cryptography API to encrypt and decrypt text using AES-GCM (AES Galois counter mode).
/**
* Encrypts plaintext using AES-GCM with supplied password, for decryption with aesGcmDecrypt().
* (c) Chris Veness MIT Licence
*
* @param {String} plaintext - Plaintext to be encrypted.
* @param {String} password - Password to use to encrypt plaintext.
* @returns {String} Encrypted ciphertext.
*
* @example
* const ciphertext = await aesGcmEncrypt('my secret text', 'pw');
@chrisveness
chrisveness / crypto-pbkdf2.js
Last active December 21, 2023 19:20
Uses the SubtleCrypto interface of the Web Cryptography API to hash a password using PBKDF2, and validate a stored password hash against a subsequently supplied password. Note that both bcrypt and scrypt offer better defence against ASIC/GPU attacks, but are not available within WebCrypto.
/**
* Returns PBKDF2 derived key from supplied password.
*
* Stored key can subsequently be used to verify that a password matches the original password used
* to derive the key, using pbkdf2Verify().
*
* @param {String} password - Password to be hashed using key derivation function.
* @param {Number} [iterations=1e6] - Number of iterations of HMAC function to apply.
* @returns {String} Derived key as base64 string.
*
@chrisveness
chrisveness / crypto-sha.js
Last active July 20, 2023 04:45
Uses the SubtleCrypto interface of the Web Cryptography API to hash a message using SHA-256.
/**
* Returns SHA-256 hash from supplied message.
*
* @param {String} message.
* @returns {String} hash as hex string.
*
* @example
* sha256('abc').then(hash => console.log(hash));
* const hash = await sha256('abc');
*/
@chrisveness
chrisveness / utf8-regex.js
Last active May 25, 2023 01:53
Utf8 string encode/decode using regular expressions
/**
* Encodes multi-byte Unicode string into utf-8 multiple single-byte characters
* (BMP / basic multilingual plane only).
*
* Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars.
*
* Can be achieved in JavaScript by unescape(encodeURIComponent(str)),
* but this approach may be useful in other languages.
*
* @param {string} unicodeString - Unicode string to be encoded as UTF-8.
@chrisveness
chrisveness / base64.js
Last active May 6, 2023 02:55
Encode/decode ASCII string to/from base64
/**
* Encode string into Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648].
* As per RFC 4648, no newlines are added.
*
* Characters in str must be within ISO-8859-1 with Unicode code point <= 256.
*
* Can be achieved JavaScript with btoa(), but this approach may be useful in other languages.
*
* @param {string} str ASCII/ISO-8859-1 string to be encoded as base-64.
* @returns {string} Base64-encoded string.
@chrisveness
chrisveness / sha3-32bit.js
Created April 3, 2017 10:30
32-bit version of SHA-3 (Keccak) algorithm using bit-interleaving
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* SHA-3 (FIPS 202) ‘Keccak’ reference implementation in JavaScript (c) Chris Veness 2016-2017 */
/* MIT Licence */
/* www.movable-type.co.uk/scripts/sha3.html */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
'use strict';
/**
@chrisveness
chrisveness / index.html
Last active January 3, 2023 06:50
JavaScript AES client/server interoperability test
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AES client/server test</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.min.css">
<style>
body { font-size: 80%; padding: 1em; }
form { margin-top: 2em; }
label { display: inline-block; width: 6em; }
@chrisveness
chrisveness / mongodb-objectid.js
Created September 14, 2016 11:32
Generates a MongoDB-style ObjectId in Node.js
/**
* Generates a MongoDB-style ObjectId in Node.js. Uses nanosecond timestamp in place of counter;
* should be impossible for same process to generate multiple objectId in same nanosecond? (clock
* drift can result in an *extremely* remote possibility of id conflicts).
*
* @returns {string} Id in same format as MongoDB ObjectId.
*/
function objectId() {
const os = require('os');
const crypto = require('crypto');
@chrisveness
chrisveness / geocode.php
Last active March 5, 2019 15:29
Geocode an address using Google API
<?php
/**
* Geocodes an address using Google API (limit 2500/day).
*
* @param string $address - Address to be geocoded.
* @param string [$region=gb] - Region results are to biased to.
* @return object {lat, lon, status, address}.
*/
function geocode($address, $region='gb')
@chrisveness
chrisveness / standard-deviation.js
Created September 21, 2016 22:13
Standard deviation of set of values
/**
* Returns standard deviation of set of values.
*
* @param {number[]} values - Array of values.
* @returns {number} Standard devation of values.
*/
function stdDeviation(values) {
const avgOfValues = average(values);
const squaresOfDiffs = values.map(value => (value-avgOfValues)**2);
const avgOfSquaresOfDiffs = average(squaresOfDiffs);