tic-crypto/README.md

110 lines
3.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# tic-crypto
时光链区块链密码学算法工具库:为区块链相关应用开发提供一套底层的基础算法工具库,用来处理哈希、加解密、签名、助记词、等等。
- 支持 md5、sha256 等算法的哈希
- 基于 bip39 等算法的助记词生成、检验
- 基于 secp256k1 等曲线算法的签名、交易的加解密
- 其他辅助算法工具
## 硬件环境
- 机型Mac 或 PC 机
- 内存8GB 以上
- 硬盘500G 以上
## 软件环境
- 操作系统:跨平台通用,支持 MacOS, Linux, Windows
- 开发环境:推荐 Visual Studio Code
- 运行环境nodejs 12.16 版本
## 安装指南
在前后端软件的 package.json 的依赖清单中引入本库:
```
npm install git+https://git.tic.cc/npm/tic-crypto#RELEASE_OR_BRANCH --save
```
## 用法
基本用法示例:
```
let ticc=require('tic-crypto') // 引用
let sw=ticc.randomize_secword() // 生成一个随机的助记词(即密语)。或者使用现成的密语。
let kp=ticc.secword_to_keypair({secword:sw}) // 把密语转换成公私钥
let address=ticc.secword_to_address({secword:sw}) // 把密语转换成地址
```
## 其他
```
const keyPair = crypto.generateKeyPairSync('rsa', {
modulusLength: 520,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: ''
}
})
```
这样生成的 keyPair.privateKey 开头是 -----BEGIN ENCRYPTED PRIVATE KEY-----
如果直接
```
crypto.privateEncrypt(kp.privateKey, Buffer.from('sdafasfdsaf'))
```
会报错
```
Uncaught TypeError: Passphrase required for encrypted key
```
所以要这样才行
```
crypto.privateEncrypt({key:kp.privateKey, passphrase:''}, Buffer.from('sdafasfdsaf'))
```
我从 https://www.cnblogs.com/chyingp/p/nodejs-asymmetric-enc-dec.html 抄到一个 privateKey 可以直接使用,不需要 passphrase
返回 Buffer。每次结果都一样
这样生成的 keyPair.publicKey 开头是 -----BEGIN PUBLIC KEY-----
可以直接
```
crypto.publicEncrypt(kp.publicKey, Buffer.from('sdafasfdsaf'))
```
返回 Buffer。每次结果不一样
似乎 crypto 一定要 rsa 公私钥才可以用加解密ticc.randomize_keypair() 生成的 ecc 公私钥不行。
而 eccrypto 和 eccrypto-js 可以用。eccrypto.generateKeyPair() 生成的和 ticc.randomize_keypair() 一样
eccrypto 在 windows 上的安装有麻烦,一来需要手工安装 OpenSSL 到 c:\openssl-win64\,二来 openssl 1.1.0 起把 libeay32.lib 改名为 libcrypto.dll而 eccrypto 需要 c:\openssl-win64\lib\libeay32.lib会报错
eccrypto-js 在 devDependencies 里继承了 eccrypto因此 npm i --production 即可
base32 有多种字符集:[Base32 - Wikipedia](https://en.wikipedia.org/wiki/Base32)
IPFS 用的是 RFC4648 字符集
- 从数到数符串Number(数).toString(进制数)0x 数.toString(进制数), 0b 数.toString(进制数)
- 从数符串到数字parseInt(str, 进制数)
- Buffer 到数符串: Buffer.toString(编码方案例如'hex','base64',默认'utf8')
- 字符串到 Buffer: Buffer.from(data, 编码方案如'hex','base64',默认'utf8')