• Vui lòng đọc nội qui diễn đàn để tránh bị xóa bài viết
  • Tìm kiếm trước khi đặt câu hỏi

[VB.NET] Tạo Password ngẫu nhiên

Các thủ thuật liên quan đến xử lý chuỗi và thời gian

Điều hành viên: tungcan5diop, QUANITGROBEST

Hình đại diện của người dùng
clarkkent
Mạnh Thường Quân
Mạnh Thường Quân
Bài viết: 1641
Ngày tham gia: T.Tư 16/04/2008 11:25 am
Đến từ: Chợ Lách - Bến Tre
Been thanked: 31 time
Liên hệ:

[VB.NET] Tạo Password ngẫu nhiên

Gửi bàigửi bởi clarkkent » T.Sáu 22/05/2009 9:24 am

Thủ thuật: [VB.NET] Tạo Password ngẫu nhiên
Tác giả: Sưu tầm
Mô tả: [VB.NET] Tạo Password ngẫu nhiên: ngẫu nhiên, ngẫu nhiên với tùy chọn độ dài, ngẫu nhiên với tùy chọn độ dài trong 1 khoảng


Class

Mã: Chọn hết

  1. Imports System
  2. Imports System.Security.Cryptography
  3. ' <summary>
  4. ' This class can generate random passwords, which do not include ambiguous
  5. ' characters, such as I, l, and 1. The generated password will be made of
  6. ' 7-bit ASCII symbols. Every four characters will include one lower case
  7. ' character, one upper case character, one number, and one special symbol
  8. ' (such as '%') in a random order. The password will always start with an
  9. ' alpha-numeric character; it will not start with a special symbol (we do
  10. ' this because some back-end systems do not like certain special
  11. ' characters in the first position).
  12. ' </summary>
  13. Public Class cRamdomPassword
  14.     ' Define default min and max password lengths.
  15.     Private Shared DEFAULT_MIN_PASSWORD_LENGTH As Integer = 8
  16.     Private Shared DEFAULT_MAX_PASSWORD_LENGTH As Integer = 10
  17.  
  18.     ' Define supported password characters divided into groups.
  19.     ' You can add (or remove) characters to (from) these groups.
  20.     Private Shared PASSWORD_CHARS_LCASE As String = "abcdefghijklmnopqrstuvwxyz"
  21.     Private Shared PASSWORD_CHARS_UCASE As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  22.     Private Shared PASSWORD_CHARS_NUMERIC As String = "0123456789"
  23.     Private Shared PASSWORD_CHARS_SPECIAL As String = "*$-+?_&=!%{}/"
  24.  
  25.     ' <summary>
  26.     ' Generates a random password.
  27.     ' </summary>
  28.     ' <returns>
  29.     ' Randomly generated password.
  30.     ' </returns>
  31.     ' <remarks>
  32.     ' The length of the generated password will be determined at
  33.     ' random. It will be no shorter than the minimum default and
  34.     ' no longer than maximum default.
  35.     ' </remarks>
  36.     Public Shared Function Generate() As String
  37.         Generate = Generate(DEFAULT_MIN_PASSWORD_LENGTH, _
  38.                             DEFAULT_MAX_PASSWORD_LENGTH)
  39.     End Function
  40.  
  41.     ' <summary>
  42.     ' Generates a random password of the exact length.
  43.     ' </summary>
  44.     ' <param name="length">
  45.     ' Exact password length.
  46.     ' </param>
  47.     ' <returns>
  48.     ' Randomly generated password.
  49.     ' </returns>
  50.     Public Shared Function Generate(ByVal length As Integer) As String
  51.         Generate = Generate(length, length)
  52.     End Function
  53.  
  54.     ' <summary>
  55.     ' Generates a random password.
  56.     ' </summary>
  57.     ' <param name="minLength">
  58.     ' Minimum password length.
  59.     ' </param>
  60.     ' <param name="maxLength">
  61.     ' Maximum password length.
  62.     ' </param>
  63.     ' <returns>
  64.     ' Randomly generated password.
  65.     ' </returns>
  66.     ' <remarks>
  67.     ' The length of the generated password will be determined at
  68.     ' random and it will fall with the range determined by the
  69.     ' function parameters.
  70.     ' </remarks>
  71.     Public Shared Function Generate(ByVal minLength As Integer, _
  72.                                     ByVal maxLength As Integer) _
  73.         As String
  74.  
  75.         ' Make sure that input parameters are valid.
  76.         If (minLength <= 0 Or maxLength <= 0 Or minLength > maxLength) Then
  77.             Generate = Nothing
  78.         End If
  79.  
  80.         ' Create a local array containing supported password characters
  81.         ' grouped by types. You can remove character groups from this
  82.         ' array, but doing so will weaken the password strength.
  83.         Dim charGroups As Char()() = New Char()() _
  84.         { _
  85.             PASSWORD_CHARS_LCASE.ToCharArray(), _
  86.             PASSWORD_CHARS_UCASE.ToCharArray(), _
  87.             PASSWORD_CHARS_NUMERIC.ToCharArray(), _
  88.             PASSWORD_CHARS_SPECIAL.ToCharArray() _
  89.         }
  90.  
  91.         ' Use this array to track the number of unused characters in each
  92.         ' character group.
  93.         Dim charsLeftInGroup As Integer() = New Integer(charGroups.Length - 1) {}
  94.  
  95.         ' Initially, all characters in each group are not used.
  96.         Dim I As Integer
  97.         For I = 0 To charsLeftInGroup.Length - 1
  98.             charsLeftInGroup(I) = charGroups(I).Length
  99.         Next
  100.  
  101.         ' Use this array to track (iterate through) unused character groups.
  102.         Dim leftGroupsOrder As Integer() = New Integer(charGroups.Length - 1) {}
  103.  
  104.         ' Initially, all character groups are not used.
  105.         For I = 0 To leftGroupsOrder.Length - 1
  106.             leftGroupsOrder(I) = I
  107.         Next
  108.  
  109.         ' Because we cannot use the default randomizer, which is based on the
  110.         ' current time (it will produce the same "random" number within a
  111.         ' second), we will use a random number generator to seed the
  112.         ' randomizer.
  113.  
  114.         ' Use a 4-byte array to fill it with random bytes and convert it then
  115.         ' to an integer value.
  116.         Dim randomBytes As Byte() = New Byte(3) {}
  117.  
  118.         ' Generate 4 random bytes.
  119.         Dim rng As RNGCryptoServiceProvider = New RNGCryptoServiceProvider()
  120.  
  121.         rng.GetBytes(randomBytes)
  122.  
  123.         ' Convert 4 bytes into a 32-bit integer value.
  124.         Dim seed As Integer = ((randomBytes(0) And &H7F) << 24 Or _
  125.                                 randomBytes(1) << 16 Or _
  126.                                 randomBytes(2) << 8 Or _
  127.                                 randomBytes(3))
  128.  
  129.         ' Now, this is real randomization.
  130.         Dim random As Random = New Random(seed)
  131.  
  132.         ' This array will hold password characters.
  133.         Dim password As Char() = Nothing
  134.  
  135.         ' Allocate appropriate memory for the password.
  136.         If (minLength < maxLength) Then
  137.             password = New Char(random.Next(minLength - 1, maxLength)) {}
  138.         Else
  139.             password = New Char(minLength - 1) {}
  140.         End If
  141.  
  142.         ' Index of the next character to be added to password.
  143.         Dim nextCharIdx As Integer
  144.  
  145.         ' Index of the next character group to be processed.
  146.         Dim nextGroupIdx As Integer
  147.  
  148.         ' Index which will be used to track not processed character groups.
  149.         Dim nextLeftGroupsOrderIdx As Integer
  150.  
  151.         ' Index of the last non-processed character in a group.
  152.         Dim lastCharIdx As Integer
  153.  
  154.         ' Index of the last non-processed group.
  155.         Dim lastLeftGroupsOrderIdx As Integer = leftGroupsOrder.Length - 1
  156.  
  157.         ' Generate password characters one at a time.
  158.         For I = 0 To password.Length - 1
  159.  
  160.             ' If only one character group remained unprocessed, process it;
  161.             ' otherwise, pick a random character group from the unprocessed
  162.             ' group list. To allow a special character to appear in the
  163.             ' first position, increment the second parameter of the Next
  164.             ' function call by one, i.e. lastLeftGroupsOrderIdx + 1.
  165.             If (lastLeftGroupsOrderIdx = 0) Then
  166.                 nextLeftGroupsOrderIdx = 0
  167.             Else
  168.                 nextLeftGroupsOrderIdx = random.Next(0, lastLeftGroupsOrderIdx)
  169.             End If
  170.  
  171.             ' Get the actual index of the character group, from which we will
  172.             ' pick the next character.
  173.             nextGroupIdx = leftGroupsOrder(nextLeftGroupsOrderIdx)
  174.  
  175.             ' Get the index of the last unprocessed characters in this group.
  176.             lastCharIdx = charsLeftInGroup(nextGroupIdx) - 1
  177.  
  178.             ' If only one unprocessed character is left, pick it; otherwise,
  179.             ' get a random character from the unused character list.
  180.             If (lastCharIdx = 0) Then
  181.                 nextCharIdx = 0
  182.             Else
  183.                 nextCharIdx = random.Next(0, lastCharIdx + 1)
  184.             End If
  185.  
  186.             ' Add this character to the password.
  187.             password(I) = charGroups(nextGroupIdx)(nextCharIdx)
  188.  
  189.             ' If we processed the last character in this group, start over.
  190.             If (lastCharIdx = 0) Then
  191.                 charsLeftInGroup(nextGroupIdx) = _
  192.                                 charGroups(nextGroupIdx).Length
  193.                 ' There are more unprocessed characters left.
  194.             Else
  195.                 ' Swap processed character with the last unprocessed character
  196.                 ' so that we don't pick it until we process all characters in
  197.                 ' this group.
  198.                 If (lastCharIdx <> nextCharIdx) Then
  199.                     Dim temp As Char = charGroups(nextGroupIdx)(lastCharIdx)
  200.                     charGroups(nextGroupIdx)(lastCharIdx) = _
  201.                                 charGroups(nextGroupIdx)(nextCharIdx)
  202.                     charGroups(nextGroupIdx)(nextCharIdx) = temp
  203.                 End If
  204.  
  205.                 ' Decrement the number of unprocessed characters in
  206.                 ' this group.
  207.                 charsLeftInGroup(nextGroupIdx) = _
  208.                            charsLeftInGroup(nextGroupIdx) - 1
  209.             End If
  210.  
  211.             ' If we processed the last group, start all over.
  212.             If (lastLeftGroupsOrderIdx = 0) Then
  213.                 lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1
  214.                 ' There are more unprocessed groups left.
  215.             Else
  216.                 ' Swap processed group with the last unprocessed group
  217.                 ' so that we don't pick it until we process all groups.
  218.                 If (lastLeftGroupsOrderIdx <> nextLeftGroupsOrderIdx) Then
  219.                     Dim temp As Integer = _
  220.                                 leftGroupsOrder(lastLeftGroupsOrderIdx)
  221.                     leftGroupsOrder(lastLeftGroupsOrderIdx) = _
  222.                                 leftGroupsOrder(nextLeftGroupsOrderIdx)
  223.                     leftGroupsOrder(nextLeftGroupsOrderIdx) = temp
  224.                 End If
  225.  
  226.                 ' Decrement the number of unprocessed groups.
  227.                 lastLeftGroupsOrderIdx = lastLeftGroupsOrderIdx - 1
  228.             End If
  229.         Next
  230.  
  231.         ' Convert password characters into a string and return the result.
  232.         Generate = New String(password)
  233.     End Function
  234. End Class
  235.  


