有没有简单的方法来检查base64图像url是否有效?我通过ajax / xhr从服务器获取base64 url,想要避免我的网站上的xss。
有没有简单的方法来检查base64图像url是否有效?我通过ajax / xhr从服务器获取base64 url,想要避免我的网站上的xss。
我使用@wolfshirts的答案编写了一个异步函数。它对我有效。
@wolfshirts的函数将不起作用,因为return语句放置在错误的作用域中。
async function isBase64UrlImage(base64String: string) {
let image = new Image()
image.src = base64String
return await (new Promise((resolve)=>{
image.onload = function () {
if (image.height === 0 || image.width === 0) {
resolve(false);
return;
}
resolve(true)
}
image.onerror = () =>{
resolve(false)
}
}))
}
"/"表示JPEG。
"i"表示PNG。
"R"表示GIF。
"U"表示WebP。
let data = //suspectedBase64Image
function isImage(data){
let knownTypes = {
'/': 'data:image/jpg;base64,',
'i': 'data:image/png;base64,',
/*ETC*/
}
let image = new Image()
if(!knownTypes[data[0]]){
console.log("encoded image didn't match known types");
return false;
}else{
image.src = knownTypes[0]+data
image.onload = function(){
//This should load the image so that you can actually check
//height and width.
if(image.height === 0 || image.width === 0){
console.log('encoded image missing width or height');
return false;
}
}
return true;
}
这是一些基本的健全性检查,您可以使用它。
您可以深入使用并将魔术数字转换为base64,然后在base64数据中检查它们。此代码假设您在开头缺少数据类型。有些base64将在base64开头处的字典中显示数据类型。