did-sdk-js
Version:
js sdk for did and vc according to mcps did spec
180 lines (179 loc) • 9.21 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Secp256k1 = void 0;
const errors_1 = require("../errors");
const crypto_1 = require("./crypto");
const eccryptoJS = require("eccrypto-js");
const enc = require("enc-utils");
const ecies_1 = require("./lib/ecies");
const SECP256K1 = require('secp256k1');
const crypto = require("crypto");
const eccrypto = require("eccrypto");
class Secp256k1 extends crypto_1.Crypto {
/**
* Calculates the public key from a given private key.
* @param privateKeyHex The private key hexstring
* @param mode Pubkey Type 'compress' or ''
* @returns Public key {type:type, value:hexstring}
*/
static getPublicKeyFromPrivateKey(privateKeyHex, mode = '') {
if (!privateKeyHex || privateKeyHex.length !== crypto_1.Crypto.PRIVKEY_LEN * 2) {
throw new errors_1.SdkError('invalid privateKey');
}
// compressed
// eccrypto.getPublicCompressed
let publicKeyByte = eccrypto.getPublic(Buffer.from(privateKeyHex, "hex"));
let compressedPubKeyByte = SECP256K1.publicKeyConvert(publicKeyByte, true);
return Buffer.from(compressedPubKeyByte).toString("hex");
// const secp256k1pubkey = new EC('secp256k1').keyFromPrivate(privateKeyHex, 'hex').getPublic();
// return Buffer.from(secp256k1pubkey.encodeCompressed()).toString('hex');
}
static generateMnemonicAndKey() {
let mnemonic = Secp256k1.generateMnemonic();
let privateKey = Secp256k1.getPrivateKeyFromMnemonic(mnemonic);
let publicKey = Secp256k1.getPublicKeyFromPrivateKey(privateKey);
return { mnemonic, privateKey, publicKey };
}
static generateKey() {
// A new random 32-byte private key.
let privateKeyByte = eccrypto.generatePrivate();
// Corresponding uncompressed (65-byte) public key.
let publicKeyByte = eccrypto.getPublic(privateKeyByte);
let privateKey = Buffer.from(privateKeyByte).toString("hex");
let publicKey = Buffer.from(publicKeyByte).toString("hex");
return { privateKey, publicKey };
}
static kdf() {
var sodium = require('sodium-native');
sodium.crypto_kdf_derive_from_key;
}
/**
* Generates a signature (base64 string) for a signDocSerialize based on given private key.
* @param signMsg from protobuf and tx.
* @param privateKeyHex The private key.
* @returns Signature. Does not include tx.
*/
static sign(signMsg, privateKeyHex) {
return __awaiter(this, void 0, void 0, function* () {
// Always hash you message to sign!
let msg = crypto.createHash("sha256").update(signMsg).digest();
let sigValue = '';
let sig = SECP256K1.sign(msg, Buffer.from(privateKeyHex, 'hex')).signature;
return sig.toString('base64');
// let signature = await eccrypto.sign(Buffer.from(privateKeyHex, 'hex'), msg)
// signature = Buffer.from(signature).toString('base64');
// if (!signature) {
// throw Error(' generate Signature error ')
// }
// return signature;
// const msghash:Buffer = Buffer.from(Sha256(signDocSerialize,{ asBytes: true }));
// let prikeyArr:Buffer = Buffer.from(private_key,'hex');
// let Secp256k1Sig = Secp256k1.sign(msghash, prikeyArr);
// signature = Secp256k1Sig.signature.toString('base64');
});
}
/**
* Verifies a signature (64 byte <r,s>) given the sign bytes and public key.
* @param sigValue The signature base64 string.
* @param signMsg Unsigned transaction sign msg string.
* @param publicKeyHex The public key.
* @returns Signature. Does not include tx.
*/
static signVerify(signMsg, sigValue, publicKeyHex) {
return __awaiter(this, void 0, void 0, function* () {
const publicKey = Buffer.from(publicKeyHex, 'hex');
let msg = crypto.createHash("sha256").update(signMsg).digest();
// return ecc.verify(msg, publicKey, Buffer.from(sigValue, 'base64'));
return SECP256K1.verify(msg, Buffer.from(sigValue, 'base64'), publicKey);
// return await eccrypto.verify(publicKey, msg, Buffer.from(sigValue, 'base64')).then(function () {
// // console.log("Signature is OK");
// return true
// }).catch(function () {
// // console.log("Signature is BAD");
// return false
// });
});
}
static encrypt(msg, publicKeyHex) {
return __awaiter(this, void 0, void 0, function* () {
let cipher = ecies_1.encrypt(Buffer.from(publicKeyHex, "hex"), Buffer.from(msg));
return cipher.serialize().toString('hex');
});
}
static encryptv2(msg, publicKeyHex) {
return __awaiter(this, void 0, void 0, function* () {
let encrypted = yield eccryptoJS.encrypt(Buffer.from(publicKeyHex, "hex"), eccryptoJS.utf8ToBuffer(msg));
return Secp256k1.encSerialize(encrypted).toString('hex');
// let bs = enc.concatBuffers(encrypted.ephemPublicKey, encrypted.mac, encrypted.iv, encrypted.ciphertext)
// return bs.toString('hex')
// return eccryptoJS.serialize(encrypted).toString('hex')
});
}
static encryptv1(msg, publicKeyHex) {
return __awaiter(this, void 0, void 0, function* () {
let ec = yield eccrypto.encrypt(Buffer.from(publicKeyHex, "hex"), Buffer.from(msg));
let bs = enc.concatBuffers(ec.ephemPublicKey, ec.mac, ec.iv, ec.ciphertext);
return bs.toString('hex');
});
}
static decrypt(encryptDataHex, privateKeyHex) {
return __awaiter(this, void 0, void 0, function* () {
let enc = ecies_1.Encrypted.deserialize(Buffer.from(encryptDataHex, 'hex'));
let plain = ecies_1.decrypt(Buffer.from(privateKeyHex, "hex"), enc);
return plain.toString();
});
}
// hex编码
static decryptv2(encryptDataHex, privateKeyHex) {
return __awaiter(this, void 0, void 0, function* () {
let encryptData = Secp256k1.encDeserialize(Buffer.from(encryptDataHex, 'hex'));
let decrypted = yield eccryptoJS.decrypt(Buffer.from(privateKeyHex, 'hex'), encryptData);
return Buffer.from(decrypted).toString();
});
}
// hex编码
static decryptv1(encryptDataHex, privateKeyHex) {
return __awaiter(this, void 0, void 0, function* () {
let encryptData = eccryptoJS.deserialize(Buffer.from(encryptDataHex, 'hex'));
let decrypted = yield eccrypto.decrypt(Buffer.from(privateKeyHex, 'hex'), encryptData);
return Buffer.from(decrypted).toString();
});
}
static encSerialize(encInfo) {
return enc.concatBuffers(encInfo.ephemPublicKey, encInfo.iv, encInfo.ciphertext, encInfo.mac);
}
static encDeserialize(cipherData) {
const slice0 = eccryptoJS.LENGTH_0;
const slice_pubkey = slice0 + eccryptoJS.PREFIXED_DECOMPRESSED_LENGTH;
const slice_iv = slice_pubkey + eccryptoJS.IV_LENGTH;
const slice_data = cipherData.length - eccryptoJS.MAC_LENGTH;
const slice_mac = cipherData.length;
return {
ephemPublicKey: cipherData.slice(slice0, slice_pubkey),
iv: cipherData.slice(slice_pubkey, slice_iv),
ciphertext: cipherData.slice(slice_iv, slice_data),
mac: cipherData.slice(slice_data, slice_mac),
};
}
}
exports.Secp256k1 = Secp256k1;
/*
add by gangm: 基于"github.com/obscuren/ecies"库
ECIES几个标准:ANSI X9.63, IEEE 1363a 和 ISO/IEC 18033-2
这里选用: IEEE 1363a
为了多语言兼容,这里统一兼容java库org.bouncycastle.crypto中“ECIESWITHSHA256ANDAES-CBC”的实现
aes/cbc模式需要额外添加iv信息:https://github.com/bcgit/bc-java/issues/493
也为了方便后续扩展,加密结果返回原始数据(iv/pubkey/cipher/hmac),上层封装具体序列化方式(比如:publicKey(65) + iv(16) + cipher_text + hmac)
*/
Secp256k1.PRIVKEY_LEN = 32;
Secp256k1.KEY_TYPE = "secp256k1";
//# sourceMappingURL=secp256k1.js.map
;