在HTML5中可以使用JS + Canvas標簽生成圖片,利用”canvas.toDataURL()”可以獲取到圖片的Base64碼。
同樣的JS Canvas繪圖代碼,在同一個瀏覽器下生成的圖片是相同的(字節碼相同)。
但是由於系統的差別、渲染引擎的不同,同樣的JS Canvas繪圖代碼,在不同的瀏覽器下得到的圖片也是不同的(字節碼不同。注意:也有相同的可能,但是概率較小)。
利用上述原理,同一段JS Canvas繪圖代碼,返回生成圖片的HASH值作為“HTML5 Canvas指紋”。
【在線測試工具】
https://browserleaks.com/canvas
如附圖1所示,我的谷歌瀏覽器的“HTML5 Canvas指紋”在793798 個相同UA的瀏覽器中,僅有317個相同的,唯一性高達99.96%。
【”HTML5 Canvas指紋算法”示例代碼】
// 計算字符串的hash值
function hashstr(s){ var hash = 0; if (s.length == 0) return hash; for (i = 0; i < s.length; i++) { char = s.charCodeAt(i); hash = ((hash<<5)-hash)+char; hash = hash & hash; // Convert to 32bit integer } return hash; }
使用canvas繪圖,並返回圖片的Base64碼對應的hash值
function getCanvasFp() { var result = ""; // Very simple now, need to make it more complex (geo shapes etc) var canvas = document.createElement('canvas'); canvas.width = 2000; canvas.height = 200; canvas.style.display = 'inline'; var ctx = canvas.getContext('2d'); // detect browser support of canvas winding // http://t.cn/R7wzrRy // http://t.cn/AiFHoZG5 ctx.rect(0, 0, 10, 10); ctx.rect(2, 2, 6, 6); result += 'canvas winding:' + ((ctx.isPointInPath(5, 5, 'evenodd') === false) ? 'yes' : 'no'); ctx.textBaseline = 'alphabetic'; ctx.fillStyle = '#f60'; ctx.fillRect(125, 1, 62, 20); ctx.fillStyle = '#069'; // http://t.cn/AiFHoZGx ctx.font = '11pt no-real-font-123'; ctx.fillText('Cwm fjordbank glyphs vext quiz, \ud83d\ude03', 2, 15); ctx.fillStyle = 'rgba(102, 204, 0, 0.2)'; ctx.font = '18pt Arial'; ctx.fillText('Cwm fjordbank glyphs vext quiz, \ud83d\ude03', 4, 45); // canvas blending // http://t.cn/AiFHoZGt // http://t.cn/AiFHoZGM ctx.globalCompositeOperation = 'multiply'; ctx.fillStyle = 'rgb(255,0,255)'; ctx.beginPath(); ctx.arc(50, 50, 50, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); ctx.fillStyle = 'rgb(0,255,255)'; ctx.beginPath(); ctx.arc(100, 50, 50, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); ctx.fillStyle = 'rgb(255,255,0)'; ctx.beginPath(); ctx.arc(75, 100, 50, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); ctx.fillStyle = 'rgb(255,0,255)'; // canvas winding // http://t.cn/R7wzrRy // http://t.cn/AiFHoZGf ctx.arc(75, 75, 75, 0, Math.PI * 2, true); ctx.arc(75, 75, 25, 0, Math.PI * 2, true); ctx.fill('evenodd'); if (canvas.toDataURL) { result += ';canvas fp:' + canvas.toDataURL(); } return hashstr(result); }