Skip to content

Commit

Permalink
Update crypto.js
Browse files Browse the repository at this point in the history
  • Loading branch information
txthinking authored Nov 8, 2022
1 parent 4a607a8 commit b7df061
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions crypto.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { AES } from "https://deno.land/x/god_crypto@v1.4.10/mod.ts";
import { decode as hexdecode } from "https://deno.land/std@0.130.0/encoding/hex.ts";
import { encode as hexencode } from "https://deno.land/std@0.130.0/encoding/hex.ts";
import { randomBytes } from "https://deno.land/std@0.130.0/node/crypto.ts";

var crypto = (key) => {
if(key.length != 32){
if (key.length != 32) {
throw new Error("crypto key must be 32 length");
return;
}
Expand All @@ -15,16 +13,24 @@ var crypto = (key) => {
v: v,
t: parseInt(Date.now() / 1000),
});
var iv = randomBytes(16);
var kv = new AES(key, { mode: "cfb", iv: iv });
var b = await kv.encrypt(text);
return new TextDecoder().decode(hexencode(new Uint8Array([...iv, ...b])));
var iv = window.crypto.getRandomValues(new Uint8Array(16));
var ab = await window.crypto.subtle.encrypt(
{
name: "AES-CBC",
iv,
},
await window.crypto.subtle.importKey("raw", new TextEncoder().encode(key).buffer, "AES-CBC", false, ["encrypt", "decrypt"]),
new TextEncoder().encode(text)
);

return new TextDecoder().decode(hexencode(new Uint8Array([...iv, ...new Uint8Array(ab)])));
},
decrypt: async (k, c, lifecycle) => {
var b = hexdecode(new TextEncoder().encode(c));
var kv = new AES(key, { mode: "cfb", iv: b.slice(0, 16) });
var r = await kv.decrypt(b.slice(16));
var o = JSON.parse(r.toString());
var ab = await window.crypto.subtle.decrypt({ name: "AES-CBC", iv: b.slice(0, 16) }, await window.crypto.subtle.importKey("raw", new TextEncoder().encode(key).buffer, "AES-CBC", false, ["encrypt", "decrypt"]), b.slice(16));
var b = new Uint8Array(ab);
var s = new TextDecoder().decode(b);
var o = JSON.parse(s);
if (lifecycle && o.t + lifecycle < parseInt(Date.now() / 1000)) {
return null;
}
Expand Down

0 comments on commit b7df061

Please sign in to comment.