Reduce code duplication in key handling