1. 服務(wù)端數(shù)字證書驗(yàn)證的問題
在鴻蒙客戶端對服務(wù)端發(fā)起HTTPS請求時(shí),如果使用HttpRequest的request發(fā)起請求,那么就存在服務(wù)端數(shù)字證書的驗(yàn)證問題,你只有兩個(gè)選擇,一個(gè)是使用系統(tǒng)的CA,一個(gè)是使用自己選定的CA,在上文鴻蒙網(wǎng)絡(luò)編程系列26-HTTPS證書自選CA校驗(yàn)示例中,對此進(jìn)行了介紹。但是,還有一些更常見的問題難以解決:
- 可不可以跳過對服務(wù)端數(shù)字證書的驗(yàn)證
- 可不可以自定義驗(yàn)證規(guī)則,比如,只驗(yàn)證數(shù)字證書的公玥,忽略有效期,就是說失效了也可以繼續(xù)用
如果你還是使用HttpRequest的話,答案是否定的。但是,鴻蒙開發(fā)者很貼心的推出了遠(yuǎn)場通信服務(wù),可以使用rcp模塊的方法發(fā)起請求,并且在請求時(shí)指定服務(wù)端證書的驗(yàn)證方式,關(guān)鍵點(diǎn)就在SecurityConfiguration接口上,該接口的remoteValidation屬性支持遠(yuǎn)程服務(wù)器證書的四種驗(yàn)證模式:
- 'system':使用系統(tǒng)CA,默認(rèn)值
- 'skip':跳過驗(yàn)證
- CertificateAuthority:選定CA
- ValidationCallback:自定義證書校驗(yàn)
Talk is cheap, show you the code!
2. 實(shí)現(xiàn)HTTPS服務(wù)端證書四種校驗(yàn)方式示例
本示例運(yùn)行后的界面如下所示:

選擇證書驗(yàn)證模式,在請求地址輸入要訪問的https網(wǎng)址,然后單擊“請求”按鈕,就可以在下面的日志區(qū)域顯示請求結(jié)果。
下面詳細(xì)介紹創(chuàng)建該應(yīng)用的步驟。
步驟1:創(chuàng)建Empty Ability項(xiàng)目。
步驟2:在module.json5配置文件加上對權(quán)限的聲明:
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]這里添加了獲取互聯(lián)網(wǎng)信息的權(quán)限。
步驟3:在Index.ets文件里添加如下的代碼:
import util from '@ohos.util';
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
@Entry
@Component
struct Index {
//連接、通訊歷史記錄
@State msgHistory: string = ''
//請求的HTTPS地址
@State httpsUrl: string = "https://47.**.**.***:8081/hello"
//服務(wù)端證書驗(yàn)證模式,默認(rèn)系統(tǒng)CA
@State certVerifyType: number = 0
//是否顯示選擇CA的組件
@State selectCaShow: Visibility = Visibility.None
//選擇的ca文件
@State caFileUri: string = ''
scroller: Scroller = new Scroller()
build() {
Row() {
Column() {
Text("遠(yuǎn)場通訊HTTPS證書校驗(yàn)示例")
.fontSize(14)
.fontWeight(FontWeight.Bold)
.width('100%')
.textAlign(TextAlign.Center)
.padding(10)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Text("選擇服務(wù)器HTTPS證書的驗(yàn)證模式:")
.fontSize(14)
.width(90)
.flexGrow(1)
}
.width('100%')
.padding(10)
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
Column() {
Text('系統(tǒng)CA').fontSize(14)
Radio({ value: '0', group: 'rgVerify' }).checked(true)
.height(50)
.width(50)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.certVerifyType = 0
}
})
}
Column() {
Text('指定CA').fontSize(14)
Radio({ value: '1', group: 'rgVerify' }).checked(false)
.height(50)
.width(50)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.certVerifyType = 1
}
})
}
Column() {
Text('跳過驗(yàn)證').fontSize(14)
Radio({ value: '2', group: 'rgVerify' }).checked(false)
.height(50)
.width(50)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.certVerifyType = 2
}
})
}
Column() {
Text('自定義驗(yàn)證').fontSize(14)
Radio({ value: '3', group: 'rgVerify' }).checked(false)
.height(50)
.width(50)
.onChange((isChecked: boolean) => {
if (isChecked) {
this.certVerifyType = 3
}
})
}
}
.width('100%')
.padding(10)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Text("服務(wù)端證書CA")
.fontSize(14)
.width(90)
.flexGrow(1)
Button("選擇")
.onClick(() => {
this.selectCA()
})
.width(70)
.fontSize(14)
}
.width('100%')
.padding(10)
.visibility(this.certVerifyType == 1 ? Visibility.Visible : Visibility.None)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Text("請求地址:")
.fontSize(14)
.width(80)
TextInput({ text: this.httpsUrl })
.onChange((value) => {
this.httpsUrl = value
})
.width(110)
.fontSize(12)
.flexGrow(1)
Button("請求")
.onClick(() => {
this.doHttpRequest()
})
.width(60)
.fontSize(14)
}
.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%')
}
//自定義證書驗(yàn)證方式
selfDefServerCertValidation: rcp.ValidationCallback = (context: rcp.ValidationContext) => {
//此處編寫證書有效性判斷邏輯
return true;
}
//生成rcp配置信息
buildRcpCfg() {
let caCert: rcp.CertificateAuthority = {
content: this.getCAContent()
}
//服務(wù)器端證書驗(yàn)證模式
let certVerify: 'system' | 'skip' | rcp.CertificateAuthority | rcp.ValidationCallback = "system"
if (this.certVerifyType == 0) { //系統(tǒng)驗(yàn)證
certVerify = 'system'
} else if (this.certVerifyType == 1) { //選擇CA證書驗(yàn)證
certVerify =caCert
} else if (this.certVerifyType == 2) { //跳過驗(yàn)證
certVerify = 'skip'
} else if (this.certVerifyType == 3) { //自定義證書驗(yàn)證
certVerify = this.selfDefServerCertValidation
}
let secCfg: rcp.SecurityConfiguration = { remoteValidation: certVerify }
let reqCfg: rcp.Configuration = { security: secCfg }
let sessionCfg: rcp.SessionConfiguration = { requestConfiguration: reqCfg }
return sessionCfg
}
//發(fā)起http請求
doHttpRequest() {
let rcpCfg = this.buildRcpCfg()
let rcpSession: rcp.Session = rcp.createSession(rcpCfg)
rcpSession.get(this.httpsUrl).then((response) => {
if (response.body != undefined) {
let result = buf2String(response.body)
this.msgHistory += '請求響應(yīng)信息: ' + result + "\r\n";
}
}).catch((err: BusinessError) => {
this.msgHistory += `err: err code is ${err.code}, err message is ${JSON.stringify(err)}\r\n`;
})
}
//選擇CA證書文件
selectCA() {
let documentPicker = new picker.DocumentViewPicker();
documentPicker.select().then((result) => {
if (result.length > 0) {
this.caFileUri = result[0]
this.msgHistory += "select file: " + this.caFileUri + "\r\n";
}
}).catch((e: BusinessError) => {
this.msgHistory += 'DocumentViewPicker.select failed ' + e.message + "\r\n";
});
}
//加載CA文件內(nèi)容
getCAContent(): string {
let caContent = ""
try {
let buf = new ArrayBuffer(1024 * 4);
let file = fs.openSync(this.caFileUri, fs.OpenMode.READ_ONLY);
let readLen = fs.readSync(file.fd, buf, { offset: 0 });
caContent = buf2String(buf.slice(0, readLen))
fs.closeSync(file);
} catch (e) {
this.msgHistory += 'readText failed ' + e.message + "\r\n";
}
return caContent
}
}
//ArrayBuffer轉(zhuǎn)utf8字符串
function buf2String(buf: ArrayBuffer) {
let msgArray = new Uint8Array(buf);
let textDecoder = util.TextDecoder.create("utf-8");
return textDecoder.decodeWithStream(msgArray)
}
步驟4:編譯運(yùn)行,可以使用模擬器或者真機(jī)。
步驟5:選擇默認(rèn)“系統(tǒng)CA”,輸入請求網(wǎng)址(假設(shè)web服務(wù)端使用的是自簽名證書),然后單擊“請求”按鈕,這時(shí)候會(huì)出現(xiàn)關(guān)于數(shù)字證書的錯(cuò)誤信息,如圖所示:

