0

我正在encryption/decryption为用户输入字符串或简单地编写一个应用程序plain text。我使用class我找到并修改的这个。

Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Imports System.Text.Encoding
Imports System.ComponentModel

Public Class Crypto

#Region "Class Variables"
Public Enum KeySize As Integer
    AES = 128
End Enum

Public Enum Algorithm As Integer
    SHA256 = 1
    Rijndael = 3
End Enum

Public Enum EncodingType As Integer
    HEX = 0
    BASE_64 = 1
End Enum

'Initialization Vectors that we will use for symmetric encryption/decryption. These
'byte arrays are completely arbitrary, and you can change them to whatever you like.
Private Shared IV_8 As Byte() = New Byte() {2, 63, 9, 36, 235, 174, 78, 12}
Private Shared IV_16 As Byte() = New Byte() {15, 199, 56, 77, 244, 126, 107, 239, _
                                      9, 10, 88, 72, 24, 202, 31, 108}
Private Shared IV_24 As Byte() = New Byte() {37, 28, 19, 44, 25, 170, 122, 25, _
                                      25, 57, 127, 5, 22, 1, 66, 65, _
                                      14, 155, 224, 64, 9, 77, 18, 251}
Private Shared IV_32 As Byte() = New Byte() {133, 206, 56, 64, 110, 158, 132, 22, _
                                      99, 190, 35, 129, 101, 49, 204, 248, _
                                      251, 243, 13, 194, 160, 195, 89, 152, _
                                      149, 227, 245, 5, 218, 86, 161, 124}

'Salt value used to encrypt a plain text key. Again, this can be whatever you like
Private Shared SALT_BYTES As Byte() = New Byte() {162, 27, 98, 1, 28, 239, 64, 30, 156, 102, 223}

'File names to be used for private keys
Private Const KEY_PRIVATE As String = "private.key"

'Error messages
Private Const ERR_NO_KEY As String = "No encryption key was provided"
Private Const ERR_NO_ALGORITHM As String = "No algorithm was specified"
Private Const ERR_NO_CONTENT As String = "No content was provided"
Private Const ERR_INVALID_PROVIDER As String = "An invalid cryptographic provider was specified for this method"

'Initialization variables
Private Shared _key As String
Private Shared _algorithm As Algorithm = -1
Private Shared _content As String
Private Shared _exception As CryptographicException
Private Shared _encodingType As EncodingType = EncodingType.HEX
#End Region

#Region "Public Functions"
<Description("The key that is used to encrypt and decrypt data")> _
Public Shared Property Key() As String
    Get
        Return _key
    End Get
    Set(ByVal value As String)
        _key = value
    End Set
End Property

<Description("The algorithm that will be used for encryption and decryption")> _
Public Shared Property EncryptionAlgorithm() As Algorithm
    Get
        Return _algorithm
    End Get
    Set(ByVal value As Algorithm)
        _algorithm = value
    End Set
End Property

<Description("The format in which content is returned after encryption, or provided for decryption")> _
Public Shared Property Encoding() As EncodingType
    Get
        Return _encodingType
    End Get
    Set(ByVal value As EncodingType)
        _encodingType = value
    End Set
End Property

<Description("Encrypted content to be retrieved after an encryption call, or provided for a decryption call")> _
Public Shared Property Content() As String
    Get
        Return _content
    End Get
    Set(ByVal Value As String)
        _content = Value
    End Set
End Property

<Description("If an encryption or decryption call returns false, then this will contain the exception")> _
Public Shared ReadOnly Property CryptoException() As CryptographicException
    Get
        Return _exception
    End Get
End Property

<Description("Encryption of a string using the 'Key' and 'EncryptionAlgorithm' properties")> _
Public Shared Function EncryptString(ByVal Content As String) As Boolean
    Dim cipherBytes() As Byte

    Try
        cipherBytes = _Encrypt(Content)
    Catch ex As CryptographicException
        _exception = New CryptographicException(ex.Message, ex.InnerException)
        Return False
    End Try

    If _encodingType = EncodingType.HEX Then
        _content = BytesToHex(cipherBytes)
    Else
        _content = System.Convert.ToBase64String(cipherBytes)
    End If

    Return True
