百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分析 > 正文

鸿蒙网络编程系列40-TLS数字证书查看及验签示例

liebian365 2024-11-09 13:44 18 浏览 0 评论

1. TLS数字证书验签简介

数字证书的验签是网络编程中一个重要的功能,它保证了数字证书的真实性,在此基础上,我们才可以信任该证书,从而信任基于该证书建立的安全通道,所以说,数字证书的验签是通讯安全的基石,了解数字证书验签的原理和方法,有助于我们建立安全的通讯。

用户数字证书的验签是通过签发该数字证书的CA证书完成的,因为用户数字证书是由CA证书的私钥签名的,使用CA的公钥可以验证数字证书的合法性,鸿蒙的X509Cert数字证书类提供了验签方法verify:

verify(key: cryptoFramework.PubKey): Promise<void>

该方法可以通过CA的公钥来验证证书的有效性。

本文将通过一个示例演示数字证书内容的查看方法以及如何对一个数字证书进行验签。

2. TLS数字证书查看及验签演示

本示例运行后的界面如图所示:

单击CA证书后面的“选择”按钮,选择一个CA证书,再单击“查看”按钮可以查看该证书的详细信息,如图所示:

然后再选择一个不是该CA证书签发的用户证书,比如百度的证书,再单击“验签”按钮:

很显然,验签失败了。再选择一个该CA证书签名的用户证书,然后单击“验签”按钮:

这次验签就通过了。

3.TLS数字证书查看及验签示例编写

下面详细介绍创建该示例的步骤。

步骤1:创建Empty Ability项目。

步骤2:在Index.ets文件里添加如下的代码:

import { BusinessError } from '@kit.BasicServicesKit';
import { cert } from '@kit.DeviceCertificateKit';
import fs from '@ohos.file.fs';
import { picker } from '@kit.CoreFileKit';

@Entry
@Component
struct Index {
  //连接、通讯历史记录
  @State msgHistory: string = ''
  //CA证书是否已选择
  @State caFileSelect: boolean = false
  //用户证书是否已选择
  @State certFileSelect: boolean = false
  //选择的ca文件
  @State caFileUri: string = ''
  //选择的用户证书文件
  @State certFileUri: string = ''
  scroller: Scroller = new Scroller()