Sử dụng

Mã: Chọn hết

  1.    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.         Dim i As Integer
  3.  
  4.         'ngẫu nhiên có độ dài từ 6 -> 20 số
  5.         For i = 1 To 100
  6.             ListBox1.Items.Add(cRamdomPassword.Generate(6, 20))
  7.         Next
  8.  
  9.         'ngẫu nhiên
  10.         For i = 1 To 100
  11.             ListBox1.Items.Add(cRamdomPassword.Generate())
  12.         Next
  13.  
  14.         'ngẫu nhiên có độ dài là 6
  15.         For i = 1 To 100
  16.             ListBox1.Items.Add(cRamdomPassword.Generate(6))
  17.         Next
  18.     End Sub


• Hôm bây: www.tinsoftware.com ^ ^
Cố gắng lên...

mataattane2002
Bài viết: 6
Ngày tham gia: T.Bảy 29/03/2008 8:47 am

Re: [VB.NET] Tạo Password ngẫu nhiên

Gửi bàigửi bởi mataattane2002 » T.Bảy 13/06/2009 4:14 am

Cảm ơn đã chia sẻ, sau khi tạo password ngẫu nhiên cho người sử dụng, làm cách nào để gửi được email cho người sử dụng qua vb.net . Hướng dẫn mình với. pls


Quay về “[.NET] Chuỗi và Thời gian”

Đang trực tuyến

Đang xem chuyên mục này: Không có thành viên nào trực tuyến.2 khách