2015-05-31 57 views
1

我必須使用與OFB加密模式的AES加密時「指定了無效的算法」,我使用VB.NET 4.5,窗口8和下面的代碼:使用AES與OFB加密模式(VB.NET)

Public Function DoEncryption(ByVal KeyArray() As Byte, ByVal IVArray() As Byte, ByVal Buffer As String) As Byte() 
    Dim encrypted() As Byte 
    Using a As Aes = Aes.Create() 
     a.Mode = CipherMode.OFB 

     Dim encryptor As ICryptoTransform 
     encryptor = a.CreateEncryptor(KeyArray, IVArray) 


     ' Create the streams used for encryption. 
     Using msEncrypt As New MemoryStream() 
      Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write) 
       Using swEncrypt As New StreamWriter(csEncrypt) 

        'Write all data to the stream. 
        swEncrypt.Write(Buffer) 
       End Using 
       encrypted = msEncrypt.ToArray() 
      End Using 
     End Using 
    End Using 

    Return encrypted 

End Function 

我在

swEncrypt.Write(Buffer) 

任何建議「無效的算法指定」的錯誤?

+1

OFB。檢查[AesManaged.Mode屬性](https://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.mode(v = vs.110).aspx)底部的註釋: 「不支持CFB和OFB模式。」我不確定Aes類與AesManaged有多大不同,但支持它而不支持其他類型會很奇怪。你可能會看看BouncyCastle – Plutonix

+0

非常感謝@Plutonix,我會嘗試從nuget的Bouncy Castle並給予反饋,奇怪的是當我嘗試使用CFB時,它可以正常工作:( –

回答

1

是它的工作原理使用BouncyCastle的作爲@Plutonix提到 我的新代碼BouncyCastle的使用的NuGet是後安裝:

Imports System.Security.Cryptography 
Imports System.IO 
Imports Org.BouncyCastle.Crypto 
Imports Org.BouncyCastle.Security 
Imports Org.BouncyCastle.Crypto.Parameters 
Public Class EncryptionFunction 
Public Function DoEncryption(ByVal KeyArray() As Byte, ByVal IVArray() As Byte, ByVal Buffer As Byte()) As Byte() 

     Dim ae As New CipherKeyGenerator() 
     ae.Init(New KeyGenerationParameters(New SecureRandom(), 256)) 
     Dim aesKeyParam As KeyParameter = ParameterUtilities.CreateKeyParameter("AES", KeyArray) 
     Dim aesIVKeyParam As ParametersWithIV = New ParametersWithIV(aesKeyParam, IVArray) 
     Dim cipher As IBufferedCipher = CipherUtilities.GetCipher("AES/OFB/NoPadding") 
     cipher.Init(True, aesIVKeyParam) 
     Dim encrypted() As Byte = cipher.DoFinal(Buffer) 


     Return encrypted 

    End Function 
End Class 

謝謝:)不支持