ชุมชนคนรักภาษาเบสิค - Visual Basic Community

 ลืมรหัสผ่าน
 ลงทะเบียน
ค้นหา
ดู: 261|ตอบกลับ: 0

[VB.NET] โค้ดการเก็บข้อมูลรหัสผ่านด้วยการเข้ารหัสแบบ Long Binary (CRUD)

[คัดลอกลิงก์]

319

กระทู้

511

โพสต์

6436

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
6436






โค้ดโปรแกรมการเก็บข้อมูลรหัสผ่านด้วยการเข้ารหัสแบบ Long Binary หรือชนิดข้อมูลแบบ OLE Object สำหรับ MS Access โดยจะใช้การเข้ารหัสแบบ Rijndael (AES) Algorithm ... สำหรับการจัดการกับฐานข้อมูลเรียกว่า Parameterized Query หรือการใช้คำสั่งที่มีการส่งผ่านค่าไปยังตัวแปรพารามิเตอร์ (Parameterization) โดยตรงในการเขียน SQL Query ซึ่งเป็นวิธีที่ช่วยป้องกันการโจมตีแบบ SQL Injection ได้ดี ... โค้ดชุดนี้แอดมินเพิ่มความสวยงามด้วยการใช้ MaterialSkin เข้ามาช่วย ...

