目录

如何存储公钥

1、可以将公钥转换为十六进制或Base64格式进行存储。

2、获取公钥后,将其转换为数组。

3、将转换后的数组转换为公钥对象。

参考代码如下:

import { buffer, util } from '@kit.ArkTS'
import { cryptoFramework } from '@kit.CryptoArchitectureKit'

@Entry
@Component
struct PublicKeysStored {
  build() {
    Row() {
      Column() {
        Button('公钥转为base64编码数据存储').onClick(() => {
          let publicKeys =
            new Uint8Array([
              0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
              0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe, 0x1c, 0x67, 0xde,
              0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2,
              0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99, 0x3d, 0xe8,
              0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44,
              0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e
            ]);
          let result = new util.Base64Helper().encodeToStringSync(publicKeys)
          console.info('base64 result=',result)
          let base64 = new util.Base64Helper();
          let byte = base64.decodeSync(result)// base64
          console.info('base64 byte=',byte)
          // Convert the converted array into a public key object
          let keyBlob: cryptoFramework.DataBlob = { data: byte }
        })

        Button('公钥转为十六进制数据存储').onClick(() => {
          let publicKeys =
            new Uint8Array([
              0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
              0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe, 0x1c, 0x67, 0xde,
              0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2,
              0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99, 0x3d, 0xe8,
              0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44,
              0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e
            ]);
          let result = buffer.from(publicKeys).toString('hex')
          console.info('hex result=',result)
          let byte = new Uint8Array(buffer.from(result, 'hex').buffer)
          console.info('hex byte=',byte)
          // Convert the converted array into a public key object
          let keyBlob: cryptoFramework.DataBlob = { data: byte }
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}