End Function

Public Shared Function DecryptString() As Boolean
    Dim encText As Byte() = Nothing
    Dim clearText As Byte() = Nothing

    Try
        clearText = _Decrypt(_content)
    Catch ex As Exception
        _exception = New CryptographicException(ex.Message, ex.InnerException)
        Return False
    End Try

    _content = UTF8.GetString(clearText)

    Return True
End Function

Public Shared ReadOnly Property IsHashAlgorithm() As Boolean
    Get
        Select Case _algorithm
            Case Algorithm.SHA256
                Return True
            Case Else
                Return False
        End Select
    End Get
End Property

Public Shared Function GenerateHash(ByVal Content As String) As Boolean
    If Content Is Nothing OrElse Content.Equals(String.Empty) Then
        _exception = New CryptographicException(ERR_NO_CONTENT)
        Return False
    End If

    If _algorithm.Equals(-1) Then
        _exception = New CryptographicException(ERR_NO_ALGORITHM)
        Return False
    End If

    Dim hashAlgorithm As HashAlgorithm = Nothing

    _algorithm = Algorithm.SHA256
    hashAlgorithm = New SHA256Managed

    Try
        Dim hash() As Byte = ComputeHash(hashAlgorithm, Content)
        If _encodingType = EncodingType.HEX Then
            _content = BytesToHex(hash)
        Else
            _content = System.Convert.ToBase64String(hash)
        End If
        hashAlgorithm.Clear()
        Return True
    Catch ex As CryptographicException
        _exception = ex
        Return False
    Finally
        hashAlgorithm.Clear()
    End Try
End Function

Public Shared Sub Clear()
    _algorithm = -1
    _content = String.Empty
    _key = String.Empty
    _encodingType = EncodingType.HEX
    _exception = Nothing
End Sub

#End Region

#Region "Shared Cryptographic Functions"

Private Shared Function _Encrypt(ByVal Content As Byte()) As Byte()

    If Not IsHashAlgorithm AndAlso _key Is Nothing Then
        Throw New CryptographicException(ERR_NO_KEY)
    End If

    If _algorithm.Equals(-1) Then
        Throw New CryptographicException(ERR_NO_ALGORITHM)
    End If

    If Content Is Nothing OrElse Content.Equals(String.Empty) Then
        Throw New CryptographicException(ERR_NO_CONTENT)
    End If


    Dim cipherBytes() As Byte = Nothing
    Dim NumBytes As Integer = 0
    Dim provider As SymmetricAlgorithm

    _algorithm = Algorithm.Rijndael
    provider = New RijndaelManaged
    NumBytes = KeySize.AES

    Try
        'Encrypt the string
        cipherBytes = SymmetricEncrypt(provider, Content, _key, NumBytes)
    Catch ex As CryptographicException
        Throw New CryptographicException(ex.Message, ex.InnerException)
    Finally
        'Free any resources held by the SymmetricAlgorithm provider
        provider.Clear()
    End Try

    Return cipherBytes
End Function

Private Shared Function _Encrypt(ByVal Content As String) As Byte()
    Return _Encrypt(UTF8.GetBytes(Content))
End Function

