SRI 介绍

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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值