Skip to content

NOTE

Bun 은 아래에 문서화된 Bun 네이티브 API 외에도 [`node:crypto`](https://nodejs.org/api/crypto.html) 의 `createHash` 및 `createHmac` 함수를 구현합니다.

Bun.password

Bun.password 는 다양한 암호화 보안 알고리즘을 사용하여 비밀번호를 해싱하고 검증하는 유틸리티 함수 모음입니다.

ts
const password = "super-secure-pa$$word";

const hash = await Bun.password.hash(password);
// => $argon2id$v=19$m=65536,t=2,p=1$tFq+9AVr1bfPxQdh6E8DQRhEXg/M/SqYCNu6gVdRRNs$GzJ8PuBi+K+BVojzPfS5mjnC8OpLGtv8KJqF99eP6a4

const isMatch = await Bun.password.verify(password, hash);
// => true

Bun.password.hash 의 두 번째 인수는 해싱 알고리즘을 선택하고 구성할 수 있는 params 객체를 받습니다.

ts
const password = "super-secure-pa$$word";

// argon2 사용 (기본값)
const argonHash = await Bun.password.hash(password, {
  algorithm: "argon2id", // "argon2id" | "argon2i" | "argon2d"
  memoryCost: 4, // 킬로바이트 단위의 메모리 사용량
  timeCost: 3, // 반복 횟수
});

// bcrypt 사용
const bcryptHash = await Bun.password.hash(password, {
  algorithm: "bcrypt",
  cost: 4, // 4-31 사이의 숫자
});

해시를 생성하는 데 사용된 알고리즘은 해시 자체에 저장됩니다. bcrypt 를 사용할 때 반환된 해시는 대부분의 기존 bcrypt 구현과의 호환성을 위해 Modular Crypt Format 으로 인코딩됩니다. argon2 의 경우 결과는 더 새로운 PHC format 으로 인코딩됩니다.

verify 함수는 입력 해시를 기반으로 알고리즘을 자동으로 감지하고 올바른 검증 방법을 사용합니다. PHC 또는 MCF 인코딩 해시 모두에서 알고리즘을 올바르게 추론할 수 있습니다.

ts
const password = "super-secure-pa$$word";

const hash = await Bun.password.hash(password, {
  /* config */
});

const isMatch = await Bun.password.verify(password, hash);
// => true

모든 함수의 동기 버전도 사용할 수 있습니다. 이러한 함수는 계산 비용이 많이 들기 때문에 블로킹 API 를 사용하면 애플리케이션 성능이 저하될 수 있다는 점을 명심하세요.

ts
const password = "super-secure-pa$$word";

const hash = Bun.password.hashSync(password, {
  /* config */
});

const isMatch = Bun.password.verifySync(password, hash);
// => true

Salt

Bun.password.hash 를 사용하면 salt 가 자동으로 생성되어 해시에 포함됩니다.

bcrypt - Modular Crypt Format

다음은 Modular Crypt Format 해시 (bcrypt 사용) 입니다.

입력:

ts
await Bun.password.hash("hello", {
  algorithm: "bcrypt",
});

출력:

sh
$2b$10$Lyj9kHYZtiyfxh2G60TEfeqs7xkkGiEFFDi3iJGc50ZG/XJ1sxIFi;

형식은 다음으로 구성됩니다.

  • bcrypt: $2b
  • rounds: $10 - 라운드 (실제 라운드 수의 log10)
  • salt: $Lyj9kHYZtiyfxh2G60TEfeqs7xkkGiEFFDi3iJGc50ZG/XJ1sxIFi
  • hash: $GzJ8PuBi+K+BVojzPfS5mjnC8OpLGtv8KJqF99eP6a4

기본적으로 bcrypt 라이브러리는 72 바이트보다 긴 비밀번호를 잘라냅니다. Bun 에서 72 바이트보다 긴 비밀번호를 Bun.password.hash 에 전달하고 bcrypt 알고리즘을 사용하면 비밀번호가 bcrypt 에 전달되기 전에 SHA-512 를 통해 해싱됩니다.

ts
await Bun.password.hash("hello".repeat(100), {
  algorithm: "bcrypt",
});

따라서 500 바이트 비밀번호를 72 바이트로 조용히 잘라서 bcrypt 에 보내는 대신 Bun 은 SHA-512 를 사용하여 비밀번호를 해싱하고 해싱된 비밀번호를 bcrypt 에 보냅니다 (72 바이트를 초과하는 경우에만). 이는 더 안전한 기본 동작입니다.

argon2 - PHC format

다음은 PHC format 해시 (argon2 사용) 입니다.

입력:

ts
await Bun.password.hash("hello", {
  algorithm: "argon2id",
});

출력:

sh
$argon2id$v=19$m=65536,t=2,p=1$xXnlSvPh4ym5KYmxKAuuHVlDvy2QGHBNuI6bJJrRDOs$2YY6M48XmHn+s5NoBaL+ficzXajq2Yj8wut3r0vnrwI

형식은 다음으로 구성됩니다.

  • algorithm: $argon2id
  • version: $v=19
  • memory cost: 65536
  • iterations: t=2
  • parallelism: p=1
  • salt: $xXnlSvPh4ym5KYmxKAuuHVlDvy2QGHBNuI6bJJrRDOs
  • hash: $2YY6M48XmHn+s5NoBaL+ficzXajq2Yj8wut3r0vnrwI

Bun.hash

Bun.hash비암호화 해싱을 위한 유틸리티 모음입니다. 비암호화 해싱 알고리즘은 충돌 저항성이나 보안보다 계산 속도를 최적화합니다.

표준 Bun.hash 함수는 Wyhash 를 사용하여 임의 크기의 입력에서 64 비트 해시를 생성합니다.

ts
Bun.hash("some data here");
// 11562320457524636935n

입력은 문자열, TypedArray, DataView, ArrayBuffer 또는 SharedArrayBuffer 가 될 수 있습니다.

ts
const arr = new Uint8Array([1, 2, 3, 4]);

Bun.hash("some data here");
Bun.hash(arr);
Bun.hash(arr.buffer);
Bun.hash(new DataView(arr.buffer));

선택적으로 정수 시드를 두 번째 매개변수로 지정할 수 있습니다. 64 비트 해시의 경우 정밀도 손실을 피하기 위해 Number.MAX_SAFE_INTEGER 보다 큰 시드는 BigInt 로 제공해야 합니다.

ts
Bun.hash("some data here", 1234);
// 15724820720172937558n

Bun.hash 의 속성으로 추가 해싱 알고리즘을 사용할 수 있습니다. API 는 각각 동일하며 32 비트 해시의 경우 number 에서 64 비트 해시의 경우 bigint 로 반환 타입만 변경됩니다.

ts
Bun.hash.wyhash("data", 1234); // Bun.hash() 와 동일
Bun.hash.crc32("data", 1234);
Bun.hash.adler32("data", 1234);
Bun.hash.cityHash32("data", 1234);
Bun.hash.cityHash64("data", 1234);
Bun.hash.xxHash32("data", 1234);
Bun.hash.xxHash64("data", 1234);
Bun.hash.xxHash3("data", 1234);
Bun.hash.murmur32v3("data", 1234);
Bun.hash.murmur32v2("data", 1234);
Bun.hash.murmur64v2("data", 1234);
Bun.hash.rapidhash("data", 1234);

Bun.CryptoHasher

Bun.CryptoHasher 는 다양한 암호화 해시 알고리즘을 사용하여 문자열 또는 이진 데이터의 해시를 점진적으로 계산할 수 있는 범용 유틸리티 클래스입니다. 다음 알고리즘이 지원됩니다.

  • "blake2b256"
  • "blake2b512"
  • "md4"
  • "md5"
  • "ripemd160"
  • "sha1"
  • "sha224"
  • "sha256"
  • "sha384"
  • "sha512"
  • "sha512-224"
  • "sha512-256"
  • "sha3-224"
  • "sha3-256"
  • "sha3-384"
  • "sha3-512"
  • "shake128"
  • "shake256"
ts
const hasher = new Bun.CryptoHasher("sha256");
hasher.update("hello world");
hasher.digest();
// Uint8Array(32) [ <byte>, <byte>, ... ]

초기화되면 .update() 를 사용하여 해셔에 데이터를 점진적으로 공급할 수 있습니다. 이 메서드는 string, TypedArrayArrayBuffer 를 받습니다.

ts
const hasher = new Bun.CryptoHasher("sha256");

hasher.update("hello world");
hasher.update(new Uint8Array([1, 2, 3]));
hasher.update(new ArrayBuffer(10));

string 이 전달되면 선택적 두 번째 매개변수를 사용하여 인코딩을 지정할 수 있습니다 (기본값 'utf-8'). 다음 인코딩이 지원됩니다.

카테고리인코딩
이진 인코딩"base64" "base64url" "hex" "binary"
문자 인코딩"utf8" "utf-8" "utf16le" "latin1"
레거시 문자 인코딩"ascii" "binary" "ucs2" "ucs-2"
ts
hasher.update("hello world"); // 기본값 utf8
hasher.update("hello world", "hex");
hasher.update("hello world", "base64");
hasher.update("hello world", "latin1");

데이터가 해셔에 입력된 후 .digest() 를 사용하여 최종 해시를 계산할 수 있습니다. 기본적으로 이 메서드는 해시를 포함하는 Uint8Array 를 반환합니다.

ts
const hasher = new Bun.CryptoHasher("sha256");
hasher.update("hello world");

hasher.digest();
// => Uint8Array(32) [ 185, 77, 39, 185, 147, ... ]

.digest() 메서드는 선택적으로 해시를 문자열로 반환할 수 있습니다. 이렇게 하려면 인코딩을 지정하세요.

ts
hasher.digest("base64");
// => "uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="

hasher.digest("hex");
// => "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"

또는 이 메서드는 해시를 기존 TypedArray 인스턴스에 쓸 수 있습니다. 이는 일부 성능에 민감한 애플리케이션에서 필요할 수 있습니다.

ts
const arr = new Uint8Array(32);

hasher.digest(arr);

console.log(arr);
// => Uint8Array(32) [ 185, 77, 39, 185, 147, ... ]

Bun.CryptoHasher 의 HMAC

Bun.CryptoHasher 를 사용하여 HMAC 다이제스트를 계산할 수 있습니다. 이렇게 하려면 생성자에 키를 전달하세요.

ts
const hasher = new Bun.CryptoHasher("sha256", "secret-key");
hasher.update("hello world");
console.log(hasher.digest("hex"));
// => "095d5a21fe6d0646db223fdf3de6436bb8dfb2fab0b51677ecf6441fcf5f2a67"

HMAC 을 사용할 때는 더 제한된 알고리즘 세트만 지원됩니다.

  • "blake2b512"
  • "md5"
  • "sha1"
  • "sha224"
  • "sha256"
  • "sha384"
  • "sha512-224"
  • "sha512-256"
  • "sha512"

비 HMAC Bun.CryptoHasher 와 달리 HMAC Bun.CryptoHasher 인스턴스는 .digest() 가 호출된 후 재설정되지 않으며 동일한 인스턴스를 다시 사용하려고 하면 오류가 발생합니다.

.copy().update() 와 같은 다른 메서드는 지원되지만 (.digest() 이전인 경우에만) .digest() 와 같이 해셔를 최종화하는 메서드는 지원되지 않습니다.

ts
const hasher = new Bun.CryptoHasher("sha256", "secret-key");
hasher.update("hello world");

const copy = hasher.copy();
copy.update("!");
console.log(copy.digest("hex"));
// => "3840176c3d8923f59ac402b7550404b28ab11cb0ef1fa199130a5c37864b5497"

console.log(hasher.digest("hex"));
// => "095d5a21fe6d0646db223fdf3de6436bb8dfb2fab0b51677ecf6441fcf5f2a67"

Bun by www.bunjs.com.cn 편집