Private Shared Function _Decrypt(ByVal Content As Byte()) As Byte()

    If _algorithm.Equals(-1) Then
        Throw New CryptographicException(ERR_NO_ALGORITHM)
    End If

    If Content Is Nothing OrElse Content.Length.Equals(0) Then
        Throw New CryptographicException(ERR_NO_CONTENT)
    End If

    Dim encText As String = UTF8.GetString(Content)

    Dim clearBytes() As Byte = Nothing
    Dim NumBytes As Integer = 0
    Dim provider As SymmetricAlgorithm

    _algorithm = Algorithm.Rijndael
    provider = New RijndaelManaged
    NumBytes = KeySize.AES

    Try
        clearBytes = SymmetricDecrypt(provider, encText, _key, NumBytes)
    Catch ex As CryptographicException
        Throw ex
    Finally
        'Free any resources held by the SymmetricAlgorithm provider
        provider.Clear()
    End Try

    'Now return the plain text content
    Return clearBytes
End Function

Private Shared Function _Decrypt(ByVal Content As String) As Byte()
    Return _Decrypt(UTF8.GetBytes(Content))
End Function
#End Region

#Region "Compute Hash"

Private Shared Function ComputeHash(ByVal Provider As HashAlgorithm, ByVal plainText As String) As Byte()
    'All hashing mechanisms inherit from the HashAlgorithm base class so we can use that to cast the crypto service provider
    Dim hash As Byte() = Provider.ComputeHash(UTF8.GetBytes(plainText))
    Provider.Clear()
    Return hash
End Function
#End Region

#Region "Symmetric Cryptography"
Private Shared Function SymmetricEncrypt(ByVal Provider As SymmetricAlgorithm, ByVal plainText As Byte(), ByVal key As String, ByVal keySize As Integer) As Byte()
    'All symmetric algorithms inherit from the SymmetricAlgorithm base class, to which we can cast from the original crypto service provider
    Dim ivBytes As Byte() = Nothing
    Select Case keySize / 8 'Determine which initialization vector to use
        Case 8
            ivBytes = IV_8
        Case 16
            ivBytes = IV_16
        Case 24
            ivBytes = IV_24
        Case 32
            ivBytes = IV_32
        Case Else
            'Throw an error because an invalid key length has been passed
    End Select

    Provider.KeySize = keySize

    'Generate a secure key based on the original password by using SALT
    Dim keyStream As Byte() = DerivePassword(key, keySize / 8)

    'Initialize our encryptor object
    Dim trans As ICryptoTransform = Provider.CreateEncryptor(keyStream, ivBytes)

    'Perform the encryption on the textStream byte array
    Dim result As Byte() = trans.TransformFinalBlock(plainText, 0, plainText.GetLength(0))

    'Release cryptographic resources
    Provider.Clear()
    trans.Dispose()

    Return result
End Function

Private Shared Function SymmetricDecrypt(ByVal Provider As SymmetricAlgorithm, ByVal encText As String, ByVal key As String, ByVal keySize As Integer) As Byte()
    'All symmetric algorithms inherit from the SymmetricAlgorithm base class, to which we can cast from the original crypto service provider
    Dim ivBytes As Byte() = Nothing
    Select Case keySize / 8 'Determine which initialization vector to use
        Case 8
            ivBytes = IV_8
        Case 16
            ivBytes = IV_16
        Case 24
            ivBytes = IV_24
        Case 32
            ivBytes = IV_32
        Case Else
            'TODO: Throw an error because an invalid key length has been passed
    End Select

    'Generate a secure key based on the original password by using SALT
    Dim keyStream As Byte() = DerivePassword(key, keySize / 8)

    'Convert our hex-encoded cipher text to a byte array
    Dim textStream As Byte() = HexToBytes(encText)
    Provider.KeySize = keySize

    'Initialize our decryptor object
    Dim trans As ICryptoTransform = Provider.CreateDecryptor(keyStream, ivBytes)

    'Initialize the result stream
    Dim result() As Byte = Nothing

    Try
        'Perform the decryption on the textStream byte array
        result = trans.TransformFinalBlock(textStream, 0, textStream.GetLength(0))
    Catch ex As Exception
        Throw New System.Security.Cryptography.CryptographicException("The following exception occurred during decryption: " & ex.Message)
    Finally
        'Release cryptographic resources
        Provider.Clear()
        trans.Dispose()
    End Try

    Return result
