crypto#createHash TypeScript Examples

The following examples show how to use crypto#createHash. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From DefinitelyTyped-tools with MIT License 7 votes vote down vote up
export function getSystemInfo(): SystemInfo {
  const info = {
    cpus: os.cpus().map(({ times, ...cpu }) => cpu),
    arch: os.arch(),
    platform: os.platform(),
    release: os.release(),
    totalmem: os.totalmem(),
    nodeVersion: process.version,
  };

  return {
    ...info,
    hash: createHash("md5").update(JSON.stringify(info)).digest("hex"),
  };
}
Example #2
Source File: crypto.test.ts    From worktop with MIT License 6 votes vote down vote up
SHA384('should return correct values as hexstrings', async () => {
	assert.is(
		await crypto.SHA384(''),
		createHash('sha384').update('').digest('hex'),
		'~> 38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b'
	);

	assert.is(
		await crypto.SHA384('hello'),
		createHash('sha384').update('hello').digest('hex'),
		'~> 59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553bcdb9c666fa90125a3c79f90397bdf5f6a13de828684f'
	);

	assert.is(
		await crypto.SHA384('hello1'),
		createHash('sha384').update('hello1').digest('hex'),
		'~> 7a79ada28c7218353974345bfc7c2c463577219dc4ecc155341e770ce235634c7f5224bf586e51fe6d890cfe41e1c59a'
	);

	assert.is(
		await crypto.SHA384('hello world'),
		createHash('sha384').update('hello world').digest('hex'),
		'~> fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bd'
	);
});
Example #3
Source File: generateOperationId.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export function generateOperationId(
  operation: Operation,
  fragments: { [fragmentName: string]: Fragment },
  fragmentsReferenced?: Iterable<string>
) {
  if (!fragmentsReferenced) {
    fragmentsReferenced = collectFragmentsReferenced(operation.selectionSet, fragments);
  }

  const sourceWithFragments = [
    operation.source,
    ...Array.from(fragmentsReferenced).map(fragmentName => {
      const fragment = fragments[fragmentName];
      if (!fragment) {
        throw new Error(`Cannot find fragment "${fragmentName}"`);
      }
      return fragment.source;
    }),
  ].join('\n');

  const hash = createHash('sha256');
  hash.update(sourceWithFragments);
  const operationId = hash.digest('hex');

  return { operationId, sourceWithFragments };
}
Example #4
Source File: CacheClient.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
   * Ensures keys are well-formed for any/all cache stores.
   */
  private getNormalizedKey(candidateKey: string): string {
    // Remove potentially invalid characters.
    const wellFormedKey = Buffer.from(candidateKey).toString('base64');

    // Memcache in particular doesn't do well with keys > 250 bytes.
    // Padded because a plugin ID is also prepended to the key.
    if (wellFormedKey.length < 200) {
      return wellFormedKey;
    }

    return createHash('md5').update(candidateKey).digest('base64');
  }
