base64: encode_url (#6622)
parent
31ef921ef2
commit
df82ef6bc7
|
@ -48,6 +48,26 @@ pub fn encode(data string) string {
|
|||
return tos(buffer, encode_in_buffer(data, buffer))
|
||||
}
|
||||
|
||||
// decode decodes base64url string to string
|
||||
pub fn decode_url(data string) string {
|
||||
mut result := data.replace('-', '+') // 62nd char of encoding
|
||||
result = data.replace('_', '/') // 63rd char of encoding
|
||||
match result.len % 4 { // Pad with trailing '='s
|
||||
2 { result += "==" } // 2 pad chars
|
||||
3 { result += "=" } // 1 pad char
|
||||
else { } // no padding
|
||||
}
|
||||
return base64.decode(data)
|
||||
}
|
||||
|
||||
// encode encodes given string to base64url string
|
||||
pub fn encode_url(data string) string {
|
||||
mut result := base64.encode(data)
|
||||
// 62nd char of encoding, 63rd char of encoding, remove any trailing '='s
|
||||
result = result.replace_each(['+', '-', '/', '_', '=', ''])
|
||||
return result
|
||||
}
|
||||
|
||||
/*
|
||||
decode_in_buffer - expects a string reference, and a buffer in which to store its decoded version.
|
||||
@param data - a reference/pointer to the input string that will be decoded.
|
||||
|
|
|
@ -31,12 +31,12 @@ const (
|
|||
TestPair{'asure.', 'YXN1cmUu'},
|
||||
TestPair{'sure.', 'c3VyZS4='},
|
||||
]
|
||||
|
||||
|
||||
man_pair = TestPair{
|
||||
'Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.',
|
||||
'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4='
|
||||
}
|
||||
|
||||
|
||||
)
|
||||
|
||||
fn test_decode() {
|
||||
|
@ -67,3 +67,13 @@ fn test_encode() {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn test_encode_url() {
|
||||
test := base64.encode_url('Hello Base64Url encoding!')
|
||||
assert test == 'SGVsbG8gQmFzZTY0VXJsIGVuY29kaW5nIQ'
|
||||
}
|
||||
|
||||
fn test_decode_url() {
|
||||
test := base64.decode_url("SGVsbG8gQmFzZTY0VXJsIGVuY29kaW5nIQ")
|
||||
assert test == 'Hello Base64Url encoding!'
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue