class Util {

  public static void validateKeyset(Keyset keyset) throws GeneralSecurityException {
    int primaryKeyId = keyset.getPrimaryKeyId();
    boolean hasPrimaryKey = false;
    boolean containsOnlyPublicKeyMaterial = true;
    int numEnabledKeys = 0;
    for (Keyset.Key key : keyset.getKeyList()) {
      if (key.getStatus() != KeyStatusType.ENABLED) {
        continue;
      }
      validateKey(key);
      if (key.getKeyId() == primaryKeyId) {
        if (hasPrimaryKey) {
          throw new GeneralSecurityException("keyset contains multiple primary keys");
        }
        hasPrimaryKey = true;
      }
      if (key.getKeyData().getKeyMaterialType() != KeyData.KeyMaterialType.ASYMMETRIC_PUBLIC) {
        containsOnlyPublicKeyMaterial = false;
      }
      numEnabledKeys++;
    }
    if (numEnabledKeys == 0) {
      throw new GeneralSecurityException("keyset must contain at least one ENABLED key");
    }
    // Checks that a keyset contains a primary key, except when it contains only public keys.
    if (!hasPrimaryKey && !containsOnlyPublicKeyMaterial) {
      throw new GeneralSecurityException("keyset doesn't contain a valid primary key");
    }
  }

}