Example #5
Source File: index.ts    From diablo2 with MIT License 6 votes vote down vote up
async function main(): Promise<void> {
  console.time('ReadMpq');
  const fileData = await fs.readFile(MpqFileName);
  const mpqFileHash = createHash('sha256').update(fileData).digest('base64');
  const mpq = Mpq.load(fileData);
  console.timeEnd('ReadMpq');

  console.log('LoadedMPQ', MpqFileName, { hash: mpqFileHash });

  const files = [
    'data/global/excel/Armor.bin',
    'data/global/excel/Weapons.bin',
    'data/global/excel/MonStats.bin',
    'data/global/excel/MonStats2.bin',
    'data/global/excel/MonStats2.bin',
    'data/local/LNG/ENG/string.tbl',
    'data/local/LNG/ENG/expansionstring.tbl',
    'data/local/LNG/ENG/patchstring.tbl',
  ];

  for (const fileName of files) {
    const data = await mpq.extract(fileName);
    if (data == null) continue;

    const hash = createHash('sha3-224').update(data).digest('hex');
    console.log(fileName, data.length, hash);
  }
}
Example #6
Source File: api-keys.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
generate = wrapHandler(async (event) => {
  await connectToDatabase();
  const key = randomBytes(16).toString('hex');
  // Store a hash of the API key instead of the key itself
  let apiKey = await ApiKey.create({
    hashedKey: createHash('sha256').update(key).digest('hex'),
    lastFour: key.substr(-4),
    user: { id: getUserId(event) }
  });
  apiKey = await apiKey.save();
  return {
    statusCode: 200,
    body: JSON.stringify({ ...apiKey, key: key })
  };
})
Example #7
Source File: guest.ts    From project-loved-web with MIT License 6 votes vote down vote up
guestRouter.get(
  '/survey',
  asyncHandler(async (req, res) => {
    if (
      config.surveyConfirmationSecret == null ||
      config.surveyId == null ||
      config.surveyLinkTemplate == null ||
      req.query.id !== config.surveyId
    ) {
      return res.status(404).json({ error: 'Survey not found' });
    }

    const user = res.typedLocals.user as UserWithRoles | undefined;

    if (user == null) {
      return res.redirect('/api/auth/begin?' + qs.stringify({ back: `/survey/${req.query.id}` }));
    }

    const confirmation = createHash('md5')
      .update(user.id + config.surveyConfirmationSecret)
      .digest('hex');
    const link = config.surveyLinkTemplate.replace('{confirmation}', `${user.id}-${confirmation}`);

    res.redirect(link);
  }),
);
Example #8
Source File: compiler-metadata.ts    From remix-project with MIT License 6 votes vote down vote up
async setBuildInfo (version, input, output, path) {
    input = JSON.parse(input)
    const solcLongVersion = version.replace('.Emscripten.clang', '')
    const solcVersion = solcLongVersion.substring(0, solcLongVersion.indexOf('+commit'))
    const format = 'hh-sol-build-info-1'
    const json = JSON.stringify({
      _format: format,
      solcVersion,
      solcLongVersion,
      input
    })
    const id =  createHash('md5').update(Buffer.from(json)).digest().toString('hex')
    const buildFilename = this.joinPath(path, this.innerPath, 'build-info/' +  id + '.json')
    const buildData = {id, _format: format, solcVersion, solcLongVersion, input, output}
    await this.call('fileManager', 'writeFile', buildFilename, JSON.stringify(buildData, null, '\t'))
  }
Example #9
Source File: acknowledgement.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
static deserialize(preArray: Uint8Array, ownPubKey: PeerId, senderPubKey: PeerId): Acknowledgement {
    if (preArray.length != Acknowledgement.SIZE) {
      throw Error(`Invalid arguments`)
    }

    let arr: Uint8Array
    if (typeof Buffer !== 'undefined' && Buffer.isBuffer(preArray)) {
      arr = Uint8Array.from(arr)
    } else {
      arr = preArray
    }

    const [ackSignature, challengeSignature, ackKey] = u8aSplit(arr, [
      SECP256K1_CONSTANTS.SIGNATURE_LENGTH,
      AcknowledgementChallenge.SIZE,
      SECRET_LENGTH
    ])

    const challengeToVerify = createHash(HASH_ALGORITHM).update(new HalfKey(ackKey).toChallenge().serialize()).digest()

    if (!ecdsaVerify(challengeSignature, challengeToVerify, ownPubKey.pubKey.marshal())) {
      throw Error(`Challenge signature verification failed.`)
    }

    const ackToVerify = createHash(HASH_ALGORITHM)
      .update(Uint8Array.from([...challengeSignature, ...ackKey]))
      .digest()

    if (!ecdsaVerify(ackSignature, ackToVerify, senderPubKey.pubKey.marshal())) {
      throw Error(`Acknowledgement signature verification failed.`)
    }

    return new Acknowledgement(ackSignature, challengeSignature, new HalfKey(ackKey))
  }
Example #10
Source File: DownloadedUpdateHelper.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
function hashFile(file: string, algorithm = "sha512", encoding: "base64" | "hex" = "base64", options?: any): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    const hash = createHash(algorithm)
    hash
      .on("error", reject)
      .setEncoding(encoding)

    createReadStream(file, {...options, highWaterMark: 1024 * 1024 /* better to use more memory but hash faster */})
      .on("error", reject)
      .on("end", () => {
        hash.end()
        resolve(hash.read() as string)
      })
      .pipe(hash, {end: false})
  })
}
Example #11
Source File: utils.ts    From tbtcswaps with MIT License 6 votes vote down vote up
export function sha256(buffer:Buffer){
  return createHash('sha256').update(buffer).digest('hex');
}
Example #12
Source File: crypto.test.ts    From worktop with MIT License 6 votes vote down vote up
SHA1('should return correct values as hexstrings', async () => {
	assert.is(
		await crypto.SHA1(''),
		createHash('sha1').update('').digest('hex'),
		'~> da39a3ee5e6b4b0d3255bfef95601890afd80709'
	);

	assert.is(
		await crypto.SHA1('hello'),
		createHash('sha1').update('hello').digest('hex'),
		'~> aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d'
	);

	assert.is(
		await crypto.SHA1('hello1'),
		createHash('sha1').update('hello1').digest('hex'),
		'~> 88fdd585121a4ccb3d1540527aee53a77c77abb8'
	);

	assert.is(
		await crypto.SHA1('hello world'),
		createHash('sha1').update('hello world').digest('hex'),
		'~> 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed'
	);
});
Example #13
Source File: mavlink.ts    From node-mavlink with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
   * Calculate key based on secret passphrase
   *
   * @param passphrase secret to generate the key
   * @returns key as a buffer
   */
  static key(passphrase: string) {
    return createHash('sha256')
      .update(passphrase)
      .digest()
  }
Example #14
Source File: crypto.test.ts    From worktop with MIT License 6 votes vote down vote up
SHA512('should return correct values as hexstrings', async () => {
	assert.is(
		await crypto.SHA512(''),
		createHash('sha512').update('').digest('hex'),
		'~> cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'
	);

	assert.is(
		await crypto.SHA512('hello'),
		createHash('sha512').update('hello').digest('hex'),
		'~> 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043'
	);

	assert.is(
		await crypto.SHA512('hello1'),
		createHash('sha512').update('hello1').digest('hex'),
		'~> 1dabfeadb6451e4903649fe6efec8ecda6b40e5ba99f73dfb5510956df496ecb1ebb625b9376bbcef223b354481633e9b977872aef979478e6451975e714c31f'
	);

	assert.is(
		await crypto.SHA512('hello world'),
		createHash('sha512').update('hello world').digest('hex'),
		'~> 309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f'
	);
});
Example #15
Source File: password.utils.ts    From rest-api.ts with MIT License 6 votes vote down vote up
export function hashPassword(password: string): string {
  return createHash('sha256').update(`${password}_${salt}`).digest('hex');
}
Example #16
Source File: getHashDijest.ts    From svelte-preprocess-cssmodules with MIT License 6 votes vote down vote up
getHashDigest = (
  buffer: Buffer,
  hashType: string,
  digestType: string,
  maxLength = 9999
): string => {
  const hash = createHash(hashType || 'md4');

  hash.update(buffer);

  if (
    digestType === 'base26' ||
    digestType === 'base32' ||
    digestType === 'base36' ||
    digestType === 'base49' ||
    digestType === 'base52' ||
    digestType === 'base58' ||
    digestType === 'base62' ||
    digestType === 'base64'
  ) {
    return encodeBufferToBase(hash.digest(), parseInt(digestType.substr(4), 10)).substr(
      0,
      maxLength
    );
  }
  const encoding = (digestType as 'latin1') || 'hex';
  return hash.digest(encoding).substr(0, maxLength);
}
Example #17
Source File: CreateJwkThumbprint.ts    From VerifiableCredentials-Verification-SDK-Typescript with MIT License 6 votes vote down vote up
/**
 * for a given json web key calculate the thumbprint as defined by RFC 7638
 * @param jwk json web key instance
 * @returns thumbprint
 */
export function createJwkThumbprint(jwk: { [key: string]: string }): string {
  const key = {
    crv: jwk.crv,
    e: jwk.e,
    kty: jwk.kty,
    n: jwk.n,
    x: jwk.x,
    y: jwk.y,
  };

  const preimage = JSON.stringify(key);
  const digest = createHash('sha256').update(preimage, 'utf8').digest();
  return base64url(digest);
}
Example #18
Source File: index.ts    From tsdav with MIT License 6 votes vote down vote up
appendJSON = async (filepath: string, keyData: string, valueData: string) => {
  // create if not exist
  if (!fs.existsSync(filepath)) {
    await fs.promises.writeFile(filepath, '{}');
  }

  // read from json file
  const store: Record<string, string> = JSON.parse(await fs.promises.readFile(filepath, 'utf8'));
  // hash keyData
  const hash = createHash('sha256');
  const key = hash.update(keyData).digest('base64');
  const value = Buffer.from(valueData).toString('base64');

  // store inside json
  store[key] = value;
  // write back to json
  await fs.promises.writeFile(filepath, JSON.stringify(store));
}
Example #19
Source File: [num].ts    From natemoo-re with MIT License 6 votes vote down vote up
export default async function (req: NowRequest, res: NowResponse) {
  const { query: { num }, headers } = req;
  const index = Number.parseInt(num as string) - 1;
  const dest = headers["sec-fetch-dest"] || headers["Sec-Fetch-Dest"];
  const accept = headers['accept'];
  const image = dest ? dest === 'image' : !/text\/html/.test(accept);
  
  const color = await getBlockColor(index);
  if (image) {
    const svg = renderToString(Block({ color }));
    const etag = createHash("md5").update(svg).digest("hex");
    res.setHeader("Content-Type", "image/svg+xml");
    res.setHeader("Cache-Control", "no-cache, max-age=0");
    res.setHeader("Etag", etag);
    return res.status(200).send(svg);
  }
  
  const newColor: string = getNextColor(color);
  await setBlockColor(index, newColor);
  return res.status(204).end();
}
Example #20
Source File: utility.ts    From serverless-provisioned-concurrency-autoscaling with Apache License 2.0 6 votes vote down vote up
truncate = (input: string): string => {
  return input.length <= 64
    ? input
    : input.substr(0, 32) + createHash('md5').update(input).digest('hex')
}
Example #21
Source File: trade-sync.ts    From zorro-fire-log with MIT License 6 votes vote down vote up
// hande lines from trade logs
function onTradeLogLine(tail: Tail, tl: TradeLog, schema: Schema) {
  tail.on("line", (line: string) => {
    if (line) {
      const parts = line.split(",");
      if (validateLine(parts, schema)) {
        const entry: LogEntry = mapEntry(parts, schema);
        const fbId = createHash("md5").update(line).digest("hex");
        const collection = tl.alias;
        writeToFirestore(collection, fbId, entry);
      }
    }
  });
  tail.on("error", function (error) {
    console.log("ERROR: ", error);
  });
}
Example #22
Source File: utils.ts    From snapshot-hub with MIT License 6 votes vote down vote up
export function sha256(str) {
  return createHash('sha256')
    .update(str)
    .digest('hex');
}
Example #23
Source File: index.ts    From vite-electron-react-starter with MIT License 6 votes vote down vote up
/**
 * Safe expose node.js API
 * @example
 * window.nodeCrypto('data')
 */
contextBridge.exposeInMainWorld('nodeCrypto', {
  sha256sum(data: BinaryLike) {
    const hash = createHash('sha256');
    hash.update(data);
    return hash.digest('hex');
  },
});
Example #24
Source File: mini-program-application-analysis.service.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
private augmentProgramWithVersioning(program: ts.Program): void {
    const baseGetSourceFiles = program.getSourceFiles;
    program.getSourceFiles = function (...parameters) {
      const files: readonly (ts.SourceFile & { version?: string })[] =
        baseGetSourceFiles(...parameters);

      for (const file of files) {
        if (file.version === undefined) {
          file.version = createHash('sha256').update(file.text).digest('hex');
        }
      }

      return files;
    };
  }
Example #25
Source File: get-hash.spec.ts    From svimg with ISC License 6 votes vote down vote up
describe('getHash', () => {

    let update: jest.Mock;
    let digest: jest.Mock;
    beforeEach(() => {
        digest = jest.fn();
        update = jest.fn();
        update.mockReturnValue({ digest });
        (createHash as jest.Mock).mockReset();
        (createHash as jest.Mock).mockReturnValue({ update });
    });

    it('returns an md5 hex hash', () => {
        digest.mockReturnValue('abcdefghi');

        expect(getHash('datatohash')).toEqual('abcdefghi');

        expect(createHash).toHaveBeenCalledWith('md5');
        expect(update).toHaveBeenCalledWith('datatohash');
        expect(digest).toHaveBeenCalledWith('hex');
    });

});
Example #26
Source File: util.ts    From one-platform with MIT License 6 votes vote down vote up
export default function hash(key: string) {
  return createHash('sha256').update(key).digest('hex');
}
Example #27
Source File: makeHash.ts    From excalidraw-json with MIT License 6 votes vote down vote up
export function makeHash<T extends string = string>(
  ...args: Array<string | Buffer | null>
): T {
  const hash = createHash('sha512');

  for (const arg of args) hash.update(arg ? arg : '');

  return hash.digest('hex') as T;
}
Example #28
Source File: OutputContainer.ts    From garment with MIT License 6 votes vote down vote up
constructor(
    public readonly cacheProvider: CacheProvider,
    target: string | File,
    public readonly cacheKeys: string[],
    dependencies: (string | File)[] = []
  ) {
    const hash = createHash('md5');
    for (const cacheKey of this.cacheKeys) {
      hash.update(JSON.stringify(cacheKey));
    }
    this.hash = hash.digest('hex');

    if (typeof target === 'string') {
      this.target = target;
      this.targetBaseDir = Path.dirname(target);
    } else {
      this.target = target.absolutePath ?? target.path;
      this.targetBaseDir = target.baseDir ?? Path.dirname(this.target);
    }

    this.dependencies = dependencies.map(dep =>
      typeof dep === 'string' ? dep : dep.absolutePath ?? dep.path
    );

    this.logger = new Logger('', '', 'silly');
    this.logger.interceptors.push(({ level, args }) => {
      this.logs.push({
        level,
        content: args,
        scope: '    '
      });
      return false; // creating logger instance which doesn't output to the console
    });
  }
Example #29
Source File: about.ts    From WebCord with MIT License 6 votes vote down vote up
/**
 * Fetches user avatar by making the requests to both GitHub and Gravatar
 * services and picking the promise that resolves first. It is also designed to
 * cancel all presenting fetches when once has been already resolved to conserve
 * the network and cleanup the code.
 */
async function getUserAvatar(person: Person, size = 96) {
    const sources = [], promises = [], controler = new AbortController();
    sources.push("https://github.com/"+encodeURIComponent(person.name)+".png?size="+size.toString());
    if(person.email)
        sources.push("https://gravatar.com/avatar/"+createHash("md5").update(person.email).digest('hex')+'?d=404&s='+size.toString())
    for(const source of sources) {
        promises.push(fetch(source, { signal: controler.signal }).then(async (data) => {
            if(data.ok && data.headers.get("Content-Type")?.startsWith("image")) {
                const blobUrl =  URL.createObjectURL(await data.blob());
                const image = document.createElement('img');
                image.src = blobUrl;
                image.addEventListener('load', () => URL.revokeObjectURL(blobUrl));
                return image;
            } else if(data.ok)
                throw new Error('[Avatar] Not an image!')
            else
                throw new Error('[Avatar] HTTP '+data.status.toString()+data.statusText);
        }));
    }
    return await Promise.any(promises).finally(() => controler.abort());
}