Anton Kovalenko
2 years ago
4 changed files with 119 additions and 23 deletions
@ -0,0 +1,38 @@
|
||||
const receiverPublicKey = "02d38170b929dc26be2192071756edd5fb94c4e0cf1aec352ce4c8245e635d9bed"; |
||||
|
||||
import {hkdf} from "@noble/hashes/hkdf"; |
||||
import {sha256} from "@noble/hashes/sha256"; |
||||
import * as jscrypto from "jscrypto"; |
||||
import * as secp from "@noble/secp256k1"; |
||||
import { bech32 } from 'bech32'; |
||||
|
||||
let receiverPoint; |
||||
|
||||
function getReceiverPoint() { |
||||
if (receiverPoint) |
||||
return receiverPoint; |
||||
receiverPoint = secp.Point.fromHex(receiverPublicKey); |
||||
return receiverPoint; |
||||
} |
||||
|
||||
const noIV = jscrypto.Hex.parse("00000000000000000000000000000000"); |
||||
|
||||
export function ecEncrypt(plainText) { |
||||
const pub = getReceiverPoint(); |
||||
const iv = noIV; |
||||
const ek = secp.utils.randomPrivateKey(); |
||||
const epk = secp.Point.fromPrivateKey(ek); |
||||
const sharedSecret = secp.getSharedSecret(ek, pub); |
||||
const key = hkdf(sha256,new Uint8Array([...epk.toRawBytes(),...sharedSecret])); |
||||
const jskkey = new jscrypto.Word32Array(key); |
||||
|
||||
const ed = jscrypto.AES.encrypt(jscrypto.Utf8.parse(plainText), |
||||
jskkey,{mode:jscrypto.mode.GCM, padding:jscrypto.pad.NoPadding, iv: noIV}); |
||||
const at = jscrypto.mode.GCM.mac(jscrypto.AES,jskkey,noIV,null,ed.cipherText,16); |
||||
|
||||
const ctbytes = new Uint8Array([...at.toUint8Array(), |
||||
...epk.toRawBytes(true), |
||||
...ed.cipherText.toUint8Array()]); |
||||
const bech = bech32.encode("",bech32.toWords(ctbytes), 1024); |
||||
return bech.slice(1,-6) |
||||
} |
Loading…
Reference in new issue