  build() {
    Row() {
      Column() {
        Text("数字证书查看及验签示例")
          .fontSize(14)
          .fontWeight(FontWeight.Bold)
          .width('100%')
          .textAlign(TextAlign.Center)
          .padding(10)

        Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
          Text("CA证书")
            .fontSize(14)
            .width(90)
            .flexGrow(1)

          Button("选择")
            .onClick(async () => {
              this.caFileUri = await selectSingleDocFile(getContext(this))
              if (this.caFileUri) {
                this.caFileSelect = true
              }
            })
            .width(70)
            .fontSize(14)

          Button("查看")
            .onClick(() => {
              this.viewCertInfo(this.caFileUri)
            })
            .width(70)
            .fontSize(14)
            .enabled(this.caFileSelect)
        }
        .width('100%')
        .padding(10)

        Text(this.caFileUri)
          .width('100%')
          .padding(10)

        Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
          Text("用户证书:")
            .fontSize(14)
            .width(90)
            .flexGrow(1)

          Button("选择")
            .onClick(async () => {
              this.certFileUri = await selectSingleDocFile(getContext(this))
              if (this.certFileUri) {
                this.certFileSelect = true
              }
            })
            .width(70)
            .fontSize(14)

          Button("查看")
            .onClick(() => {
              this.viewCertInfo(this.certFileUri)
            })
            .width(70)
            .fontSize(14)
            .enabled(this.certFileSelect)

          Button("验签")
            .onClick(() => {
              this.verifyCert(this.caFileUri, this.certFileUri)
            })
            .width(70)
            .fontSize(14)
            .enabled(this.certFileSelect && this.caFileSelect)
        }
        .width('100%')
        .padding(10)

        Text(this.certFileUri)
          .width('100%')
          .padding(10)

        Scroll(this.scroller) {
          Text(this.msgHistory)
            .textAlign(TextAlign.Start)
            .padding(10)
            .width('100%')
            .backgroundColor(0xeeeeee)
        }
        .align(Alignment.Top)
        .backgroundColor(0xeeeeee)
        .height(300)
        .flexGrow(1)
        .scrollable(ScrollDirection.Vertical)
        .scrollBar(BarState.On)
        .scrollBarWidth(20)
      }
      .width('100%')
      .justifyContent(FlexAlign.Start)
      .height('100%')
    }
    .height('100%')
  }

  //输出指定证书文件的证书信息
  async viewCertInfo(filePath: string) {
    let x509Cert = await this.getCertFromFile(filePath)
    if (x509Cert != undefined) {
      this.showCertInfo(x509Cert)
    } else {
      this.msgHistory += "错误的证书文件格式:" + filePath + "\r\n";
    }
  }

  //从文件获取X509证书
  async getCertFromFile(filePath: string): Promise<cert.X509Cert | undefined> {
    let newCert: cert.X509Cert | undefined = undefined
    //读取文件内容
    let certData = readArrayBufferContentFromFile(filePath);
    if (certData) {
      let encodingBlob: cert.EncodingBlob = {
        data: new Uint8Array(certData),
        encodingFormat: cert.EncodingFormat.FORMAT_PEM
      };
      //创建X509数字证书
      await cert.createX509Cert(encodingBlob)
        .then((x509Cert: cert.X509Cert) => {
          newCert = x509Cert
        })
        .catch((err: BusinessError) => {
          this.msgHistory += `创建X509证书失败: 错误码 ${err.code}, 错误信息 ${JSON.stringify(err)}\r\n`;
        })
    }
    return newCert
  }

  //输出证书信息
  async showCertInfo(x509Cert: cert.X509Cert) {
    try {
      let issuerName = x509Cert.getIssuerX500DistinguishedName().getName()
      this.msgHistory += `颁发者可分辨名称:${issuerName}\r\n`;
      let subjectName = x509Cert.getSubjectX500DistinguishedName().getName()
      this.msgHistory += `证书主题可分辨名称:${subjectName}\r\n`;
      let subjectCNName = x509Cert.getSubjectX500DistinguishedName().getName("CN")
      this.msgHistory += `证书主题CN名称:${subjectCNName}\r\n`;
      this.msgHistory += `证书有效期:${x509Cert.getNotBeforeTime()}至${x509Cert.getNotAfterTime()}\r\n`;
      this.msgHistory += `证书签名算法:${x509Cert.getSignatureAlgName()}\r\n`;
    } catch (e) {
      this.msgHistory += '输出证书信息异常: ' + e.message + "\r\n";
    }
  }

  //使用CA证书验证用户证书
  async verifyCert(caFilePath: string, certFilePath: string) {
    //获取CA证书
    let caCert = await this.getCertFromFile(caFilePath)
    if (caCert == undefined) {
      this.msgHistory += "错误的证书文件格式:" + caFilePath + "\r\n";
      return
    }

    //获取用户证书
    let userCert = await this.getCertFromFile(certFilePath)
    if (userCert == undefined) {
      this.msgHistory += "错误的证书文件格式:" + certFilePath + "\r\n";
    }

    //使用CA证书公玥验证用户证书
    userCert?.verify(caCert.getPublicKey()).then(() => {
      this.msgHistory += "证书验签通过\r\n";
    })
      .catch((err: BusinessError) => {
        this.msgHistory += `验签失败:错误码 ${err.code}, 错误信息 ${JSON.stringify(err)}\r\n`;
      })
  }
}

//选择单个文件并返回选中文件地址
async function selectSingleDocFile(context: Context): Promise<string> {
  let selectedFilePath: string = ""
  let documentPicker = new picker.DocumentViewPicker(context);
  await documentPicker.select({ maxSelectNumber: 1 }).then((result) => {
    if (result.length > 0) {
      selectedFilePath = result[0]
    }
  })
  return selectedFilePath
}

//从文件读取二进制内容
function readArrayBufferContentFromFile(fileUri: string): ArrayBuffer {
  let file = fs.openSync(fileUri, fs.OpenMode.READ_ONLY);
  let fsStat = fs.statSync(file.fd);
  let buf = new ArrayBuffer(fsStat.size);
  fs.readSync(file.fd, buf);
  fs.fsyncSync(file.fd)
  fs.closeSync(file);
  return buf
}

步骤3:编译运行,可以使用模拟器或者真机。

步骤4:按照本节第2部分“TLS数字证书查看及验签演示”操作即可。

4.代码分析