มาดูโค้ดฉบับเต็มจากฟอร์มหลัก (frmPassCodeBook.vb)
  1. Imports System.Data.OleDb
  2. Imports MaterialSkin

  3. Public Class frmPassCodeBook
  4.     '// Add new or Edit data.
  5.     Dim blnNewData As Boolean = False   '// Edit mode.
  6.     Dim PK As Long  '// เก็บค่า Primary Key ทั้งการเพิ่มและแก้ไขข้อมูล

  7.     ' / ------------------------------------------------------------------------------------------------
  8.     ' / S T A R T ... H E R E
  9.     ' / ------------------------------------------------------------------------------------------------
  10.     Private Sub frmPassCodeBook_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  11.         '// Initialize MaterialSkin .Net Framework 4.0
  12.         Dim SkinManager As MaterialSkinManager = MaterialSkinManager.Instance
  13.         SkinManager.AddFormToManage(Me)
  14.         SkinManager.Theme = MaterialSkinManager.Themes.LIGHT
  15.         '//SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.Amber500, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE)
  16.         SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.Green600, Primary.Green700, Primary.Green200, Accent.Red100, TextShade.WHITE)

  17.         '// ตั้งค่าขนาดของฟอร์มแบบ Run Time
  18.         Me.Size = New Size(1020, 720)
  19.         '// คำนวณตำแหน่งที่กึ่งกลางของหน้าจอ
  20.         Me.Location = New Point((Screen.PrimaryScreen.WorkingArea.Width - Me.Width) \ 2,
  21.         (Screen.PrimaryScreen.WorkingArea.Height - Me.Height) \ 2)

  22.         '// โหลดข้อมูลลงตารางกริด
  23.         dgvData.DataSource = RetrieveData()
  24.         Call SetupDataGridView(dgvData)
  25.         lblRecordCount.Text = "[Total: " & dgvData.Rows.Count & " Record.]"
  26.         '// เริ่มโหมดว่างเปล่าเพื่อทำรายการใหม่ หรือเลือกรายการขึ้นมาแก้ไข
  27.         Call NewMode()
  28.     End Sub

  29.     ' / ------------------------------------------------------------------------------------------------
  30.     ' / Add New Mode
  31.     ' / ------------------------------------------------------------------------------------------------
  32.     Private Sub NewMode()
  33.         '// Clear all TextBox.
  34.         For Each c In GroupBox1.Controls
  35.             If TypeOf c Is TextBox Then
  36.                 DirectCast(c, TextBox).Clear()
  37.                 DirectCast(c, TextBox).Enabled = False
  38.             End If
  39.             If TypeOf c Is DateTimePicker Then DirectCast(c, DateTimePicker).Enabled = False
  40.         Next
  41.         itemAdd.Enabled = True
  42.         itemSave.Enabled = False
  43.         itemDelete.Enabled = True
  44.         itemDelete.Text = "DELETE DATA"
  45.         itemExit.Enabled = True
  46.     End Sub

  47.     ' / ------------------------------------------------------------------------------------------------
  48.     ' / Edit Data Mode
  49.     ' / ------------------------------------------------------------------------------------------------
  50.     Private Sub EditMode()
  51.         '// Clear all TextBox
  52.         For Each c In GroupBox1.Controls
  53.             If TypeOf c Is TextBox Then
  54.                 DirectCast(c, TextBox).Enabled = True
  55.             End If
  56.             If TypeOf c Is DateTimePicker Then DirectCast(c, DateTimePicker).Enabled = True
  57.         Next
  58.         itemAdd.Enabled = False
  59.         itemSave.Enabled = True
  60.         itemDelete.Enabled = True
  61.         itemDelete.Text = "CANCEL"
  62.     End Sub

  63.     ' / ------------------------------------------------------------------------------------------------
  64.     ' / Add new data.
  65.     ' / ------------------------------------------------------------------------------------------------
  66.     Private Sub itemAdd_Click(sender As System.Object, e As System.EventArgs) Handles itemAdd.Click
  67.         blnNewData = True
  68.         Call EditMode()
  69.         txtUrl.Focus()
  70.     End Sub

  71.     ' / ------------------------------------------------------------------------------------------------
  72.     ' / Save Data.
  73.     ' / ------------------------------------------------------------------------------------------------
  74.     Private Sub itemSave_Click(sender As System.Object, e As System.EventArgs) Handles itemSave.Click
  75.         If txtUrl.Text = "" Or txtUrl.Text.Trim.Length = 0 Then
  76.             MessageBox.Show("Please enter Url or Name.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  77.             txtUrl.Focus()
  78.             Return
  79.         End If
  80.         If txtLogin.Text = "" Or txtLogin.Text.Trim.Length = 0 Then
  81.             MessageBox.Show("Please enter Login Name.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  82.             txtLogin.Focus()
  83.             Return
  84.         End If
  85.         If txtPassword.Text = "" Or txtPassword.Text.Trim.Length = 0 Then
  86.             MessageBox.Show("Please enter Password.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  87.             txtPassword.Focus()
  88.             Return
  89.         End If
  90.         '// Details Class in modDataBase.vb
  91.         '// กำหนดค่าให้กับตัวแปร เพื่อส่งออกไปทำการบันทึกข้อมูล
  92.         Dim result As New Details
  93.         With result
  94.             .PK = PK
  95.             .Login = txtLogin.Text
  96.             .Encrypted = txtPassword.Text
  97.             .Url = txtUrl.Text
  98.             .Email = txtEmail.Text
  99.             .Phone = txtPhone.Text
  100.             .DateModified = dtpDateModified.Value
  101.         End With
  102.         '// blnNewData = True คือการเพิ่มข้อมูล
  103.         If blnNewData Then
  104.             '// หาค่า Primary Key จาก SetupNewPK อยู่ใน modDataBase.vb
  105.             result.PK = SetupNewPK("SELECT MAX(UserData.PK) AS MaxPK FROM UserData")
  106.             '// ส่งค่า blnNewData = True บอกว่าเป็นการเพิ่มข้อมูลใหม่ และค่าของ Control บนฟอร์มไปด้วย
  107.             Call SaveData(blnNewData, result)
  108.             Call NewMode()

  109.             '// การแก้ไขข้อมูล
  110.         Else
  111.             'blnNewData = False
  112.             '// ส่งค่า blnNewData = False บอกว่าเป็นการเพิ่มข้อมูลใหม่ และส่งค่าของ Control บนฟอร์มไปด้วย
  113.             Call SaveData(blnNewData, result)
  114.             Call NewMode()
  115.         End If
  116.         '// Refresh data.
  117.         Call btnRefresh_Click(sender, e)
  118.     End Sub

  119.     ' / ------------------------------------------------------------------------------------------------
  120.     ' / DELETE DATA
  121.     ' / ------------------------------------------------------------------------------------------------
  122.     Private Sub itemDelete_Click(sender As System.Object, e As System.EventArgs) Handles itemDelete.Click
  123.         If itemDelete.Text = "DELETE DATA" Then
  124.             '// เช็คก่อนว่ามีรายแถวอยู่หรือไม่ หรือมีการคลิ๊กเลือกแถวรายการหรือเปล่า
  125.             If dgvData.RowCount = 0 Or dgvData.CurrentRow Is Nothing Then Exit Sub
  126.             Dim Url As String = dgvData.Item(1, dgvData.CurrentRow.Index).Value
  127.             '// ถามยืนยันการลบข้อมูล
  128.             Dim Result As Byte = MessageBox.Show("Are you sure you want to delete the data?" & vbCrLf & "URL/Name: " & Url, "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
  129.             If Result = DialogResult.Yes Then
  130.                 '// Receive Primary Key value to confirm the deletion.
  131.                 PK = dgvData.Item(0, dgvData.CurrentRow.Index).Value
  132.                 '// ลบข้อมูล (modDataBase.vb)
  133.                 Call DeleteData(PK)
  134.                 '// ทำการแสดงผลรายการใหม่
  135.                 Call btnRefresh_Click(sender, e)
  136.                 Call NewMode()
  137.             End If
  138.         ElseIf itemDelete.Text = "CANCEL" Then
  139.             '// เริ่มโหมดว่างเปล่าเพื่อทำรายการใหม่ หรือเลือกรายการขึ้นมาแก้ไข
  140.             Call NewMode()
  141.         End If
  142.     End Sub

  143.     ' / ------------------------------------------------------------------------------------------------
  144.     ' / แสดงผลข้อมูลทั้งหมด
  145.     ' / ------------------------------------------------------------------------------------------------
  146.     Private Sub btnRefresh_Click(sender As System.Object, e As System.EventArgs) Handles btnRefresh.Click
  147.         dgvData.DataSource = RetrieveData()
  148.         lblRecordCount.Text = "[Total: " & dgvData.Rows.Count & " Record.]"
  149.     End Sub

  150.     ' / ------------------------------------------------------------------------------------------------
  151.     ' / การค้นหาข้อมูล
  152.     ' / ------------------------------------------------------------------------------------------------
  153.     Private Sub txtSearch_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtSearch.KeyPress
  154.         '// Undesirable characters for the database ex.  ', * or %
  155.         txtSearch.Text = txtSearch.Text.Replace("'", "").Replace("*", "").Replace("%", "")
  156.         If Trim(txtSearch.Text) = "" Or Len(Trim(txtSearch.Text)) = 0 Then Exit Sub
  157.         '// RetrieveData(True) It means searching for information.
  158.         If e.KeyChar = Chr(13) Then '// Press Enter
  159.             '// No beep.
  160.             e.Handled = True
  161.             '//
  162.             dgvData.DataSource = RetrieveData(True, txtSearch.Text)
  163.             lblRecordCount.Text = "[Total: " & dgvData.Rows.Count & " Record.]"
  164.             txtSearch.Clear()
  165.         End If
  166.     End Sub

  167.     ' / ------------------------------------------------------------------------------------------------
  168.     ' / ดับเบิ้ลคิ๊กเมาส์ในตารางกริด จากนั้นค้นหา Primary Key เพื่อนำข้อมูลไปแสดงผล
  169.     ' / ------------------------------------------------------------------------------------------------
  170.     Private Sub dgvData_CellDoubleClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvData.CellDoubleClick
  171.         If e.RowIndex >= 0 Then
  172.             '// เก็บค่านี้เอาไว้เพื่อใช้ในการอ้างอิงตอนที่ทำการอัพเดตข้อมูล
  173.             PK = CInt(dgvData.Rows(e.RowIndex).Cells("PK").Value)
  174.             blnNewData = False    '// กำหนดให้เป็นการแก้ไขข้อมูล
  175.             '// ส่งค่า PK เพื่อเป็นคีย์ไปทำการค้นข้อมูล แล้วคืนข้อมูลกลับมาในรูปแบบ Class
  176.             '// Class Details อยู่ใน modDataBase.vb
  177.             Dim result As Details = RetrieveDetails(PK)
  178.             txtLogin.Text = result.Login
  179.             txtPassword.Text = result.Encrypted
  180.             txtUrl.Text = result.Url
  181.             txtEmail.Text = result.Email
  182.             txtPhone.Text = result.Phone
  183.             dtpDateModified.Text = Format(result.DateModified, "dd/MM/yyyy")
  184.             '// โหมดในการแก้ไข
  185.             Call EditMode()
  186.             txtUrl.Focus()
  187.         End If
  188.     End Sub

  189.     '// Function to handle the KeyPress event for TextBox controls.
  190.     Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtLogin.KeyPress, txtPassword.KeyPress, txtUrl.KeyPress, txtEmail.KeyPress, txtPhone.KeyPress
  191.         If e.KeyChar = ChrW(Keys.Enter) Then
  192.             e.Handled = True '// Prevent the Enter key from adding a new line in the TextBox.
  193.             SendKeys.Send("{TAB}") '// Send the TAB key to move to the next control.
  194.         End If
  195.     End Sub

  196.     Private Sub dtpDateModified_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dtpDateModified.KeyDown
  197.         If e.KeyCode = Keys.Enter Then
  198.             e.Handled = True
  199.             SendKeys.Send("{TAB}")
  200.         End If
  201.     End Sub

  202.     Private Sub frmPassCodeBook_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  203.         Me.Dispose()
  204.         GC.SuppressFinalize(Me)
  205.         End
  206.     End Sub

  207.     Private Sub itemExit_Click(sender As System.Object, e As System.EventArgs) Handles itemExit.Click
  208.         Me.Close()
  209.     End Sub

  210. End Class
คัดลอกไปที่คลิปบอร์ด

โค้ดในส่วนของการจัดการฐานข้อมูล (modDataBase.vb)
  1. Imports System.Data.OleDb

  2. Module modDataBase
  3.     Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & MyPath(Application.StartupPath) & "\PassCodeBook.accdb;"

  4.     ' / ------------------------------------------------------------------------------------------------
  5.     '// การใช้ Key และ IV
  6.     '// Key ควรมีขนาด 16, 24 หรือ 32 bytes เพื่อความปลอดภัย
  7.     '// IV (Initialization Vector) ควรมีขนาด 16 bytes สำหรับการเข้ารหัส AES
  8.     Dim key As String = "1234567890123456" '// Key 16 bytes
  9.     Dim iv As String = "6543210987654321"  '// IV 16 bytes
  10.     ' / ------------------------------------------------------------------------------------------------

  11.     Public Class Details
  12.         '// Auto Implemented Properties for Data Fields.
  13.         Public Property PK As Integer
  14.         Public Property Login As String
  15.         Public Property Encrypted As String
  16.         Public Property Url As String
  17.         Public Property Email As String
  18.         Public Property Phone As String
  19.         Public Property DateModified As Date
  20.     End Class

  21.     ' / ------------------------------------------------------------------------------------------------
  22.     '// Save data to MS Access database.
  23.     ' / ------------------------------------------------------------------------------------------------
  24.     Sub SaveData(newdata As Boolean, details As Details)
  25.         Dim sql As String
  26.         Try
  27.             Using Conn As New OleDbConnection(ConnString)
  28.                 Conn.Open()
  29.                 '// การเพิ่มข้อมูลใหม่
  30.                 If newdata Then
  31.                     sql = "INSERT INTO UserData (PK, url, Login, Encrypted, email, phone, DateModified) VALUES (@PK, @Url, @Email, @Phone, @Login, @Encrypted, @DateModified)"

  32.                     '// การแก้ไข
  33.                 Else
  34.                     '// Update the record if it exists.
  35.                     sql = "UPDATE UserData SET PK = @PK, url = @Url, Login = @Login, Encrypted = @Encrypted, email = @Email, Phone = @Phone, DateModified = @DateModified WHERE PK = @PK"
  36.                 End If
  37.                 '// Update.
  38.                 Using Cmd As New OleDbCommand(sql, Conn)
  39.                     With Cmd.Parameters
  40.                         .AddWithValue("@PK", details.PK)
  41.                         .AddWithValue("@url", details.Url)
  42.                         .AddWithValue("@login", details.Login)
  43.                         '// การเข้ารหัสด้วย Rijndael (AES) (modEncryption.vb)
  44.                         .AddWithValue("@Encrypted", EncryptPassword(details.Encrypted, key, iv))
  45.                         .AddWithValue("@email", details.Email)
  46.                         .AddWithValue("@phone", details.Phone)
  47.                         .AddWithValue("@DateModified", Format(details.DateModified, "dd/MM/yyyy"))
  48.                     End With
  49.                     Cmd.ExecuteNonQuery()
  50.                 End Using
  51.                 MessageBox.Show("UPDATE COMPLETE.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  52.             End Using
  53.         Catch ex As Exception
  54.             MessageBox.Show("UPDATE NOT SUCCESSFUL!", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  55.         End Try
  56.     End Sub

  57.     ' / ------------------------------------------------------------------------------------------------
  58.     '// Retrieve data from MS Access database and display in DataGridView.
  59.     '// blnSearch = True คือการค้นหาข้อมูล โดยรับค่า SearchValue เป็นคีย์เวิร์ดใช้ในการค้นหา
  60.     '// blnSearch = False ก็จะแสดงผลข้อมูลออกมาทั้งหมด
  61.     '// ทั้ง 2 ค่าเป็น Optional คือหากไม่ระบุการส่งค่ามา ก็ให้มีค่าเป็น False หรือแสดงผลข้อมูลออกมาทั้งหมด
  62.     ' / ------------------------------------------------------------------------------------------------
  63.     Function RetrieveData(Optional ByVal blnSearch As Boolean = False, Optional ByVal SearchValue As String = "") As DataTable
  64.         Using Conn As New OleDbConnection(ConnString)
  65.             Conn.Open()
  66.             Dim sql As String = "SELECT PK, url, login, Encrypted, email, phone, DateModified FROM UserData"
  67.             If blnSearch Then
  68.                 sql &= " WHERE url LIKE @SearchValue OR email LIKE @SearchValue OR phone LIKE @SearchValue OR login LIKE @SearchValue"
  69.             End If
  70.             sql &= " ORDER BY PK"
  71.             '//
  72.             Using cmd As New OleDbCommand(sql, Conn)
  73.                 If blnSearch Then cmd.Parameters.AddWithValue("@SearchValue", "%" & SearchValue & "%")
  74.                 '//
  75.                 Using reader As OleDbDataReader = cmd.ExecuteReader()
  76.                     Dim dt As New DataTable()
  77.                     With dt.Columns
  78.                         .Add("PK", GetType(Integer))
  79.                         .Add("URL", GetType(String))
  80.                         .Add("Login", GetType(String))
  81.                         .Add("Encrypted", GetType(String))
  82.                         .Add("Email", GetType(String))
  83.                         .Add("Phone", GetType(String))
  84.                         .Add("DateModified", GetType(Date))
  85.                     End With
  86.                     While reader.Read()
  87.                         '// มีการเข้ารหัสของรหัสผ่านเอาไว้ตอนแสดงผลในตารางกริด
  88.                         Dim EncryptedData As Byte() = DirectCast(reader("Encrypted"), Byte())
  89.                         '// เพิ่มรายการแถวข้อมูลเข้าไปใน DataTable
  90.                         dt.Rows.Add(reader("PK"), reader("url"), reader("login"), EncryptedData, reader("email"), reader("phone"), reader("DateModified"))
  91.                     End While
  92.                     Return dt
  93.                 End Using
  94.             End Using
  95.         End Using
  96.     End Function

  97.     ' / ------------------------------------------------------------------------------------------------
  98.     ' / คืนค่าข้อมูลจากตารางกริดไปแสดงผลลงใน Control
  99.     ' / ------------------------------------------------------------------------------------------------
  100.     Public Function RetrieveDetails(PK As Integer) As Details
  101.         '// Class Details เพื่อคืนค่ากลับไปแสดงผลในฟอร์ม
  102.         Dim result As New Details()
  103.         Try
  104.             Using Conn As New OleDbConnection(ConnString)
  105.                 Conn.Open()
  106.                 Using cmd As New OleDbCommand("SELECT url, login, Encrypted, email, phone, DateModified FROM UserData WHERE PK = @PK", Conn)
  107.                     cmd.Parameters.AddWithValue("@PK", PK)
  108.                     Using reader As OleDbDataReader = cmd.ExecuteReader()
  109.                         If reader.Read() Then
  110.                             result.Url = reader("url").ToString()
  111.                             result.Login = reader("login").ToString()
  112.                             '// ถอดรหัสออกมาเพื่อให้เห็น Password แบบ Plain Text.
  113.                             result.Encrypted = DecryptPassword(DirectCast(reader("Encrypted"), Byte()), key, iv)
  114.                             result.Email = reader("email").ToString()
  115.                             result.Phone = reader("phone").ToString()
  116.                             result.DateModified = reader("DateModified").ToString()
  117.                             Return (result)
  118.                         End If
  119.                     End Using
  120.                 End Using
  121.             End Using
  122.         Catch ex As Exception
  123.             MessageBox.Show("Error: " & ex.Message, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  124.         End Try
  125.         Return result '// Return the initialized structure if no data is found.
  126.     End Function

  127.     ' / ------------------------------------------------------------------------------------------------
  128.     ' / DELETE DATA
  129.     ' / ------------------------------------------------------------------------------------------------
  130.     Public Sub DeleteData(PK As Integer)
  131.         Try
  132.             Using Conn As New OleDbConnection(ConnString)
  133.                 Conn.Open()
  134.                 Dim sql As String = "DELETE FROM UserData WHERE PK = @PK"
  135.                 Using cmd As New OleDbCommand(sql, Conn)
  136.                     cmd.Parameters.AddWithValue("@PK", PK)
  137.                     Try
  138.                         cmd.ExecuteNonQuery()
  139.                         MessageBox.Show("DELETE COMPLETE.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  140.                     Catch ex As Exception
  141.                         MessageBox.Show("Error: " & ex.Message)
  142.                     End Try
  143.                 End Using
  144.             End Using
  145.         Catch ex As Exception
  146.             MessageBox.Show("Error: " & ex.Message, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  147.         End Try
  148.     End Sub

  149.     ' / ------------------------------------------------------------------------------------------------
  150.     ' / Function to find and create the new Primary Key not to duplicate.
  151.     ' / ------------------------------------------------------------------------------------------------
  152.     Function SetupNewPK(ByVal sql As String) As Integer
  153.         Using Conn As New OleDbConnection(ConnString)
  154.             Conn.Open()
  155.             Using cmd As New OleDbCommand(sql, Conn)
  156.                 '/ Check if the information is available. And return it back
  157.                 If IsDBNull(cmd.ExecuteScalar) Then
  158.                     '// Start at 1
  159.                     SetupNewPK = 1
  160.                 Else
  161.                     SetupNewPK = cmd.ExecuteScalar + 1
  162.                 End If
  163.             End Using
  164.         End Using
  165.     End Function
  166. End Module
คัดลอกไปที่คลิปบอร์ด

โค้ดในส่วนของการเข้ารหัสและถอดรหัส (modEncryption.vb)
  1. Imports System.Security.Cryptography
  2. Imports System.Text
  3. Imports System.IO

  4. Module modEncryption

  5.     '// Rijndael (AES) ในการเข้ารหัสข้อมูล (Encryption) โดยการใช้ Key และ IV (Initialization Vector).
  6.     Public Function EncryptPassword(password As String, key As String, iv As String) As Byte()
  7.         Dim aes As New RijndaelManaged()
  8.         aes.Key = Encoding.UTF8.GetBytes(key)
  9.         aes.IV = Encoding.UTF8.GetBytes(iv)
  10.         aes.Padding = PaddingMode.PKCS7
  11.         aes.Mode = CipherMode.CBC

  12.         Dim encryptor As ICryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV)

  13.         Using ms As New MemoryStream()
  14.             Using cs As New CryptoStream(ms, encryptor, CryptoStreamMode.Write)
  15.                 Using sw As New StreamWriter(cs)
  16.                     sw.Write(password)
  17.                 End Using
  18.             End Using
  19.             Return ms.ToArray()
  20.         End Using
  21.     End Function

  22.     '// Rijndael (AES) ในการถอดรหัสข้อมูล (Decryption)
  23.     Public Function DecryptPassword(encryptedPassword As Byte(), key As String, iv As String) As String
  24.         Dim aes As New RijndaelManaged()
  25.         aes.Key = Encoding.UTF8.GetBytes(key)
  26.         aes.IV = Encoding.UTF8.GetBytes(iv)
  27.         aes.Padding = PaddingMode.PKCS7
  28.         aes.Mode = CipherMode.CBC

  29.         Dim decryptor As ICryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV)

  30.         Using ms As New MemoryStream(encryptedPassword)
  31.             Using cs As New CryptoStream(ms, decryptor, CryptoStreamMode.Read)
  32.                 Using sr As New StreamReader(cs)
  33.                     Return sr.ReadToEnd()
  34.                 End Using
  35.             End Using
  36.         End Using
  37.     End Function
  38. End Module
คัดลอกไปที่คลิปบอร์ด

โค้ดในส่วนของฟังค์ชั่น (modFunction.vb)
  1. Module modFunction
  2.     Function MyPath(ByVal AppPath As String) As String
  3.         '/ Return Value
  4.         MyPath = AppPath.ToLower.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "").Replace("\bin\x86\release", "")
  5.         '// If not found folder then put the \ (BackSlash) at the end.
  6.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  7.     End Function

  8.     ' / --------------------------------------------------------------------------------
  9.     '// Initialize DataGridView @Run Time
  10.     Public Sub SetupDataGridView(DGV As DataGridView)
  11.         With DGV
  12.             .RowHeadersVisible = False
  13.             .AllowUserToAddRows = False
  14.             .AllowUserToDeleteRows = False
  15.             .AllowUserToResizeRows = False
  16.             .MultiSelect = False
  17.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  18.             .ReadOnly = True
  19.             .Font = New Font("Tahoma", 11, FontStyle.Regular)
  20.             .RowTemplate.Height = 28
  21.             .RowTemplate.Resizable = DataGridViewTriState.False
  22.             .Columns(0).Visible = False '// Primary Key
  23.             '// Autosize Column
  24.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  25.             '// Even-Odd Color
  26.             .AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue
  27.             '// COLUMN HEADER
  28.             '// Adjust Header Styles
  29.             With .ColumnHeadersDefaultCellStyle
  30.                 .BackColor = Color.Navy
  31.                 .ForeColor = Color.Black ' Color.White
  32.                 .Font = New Font("Tahoma", 11, FontStyle.Bold)
  33.             End With
  34.             '// Before you can adjust the height of the row.
  35.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
  36.             .ColumnHeadersHeight = 30
  37.             '// Accept color background changes.
  38.             .EnableHeadersVisualStyles = False
  39.             For iCol = 0 To DGV.Columns.Count - 1
  40.                 '// Calculates odd and even numbers. If any integer divide by 2, then answer 1 is odd number.
  41.                 If iCol Mod 2 = 0 Then
  42.                     DGV.Columns(iCol).HeaderCell.Style.BackColor = Color.Gold
  43.                     '// Integer divide by 2, then answer 1 is Even number.
  44.                 Else
  45.                     DGV.Columns(iCol).HeaderCell.Style.BackColor = Color.Orange
  46.                 End If
  47.             Next
  48.         End With
  49.     End Sub

  50. End Module
คัดลอกไปที่คลิปบอร์ด

ดาวน์โหลดโค้ดฉบับเต็ม VB.NET (2010) ได้ที่นี่ ...


ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง

คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด
ขออภัย! คุณไม่ได้รับสิทธิ์ในการดำเนินการในส่วนนี้ กรุณาเลือกอย่างใดอย่างหนึ่ง ลงชื่อเข้าใช้ | ลงทะเบียน

รายละเอียดเครดิต

ข้อความล้วน|อุปกรณ์พกพา|ประวัติการแบน|G2GNet.com  

GMT+7, 2024-9-21 10:11 , Processed in 0.196320 second(s), 5 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

ตอบกระทู้ ขึ้นไปด้านบน ไปที่หน้ารายการกระทู้