HarmonyOS 远场通信服务双向证书校验时报证书格式错误

1、读取证书dck.crt,再通过x509Cert.getPublicKey获取证书内容,转换成string格式

startTLSNetConnect() {
  this.context.resourceManager.getRawFileContent("dck.crt").then((value: Uint8Array) => {
    let encodingBlob: cert.EncodingBlob = {
      data: value,
      // 根据encodingData的格式进行赋值,支持FORMAT_PEM和FORMAT_DER
      encodingFormat: cert.EncodingFormat.FORMAT_PEM
    };
    cert.createX509Cert(encodingBlob, (error, x509Cert) => {
      if (error) {
        console.error('createX509Cert failed, errCode: ' + error.code + ', errMsg: ' + error.message);
      } else {
        console.log('createX509Cert success');
        try {
          let pubKey = x509Cert.getPublicKey();
          let base64 = new util.Base64Helper();
          let pubKeyContent = base64.encodeToStringSync(pubKey.getEncoded().data)
          TLSNetWorkManager.getInstance().registerAction(pubKeyContent)
        } catch (error) {
          let e: BusinessError = error as BusinessError;
          console.error('getPublicKey failed, errCode: ' + e.code + ', errMsg: ' + e.message);
        }
      }
    })
  })
}

2、将转换成string格式的证书内容传入rcp,执行后报错

async registerAction(content: string){
  console.log("请求开始")
  const session = rcp.createSession();
  const HOST = "https://dck.gdota.club:2626/appsvr/registerSdk"
  try {
    const request = new rcp.Request(HOST, 'POST');
    request.headers = {
      'Content-Type': 'application/json'
    }
    request.content = `{"cywallid":"harmonyos3-f42f-4585-9bdb-69a99d6aa0e5","pubkey":"123456","token":"token-owner-01"}`
    request.configuration = {
      tracing: {
        infoToCollect: {
          textual: true
        }
      },
      security: {
        tlsOptions: tlsOption,
        certificate:{
          content:content,
          type: 'PEM',
          key: 'pubkey',
          keyPassword: '123456'
        }
      }
    };
    const resp = await session.fetch(request);
    console.log(`resp:${resp}`)
  } catch (error) {
    console.error(`Rcp err: Code is ${error.code}, message is ${error.data}`);
    session.close();
  }
}

3、报错信息 Rcp err: Code is 1007900058, message is Problem with the local SSL certificate

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get

对于crt格式的证书文件,rcp请求中除了传入content证书内容,还需要传入key字段即证书对应的密钥文件地址如key: “/path/dir/”,请传入必要字段后再次尝试。

可参考以下示例调用saveFile函数把raw路径下的文件发到手机相关路径下,再配置key: filesDir + ‘/client.key’:

const getRawFileContent = (ctx: Context, file: string) : string => {
  let buffer = ctx.resourceManager.getRawFileContentSync(file).buffer
  return String.fromCharCode(...new Uint8Array(buffer))
}

let context = getContext(this)
let filesDir = context.filesDir
function saveFile(fn: string) {
  let file = fs.openSync(filesDir + '/' + fn, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
  let clientContent = context.resourceManager.getRawFileContentSync(fn)
  fs.writeSync(file.fd, clientContent.buffer)
  fs.fsyncSync(file.fd)
  fs.closeSync(file)
}
saveFile('client.p12')

完整的demo示例请参考如下代码:

import { BusinessError } from '@ohos.base';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { rcp } from "@kit.RemoteCommunicationKit";
import fs from '@ohos.file.fs';

const getRawFileContent = (ctx: Context, file: string) : string => {
  let buffer = ctx.resourceManager.getRawFileContentSync(file).buffer
  return String.fromCharCode(...new Uint8Array(buffer))
}

let context = getContext(this)
let filesDir = context.filesDir
function saveFile(fn: string) {
  let file = fs.openSync(filesDir + '/' + fn, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
  let clientContent = context.resourceManager.getRawFileContentSync(fn)
  fs.writeSync(file.fd, clientContent.buffer)
  fs.fsyncSync(file.fd)
  fs.closeSync(file)
}
saveFile('dck01.crt')
saveFile('private.key')

const selfDefinedRemoteValidation = (context: rcp.ValidationContext) => {
  console.log('context')
  return true
}

@Entry
@Component
struct Index {
  @State message: string = '发送请求';

  async loadData() {
    let HOST = "https://xxx"
    let request = new rcp.Request(HOST, 'POST')
    request.headers = { 'Content-Type': 'application/json' }
    request.content = `{"cywallid":"harmonyos3-f42f-4585-9bdb-69a99d6aa0e5","pubkey":"123456","token":"token-owner-01"}`
    request.configuration = {
      security: {
        remoteValidation: selfDefinedRemoteValidation,
        certificate: {
          content: getRawFileContent(getContext(this), 'dck01.crt'),
          key: filesDir + '/private.key',
          type: 'PEM',
        },
      }
    };

    let session = rcp.createSession()
    session.fetch(request).then((response:rcp.Response) => {
      if (response.statusCode == 200) {
        //hilog.info(0x0000, 'wsrequest', 'get success %{public}s', response.toString())
      }
      hilog.info(0x0000, 'wsrequest', 'get fail %{public}d', response.statusCode)
    }).catch((err: BusinessError) => {
      console.info('get error:' + JSON.stringify(err));
    })
  }

  build() {
    Column() {
      Text(this.message)
        .fontSize('34fp')
        .onClick(() => {
          this.loadData()
        })
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
    .width('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 证书校验器报19030001错误
38浏览 • 1回复 待解决
HarmonyOS怎么校验服务器SSL证书状态?
2837浏览 • 1回复 待解决
HarmonyOS axios如何忽略证书校验
34浏览 • 1回复 待解决
http请求证书校验实现
414浏览 • 1回复 待解决
HarmonyOS 无法安装crt格式证书
734浏览 • 1回复 待解决
HarmonyOS HTTPS请求如何验证服务证书
744浏览 • 1回复 待解决
证书管理无法新增证书
433浏览 • 1回复 待解决
证书解析:解析证书CN怎么获取
522浏览 • 1回复 待解决