← 返回文章列表

数字签名

数字签名是区块链中用于身份认证、防篡改、抗抵赖的核心密码学技术。
BlockChain 评论 0

数字签名

一、概念

一段数字签名数字串,它包含电子文件经过Hash编码后产生的数字摘要,即一个Hash函数值以及发送者的公钥和私钥三部分内容。发送方通过私钥加密后发送给接收方,接收方使用公钥解密,通过对比解密后的

二、Demo

完整deme github

const ecLib = require('elliptic').ec;
const ec = new ecLib('secp256k1') // curve name
const sha256 = require('crypto-js/sha256')

// 生成我们的密钥对
const key = ec.genKeyPair();
// 拿到我们的私钥和公钥 希望拿到hex string格式的
console.log('private', key.getPrivate('hex'))
console.log('public', key.getPublic('hex'))
const doc = "zhuanzhang20yuan"
const hashedDoc = sha256(doc).toString()
const hexSignature = key.sign(hashedDoc, 'base64').toDER('hex')

console.log('hashed doc', hashedDoc)
console.log('signature', hexSignature)
// 收到签名的一方
const publicKey = ec.keyFromPublic(key.getPublic('hex'), 'hex')
console.log(publicKey.verify(hashedDoc , hexSignature))

// tamper 篡改
const tamperedDoc = 'zhuanzhang10yuan'
const hashedTamperedDoc = sha256(tamperedDoc).toString()
// console.log('tampered hased doc', hashedTamperedDoc)
console.log(publicKey.verify(hashedTamperedDoc, hexSignature))
评论: