Skip to content

Cryptocoinjs/sha256

WARNING

DEPRECATED 되었다.

JavaScript component to compute the SHA256 of strings or bytes.

덧붙여, 여기에 사용하는 crypto 라이브러리도 Deprecated 되었다.

TypeScript Implementation

import {createHash} from 'crypto';

export interface Sha256Options {
  asBytes?: boolean;
  asString?: boolean;
}

export function sha256(
  message: string | Buffer | number[],
  options?: Sha256Options,
): string | number[] {
  const sha256sum = createHash('sha256');
  if (Buffer.isBuffer(message)) {
    sha256sum.update(message);
  } else if (Array.isArray(message)) {
    sha256sum.update(Buffer.alloc(message.length));
    message.map(x => sha256sum.push(x));
  } else {
    sha256sum.update(Buffer.alloc(message.length, message, 'binary'));
  }
  const buffer = sha256sum.digest();

  if (options && options.asBytes) {
    const result = [];
    for (let i = 0; i < buffer.length; i++) {
      result.push(buffer[i]);
    }
    return result;
  } else if (options && options.asString) {
    return buffer.toString('binary');
  } else {
    return buffer.toString('hex');
  }
}

export function sha256hex(message: string): string {
  const sha256sum = createHash('sha256');
  sha256sum.update(Buffer.alloc(message.length, message, 'binary'));
  const buffer = sha256sum.digest();
  return buffer.toString('hex');
}

See also

Favorite site