65.9K
CodeProject 正在变化。 阅读更多。
Home

对称密钥加密演示

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.93/5 (5投票s)

2008 年 7 月 25 日

CPOL

1分钟阅读

viewsIcon

45057

downloadIcon

1340

此应用程序演示了如何使用 VB.NET 和 .NET Framework 3.0 执行密钥加密。

Encryption

引言

加密是将电子数据从“明文”状态转换为不可读状态的过程,通过密码(也称为算法)实现。

虽然以前相当复杂,但现在可以使用 System.Security.Cryptography 命名空间中的各种加密类,在任何 .NET 应用程序中轻松实现加密。

我编写了一个加密演示程序,演示了如何使用以下加密方法加密和解密文档:

  • AES(高级加密标准)
  • DES(数据加密标准)
  • RC2(“Ron 的代码”或“Rivest 密码”)
  • Rijndael
  • Triple DES(三重数据加密标准)

此应用程序使用持久密钥与各自的算法相结合来加密和解密数据。

Using the Code

  • 将选定的文件传递给下面的 EncryptDecrypt 方法:
  • Dim path As String = "C:\temp\Encryption\Encrypt-decrypt.doc"
    Dim encrytedPath As String = String.Empty
    
    encrytedPath = Encrypt(path)
    MessageBox.Show("The following file has been encrypted:" & _
                              vbCrLf & vbCrLf & encrytedPath)
    
    path = Decrypt(encrytedPath)
    MessageBox.Show("The following file has been decrypted:" & _
                              vbCrLf & vbCrLf & path)
  • 声明将用于加密和解密的 AES 类实例:
  • 'Create the a new instance of AES
    Private mAes As System.Security.Cryptography.Aes = _
                             System.Security.Cryptography.Aes.Create()
  • Encrypt 方法的代码:
  • ''' <summary>
    ''' This function Encryptes a document and returns the encrypted document path.
    ''' </summary>
    ''' <param name="path">The path of the file to encrypt.</param>
    ''' <returns>The path of the encrypted file.</returns>
    ''' <remarks></remarks>
    Private Function Encrypt(ByVal path As String) As String
    
        Dim outputPath As String = String.Concat(path, ".enc")
    
        'Encryption example using AES
    
        'Get a persisted key and vector
        Dim key As Byte() = GetKey()
        Dim iv As Byte() = GetIV()
    
        'When a new instance of the AES class is created, a new random Key and Vector (IV)
        ' are created automatically. You can use these to encrypt and decrypt your files,
        ' however, they are only good until a new instance of this class is created. Once
        ' a new random Key and Vector (IV) are created,
        ' you won't be able to decrypt files, because
        ' the Key and Vector (IV) will have changed. The solution is use them 1 time to 
        ' create a random Key and Vector (IV) (which can be viewed in the Immediate window 
        ' by typing "?mAes.Key" or "?mAes.IV",
        ' and pressing Enter), and then somehow persist it 
        ' in your application (like in a class, or in a .DLL,
        ' or in an encrypted file or something), 
        ' which I've done as an example in the GeyKey() and GetIV() methods.
    
        'The auto-generated random key can be used
        'by uncommenting these lines, and the corresponding
        'lines in the Decrypt method below
        'key = mAes.Key
        'iv = mAes.IV
    
        'Create the Encryptor using the Key and Vector (IV)
        Dim encryptor As ICryptoTransform = mAes.CreateEncryptor(GetKey(), GetIV())
    
        'Open both the input file for reading, and
        ' the output file for writing.
        Dim reader As New FileStream(path, FileMode.Open, FileAccess.Read)
        Dim writer As New FileStream(outputPath, FileMode.Create, FileAccess.Write)
    
        'Create an Encrypted Stream using the "encryptor" we created above
        Dim encryptedStream As _
                    New System.Security.Cryptography.CryptoStream(writer, _
                    encryptor, CryptoStreamMode.Write)
    
        Dim bites(1023) As Byte 'Stores 1 KB
        Dim bitesRead As Int32 = 0 'Number of Bytes read
        Dim totalBites As Int64 = 0 'Total Number of Bytes read
    
    
        'Loop through the entire file reading 1 kb at a time
        Do Until totalBites >= reader.Length
    
            bitesRead = reader.Read(bites, 0, 1024)
            'Read the bytes from the input file.
    
            encryptedStream.Write(bites, 0, bitesRead)
            'Write the encrypted bytes to the output file.
    
            totalBites += bitesRead
    
        Loop
    
        'Close and release streams:
        encryptedStream.Close()
        encryptedStream.Dispose()
    
        reader.Close()
        reader.Dispose()
    
        writer.Close()
        writer.Dispose()
    
        'Return the output file
        Return outputPath
    
    End Function
  • Decrypt 方法的代码:
  • ''' <summary>
    ''' This function Encryptes a document and returns the encrypted document path.
    ''' </summary>
    ''' <param name="path">The path of the file to encrypt.</param>
    ''' <returns>The path of the encrypted file.</returns>
    ''' <remarks></remarks>
    Private Function Decrypt(ByVal path As String) As String
    
        Dim decryptedPath As String = path.Replace(".enc", "")
    
        Dim key As Byte() = GetKey()
        Dim iv As Byte() = GetIV()
    
        'You can use this to generate a new Key and Vector (IV)
        'for use in your applications.
        ' *** Do not use the key that comes with this demo, 
        ' because everyone who uses this demo will have it. ***
        'key = mAes.GenerateKey()
        'iv = mAes.GenerateIV()
    
        'Create the Decryptor using the Key and Vector (IV)
        Dim decryptor As ICryptoTransform = mAes.CreateDecryptor(key, iv)
    
        'Open both the input file for reading, and
        ' the output file for writing.
        Dim reader As New FileStream(path, FileMode.Open, FileAccess.Read)
        Dim writer As New FileStream(decryptedPath, _
                          FileMode.Create, FileAccess.Write)
    
        'Create an Encrypted Stream using 
        'the "encryptor" we created above
        Dim decryptedStream As _
                        New System.Security.Cryptography.CryptoStream(writer, _
                        decryptor, CryptoStreamMode.Write)
    
        Dim bites(1023) As Byte 'Stores 1 KB
        Dim bitesRead As Int32 = 0 'Number of Bytes read
        Dim totalBites As Int64 = 0 'Total Number of Bytes read
    
    
        'Loop through the entire file reading 1 kb at a time
        Do Until totalBites >= reader.Length
    
           bitesRead = reader.Read(bites, 0, 1024)
           'Read the bytes from the input file.
    
           decryptedStream.Write(bites, 0, bitesRead)
           'Write the encrypted bytes to the output file.
    
           totalBites += bitesRead
    
        Loop
    
    
        'Close and release streams:
        decryptedStream.Close()
        decryptedStream.Dispose()
    
        reader.Close()
        reader.Dispose()
    
        writer.Close()
        writer.Dispose()
    
        Return decryptedPath
    
    End Function
  • 持久密钥和向量 (IV):
  • '*** Just a note - DO NOT USE THIS KEY FOR YOUR OWN ENCRYPTION
    ' Create a new key by using the GenerateKey() method
    Private Function GetKey() As Byte()
    
        '32 length byte array
        Dim key(31) As Byte
        key(0) = 195
        key(1) = 201
        key(2) = 141
        key(3) = 238
        key(4) = 118
        key(5) = 179
        key(6) = 108
        key(7) = 7
        key(8) = 37
        key(9) = 109
        key(10) = 7
        key(11) = 48
        key(12) = 66
        key(13) = 141
        key(14) = 2
        key(15) = 65
        key(16) = 213
        key(17) = 136
        key(18) = 141
        key(19) = 210
        key(20) = 78
        key(21) = 234
        key(22) = 83
        key(23) = 34
        key(24) = 41
        key(25) = 238
        key(26) = 152
        key(27) = 88
        key(28) = 228
        key(29) = 72
        key(30) = 160
        key(31) = 174
    
        Return key
    
    End Function
    
    '*** Just a note - DO NOT USE THIS Vector (IV) FOR YOUR OWN ENCRYPTION
    ' Create a new Vector (IV) by using the GenerateIV() method
    Private Function GetIV() As Byte()
    
        '16 length byte array
        Dim IV(15) As Byte
        IV(0) = 30
        IV(1) = 185
        IV(2) = 3
        IV(3) = 73
        IV(4) = 26
        IV(5) = 247
        IV(6) = 159
        IV(7) = 124
        IV(8) = 211
        IV(9) = 112
        IV(10) = 251
        IV(11) = 231
        IV(12) = 69
        IV(13) = 25
        IV(14) = 132
        IV(15) = 1
    
        Return IV
    
    End Function

关注点

加密和解密每种不同算法的过程是相同的。您会发现的一个不同之处是不同密钥和向量数组中使用的字节数。

希望这个演示对您有所帮助!

© . All rights reserved.