SRI 介绍

来源:互联网 发布:艺术学博士知乎 编辑:程序博客网 时间:2024/05/17 05:07

What

Subresource Integrity (SRI) is a security feature that enables browsers to verify that files they fetch (for example, from a CDN) are delivered without unexpected manipulation.

在 <script> 和 link 标签中通过 integrity 属性,浏览器核实所获取的 js 文件(或 css 文件)确实是如 integrity 值规定的,然后再加载 js 文件(或应用css 文件)。

例子

如下是个 script 标签

<script src="https://example.com/example-framework.js"        integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"        crossorigin="anonymous"></script>

注意 integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC",integrity 的值以 sha384- 开头,表示算法为 sha384, dash (-) 之后跟随的是 base64-encoded hash。

当前所允许的 hash 算法有 sha256, sha384, and sha512

生成 SRI hashes 值

命令行有两种方法。

方法一:

cat FILENAME.js | openssl dgst -sha384 -binary | openssl enc -base64 -A  

方法二:

shasum -b -a 384 FILENAME.js | xxd -r -p | base64

注意,这里 shah 算法是 sha384,如果生成其他的 hash 值,是否也像这样,只需稍作修改即可(可能吧,但是未验证)。

还有在线工具 https://srihash.org/

浏览器如何处理 SRI (Subresource Integrity)

  1. When a browser encounters a <script> or <link> element with an integrity attribute, before executing the script or before applying any stylesheet specified by the <link> element, the browser must first compare the script or stylesheet to the expected hash given in the integrity value.

  2. If the script or stylesheet doesn’t match its associated integrity value, then the browser must refuse to execute the script or apply the stylesheet, and must instead return a network error indicating that fetching of that script or stylesheet failed.

参考

  1. Subresource Integrity
    https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
原创粉丝点击