Octoping의 블로그

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를 실행할 수 있기 때문에 암호화 키를 생성하는 등의 사용에는 조심해야 한다.

profile

Octoping의 블로그

@Octoping

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!