browserify-hybrid-crypto
Version:
TypeScript implementation Hybrid encryption and signing library built on Web Crypto (AES + RSA + HMAC).
31 lines (28 loc) • 1.01 kB
text/typescript
export function getCryptoImpl() {
return crypto;
}
export function toBase64(data: ArrayBuffer | Uint8Array): string {
const uint8 = data instanceof Uint8Array ? data : new Uint8Array(data);
if (typeof window !== "undefined" && window.btoa) {
return window.btoa(String.fromCharCode(...uint8));
} else if (typeof Buffer !== "undefined") {
return Buffer.from(uint8).toString("base64");
} else {
throw new Error("No base64 implementation available");
}
}
export function fromBase64(base64: string): ArrayBuffer {
if (typeof window !== "undefined" && window.atob) {
const binary = window.atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i) & 0xff;
}
return bytes.buffer;
} else if (typeof Buffer !== "undefined") {
const buf = Buffer.from(base64, "base64");
return new Uint8Array(buf).buffer;
} else {
throw new Error("No base64 implementation available");
}
}