本示例关键点有两个,一个是从证书文件中获取证书信息创建X509Cert对象,这是通过方法getCertFromFile实现的;另一个是使用CA证书验签用户证书,在获取CA公钥的时候使用的是X509Cert的getPublicKey方法,需要注意的是,该方法获取的公钥只能用于验签,不能用来获取公钥的内容,否则会出现异常。

(本文作者原创,除非明确授权禁止转载)

本文源码地址:

https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/tls/CertVerify

本系列源码地址:

HarmonyOSNetworkSamples: 鸿蒙网络编程示例仓库

相关推荐

4万多吨豪华游轮遇险 竟是因为这个原因……

(观察者网讯)4.7万吨豪华游轮搁浅,竟是因为油量太低?据观察者网此前报道,挪威游轮“维京天空”号上周六(23日)在挪威近海发生引擎故障搁浅。船上载有1300多人,其中28人受伤住院。经过数天的调...

“菜鸟黑客”必用兵器之“渗透测试篇二”

"菜鸟黑客"必用兵器之"渗透测试篇二"上篇文章主要针对伙伴们对"渗透测试"应该如何学习?"渗透测试"的基本流程?本篇文章继续上次的分享,接着介绍一下黑客们常用的渗透测试工具有哪些?以及用实验环境让大家...

科幻春晚丨《震动羽翼说“Hello”》两万年星间飞行,探测器对地球的最终告白

作者|藤井太洋译者|祝力新【编者按】2021年科幻春晚的最后一篇小说,来自大家喜爱的日本科幻作家藤井太洋。小说将视角放在一颗太空探测器上,延续了他一贯的浪漫风格。...

麦子陪你做作业(二):KEGG通路数据库的正确打开姿势

作者:麦子KEGG是通路数据库中最庞大的,涵盖基因组网络信息,主要注释基因的功能和调控关系。当我们选到了合适的候选分子,单变量研究也已做完,接着研究机制的时便可使用到它。你需要了解你的分子目前已有哪些...

知存科技王绍迪:突破存储墙瓶颈,详解存算一体架构优势

智东西(公众号:zhidxcom)编辑|韦世玮智东西6月5日消息,近日,在落幕不久的GTIC2021嵌入式AI创新峰会上,知存科技CEO王绍迪博士以《存算一体AI芯片:AIoT设备的算力新选择》...

每日新闻播报(September 14)_每日新闻播报英文

AnOscarstatuestandscoveredwithplasticduringpreparationsleadinguptothe87thAcademyAward...

香港新巴城巴开放实时到站数据 供科技界研发使用

中新网3月22日电据香港《明报》报道,香港特区政府致力推动智慧城市,鼓励公私营机构开放数据,以便科技界研发使用。香港运输署21日与新巴及城巴(两巴)公司签署谅解备忘录,两巴将于2019年第3季度,开...

5款不容错过的APP: Red Bull Alert,Flipagram,WifiMapper

本周有不少非常出色的app推出,鸵鸟电台做了一个小合集。亮相本周榜单的有WifiMapper's安卓版的app,其中包含了RedBull的一款新型闹钟,还有一款可爱的怪物主题益智游戏。一起来看看我...

Qt动画效果展示_qt显示图片

今天在这篇博文中,主要实践Qt动画,做一个实例来讲解Qt动画使用,其界面如下图所示(由于没有录制为gif动画图片,所以请各位下载查看效果):该程序使用应用程序单窗口,主窗口继承于QMainWindow...

如何从0到1设计实现一门自己的脚本语言

作者:dong...

三年级语文上册 仿写句子 需要的直接下载打印吧

描写秋天的好句好段1.秋天来了,山野变成了美丽的图画。苹果露出红红的脸庞,梨树挂起金黄的灯笼,高粱举起了燃烧的火把。大雁在天空一会儿写“人”字,一会儿写“一”字。2.花园里,菊花争奇斗艳,红的似火,粉...

C++|那些一看就很简洁、优雅、经典的小代码段

目录0等概率随机洗牌:1大小写转换2字符串复制...

二年级上册语文必考句子仿写,家长打印,孩子照着练

二年级上册语文必考句子仿写,家长打印,孩子照着练。具体如下:...

一年级语文上 句子专项练习(可打印)

...

亲自上阵!C++ 大佬深度“剧透”:C++26 将如何在代码生成上对抗 Rust?

...

取消回复欢迎 发表评论: