[Kimchi-devel] [PATCH V2] add a base64 safe url encode and decode to js utils

Hongliang Wang hlwang at linux.vnet.ibm.com
Tue Jul 22 03:31:51 UTC 2014


On 07/22/2014 10:20 AM, shaohef at linux.vnet.ibm.com wrote:
> From: ShaoHe Feng <shaohef at linux.vnet.ibm.com>

> Most webs use safe url base64 encode/decode to escape the special characters.
For special characters, there are functions called 
encodeURIComponent()/decodeURIComponent() which are designed to do this.
     (See: http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp , 
http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp)

For binary data (e.g. images), especially transferred between back-end 
and front-end through AJAX, Base64 is the choice.
>
> base64 encode/decode is similar to base64 safe url encode/decode.
>
> The difference is the alphabet.
> The base64 safe url alphabet uses '-' instead of '+' and '_' instead of '/'.
>
> after this patch:
> In backend, we can encode an url:
>>>> base64.urlsafe_b64encode("/vnc_auto.html?port=64667&path=?token=opensuse12&encrypt=1")
> 'L3ZuY19hdXRvLmh0bWw_cG9ydD02NDY2NyZwYXRoPT90b2tlbj1vcGVuc3VzZTEyJmVuY3J5cHQ9MQ=='
> and in UI, we can decode it:
> kimchi.urlSafeB64Decode("L3ZuY19hdXRvLmh0bWw_cG9ydD02NDY2NyZwYXRoPT90b2tlbj1vcGVuc3VzZTEyJmVuY3J5cHQ9MQ==")
> "/vnc_auto.html?port=64667&path=?token=opensuse12&encrypt=1"
>
> or
>
> In UI, we can encode an url:
> kimchi.urlSafeB64Encode("/vnc_auto.html?port=64667&path=?token=opensuse12&encrypt=1")
> "L3ZuY19hdXRvLmh0bWw_cG9ydD02NDY2NyZwYXRoPT90b2tlbj1vcGVuc3VzZTEyJmVuY3J5cHQ9MQ=="
> and in backend, we can decode it:
>>>> base64.urlsafe_b64decode("L3ZuY19hdXRvLmh0bWw_cG9ydD02NDY2NyZwYXRoPT90b2tlbj1vcGVuc3VzZTEyJmVuY3J5cHQ9MQ==")
> '/vnc_auto.html?port=64667&path=?token=opensuse12&encrypt=1'
>
> Safe url base64 is a variant of base64.
> More info:
> http://en.wikipedia.org/wiki/Base64#Implementations_and_history
>
> Signed-off-by: ShaoHe Feng <shaohef at linux.vnet.ibm.com>
> ---
>   ui/js/src/kimchi.utils.js | 8 ++++++++
>   1 file changed, 8 insertions(+)
>
> diff --git a/ui/js/src/kimchi.utils.js b/ui/js/src/kimchi.utils.js
> index c7103f8..480b9b5 100644
> --- a/ui/js/src/kimchi.utils.js
> +++ b/ui/js/src/kimchi.utils.js
> @@ -183,3 +183,11 @@ kimchi.escapeStr = function(str) {
>
>       return str;
>   };
> +
> +kimchi.urlSafeB64Decode = function(str) {
> +    return atob(str.replace(/-/g, '+').replace(/_/g, '/'));
> +}
> +
> +kimchi.urlSafeB64Encode = function(str) {
> +    return btoa(str).replace(/\+/g, '-').replace(/\//g, '_');
> +}




More information about the Kimchi-devel mailing list