I need to decrypt content encoded using the AES/OFB/NoPadding
combo in C#. This doesn't seem to be supported natively: the following code won't do it as
var aes = new AesManaged
{
Padding = PaddingMode.None,
Mode = CipherMode.OFB,
KeySize = 128,
BlockSize = 128
};
Produces:
System.Security.Cryptography.CryptographicException:
Specified cipher mode is not valid for this algorithm.
The closest issue that I could find here on SO is this one, which uses BouncyCastle to do encryption:
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
Other issues (like this one) contain more information but also lots of custom code - I'd rather use BouncyCastle. Can anybody help me with the decryption, or point me to some helpful documentation?
From the code in the actual question, the only step necessary to trigger decryption instead of encryption was to change the boolean parameter in the cipher.Init
invocation:
cipher.Init(False, aesIVKeyParam) // False == decryption, True == encryption
The final snippet in C# is
private static byte[] DoDecryption(byte[] keyArray, byte[] ivArray, byte[] encoded)
{
var aesKeyParam = ParameterUtilities.CreateKeyParameter("AES", keyArray);
var aesIvKeyParam = new ParametersWithIV(aesKeyParam, ivArray);
var cipher = CipherUtilities.GetCipher("AES/OFB/NOPADDING");
cipher.Init(false, aesIvKeyParam);
var decrypted = cipher.DoFinal(encoded);
return decrypted;
}