Skip to content

Commit

Permalink
feat(AES): add OFB block mode
Browse files Browse the repository at this point in the history
  • Loading branch information
aykxt committed Mar 13, 2021
1 parent 39bb513 commit 3e54974
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 4 deletions.
2 changes: 1 addition & 1 deletion aes.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { AesCbc, AesCfb, AesEcb } from "./src/aes/mod.ts";
export { AesCbc, AesCfb, AesEcb, AesOfb } from "./src/aes/mod.ts";
export { Padding } from "./src/utils/padding.ts";
2 changes: 1 addition & 1 deletion mod.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export { BlowfishCbc, BlowfishEcb } from "./blowfish.ts";
export { AesCbc, AesCfb, AesEcb } from "./aes.ts";
export { AesCbc, AesCfb, AesEcb, AesOfb } from "./aes.ts";
export { Padding } from "./src/utils/padding.ts";
31 changes: 31 additions & 0 deletions src/aes/cipher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,34 @@ export class AesCfb implements BlockCipher {
return unpad(decrypted, this.padding, AES.BLOCK_SIZE);
}
}

export class AesOfb implements BlockCipher {
#aes: AES;
#prev: Uint8Array;

constructor(
key: Uint8Array,
iv: Uint8Array,
) {
checkIvSize(iv.length);

this.#prev = iv.slice();
this.#aes = new AES(key);
}

encrypt(data: Uint8Array): Uint8Array {
const encrypted = data.slice();

for (let i = 0; i < data.length; i += AES.BLOCK_SIZE) {
this.#aes.encrypt(this.#prev);

for (let j = 0; j < AES.BLOCK_SIZE; j++) {
encrypted[i + j] ^= this.#prev[j];
}
}

return encrypted;
}

decrypt = this.encrypt;
}
2 changes: 1 addition & 1 deletion src/aes/mod.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { AesCbc, AesCfb, AesEcb } from "./cipher.ts";
export { AesCbc, AesCfb, AesEcb, AesOfb } from "./cipher.ts";
18 changes: 17 additions & 1 deletion tests/aes.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { assertEquals, assertThrows } from "../dev_deps.ts";
import { AesCbc, AesCfb, AesEcb } from "../aes.ts";
import { AesCbc, AesCfb, AesEcb, AesOfb } from "../aes.ts";

// deno-fmt-ignore
const iv = new Uint8Array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]);
Expand Down Expand Up @@ -78,3 +78,19 @@ Deno.test("AES-128-CFB ", () => {

assertEquals(dec, original);
});

Deno.test("AES-128-OFB ", () => {
// deno-fmt-ignore
const key = new Uint8Array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]);
const iv = new Uint8Array(16);

const original = new Uint8Array(32);

const cipher = new AesOfb(key, iv);
const decipher = new AesOfb(key, iv);

const enc = cipher.encrypt(original);
const dec = decipher.decrypt(enc);

assertEquals(dec, original);
});

0 comments on commit 3e54974

Please sign in to comment.