Math.random() 을 통한 난수 만들기
Math.random() 함수를 이용하면 0이상 1 미만의 난수를 출력한다.
따라서 다음과 같이 난수를 뽑아낼 수 있다.
// 0 이상 1 미만의 난수 구하기
Math.random();
// 두 값 사이의 난수 구하기
Math.random() * (max - min) + min;
// 두 값 사이의 정수 난수 구하기
Math.floor(Math.random() * (max - min)) + min;
window.crypto.getRandomValues()를 통한 난수 만들기
Math.random()은 암호학적으로 안전한 난수를 제공하지는 않다.
따라서 보안과 관련된 곳에는 window.crypto.getRandomValues()를 사용하자.
self.crypto.getRandomvalues() 를 사용하면 매개변수로 제공된 배열의 값들을 암호학에서의 '무작위' 값으로 바꿔준다.
입력받을 수 있는 배열의 타입은 다음과 같다.
Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, BigUint64Array
const randomArr = new Uint32Array(6);
console.log(randomArr);
self.crypto.getRandomValues(randomArr);
console.log("무작위로 생성된 6개의 값 = " + randomArr);
const lotto = randomArr.map(el => el % 45 + 1);
console.log("로또 번호 = " + lotto);
getRandomValues는 안전하지 않은 연결에서 사용할 수 있는 유일한 Crypto 인터페이스 멤버라는 특징이 있다.
안전하지 않은 연결에서도 getRandomValues를 실행할 수 있기 때문에 암호화 키를 생성하는 등의 사용에는 조심해야 한다.
'언어 > Javascript & Typescript' 카테고리의 다른 글
함수의 파라미터를 리터럴로 받는 방법과 응용 (0) | 2023.08.22 |
---|---|
레거시 프론트엔드 프로젝트 점진적으로 개선하기 (0) | 2023.04.13 |
CDN에서 받아온 js에 타입 넣기 (0) | 2023.04.13 |
배열 안의 원소들을 파라미터로 하는 Promise 체이닝하기 (0) | 2023.04.13 |
현재 날짜를 원하는 포맷으로 출력하기 (2) | 2022.06.21 |