以下は、Math.random()関数を使用してランダムなバイト列を生成する方法です。これは、完全な暗号学的安全性を提供するものではなく、偽の乱数の生成に関する問題があるため、セキュリティ要件が厳しい場合には使用しないでください。
// バイト列を生成する関数 function generateRandomBytes(length) { const bytes = new Uint8Array(length); for (let i = 0; i < length; i++) { bytes[i] = Math.floor(Math.random() * 256); } return bytes; } // バイト列をファイルに書き込む関数 function writeBytesToFile(bytes) { const blob = new Blob([bytes], { type: "application/octet-stream" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.setAttribute("href", url); link.setAttribute("download", "random_bytes.bin"); link.style.display = "none"; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); } // 使用例 const bytes = generateRandomBytes(1024); // 1024バイトのランダムなバイト列を生成 writeBytesToFile(bytes); // ファイルに書き込む
このコードでは、generateRandomBytes()関数を使用して、指定された長さのランダムなバイト列を生成し、そのバイト列をBlobオブジェクトに変換して、それをファイルに書き込むためのdownload属性が設定されたa要素を作成し、それをクリックしてダウンロードすることで、ランダムなバイト列をファイルに書き込んでいます。