public static Verify ( byte authEncryptedBytes, byte authKey ) : bool | ||
authEncryptedBytes | byte | |
authKey | byte | |
Résultat | bool |
public static bool Verify(byte[] authEncryptedBytes, byte[] authKey)
{
if (authKey == null || authKey.Length != KeySizeBytes)
throw new ArgumentException($"AuthKey needs to be {KeySize} bits", nameof(authKey));
if (authEncryptedBytes == null || authEncryptedBytes.Length == 0)
throw new ArgumentException("Encrypted Message Required!", nameof(authEncryptedBytes));
using (var hmac = CreateHashAlgorithm(authKey))
{
var sentTag = new byte[KeySizeBytes];
//Calculate Tag
var calcTag = hmac.ComputeHash(authEncryptedBytes, 0, authEncryptedBytes.Length - sentTag.Length);
const int ivLength = AesUtils.BlockSizeBytes;
//return false if message length is too small
if (authEncryptedBytes.Length < sentTag.Length + ivLength)
return false;
//Grab Sent Tag
Buffer.BlockCopy(authEncryptedBytes, authEncryptedBytes.Length - sentTag.Length, sentTag, 0, sentTag.Length);
//Compare Tag with constant time comparison
var compare = 0;
for (var i = 0; i < sentTag.Length; i++)
compare |= sentTag[i] ^ calcTag[i];
//return false if message doesn't authenticate
if (compare != 0)
return false;
}
return true; //Haz Success!
}
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); } }