End Function
#End Region

#Region "Utility Functions"
'********************************************************
'* BytesToHex: Converts a byte array to a hex-encoded
'*             string
'********************************************************
Private Shared Function BytesToHex(ByVal bytes() As Byte) As String
    Dim hex As New StringBuilder
    For n As Integer = 0 To bytes.Length - 1
        hex.AppendFormat("{0:X2}", bytes(n))
    Next
    Return hex.ToString
End Function

'********************************************************
'* HexToBytes: Converts a hex-encoded string to a
'*             byte array
'********************************************************
Private Shared Function HexToBytes(ByVal Hex As String) As Byte()
    Dim numBytes As Integer = Hex.Length / 2
    Dim bytes(numBytes - 1) As Byte
    For n As Integer = 0 To numBytes - 1
        Dim hexByte As String = Hex.Substring(n * 2, 2)
        bytes(n) = Integer.Parse(hexByte, Globalization.NumberStyles.HexNumber)
    Next
    Return bytes
End Function

'********************************************************
'* ClearBuffer: Clears a byte array to ensure
'*              that it cannot be read from memory
'********************************************************
Private Shared Sub ClearBuffer(ByVal bytes() As Byte)
    If bytes Is Nothing Then Exit Sub
    For n As Integer = 0 To bytes.Length - 1
        bytes(n) = 0
    Next
End Sub

'********************************************************
'* GenerateSalt: No, this is not a culinary routine. This
'*               generates a random salt value for
'*               password generation
'********************************************************
Private Shared Function GenerateSalt(ByVal saltLength As Integer) As Byte()
    Dim salt() As Byte
    If saltLength > 0 Then
        salt = New Byte(saltLength) {}
    Else
        salt = New Byte(0) {}
    End If

    Dim seed As New RNGCryptoServiceProvider
    seed.GetBytes(salt)
    Return salt
End Function

'********************************************************
'* DerivePassword: This takes the original plain text key
'*                 and creates a secure key using SALT
'********************************************************
Private Shared Function DerivePassword(ByVal originalPassword As String, ByVal passwordLength As Integer) As Byte()
    Dim derivedBytes As New Rfc2898DeriveBytes(originalPassword, SALT_BYTES, 5)
    Return derivedBytes.GetBytes(passwordLength)
End Function

#End Region

End Class

我刚开始使用BackgroundWorker. 执行工人使用,

If Not BackgroundWorker.IsBusy = True Then
       BackgroundWorker.RunWorkerAsync()
End If

在按钮单击事件上。然后我调用要执行的动作,即生成密文;

Private Sub BackgroundWorker_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker.DoWork
    'Perform operation 

    Crypto.EncryptionAlgorithm = Crypto.Algorithm.Rijndael
    Crypto.Key = hvalue
    Crypto.Encoding = Crypto.EncodingType.HEX
    Crypto.EncryptString(txtInput.Text)

    System.Threading.Thread.Sleep(500)
End Sub

然后得到加密过程的输出并设置用户控制;

Private Sub BackgroundWorker_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker.RunWorkerCompleted
    If e.Error Is Nothing Then
        'Complete encryption
        txtOutput.Text = Crypto.Content
        Crypto.Clear()
        'Set controls
        txtOutput.Show()
        btnPrint.Enabled = True
        btnNW.Enabled = True
        btnCopy.Enabled = True
        btnSave.Enabled = True
    Else
        txtOutput.Hide()
        btnPrint.Enabled = False
        btnNW.Enabled = False
        btnCopy.Enabled = False
        btnSave.Enabled = False
    End If
End Sub

我现在的问题是如何开始工作以ReportProgress显示progress.encryption/decryption

我相信在密码学课程中有一些事情要做,processed bytes然后将它们显示在progressbar或按百分比显示在textbox或什至label

作为参考,这里是原始类;

.NET 框架的密码学 101

4

0 回答 0