0

假设我们有这段代码在构造函数中运行:

    Dim initVectorBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(initVector)
    Dim saltValueBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(saltValue)

    Dim passPharse As String = GenerateKeyString(EncryptionKey)

    Dim password As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(passPharse, saltValueBytes, passwordIterations)

    Dim keyBytes As Byte() = password.GetBytes(CInt(keySize / 8))

    mSymmetricKey = New RijndaelManaged()
    mSymmetricKey.Padding = PaddingMode.PKCS7

    mSymmetricKey.Mode = CipherMode.CBC
    mSymmetricKey.BlockSize = 128

    mSymmetricKey.Key = keyBytes
    mSymmetricKey.IV = initVectorBytes

    mDecryptor = mSymmetricKey.CreateDecryptor()
    mEncryptor = mSymmetricKey.CreateEncryptor()

然后是2个公共功能:

Public Function Encrypt(ByVal plainText As String) As String
    Dim plainTextBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(plainText)
    Dim cipherTextBytes As Byte() = mEncryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length)

    Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)

    Return cipherText
End Function
Public Function Decrypt(ByVal cipherText As String) As String
    Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)

    Dim plainTextBytes As Byte() = mDecryptor.TransformFinalBlock(cipherTextBytes, 0, cipherTextBytes.Length)

    Dim plainText As String = System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, plainTextBytes.Length)

    Return plainText
End Function

从多个线程调用它们会是线程安全的吗?

4

1 回答 1

2

根据文档,它不是线程安全的。您将在和变量中拥有RijndaelManagedTransform实例。TransformFinalBlock是一个实例方法,根据 MSDN,它不是线程安全的:mDecryptormEncryptor

此类型的任何公共静态(在 Visual Basic 中为 Shared)成员都是线程安全的。不保证任何实例成员都是线程安全的。

如果你想保证有一个线程安全的代码,你可能需要同步对 TransformFinalBlock 方法的调用。

于 2009-11-17T09:34:57.360 回答