--- a/libavformat/hls.c
+++ b/libavformat/hls.c
@@ -212,6 +212,8 @@
     int http_persistent;
     int http_multiple;
     int http_seekable;
+    char *key_uri_replace_old;
+    char *key_uri_replace_new;
     AVIOContext *playlist_pb;
 } HLSContext;
 
@@ -1256,8 +1258,16 @@
     } else if (seg->key_type == KEY_AES_128) {
         char iv[33], key[33], url[MAX_URL_SIZE];
         if (strcmp(seg->key, pls->key_url)) {
+            char *key_url = NULL;
             AVIOContext *pb = NULL;
-            if (open_url(pls->parent, &pb, seg->key, &c->avio_opts, opts, NULL) == 0) {
+            if (NULL != c->key_uri_replace_old && \
+                NULL != c-> key_uri_replace_new && \
+                '\0' != c->key_uri_replace_old[0]) {
+                key_url = av_strireplace(seg->key, c->key_uri_replace_old, c->key_uri_replace_new);
+            } else {
+                key_url = seg->key;
+            }
+            if (open_url(pls->parent, &pb, key_url, &c->avio_opts, opts, NULL) == 0) {
                 ret = avio_read(pb, pls->key, sizeof(pls->key));
                 if (ret != sizeof(pls->key)) {
                     av_log(pls->parent, AV_LOG_ERROR, "Unable to read key file %s\n",
@@ -1269,6 +1279,8 @@
                        seg->key);
             }
             av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
+            if (key_url != seg->key)
+                av_free(key_url);
         }
         ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
         ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
@@ -2405,6 +2417,8 @@
         OFFSET(http_multiple), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, FLAGS},
     {"http_seekable", "Use HTTP partial requests, 0 = disable, 1 = enable, -1 = auto",
         OFFSET(http_seekable), AV_OPT_TYPE_BOOL, { .i64 = -1}, -1, 1, FLAGS},
+    { "key_uri_old", "allow to replace part of AES key uri - old", OFFSET(key_uri_replace_old), AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, FLAGS },
+    { "key_uri_new", "allow to replace part of AES key uri - new", OFFSET(key_uri_replace_new), AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, FLAGS },
     {NULL}
 };