# C# SHA-256 從中間到外一步一步解決 ```csharp= using System.Security.Cryptography; //這東西記得加在頂端 string HashPassword = BitConverter.ToString(SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(txtPassword.Text))).Replace("-",""); ``` >恐怖如斯 學長加密程式碼 > 以下為拆解與解釋~~ ## 步驟 [TOC] ## 1. txtPassword.Text TextBox使用者輸入內容 ## 2. 轉乘byte 字串轉成位元組陣列(byte[]),因為 SHA-256 只能處理二進位資料,不能直接處理字串。 ```csharp= byte[] passwordBytes = Encoding.UTF8.GetBytes(txtPassword.Text); 輸入:"mypassword123" 輸出:[109, 121, 112, 97, 115, 115, 119, 111, 114, 100, 49, 50, 51] ``` ### Encoding 字串 → 位元組(byte[]) ```csharp= Encoding.UTF8.GetBytes(資料) ``` 位元組(byte[]) → 字串 ```csharp= Encoding.UTF8.GetString(資料); ``` ## 3. SHA256計算 SHA256.Create() 建立一個 SHA-256 加密物件,然後 .ComputeHash(...) 計算密碼的 SHA-256 雜湊值。 ```csharp= byte[] hashBytes = SHA256.Create().ComputeHash(passwordBytes); 輸出: [240, 14, 31, 187, 204, 220, 201, 211, 8, 77, 210, 158, 52, 98, 27, 236, 245, 209, 83, 71, 18, 122, 1, 157, 97, 154, 79, 123, 236, 240, 33, 145] ``` ## 4. 十六進位字串 這會把 byte 陣列 轉換成 十六進位字串,但會有 - 分隔: ```csharp= string hexHash = BitConverter.ToString(hashBytes); 輸出: "F0-0E-1F-BB-CC-DC-C9-D3-08-4D-D2-9E-34-62-1B-EC-F5-D1-53-47-12-7A-01-9D-61-9A-4F-7B-EC-F0-21-91" ``` ### BitConverter 將 byte[] 轉換成十六進位字串 ```csharp= BitConverter.ToString(bytes) ``` 將數值轉換成 byte[] ```csharp= byte[] bytes = BitConverter.GetBytes(number); ``` ## 5. Replace 去掉- 每個 byte 之間插入 -,所以 .Replace("-", "") 把 - 刪掉 ```csharp= string finalHash = hexHash.Replace("-", ""); 輸出: "F00E1FBBCDCCC9D3084DD29E34621BECF5D15347127A019D619A4F7BECF02191" ```