步驟6:選擇“指定CA”類型,然后單擊出現(xiàn)的“選擇”按鈕,可以在本機(jī)選擇CA證書文件,然后單擊“請求”按鈕:

可以看到,得到了正確的請求結(jié)果。
步驟7:選擇“跳過驗(yàn)證”類型,然后然后單擊“請求”按鈕:

也得到了正確的請求結(jié)果。
步驟8:選擇“自定義驗(yàn)證”類型,然后然后單擊“請求”按鈕:

也得到了正確的請求結(jié)果。
3. 關(guān)鍵功能分析
關(guān)鍵點(diǎn)主要有兩塊,第一塊是設(shè)置驗(yàn)證模式:
//服務(wù)器端證書驗(yàn)證模式
let certVerify: 'system' | 'skip' | rcp.CertificateAuthority | rcp.ValidationCallback = "system"
if (this.certVerifyType == 0) { //系統(tǒng)驗(yàn)證
certVerify = 'system'
} else if (this.certVerifyType == 1) { //選擇CA證書驗(yàn)證
certVerify =caCert
} else if (this.certVerifyType == 2) { //跳過驗(yàn)證
certVerify = 'skip'
} else if (this.certVerifyType == 3) { //自定義證書驗(yàn)證
certVerify = this.selfDefServerCertValidation
}
let secCfg: rcp.SecurityConfiguration = { remoteValidation: certVerify }
let reqCfg: rcp.Configuration = { security: secCfg }
let sessionCfg: rcp.SessionConfiguration = { requestConfiguration: reqCfg }
return sessionCfg
}
這個(gè)比較好理解,第二塊是自定義證書驗(yàn)證的方法:
//自定義證書驗(yàn)證方式
selfDefServerCertValidation: rcp.ValidationCallback = (context: rcp.ValidationContext) => {
//此處編寫證書有效性判斷邏輯
return true;
}
這里為簡單起見,自定義規(guī)則是所有的驗(yàn)證都通過,讀者可以根據(jù)自己的需要來修改,比如不驗(yàn)證證書的有效期。
(本文作者原創(chuàng),除非明確授權(quán)禁止轉(zhuǎn)載)
本文源碼地址:
https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/rcp/RCPCertVerify
本系列源碼地址: