0

文字列の暗号化と復号化には、次の 2 つの方法を使用します。

'Encrypts string. Returns encrypted byte array.
Public Function Encrypt(ByVal str As String) As Byte()
    Dim inputInBytes() As Byte = Encoding.Unicode.GetBytes(str)

    Dim laesProvider As New AesCryptoServiceProvider()
    laesProvider.Key = _key
    laesProvider.Mode = CipherMode.CBC
    laesProvider.IV = _IV
    laesProvider.Padding = PaddingMode.PKCS7
    Dim lencryptor As ICryptoTransform = laesProvider.CreateEncryptor

    Dim encryptedStream As New MemoryStream
    Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, lencryptor, CryptoStreamMode.Write)

    cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
    cryptStream.FlushFinalBlock()
    encryptedStream.Position = 0

    Dim result(encryptedStream.Length - 1) As Byte
    encryptedStream.Read(result, 0, encryptedStream.Length)
    cryptStream.Close()
    Return result
End Function

'Decrypts bytearray. Returns string.
Public Function DecryptToStr(ByVal inputInBytes() As Byte) As String

    Dim laesProvider As New AesCryptoServiceProvider()
    laesProvider.Key = _key
    laesProvider.Mode = CipherMode.CBC
    laesProvider.IV = _IV
    laesProvider.Padding = PaddingMode.PKCS7
    Dim ldecryptor As ICryptoTransform = laesProvider.CreateDecryptor

    ' Provide a memory stream to decrypt information into 
    Dim decryptedStream As MemoryStream = New MemoryStream()
    Dim cryptStream As CryptoStream = New CryptoStream(decryptedStream, ldecryptor, CryptoStreamMode.Write)
    cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
    cryptStream.FlushFinalBlock() '#### This is where the exception is thrown ####
    decryptedStream.Position = 0

    ' Read the memory stream and convert it back into a string 
    Dim result(decryptedStream.Length - 1) As Byte
    decryptedStream.Read(result, 0, decryptedStream.Length)
    cryptStream.Close()

    Return Encoding.Unicode.GetString(result)
End Function

特定の長さの文字列を復号化しようとすると、エラーが発生します。文字列が社会保障 # (ダッシュを含む 11 文字) の場合、「入力データは完全なブロックではありません」CryptographicException がスローされます。たとえば、正確に 8 文字の長さの文字列を渡すと、すべてが期待どおりに機能します。PKCS7 のパディングがさまざまな長さに対応できると思いました。簡単なものが欠けていると確信していますが、何時間もグーグルで検索した後、答えがわかりません。

4

1 に答える 1

0

問題は暗号化方法ではなく、格納されているデータベースに設定された varbinary の長さにありました。そのため、暗号化されたデータは切り捨てられていました。

于 2011-10-18T13:28:24.967 に答える