当前位置: 首页 > news >正文

Okhttp hostnameVerifier详解

hostnameVerifier

  • 方法简介
  • 核心原理
  • 参考资料

方法简介

本篇博文以Okhttp 4.6.0来解析hostnameVerfier的作用,顾名思义,该方法的主要作用就是鉴定hostnname的合法性。Okhttp在初始化的时候我们可以自己配置hostnameVerfier

new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).writeTimeout(35, TimeUnit.SECONDS)  .hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {//注意这里在生产环境中千万不要直接写死true          return true;}}).build();

但是网上好多资料将verfiy直接返回true是十分危险的。当然如果vertify返回fasle意味着hostname验证不通过,http请求无法成功,比如我以自己的博客地址发起http请求,错误信息如下:
在这里插入图片描述

{http errorCode=-500, mErrorMsg=Hostname yanchen.blog.csdn.net not verified:certificate: sha256/tlnf6pbfeu257hnJ9e6j4A1ZWH3vVMzn3Zn3F9kLHdg=DN: CN=*.blog.csdn.netsubjectAltNames: [*.blog.csdn.net]}

执行vertify的地方是在RealConnection里面,执行之后。
在这里插入图片描述

除了自定义hostnameVerfier之外,Okhttp提供了默认实现,现在就分析下起内部原理。

核心原理

在Okhttp内置了OkHostnameVerifier,该方法通过session.peerCertificates[0] as X509Certificate获取证书的对象

override fun verify(host: String, session: SSLSession): Boolean {return try {verify(host, session.peerCertificates[0] as X509Certificate)} catch (_: SSLException) {false}}fun verify(host: String, certificate: X509Certificate): Boolean {return when {host.canParseAsIpAddress() -> verifyIpAddress(host, certificate)else -> verifyHostname(host, certificate)}}

通过X509Certificate对象提供了一系列get方法可以获取到证书的公钥,序列号等一系列信息。见下图:
在这里插入图片描述
最终会调用verifyHostname方法,通过certificate获取getSubjectAltNames拿到SubjectAltName之后,将hostname与SubjectAltName进行比对,如果符合就返回true,否则就返回fasle.

private fun verifyHostname(hostname: String, certificate: X509Certificate): Boolean {val hostname = hostname.toLowerCase(Locale.US)return getSubjectAltNames(certificate, ALT_DNS_NAME).any {verifyHostname(hostname, it)}}//hostname和SubjectAltName比对
private fun verifyHostname(hostname: String?, pattern: String?): Boolean {var hostname = hostnamevar pattern = pattern//检验客户端域名的有效性if (hostname.isNullOrEmpty() ||hostname.startsWith(".") ||hostname.endsWith("..")) {// Invalid domain namereturn false}//检验证书中SubjectAltName的有效性if (pattern.isNullOrEmpty() ||pattern.startsWith(".") ||pattern.endsWith("..")) {// Invalid pattern/domain namereturn false}// Normalize hostname and pattern by turning them into absolute domain names if they are not// yet absolute. This is needed because server certificates do not normally contain absolute// names or patterns, but they should be treated as absolute. At the same time, any hostname// presented to this method should also be treated as absolute for the purposes of matching// to the server certificate.//   www.android.com  matches www.android.com//   www.android.com  matches www.android.com.//   www.android.com. matches www.android.com.//   www.android.com. matches www.android.comif (!hostname.endsWith(".")) {hostname += "."}if (!pattern.endsWith(".")) {pattern += "."}// Hostname and pattern are now absolute domain names.pattern = pattern.toLowerCase(Locale.US)// Hostname and pattern are now in lower case -- domain names are case-insensitive.if ("*" !in pattern) {// Not a wildcard pattern -- hostname and pattern must match exactly.return hostname == pattern}// Wildcard pattern// WILDCARD PATTERN RULES:// 1. Asterisk (*) is only permitted in the left-most domain name label and must be the//    only character in that label (i.e., must match the whole left-most label).//    For example, *.example.com is permitted, while *a.example.com, a*.example.com,//    a*b.example.com, a.*.example.com are not permitted.// 2. Asterisk (*) cannot match across domain name labels.//    For example, *.example.com matches test.example.com but does not match//    sub.test.example.com.// 3. Wildcard patterns for single-label domain names are not permitted.if (!pattern.startsWith("*.") || pattern.indexOf('*', 1) != -1) {// Asterisk (*) is only permitted in the left-most domain name label and must be the only// character in that labelreturn false}// Optimization: check whether hostname is too short to match the pattern. hostName must be at// least as long as the pattern because asterisk must match the whole left-most label and// hostname starts with a non-empty label. Thus, asterisk has to match one or more characters.if (hostname.length < pattern.length) {return false // Hostname too short to match the pattern.}if ("*." == pattern) {return false // Wildcard pattern for single-label domain name -- not permitted.}// Hostname must end with the region of pattern following the asterisk.val suffix = pattern.substring(1)if (!hostname.endsWith(suffix)) {return false // Hostname does not end with the suffix.}// Check that asterisk did not match across domain name labels.val suffixStartIndexInHostname = hostname.length - suffix.lengthif (suffixStartIndexInHostname > 0 &&hostname.lastIndexOf('.', suffixStartIndexInHostname - 1) != -1) {return false // Asterisk is matching across domain name labels -- not permitted.}// Hostname matches pattern.return true}

那么SubjectAltName是什么?我们可以通过如下方法获取:

new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {try {X509Certificate x509Certificate= (X509Certificate) session.getPeerCertificates()[0];Collection<List<?>> subjectAltNames = x509Certificate.getSubjectAlternativeNames();for (List<?> subjectAltName : subjectAltNames) {if (subjectAltName == null || subjectAltName.size() < 2) continue;int type = (int)subjectAltName.get(0);if (type!= 2) continue;String altName = (String)subjectAltName.get(1);LogUtil.logD("hostnameVerifier","x509Certificate altName=="+altName);}} catch (Exception e) {}     return true;}}

在这里插入图片描述
在这里插入图片描述
Okhttp 内置的hostname校验逻辑很简单,大家可以自行查看起源码即可。

参考资料

  1. Android CertificateSource系统根证书的检索和获取
  2. Android https TrustManager checkServerTrusted 详解
  3. Android RootTrustManager 证书校验简单分析
  4. Android CertificateSource系统根证书的检索和获取
  5. Android AndroidNSSP的简单说明
  6. Okhttp之RealConnection建立链接简单分析

相关文章:

Okhttp hostnameVerifier详解

hostnameVerifier 方法简介核心原理参考资料 方法简介 本篇博文以Okhttp 4.6.0来解析hostnameVerfier的作用&#xff0c;顾名思义&#xff0c;该方法的主要作用就是鉴定hostnname的合法性。Okhttp在初始化的时候我们可以自己配置hostnameVerfier&#xff1a; new OkHttpClien…...

TCP的p2p网络模式

TCP的p2p网络模式 1、tcp连接的状态有以下11种 CLOSED&#xff1a;关闭状态LISTEN&#xff1a;服务端状态&#xff0c;等待客户端发起连接请求SYN_SENT&#xff1a;客户端已发送同步连接请求&#xff0c;等待服务端相应SYN_RECEIVED&#xff1a;服务器收到客户端的SYN请请求&…...

力扣-贪心算法4

406.根据身高重建队列 406. 根据身高重建队列 题目 假设有打乱顺序的一群人站成一个队列&#xff0c;数组 people 表示队列中一些人的属性&#xff08;不一定按顺序&#xff09;。每个 people[i] [hi, ki] 表示第 i 个人的身高为 hi &#xff0c;前面 正好 有 ki 个身高大于或…...

动手学深度学习6.2 图像卷积-笔记练习(PyTorch)

以下内容为结合李沐老师的课程和教材补充的学习笔记&#xff0c;以及对课后练习的一些思考&#xff0c;自留回顾&#xff0c;也供同学之人交流参考。 本节课程地址&#xff1a;卷积层_哔哩哔哩_bilibili 代码_哔哩哔哩_bilibili 本节教材地址&#xff1a;6.2. 图像卷积 — 动…...

展开说说:Android服务之bindService解析

前面两篇文章我们分别总结了Android四种Service的基本使用以及源码层面总结一下startService的执行过程&#xff0c;本篇继续从源码层面总结bindService的执行过程。 本文依然按着是什么&#xff1f;有什么&#xff1f;怎么用&#xff1f;啥原理&#xff1f;的步骤来分析。 b…...

node-sass 老版本4.14.0 安装失败解决办法

旧项目 npm install 发现 node-sass 安装 失败 切换淘宝镜像之后 不能完全解决问题。因为需要编译&#xff0c;本地没有Python环境不能实现 安装node-sass时&#xff0c;在install阶段会从Github上下载一个叫binding.node的文件&#xff0c;而「GitHub Releases」里的文件…...

最近很火的字幕截图生成器

网址 https://disksing.com/fake-screenshot/ 最近很火的字幕截图生成器&#xff0c;对于自媒体来说真的太实用了 另外透露一下&#xff0c;你仔细研究就会发现&#xff0c;这是个纯前端的项目...

使用RabbitMQ实现可靠的消息传递机制

使用RabbitMQ实现可靠的消息传递机制 大家好&#xff0c;我是微赚淘客系统3.0的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01; 1. RabbitMQ简介 RabbitMQ是一个开源的消息代理软件&#xff0c;实现了高级消息队列协议&#xff08;AMQP&…...

Function Call ReACT,Agent应用落地的加速器_qwen的function calling和react有什么不同

探索智能体Agent的未来之路&#xff1a;Function Call与ReACT框架的较量&#xff0c;谁能引领未来&#xff1f; 引言 各大平台出现智能体应用创建&#xff0c;智能体逐渐落地&#xff0c;背后的使用哪种框架&#xff1f; 随着各大平台&#xff0c;例如百度千帆APPbuilder、阿…...

Java的JSONPath(fastjson)使用总结

背景 最近使用json实现复杂业务配置, 因为功能需要解析读取json的中节点数据。如果使用循环或者stream处理&#xff0c;可以实现&#xff0c;但是都过于麻烦。在想能否使用更简单json读取方式&#xff0c;正好发现fastjson支持该功能&#xff0c;本文做一个记录 案例说明 示…...

【大模型】大语言模型:光鲜背后的阴影——事实准确性和推理能力的挑战

大语言模型&#xff1a;光鲜背后的阴影——事实准确性和推理能力的挑战 引言一、概念界定二、事实准确性的局限2.1 训练数据的偏差2.2 知识的时效性问题2.3 复杂概念的理解与表述 三、推理能力的局限3.1 表层理解与深层逻辑的脱节3.2 缺乏常识推理3.3 无法进行长期记忆和连续推…...

Java面向对象练习(1.手机类)(2024.7.4)

手机类 package Phone;public class Phone {private String brand;private int price;private String color;public Phone(){}public Phone(String brand, int price, String color){this.brand brand;this.price price;this.color color;}public void setBrand(String bra…...

智慧生活新篇章,Vatee万腾平台领航前行

在21世纪的科技浪潮中&#xff0c;智慧生活已不再是一个遥远的梦想&#xff0c;而是正逐步成为我们日常生活的现实。从智能家居的温馨便捷&#xff0c;到智慧城市的高效运转&#xff0c;科技的每一次进步都在为我们的生活增添新的色彩。而在这场智慧生活的变革中&#xff0c;Va…...

Spring Cloud Gateway报sun.misc.Unsafe.park(Native Method)

项目引入spring cloud gateway的jar报&#xff0c;启动的时候报&#xff1a; [2024-07-05 10:10:16.162][main][ERROR][org.springframework.boot.web.embedded.tomcat.TomcatStarter][61]:Error starting Tomcat context. Exception: org.springframework.beans.factory.Bean…...

select single , select endselect

select single , select endselect single 根据条件找到一条数据&#xff0c;就出来了。 select endselect是在里面循环&#xff0c;每次找一条&#xff0c;依次放到into table中&#xff0c;或者放到into work area中&#xff0c;下面append table 。 实际开发中不建议这么操…...

后端学习(一)

添加数据库包&#xff1a; 数据库连接时 发生错误&#xff1a; 解决方式&#xff1a; SqlConnection conn new SqlConnection("serverlocalhost;databaseMyBBSDb;uidsa;pwd123456;Encryptfalse;") ;conn.Open();SqlCommand cmd new SqlCommand("SELECT * FROM…...

【活动行】参与上海两场线下活动,教育生态行业赛总决赛活动和WAIC人工智能大会活动 - 上海活动总结

目录 背景决赛最后一公里领域范围 决赛作品AI智教相机辅导老师Copilot辅导老师Copilot雅思写作竞技场 优秀作品总结 背景 决赛 百度发起的千帆杯教育生态行业赛于2024年7月4日进行线下决赛&#xff0c;博主虽然没能进入决赛&#xff0c;但也非常荣幸能够以嘉宾身份到现场给进…...

conda 安装设置

安装anaconda 推荐官网下载和安装,最新版本是anaconda3+python3.11,个人选择。有可能找不到 Index of /anaconda/archive/ | 清华大学开源软件镜像站 | Tsinghua Open Source Mirror Tips:小白一定要全部勾选,特别第二项“add anaconda3 to my path environment variable…...

用PlantUML和语雀画UML类图

概述 首先阐述一下几个简单概念&#xff1a; UML&#xff1a;是统一建模语言&#xff08;Unified Modeling Language&#xff09;的缩写&#xff0c;它是一种用于软件工程的标准化建模语言&#xff0c;旨在提供一种通用的方式来可视化软件系统的结构、行为和交互。UML由Grady…...

uniapp微信小程序电子签名

先上效果图&#xff0c;不满意可以直接关闭这页签 新建成单独的组件&#xff0c;然后具体功能引入&#xff0c;具体功能点击签名按钮&#xff0c;把当前功能页面用样式隐藏掉&#xff0c;v-show和v-if也行&#xff0c;然后再把这个组件显示出来。 【签名-撤销】原理是之前绘画时…...

Unity安卓构建72小时实战指南:从零到真机运行

1. 这不是“又一本Unity教程”&#xff0c;而是我带三个新人从零上线第一款安卓游戏的真实路径你点开这个标题&#xff0c;大概率正站在两个路口之间&#xff1a;一边是满屏“30天速成Unity”“零基础做爆款”的短视频封面&#xff0c;一边是你刚下载完Unity Hub、卡在Android …...

录音会议纪要整理不同使用场景,实用口碑选择建议

针对不同场景的录音整理需求&#xff08;短录音、中长录音、长内容深度整理&#xff09;&#xff0c;本文基于实际使用体验&#xff0c;分享不同场景下的工具选择建议与使用心得。一、场景一&#xff1a;短录音&#xff08;15-60分钟&#xff0c;发音清晰&#xff09;典型场景&…...

如何让Rhino 3D模型在Blender中保持完整数据:import_3dm插件深度解析

如何让Rhino 3D模型在Blender中保持完整数据&#xff1a;import_3dm插件深度解析 【免费下载链接】import_3dm Blender importer script for Rhinoceros 3D files 项目地址: https://gitcode.com/gh_mirrors/im/import_3dm 当建筑师需要在Blender中渲染Rhino设计的建筑模…...

Qri高级功能:如何使用JSON Schema验证和描述数据集结构

Qri高级功能&#xff1a;如何使用JSON Schema验证和描述数据集结构 【免费下载链接】qri youre invited to a data party! 项目地址: https://gitcode.com/gh_mirrors/qr/qri Qri是一个强大的开源数据协作工具&#xff0c;它提供了丰富的功能来帮助用户管理、共享和验证…...

终极歌词同步神器LRCGET:5分钟为你的音乐库添加完美歌词

终极歌词同步神器LRCGET&#xff1a;5分钟为你的音乐库添加完美歌词 【免费下载链接】lrcget Utility for mass-downloading LRC synced lyrics for your offline music library. 项目地址: https://gitcode.com/gh_mirrors/lr/lrcget 你是否厌倦了在听歌时手动搜索歌词…...

利用FTDI芯片MPSSE模式构建Arduino兼容开发环境

1. 项目概述&#xff1a;当FTDI芯片遇上Arduino生态如果你手头有一些闲置的FTDI USB转串口模块&#xff0c;比如常见的FT232R、FT2232H&#xff0c;或者像我一样&#xff0c;从某个旧设备上拆下来一块FT2232C的老古董&#xff0c;除了用来给单片机烧录程序或者做串口调试&#…...

免费解锁AMD Ryzen隐藏性能:SMUDebugTool终极指南

免费解锁AMD Ryzen隐藏性能&#xff1a;SMUDebugTool终极指南 【免费下载链接】SMUDebugTool A dedicated tool to help write/read various parameters of Ryzen-based systems, such as manual overclock, SMU, PCI, CPUID, MSR and Power Table. 项目地址: https://gitcod…...

PDF差异对比神器diff-pdf:告别文档核对烦恼,提升工作效率的智能解决方案

PDF差异对比神器diff-pdf&#xff1a;告别文档核对烦恼&#xff0c;提升工作效率的智能解决方案 【免费下载链接】diff-pdf A simple tool for visually comparing two PDF files 项目地址: https://gitcode.com/gh_mirrors/di/diff-pdf 你是否曾在核对PDF文档时感到头疼…...

3步免费解锁Cursor Pro:告别设备限制,永久享受AI编程助手高级功能

3步免费解锁Cursor Pro&#xff1a;告别设备限制&#xff0c;永久享受AI编程助手高级功能 【免费下载链接】cursor-free-vip [Support 0.45]&#xff08;Multi Language 多语言&#xff09;自动注册 Cursor Ai &#xff0c;自动重置机器ID &#xff0c; 免费升级使用Pro 功能: …...

保姆级教程:在Ubuntu 22.04上搞定水星MW310UH无线网卡驱动(含安全启动关闭指南)

水星MW310UH无线网卡在Ubuntu 22.04的完整驱动指南当你刚拿到水星MW310UH无线网卡&#xff0c;满心欢喜地插入Ubuntu 22.04系统&#xff0c;却发现系统毫无反应时&#xff0c;那种挫败感我深有体会。作为一款性价比极高的USB无线网卡&#xff0c;MW310UH在Windows下即插即用&am…...