[研究]Fortify SCA : Insecure Randomness (不安全的亂數) 之解決(二)
2025-02-05
環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19
********************************************************************************
[研究]Fortify SCA : Insecure Randomness 之解決
https://shaurong.blogspot.com/2022/08/fortify-sca-insecure-randomness.html
[研究]Fortify SCA : Insecure Randomness (不安全的亂數) 之解決(二)
https://shaurong.blogspot.com/2025/02/fortify-sca-insecure-randomness.html
********************************************************************************
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> </form> </body> </html> |
Default.aspx.cs
using System; using System.Security.Cryptography; namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Fortify SCA 報告有 "Insecure Randomness" 問題 Random rand = new Random(Guid.NewGuid().GetHashCode()); string newPassword = "Pwd" + rand.Next(10000000, 99999999).ToString() + "$"; // max : 2147483647; // 通過 Fortify SCA 的 "Insecure Randomness" 檢查 string newPassword2 = GenerateSecurePassword(); } public static string GenerateSecurePassword() { int randomNumber = GetSecureRandomNumber(10000000, 99999999); return "Pwd" + randomNumber.ToString() + "$"; } private static int GetSecureRandomNumber(int min, int max) { if (min >= max) throw new ArgumentException("min must be less than max"); using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { byte[] bytes = new byte[4]; // 生成 4-byte 的隨機數 rng.GetBytes(bytes); int value = BitConverter.ToInt32(bytes, 0) & int.MaxValue; // 轉為正整數 return (value % (max - min + 1)) + min; } } } } |
(完)
相關
沒有留言:
張貼留言