public static DecryptAuthenticated ( byte authEncryptedBytes, byte cryptKey ) : byte[] | ||
authEncryptedBytes | byte | |
cryptKey | byte | |
return | byte[] |
public static byte[] DecryptAuthenticated(byte[] authEncryptedBytes, byte[] cryptKey)
{
if (cryptKey == null || cryptKey.Length != KeySizeBytes)
throw new ArgumentException($"CryptKey needs to be {KeySize} bits", nameof(cryptKey));
//Grab IV from message
var iv = new byte[AesUtils.BlockSizeBytes];
Buffer.BlockCopy(authEncryptedBytes, 0, iv, 0, iv.Length);
using (var aes = AesUtils.CreateSymmetricAlgorithm())
{
using (var decrypter = aes.CreateDecryptor(cryptKey, iv))
using (var decryptedStream = new MemoryStream())
{
using (var decrypterStream = new CryptoStream(decryptedStream, decrypter, CryptoStreamMode.Write))
using (var writer = new BinaryWriter(decrypterStream))
{
//Decrypt Cipher Text from Message
writer.Write(
authEncryptedBytes,
iv.Length,
authEncryptedBytes.Length - iv.Length - KeySizeBytes);
}
return decryptedStream.ToArray();
}
}
}
}
public TResponse Send <TResponse>(string httpMethod, object request) { byte[] cryptKey, authKey, iv; AesUtils.CreateCryptAuthKeysAndIv(out cryptKey, out authKey, out iv); try { var encryptedMessage = CreateEncryptedMessage(request, request.GetType().Name, cryptKey, authKey, iv, httpMethod); var encResponse = Client.Send(encryptedMessage); var authEncryptedBytes = Convert.FromBase64String(encResponse.EncryptedBody); if (!HmacUtils.Verify(authEncryptedBytes, authKey)) { throw new Exception("Invalid EncryptedBody"); } var decryptedBytes = HmacUtils.DecryptAuthenticated(authEncryptedBytes, cryptKey); var responseJson = decryptedBytes.FromUtf8Bytes(); var response = responseJson.FromJson <TResponse>(); return(response); } catch (WebServiceException ex) { throw DecryptedException(ex, cryptKey, authKey); } }