# @bicycle-codes/crypto-util 中文文档

规范地址：https://npmcn.com/package/%40bicycle-codes/crypto-util/

版本：0\.2\.8
npm 元数据更新时间：2025-03-08T00:54:25.211Z
中文译文更新时间：2026-11-08T01:39:47.142Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40bicycle-codes/crypto-util
原文对照：https://npmcn.com/package/%40bicycle-codes/crypto-util/?lang=original
项目主页：https://github.com/bicycle-codes/crypto-util
源码仓库：https://github.com/bicycle-codes/crypto-util

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：8.7 MB，90 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：7 个
- 首次发布：2024-09-12T20:35:18.085Z
- 最新版本发布：2025-03-08T00:54:24.982Z
- 近 30 天下载量：2042（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：34（近 12 个月 0 个）

## 中文简介

浏览器或节点的加密工具功能

## 安装

```sh
npm install @bicycle-codes/crypto-util
```

也可以使用：`pnpm add @bicycle-codes/crypto-util`、`yarn add @bicycle-codes/crypto-util`、`bun add @bicycle-codes/crypto-util`

## README

# 密码工具

![tests](https://github.com/bicycle-codes/crypto-util/actions/workflows/nodejs.yml/badge.svg) [![types](https://img.shields.io/npm/types/@bicycle-codes/crypto-util?style=flat-square)](https://npmcn.com/package/%40bicycle-codes/crypto-util/README.md) [![module](https://img.shields.io/badge/module-ESM%2FCJS-blue?style=flat-square)](https://npmcn.com/package/%40bicycle-codes/crypto-util/README.md) [![semantic versioning](https://img.shields.io/badge/semver-2.0.0-blue?logo=semver&style=flat-square)](https://semver.org/) [![install size](https://flat.badgen.net/packagephobia/install/@bicycle-codes/crypto-util)](https://packagephobia.com/result?p=@bicycle-codes/crypto-util) [![license](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://npmcn.com/package/%40bicycle-codes/crypto-util/LICENSE)

在浏览器或节点中使用加密密钥工作的功能.

这是一些有用的功能,可以更容易地与密码学合作. 注意这一点 _没有_ 处理存储密钥。 查看使用 [@ 自行车编码/ webauthn 键](https://github.com/bicycle-codes/webauthn-keys/) (生物计量认证)或 [索引数据库](https://github.com/jakearchibald/idb-keyval) 帮帮忙.

包括两个 [钠](https://github.com/jedisct1/libsodium.js) 基于密钥以及 [网络催眠](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) 函数.

Webcrypto 键比较可取,因为我们创建它们作为 [不可提取](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey#extractable) 键,并能够在索引数据库中坚持它们,尽管无法读取私钥.

> \[TIP\] 请求使用 [`.persist()`](https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/persist) 方法.

* * *

> \[注\] 安装大小有点大(9.77 MB),因为这包括一个精密的捆绑 [钠库](https://github.com/jedisct1/libsodium.js)。 。 。 .

* * *

**再说, [参见从打字符生成的文件](https://bicycle-codes.github.io/crypto-util/)**

* * *

## 目录

-   [安装](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-install)
-   [实例](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-example)
    -   [创建新密钥页](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-create-a-new-keypair)
    -   [使用 2 ECC 键盘创建新的 AES 键](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-use-2-ecc-keypairs-to-create-a-new-aes-key)
    -   [用 AES 密钥加密](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-encrypt-with-aes-keys)
    -   [用 AES 密钥解密](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-decrypt-with-aes-keys)
    -   [用ECC 密钥加密](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-encrypt-with-ecc-keys)
    -   [用ECC 密钥解密](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-decrypt-with-ecc-keys)
    -   [创建签名密钥包](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-create-a-signing-keypair)
    -   [验证签名](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-verify-a-signature)
-   [API 密码](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-api)
    -   [无害环境管理](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-esm)
    -   [共同联合来文](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-common-js)
    -   [预建联署材料](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-pre-built-js)
    -   [网络催眠对钠](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-webcrypto-vs-sodium)
-   [网络crypto API](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-webcrypto-api)
    -   [实例](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-example-1)
-   [网络crypto AES API](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-webcrypto-aes-api)
    -   [`aes.create`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-aescreate)
    -   [`aes.encrypt`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-aesencrypt)
    -   [`aes.decrypt`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-aesdecrypt)
-   [webcrypto RSA API 页面存档备份,存于互联网档案馆](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-webcrypto-rsa-api)
-   [eCC API 网络催眠](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-webcrypto-ecc-api)
    -   [`ecc.create`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-ecccreate)
    -   [`sign`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-sign)
    -   [`verifyWithDid`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-verifywithdid)
    -   [`getSharedKey`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-getsharedkey)
    -   [`encrypt`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-encrypt)
    -   [`decrypt`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-decrypt)
-   [aPI 钠](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-sodium-api)
-   [AES API钠](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-sodium-aes-api)
    -   [钠 + AES 实例](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-sodium--aes-example)
    -   [`aes.create`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-aescreate-1)
    -   [`aes.encrypt`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-aesencrypt-1)
    -   [`aes.decrypt`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-aesdecrypt-1)
-   [ECC API钠](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-sodium-ecc-api)
    -   [钠+ECC实例](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-sodium--ecc-example)
    -   [`ecc.create`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-ecccreate-1)
    -   [`ecc.sign`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-eccsign)
    -   [`ecc.publicKeyToDid`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-eccpublickeytodid)
    -   [`ecc.verify`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-eccverify)
    -   [`ecc.verifyWithDid`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-eccverifywithdid)
    -   [`ecc.encrypt`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-eccencrypt)
    -   [`ecc.decrypt`](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-eccdecrypt)
-   [另见](https://npmcn.com/package/%40bicycle-codes/crypto-util/#readme-see-also)

* * *

## 安装

* * *

```sh
npm i -S @bicycle-codes/crypto-util
```

* * *

## 实例

* * *

### 创建新密钥页

使用带有 ECC 密钥 [网络加密 API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)。 。 。 .

还有 你可以用 [RSA 密钥](https://github.com/bicycle-codes/crypto-util/blob/main/test/index.ts#L61)。 。 。 .

```js
import { create, KeyUse } from '@bicycle-codes/crypto-util'

// create a new keypair
const encryptKeypair = await create(KeyUse.Encrypt)
const signKeys = await create(KeyUse.Sign)
```

### 使用 2 ECC 键盘创建新的 AES 键

这需要一个 keypair + 另一个 keypair 来获取一个共享的 AES 密钥 .

```js
import { getSharedKey } from '@bicycle-codes/crypto-util/webcrypto/ecc'
import { KeyUse } from '@bicycle-codes/crypto-util/types'

const alicesKeys = await createEcc(KeyUse.Encrypt)
const bobsKeys = await createEcc(KeyUse.Encrypt)

// pass in our private key, their public key
const sharedKey = await getSharedKey(alicesKeys.privateKey, bobsKeys.publicKey)
```

Bob可以通过使用他们的私钥+爱丽丝的公钥来得到相同的密钥.

```js
const bobsSharedKey = await getSharedKey(bobsKeys.privateKey, alicesKeys.publicKey)
```

### 用 AES 密钥加密

用给定的密钥加密给定的消息 .

```js
import { create, encrypt } from '@bicycle-codes/crypto-util/webcrypto/aes'

const aesKey = await create()
const aesEncryptedText = await encrypt('hello AES', aesKey)
```

### 用 AES 密钥解密

```js
import { decrypt } from '@bicycle-codes/crypto-util/webcrypto/aes'

const decrypted = await decrypt(aesEncryptedText, aesKey)
```

### 用ECC 密钥加密

这是爱丽丝给鲍勃的信 我们用爱丽丝的私人钥匙和鲍勃的 公用钥匙.

```js
import { KeyUse } from '@bicycle-codes/crypto-util'
import {
    create,
    encrypt,
    decrypt
} from '@bicycle-codes/crypto-util/webcrypto'

const alicesKeys = await create(KeyUse.Encrypt)
const bobsKeys = await create(KeyUse.Encrypt)
const eccEncryptedText = await encrypt(
    'hello ecc',
    alicesKeys.privateKey,
    bobsKeys.publicKey
)
```

### 用ECC 密钥解密

鲍勃可以解密爱丽丝加密的信息,因为我们使用了Bob的公开 加密时键.

```js
// note keys are reversed here --
// alice's public key and bob's private key
const decrypted = await decrypt(
    eccEncryptedText,
    bobsKeys.privateKey,
    alicesKeys.publicKey
)

// => 'hello ecc'
```

### 创建签名密钥包

创建另一个用于签名的密钥派 .

```js
import { KeyUse } from '@bicycle-codes/crypto-util'
import { create } from '@bicycle-codes/crypto-util/webcrypto'

const eccSignKeys = await create(KeyUse.Sign)
```

#### 创建签名

```js
import { sign } from '@bicycle-codes/crypto-util/webcrypto/ecc'

const sig = await sign('hello dids', eccSignKeys.privateKey)
```

#### 创建 DD

ADD是一个 [分散化标识符](https://github.com/w3c/did-wg/blob/main/did-explainer.md),字符串编码用户的公钥.

如果您正在传送您的公钥和信件, 例如, 这是首选格式 .

```js
import { publicKeyToDid } from '@bicycle-codes/crypto-util'

const did = await publicKeyToDid(eccSignKeys.publicKey)
```

### 验证签名

使用 DDE 来验证签名字符串 .

```js
import { verifyWithDid, sign } from '@bicycle-codes/crypto-util/ecc'

const sig = await sign('hello dids', eccSignKeys.privateKey)
const isOk = await verifyWithDid('hello dids', sig, did)
```

* * *

## API 密码

* * *

[参见 API 文件](https://bicycle-codes.github.io/crypto-util/)

这暴露了无害环境管理和共同的联署材料 [软件包.json `exports` 字段](https://nodejs.org/api/packages.html#exports)。 。 。 .

### 无害环境管理

```js
import * as util from '@bicycle-codes/crypto-utils'
```

### 共同联合来文

```js
const util = require('@bicycle-codes/crypto-utils')
```

### 预建联署材料

这个包也暴露了精密的,预先捆绑的JS文件. 复制到一个位置 然后在 HTML 中链接.

#### 复制

```sh
cp ./node_modules/@bicycle-codes/crypto-util/dist/index.min.js ./public/crypto-util.js
```

#### HTML 语言

```html
<script type="module" src="./crypto-util.js"></script>
```

### 网络催眠对钠

用来使用 [网络crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API),从 `webcrypto` 潜行道.

* * *

## 网络crypto API

* * *

这取决于环境与 [网络crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)。 。 。 .

```js
import { aes, ecc, rsa } from '@bicycle-codes/crypto-util/webcrypto'
```

### 实例

```js
import { rsa, ecc, aes } from '@bicycle-codes/crypto-util/webcrypto'

// create some ECC keypairs
const eccKeypair = await ecc.create(KeyUse.Sign)
const eccSignKeys = await ecc.create(KeyUse.Encrypt)

// get the public key as a string
const publicKey = await ecc.exportPublicKey(eccSignKeys.publicKey)

// get the public key as a DID format string
const did = await ecc.publicKeyToDid(eccSignKeys.publicKey)

// transform a DID string to a public key instance
const publicKey = ecc.didToPublicKey(eccDid)
```

* * *

## 网络crypto AES API

* * *

### `aes.create`

创建新的 AES- GCM 密钥 .

```ts
function create (opts:{ alg, length } = {
    alg: DEFAULT_SYMM_ALGORITHM,
    length: DEFAULT_SYMM_LEN
}):Promise<CryptoKey>
```

#### `aes.create` 实例

```js
import { create } from '@bicycle-codes/crypto-util/webcrypto/aes'

const aesKey = await createAes()
```

### `aes.encrypt`

加密一个字符串 .

```ts
async function encrypt (
    msg:Msg,
    key:SymmKey|string,
    opts?:Partial<SymmKeyOpts>
):Promise<string>
```

```js
import { encrypt } from '@bicycle-codes/crypto-util/webcrypto/aes'

let aesEncryptedText:string
test('encrypt some text with AES', async t => {
    aesEncryptedText = await encrypt('hello AES', aesKey)
    // returns a string by default
})
```

### `aes.decrypt`

```ts
async function decrypt (
    msg:Msg,
    key:SymmKey|string,
    opts?:Partial<SymmKeyOpts>,
    charSize:CharSize = DEFAULT_CHAR_SIZE
):Promise<string>
```

```js
import { decrypt } from '@bicycle-codes/crypto-util/webcrypto/aes'

const decrypted = await decrypt(aesEncryptedText, aesKey)
// => 'hello AES'
```

* * *

## webcrypto RSA API 页面存档备份,存于互联网档案馆

* * *

我们曝光RSA,因为并非所有浏览器都支持ECC密钥. 见 [./src/rsa/webcrypto.ts](https://npmcn.com/package/%40bicycle-codes/crypto-util/src/rsa/webcrypto.ts) 财务报告和审定财务报表 [./测试/索引.ts](https://npmcn.com/package/%40bicycle-codes/crypto-util/test/index.ts#L61)。 。 。 .

* * *

## eCC API 网络催眠

* * *

### `ecc.create`

```ts
async function create (
    use:KeyUse,
    curve:EccCurve = EccCurve.P_256,
):Promise<CryptoKeyPair>
```

#### `create` 实例

```js
import { create } from '@bicycle-codes/crypto-util/webcrypto/ecc'

const alicesEncryptionKeys = await createEcc(KeyUse.Encrypt)
const alicesSigningKeys = await createEcc(KeyUse.Sign)
```

### `sign`

```ts
async function sign (
    msg:Msg,  // <-- string or Uint8Array
    privateKey:PrivateKey,
    { format }:{ format: 'base64'|'raw' } = { format: 'base64' },
    charSize:CharSize = DEFAULT_CHAR_SIZE,
    hashAlg:HashAlg = DEFAULT_HASH_ALGORITHM,
):Promise<ArrayBuffer|string>
```

#### 实例

```js
import { sign } from '@bicycle-codes/crypto-util/webcrypto/ecc'

const sig = await sign('hello webcrypto', eccSignKeys.privateKey)
```

### `verifyWithDid`

用 DD 格式字符串验证签名 .

```ts
async function verifyWithDid (
    msg:string,
    sig:string,
    did:DID
):Promise<boolean>
```

```js
import { verifyWithDid } from '@bicycle-codes/crypto-util/webcrypto/ecc'

const isOk = await verifyWithDid('hello dids', sig, did)
```

### `getSharedKey`

获得两个现有密钥的共享密钥 .

```ts
async function getSharedKey (
    privateKey:PrivateKey,
    publicKey:PublicKey,
    opts?:Partial<{
        alg:'AES-GCM'|'AES-CBC'|'AES-CTR'
        length:SymmKeyLength
        iv:ArrayBuffer
    }>
):Promise<SymmKey>
```

```js
let BobsKeys:CryptoKeyPair
let sharedKey:CryptoKey

const BobsKeys = await createEcc(KeyUse.Encrypt)
const sharedKey = await getSharedKey(eccKeypair.privateKey, BobsKeys.publicKey)
t.ok(sharedKey instanceof CryptoKey, 'should return a `CryptoKey`')
```

### `encrypt`

用你的私人钥匙和收件人的公用钥匙加密一些东西.

```ts
async function encrypt (
    msg:Msg,  // <-- string or Uint8Array
    privateKey:PrivateKey,
    publicKey:string|PublicKey,  // <-- base64 or key
    { format }:{ format: 'base64'|'raw' } = { format: 'base64' },
    charSize:CharSize = DEFAULT_CHAR_SIZE,
    curve:EccCurve = DEFAULT_ECC_CURVE,
    opts?:Partial<{
        alg:SymmAlg
        length:SymmKeyLength
        iv:ArrayBuffer
    }>
):Promise<Uint8Array|string>
```

#### 实例

```js
const eccEncryptedText = await ecc.encrypt(
    'hello ecc',
    alicesKeys.privateKey,
    BobsKeys.publicKey
)
```

### `decrypt`

解密一些被加密的文本 `ecc.ecncrypt`。 。 。 .

```ts
async function decrypt (
    msg:Msg,  // <-- string or Uint8Array
    privateKey:PrivateKey,
    publicKey:string|PublicKey,
    curve:EccCurve = DEFAULT_ECC_CURVE,
    opts?:Partial<{
        alg:'AES-GCM'|'AES-CBC'|'AES-CTR'
        length:SymmKeyLength
        iv:ArrayBuffer
    }>
):Promise<string>
```

#### 实例

注意这里互换的密钥 -- 公用和私用密钥都可以来自其中之一 keypair 还能用.

```js
const decrypted = await ecc.decrypt(
    eccEncryptedText,
    BobsKeys.privateKey,
    alicesKeys.publicKey
)
```

* * *

## aPI 钠

* * *

在联署材料可以运行的地方,这些工具应发挥作用.

```js
import { aes, ecc, rsa } from '@bicycle-codes/crypto-util/sodium'
```

或导入单个模块

```js
import * as aes from '@bicycle-codes/crypto-util/sodium/aes'
import * as ecc from '@bicycle-codes/crypto-util/sodium/ecc'
import * as webcryptoAes from '@bicycle-codes/crypto-util/webcrypto/aes'
```

* * *

## AES API钠

* * *

加密为 [非洲地理信息系统256](https://libsodium.gitbook.io/doc/secret-key_cryptography/aead/aegis-256) (对称密码).

### 钠 + AES 实例

```js
import {
    create,
    encrypt,
    decrypt
} from '@bicycle-codes/crypto-util/sodium/aes'

// create a new key
const key = await create()

// or create a key, return a Uint8Array
const keyAsBuffer = await createAes({ format: 'raw' })

// encrypt something
const encryptedString = await encrypt('hello sodium + AES', key)
```

### `aes.create`

创建一个新的 AES 密钥 。 过 `{ format: 'raw' }` 将返回 a `Uint8Array`。 。 。 .

```ts
async function create (opts:{
    format: 'string'|'raw'
} = { format: 'string' }):Promise<Uint8Array|string>
```

#### 实例

```js
import { create } from '@bicycle-codes/crypto-util/sodium/aes'

const aesKey = await create()
```

### `aes.encrypt`

加密给定的字符串或缓冲器。 过 `{ format: 'raw' }` 将返回 a `Uint8Array`。 。 。 .

```ts
async function encrypt (
    msg:Uint8Array|string,
    key:Uint8Array|string,
    opts:Partial<{
        iv?:Uint8Array
        format?:'string'|'raw'
    }> = { format: 'string' },
):Promise<Uint8Array|string>
```

#### 实例

```js
import { encrypt } from '@bicycle-codes/crypto-util/sodium/aes'

const encryptedString = await encryptAes('hello sodium + AES', aesKey)
```

### `aes.decrypt`

解密给定的字符串或缓冲. 过 `{ format: 'raw' }` 将返回 a `Uint8Array`。 。 。 .

```ts
async function decrypt (
    cipherText:string|Uint8Array,
    key:string|Uint8Array,
    opts:{ format:'string'|'raw' } = { format: 'string' }
):Promise<Uint8Array|string>
```

#### 实例

```ts
import { decrypt } from '@bicycle-codes/sodium/aes'

const decrypted = await decrypt(encryptedAes, aesKey)
// => "hello sodium + AES"
```

* * *

## ECC API钠

* * *

### 钠+ECC实例

```js
import * as ecc from '@bicycle-codes/crypto-util/sodium/ecc'

const keys = await ecc.create()
```

### `ecc.create`

创造出一个新的Edward keypair.

```ts
async function create (
    use:KeyUse,
    curve:EccCurve = EccCurve.P_256,
):Promise<CryptoKeyPair>
```

#### `.create` 实例

```js
import { create } from '@bicycle-codes/crypto-util/sodium/ecc'

const keys = await create()
```

### `ecc.sign`

为下潜数据创建签名 。 过 `{ format: 'raw' }` 获取一个 `Uint8Array` 而不是一个字符串.

```ts
async function sign (
    data:string|Uint8Array,
    key:LockKey,
    opts:{
        format:'string'|'raw'
    } = { format: 'string' }
):Promise<string|Uint8Array>
```

#### `ecc.sign` 实例

```js
import { sign } from '@bicycle-codes/crypto-util/webcrypto/ecc'

const sig = await sign('hello webcrypto', alicesKeys, { format: 'raw' })
```

### `ecc.publicKeyToDid`

选择一个公钥实例并返回一个 DED 格式字符串 .

```ts
async function publicKeyToDid (
    publicKey:Uint8Array|PublicKey
):Promise<DID>
```

#### `ecc.publicKeyToDid` 实例

```js
import {
  exportPublicKey,
  publicKeyToDid
} from '@bicycle-codes/crypto-util/webcrypto/ecc'

const arr = await exportPublicKey(eccSignKeys.publicKey)
const did = await publicKeyToDid(arr)
```

### `ecc.verify`

验证给定的签名 + 公钥 + 消息数据 .

```ts
async function verify (
    msg:Msg,  // <-- string or Uint8Array
    sig:string|Uint8Array|ArrayBuffer,
    publicKey:string|PublicKey,
    charSize:CharSize = DEFAULT_CHAR_SIZE,
    curve:EccCurve = DEFAULT_ECC_CURVE,
    hashAlg: HashAlg = DEFAULT_HASH_ALGORITHM
):Promise<boolean>
```

#### `ecc.verify` 实例

```js
const key = await importDid(eccDid)
const isOk = await verify('hello webcrypto', sig, key)
t.ok(isOk, 'should verify a valid signature')
```

### `ecc.verifyWithDid`

校验给定的签名 + 消息 + 公用密钥是好的, 使用给定的 DD 字符串作为公用密钥材料 .

```ts
async function verifyWithDid (
    msg:string,
    sig:string,
    did:DID
):Promise<boolean>
```

#### `ecc.verifyWithDid` 实例

```js
import { verifyWithDid } from '@bicycle-codes/crypto-util/webcrypto/ecc'

const isOk = await verifyWithDid('hello dids', sig, did)
```

### `ecc.encrypt`

使用给定的私人和公共密钥创建共享密钥,然后用密钥加密消息.

```ts
async function encrypt (
    msg:Msg,
    privateKey:PrivateKey,
    publicKey:string|PublicKey,  // <-- base64 or key
    { format }:{ format: 'base64'|'raw' } = { format: 'base64' },
    charSize:CharSize = DEFAULT_CHAR_SIZE,
    curve:EccCurve = DEFAULT_ECC_CURVE,
    opts?:Partial<{
        alg:SymmAlg
        length:SymmKeyLength
        iv:ArrayBuffer
    }>
):Promise<Uint8Array|string>
```

#### `ecc.encrypt example`

```js
import { encrypt } from '@bicycle-codes/crypto-util/webcrypto/ecc'

const eccEncryptedText = await encrypt(
    'hello ecc',
    AlicesKeys.privateKey,
    BobsKeys.publicKey
)
```

### `ecc.decrypt`

解密一个消息给一个公用和私用密钥. 在示例中,键盘被反转 `encrypt` 实例。 这通过 [迪菲·赫尔曼](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveKey#key_agreement_algorithms)。 。 。 .

```js
import { decrypt } from '@bicycle-codes/crypto-util/webcrypto/ecc'

const decrypted = await decrypt(
    eccEncryptedText,
    BobsKeys.privateKey,
    AlicesKeys.publicKey
)
```

## 另见

-   [\[问\]AES GCM——IV长度#74](https://github.com/fission-codes/keystore-idb/issues/74) - 出版这一出版物的部分动机
-   [`libsodium` 文档](https://libsodium.gitbook.io/doc)
    
    -   [AES256-GCM (法语)](https://libsodium.gitbook.io/doc/secret-key_cryptography/aead/aes-256-gcm)
    
    > 除非您绝对需要 AES- GCM, 请使用 AEGIS-256 (crypto aead aegis256 \* ()) 代替 。 它没有任何这些限制.
    
    -   [非洲地理信息系统256](https://libsodium.gitbook.io/doc/secret-key_cryptography/aead/aegis-256)
-   [网络加密 API - MDN 文件](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)
-   [存储管理器: 持久性方法](https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/persist)
-   [idb 键](https://github.com/jakearchibald/idb-keyval) -- 超简单的密钥值存储 API 构建于 `indexedDB`。 。 。 .

## 常见问题

### @bicycle-codes/crypto-util 是什么？

浏览器或节点的加密工具功能

### 如何安装 @bicycle-codes/crypto-util？

在项目目录运行 npm install @bicycle-codes/crypto-util，或使用 pnpm add / yarn add / bun add。

### @bicycle-codes/crypto-util 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @bicycle-codes/crypto-util 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @bicycle-codes/crypto-util 可以商用吗？

@bicycle-codes/crypto-util 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @bicycle-codes/crypto-util 的下载量有多少？

根据 npm 官方下载统计，@bicycle-codes/crypto-util 在 2026/10/08 – 2026/11/06 这 30 天内被下载 2,042 次，日均约 68 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @bicycle-codes/crypto-util 还在维护吗？

最新版本 0\.2\.8 发布于 2025/03/08（1\.7 年前）；至今共发布 34 个版本，其中过去 12 个月发布了 0 个；首次发布于 2024/09/13。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

