고유 식별자를 생성하는 uuid와 crypto.randomUUID

고유한 id가 필요할 땐 항상 uuid나 Date.now를 사용했었는데 다른 사람의 코드를 보고 crypto.randomUUID라는 것을 알게되었다.

둘의 사용법과 특징에 대해 정리해보자

 

uuid

uuid란 범용적으로 사용되는 고유 식별자이다. (UUIDs, Universally Unique Identifier)

 

우리가 많이 쓰는 uuid라이브러리는 UUID 정의와 같은 이름의 라이브러리이다.

uuid는 다양한 버전이 있는데, 보통 무작위로 생성되는 Verson 4를 사용한다.

import { v4 as uuidv4 } from 'uuid';
console.log(uuidv4()); // '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

 

crypto.randomUUID

crypto.randomUUID는 ECMAScript 표준의 일부로, 브러우저와 Node.js의 내장 crypto 모듈을 사용하여 생성된다.

암호학적으로 안전한 난수 생성기(CSPRNG)를 사용하여 UUID를 생성하므로, 안전성이 더 높다.

 

별도의 라이브러리 설치 필요없이 crypto.randomUUID() 메소드를 사용하면 uuid를 생성할 수 있다!

console.log(crypto.randomUUID()); // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'

 

결론

둘 다 난수id를 생성하는 방법이다.

보안의 중요도와 외부 라이브러리 유무로 결정하면 된다.

 

- UUID는 일반적인 식별자를 생성하는 데 적합하다. (데이터베이스의 레코드 식별자)

- crypto.randomUUID는 보안이 중요한 식별자를 생성하는 데 사용된다. (인증 토큰, 세션 키, 무작위 비밀번호)

 

uuid

RFC4122 (v1, v4, and v5) UUIDs. Latest version: 9.0.1, last published: 9 months ago. Start using uuid in your project by running `npm i uuid`. There are 62403 other projects in the npm registry using uuid.

www.npmjs.com

 

Crypto: randomUUID() method - Web APIs | MDN

The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.

developer.mozilla.org