decrypt method

Future<AccessToken> decrypt(
  1. BuildContext context
)

Implementation

Future<AccessToken> decrypt(BuildContext context) async {
  var sp = token.split(".");
  if (sp.length != 3) {
    throw Exception();
  }
  var deviceIdBase64 = sp[0];
  var plaintTextBase64 = sp[1];
  var receivedMac = sp[2];

  var plainText = utf8.decode(base64Url.decode(plaintTextBase64));

  var plainSplit = plainText.split(".");

  if (plainSplit.length != 2) {
    throw Exception("Invalid Token Format");
    // throw InvalidTokenFormat(context: context, payload: {
    //   "reason": "plain_text_format_invalid",
    //   "plain_text": plainText
    // });
  }

  var headerBase64Url = plainSplit[0];
  var payloadBase64Url = plainSplit[1];
  var payloadText = utf8.decode(base64Url.decode(payloadBase64Url));

  var payloadMap = json.decode(payloadText) as Map<String, dynamic>;

  if (payloadMap["dm"] == null) {
    throw Exception("Invalid Token Format");
    // throw InvalidTokenFormat(
    //     context: context,
    //     payload: {"reason": "device_id_not_found"});
  }
  var deviceHash = payloadMap["dm"];
  // var cAlg = Hmac.sha256();

  var payloadFirstMacBytes = await context.crypto
      .calculateSha256Mac(base64Url.decode(payloadBase64Url));

  // var payloadFirstMac = await cAlg.calculateMac(
  //     base64Url.decode(payloadBase64Url),
  //     secretKey: styleDb.serverConfiguration.tokenKey1);

  var payloadFirstMacBase64 = base64Url.encode(payloadFirstMacBytes);

  var secondPlain = "$headerBase64Url.$payloadFirstMacBase64";

  var secondMacBytes = await context.crypto
      .calculateSha256Mac(utf8.encode(secondPlain) as Uint8List);

  // var secondMac = await cAlg.calculateMac(utf8.encode(secondPlain),
  //     secretKey: styleDb.serverConfiguration.tokenKey2);

  var lastMacBase64 = base64Url.encode(secondMacBytes);

  if (lastMacBase64 != receivedMac) {
    throw Exception("Token Invalid");
    // throw TokenNotValid(
    //     context: context,
    //     payload: {"reason": "mac_not_valid"});
  }

  //var dAlg = Hmac(Sha1());

  var calcDBytes = await context.crypto.calculateSha1Mac(
      base64Url.decode(utf8.decode(base64Url.decode(deviceIdBase64))));

  // var calcD = await dAlg.calculateMac(
  //     base64Url.decode(utf8.decode(base64Url.decode(deviceIdBase64))),
  //     secretKey: styleDb.serverConfiguration.tokenKey3);

  var deviceCalculatedHash = base64Url.encode(calcDBytes);

  if (deviceCalculatedHash != deviceHash) {
    throw Exception("Token Invalid");
    // throw TokenNotValid(
    //     context: context,
    //     payload: {"reason": "device_id_not_valid"});
  }
  var t = AccessToken.fromMap(payloadMap);

  /// check
  //TODO: Check

  return t;
}