AES加密是目前广泛使用的对称加密算法之一,适用于各种密码管理系统。下面是在VB.NET中使用AES加密的示例代码:
Imports System.Security.Cryptography
Imports System.Text
Dim aes As Aes = Aes.Create()
加密密钥和初始化向量长度必须与AES算法的块长度相同。一般使用16字节或32字节长度的密钥。在这个示例中,我们使用长度为32字节的密钥和初始化向量。
Dim key As Byte() = Encoding.UTF8.GetBytes("12345678901234567890123456789012")
Dim iv As Byte() = Encoding.UTF8.GetBytes("abcdefghijklmnop")
Dim plaintext As Byte() = Encoding.UTF8.GetBytes("the message to encrypt")
Dim encrypted As Byte() = Nothing
Using aesAlg As Aes = Aes.Create()
aesAlg.Key = key
aesAlg.IV = iv
Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
Using msEncrypt As New IO.MemoryStream()
Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
csEncrypt.Write(plaintext, 0, plaintext.Length)
csEncrypt.FlushFinalBlock()
encrypted = msEncrypt.ToArray()
End Using
End Using
End Using
Dim encrypted As Byte() = ... ' The encrypted message
Dim plaintext As Byte() = Nothing
Using aesAlg As Aes = Aes.Create()
aesAlg.Key = key
aesAlg.IV = iv
Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)
Using msDecrypt As New IO.MemoryStream(encrypted)
Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
Using msReader As New IO.MemoryStream()
Dim buffer(8192) As Byte
Dim bytesRead As Integer
bytesRead = csDecrypt.Read(buffer, 0, buffer.Length)
While bytesRead > 0
msReader.Write(buffer, 0, bytesRead)
bytesRead = csDecrypt.Read(buffer, 0, buffer.Length)
End While