Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@cardinal-cryptography/ecies-encryption-lib",
"author": "CardinalCryptography",
"version": "0.1.4",
"version": "0.1.5",
"description": "ECIES encryption library (proxy to ts/lib)",
"main": "ts/lib/dist/index.js",
"types": "ts/lib/dist/index.d.ts",
Expand Down
33 changes: 21 additions & 12 deletions ts/lib/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,43 @@ export function generateKeypair(): Keypair {
return { sk, pk };
}

export function fromHex(hex: Uint8Array | string): Uint8Array {
return isBytes(hex)
? Uint8Array.from(hex as any)
: secp.hexToBytes(removePrefix(hex as string));
export async function getCrypto(): Promise<Crypto> {
return typeof globalThis.crypto !== "undefined"
? globalThis.crypto
: ((await import("node:crypto")).webcrypto as Crypto);
}

export function toHex(uint8: Uint8Array, withPrefix: boolean = false): string {
const hex = Array.from(uint8)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
return withPrefix ? "0x" + hex : hex;
}

export async function getCrypto(): Promise<Crypto> {
return typeof globalThis.crypto !== "undefined"
? globalThis.crypto
: ((await import("node:crypto")).webcrypto as Crypto);
export function fromHex(hex: Uint8Array | string): Uint8Array {
return isBytes(hex)
? Uint8Array.from(hex as any)
: fromStringHex(hex as string);
}


function isBytes(bytes: Uint8Array | string): boolean {
return (
bytes instanceof Uint8Array ||
(ArrayBuffer.isView(bytes) && bytes.constructor.name === "Uint8Array")
);
}

function removePrefix(hex: string): string {
return hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
function fromStringHex(hex: string): Uint8Array {
hex = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
if (hex.length % 2 !== 0) {
throw new Error("Hex string must have an even length");
}
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
}
return bytes;
}

export async function encrypt(
Expand Down
Loading