ErrorCode EncryptionParams::unserialize()

in util/EncryptionUtils.cpp [168:228]


ErrorCode EncryptionParams::unserialize(const string& input,
                                        EncryptionParams& out) {
  out.erase();
  enum {
    IN_TYPE,
    FIRST_HEX,
    LEFT_HEX,
    RIGHT_HEX,
  } state = IN_TYPE;
  int type = 0;
  int byte = 0;
  for (char c : input) {
    if (state == IN_TYPE) {
      // In type section (before ':')
      if (c == ':') {
        if (type == 0) {
          WLOG(ERROR) << "Enc type still none when ':' reached " << input;
          return ERROR;
        }
        state = FIRST_HEX;
        continue;
      }
    }
    int v = WdtUri::fromHex(c);
    if (v < 0) {
      WLOG(ERROR) << "Not hex found " << (int)c << " in " << input;
      return ERROR;
    }
    if (state == IN_TYPE) {
      // Pre : hex digits
      type = (type << 4) | v;
      continue;
    }
    if (state != RIGHT_HEX) {
      // First or Left (even) hex digit:
      byte = v << 4;
      state = RIGHT_HEX;
      continue;
    }
    // Right (odd) hex digit:
    out.data_.push_back((char)(byte | v));
    state = LEFT_HEX;
    byte = 0;  // not needed but safer
  }
  if (state == IN_TYPE) {
    WLOG(ERROR) << "Missing ':' in encryption data " << input;
    return ERROR;
  }
  if (state != LEFT_HEX) {
    WLOG(ERROR) << "Odd number of hex in encryption data " << input
                << " decoded up to: " << out.data_;
    return ERROR;
  }
  if (type <= ENC_NONE || type >= NUM_ENC_TYPES) {
    WLOG(ERROR) << "Encryption type out of range " << type;
    return ERROR;
  }
  out.type_ = static_cast<EncryptionType>(type);
  WVLOG(1) << "Deserialized Encryption Params " << out.getLogSafeString();
  return OK;
}