Getting a null reference exception when decrypting a json file using AES. Its some HMAC Initialize error.
I have used system.cryptorgraphy’s AES encryption and decryption algorithm to use encryption in my game. Does anyone have Idea about What HMAC is and how to solve this error?
I have pasted the code which I am using to to decrypt. The screenshot of the error is all attached.
public string Decrypt (string cipherText)
{
string EncryptionKey = "abc123";
cipherText = cipherText.Replace (" ", "+");
byte[] cipherBytes = Convert.FromBase64String (cipherText);
using (Aes encryptor = Aes.Create ()) {
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes (EncryptionKey, new byte[] {
0x49,
0x76,
0x61,
0x6e,
0x20,
0x4d,
0x65,
0x64,
0x76,
0x65,
0x64,
0x65,
0x76
});
encryptor.Key = pdb.GetBytes (32);
encryptor.IV = pdb.GetBytes (16);
using (MemoryStream ms = new MemoryStream ()) {
using (CryptoStream cs = new CryptoStream (ms, encryptor.CreateDecryptor (), CryptoStreamMode.Write)) {
cs.Write (cipherBytes, 0, cipherBytes.Length);
cs.Close ();
}
cipherText = Encoding.Unicode.GetString (ms.ToArray ());
}
}
return cipherText;
}
Well, as you can see from the stacktrace the problem comes from your the “Rfc2898DeriveBytes” class. It uses the “HMACSHA1” class internally. That class is derived from the HMAC class. This in turn will try to create an instance of the “System.Security.Cryptography.SHA1CryptoServiceProvider” using reflection (System.Activator). It’s most likely that this creation fails for some reason.
It’s most likely this line inside tne Initialize method of the HMAC class:
this._algo.Initialize();
“_algo” should contain the crypto provider. I suspect that “_algo” is null because the creation has failed. At least this is the most likely cause for the null ref. This is the complete Initialize method:
public override void Initialize()
{
if (this._disposed)
{
throw new ObjectDisposedException("HMAC");
}
this.State = 0;
this.Block.Initialize();
byte[] array = this.KeySetup(this.Key, 54);
this._algo.Initialize();
this.Block.Core(array);
Array.Clear(array, 0, array.Length);
}
The only two points where a null reference exception can be thrown is the Block.Initialize and the _algo.Initialize line. Block is a self initializing property that’s can’t really fail to initialize. Therefore _algo is much more likely the cause.
This might be related to the target platform that you’re using or to the .NET compatibility level that you’re using. Try using “.NET 2.0” if you’re currently using “.NET 2.0 subset”.
Ohh btw this is a HMAC