Modulo Bias로 인한 안전하지 않은 암호화 알고리즘
Biased Cryptographic Randomness (Modulo Bias)
Last updated
Biased Cryptographic Randomness (Modulo Bias)
Last updated
// 비준수: 모듈로 바이어스로 bias된 6자리 코드 생성
const crypto = require("crypto");
function generateOtpBad() {
// 0..999999 범위로 줄일 때 % 사용 -> bias 발생
const raw = crypto.randomBytes(4).readUInt32BE();
const n = raw % 1_000_000; // 취약: 균등하지 않음
return n.toString().padStart(6, "0");
}
console.log(generateOtpBad());// 준수: bias 제거 API 또는 거절 표본추출 사용
const crypto = require("crypto");
// 1) 권장: Node.js 내장 bias 제거 API
function generateOtpSafe() {
const n = crypto.randomInt(0, 1_000_000); // 상한 미포함, 균등 분포 보장
return n.toString().padStart(6, "0");
}
// 2) 대안: 거절 표본추출(rejection sampling)
function generateOtpSafeLegacy() {
const bound = 1_000_000;
const max = Math.floor(0x1_0000_0000 / bound) * bound; // 2^32에서 bound로 나누어떨어지는 최대값
while (true) {
const r = crypto.randomBytes(4).readUInt32BE();
if (r < max) {
return (r % bound).toString().padStart(6, "0");
}
}
}
console.log(generateOtpSafe());