mode-cfb.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Cipher Feedback
  2. import { ModeOfOperation } from "./mode.js";
  3. export class CFB extends ModeOfOperation {
  4. #iv: Uint8Array;
  5. #shiftRegister: Uint8Array;
  6. readonly segmentSize!: number;
  7. constructor(key: Uint8Array, iv?: Uint8Array, segmentSize: number = 8) {
  8. super("CFB", key, CFB);
  9. // This library currently only handles byte-aligned segmentSize
  10. if (!Number.isInteger(segmentSize) || (segmentSize % 8)) {
  11. throw new TypeError("invalid segmentSize");
  12. }
  13. Object.defineProperties(this, {
  14. segmentSize: { enumerable: true, value: segmentSize }
  15. });
  16. if (iv) {
  17. if (iv.length % 16) {
  18. throw new TypeError("invalid iv size (must be 16 bytes)");
  19. }
  20. this.#iv = new Uint8Array(iv);
  21. } else {
  22. this.#iv = new Uint8Array(16);
  23. }
  24. this.#shiftRegister = this.iv;
  25. }
  26. get iv(): Uint8Array { return new Uint8Array(this.#iv); }
  27. #shift(data: Uint8Array): void {
  28. const segmentSize = this.segmentSize / 8;
  29. // Shift the register
  30. this.#shiftRegister.set(this.#shiftRegister.subarray(segmentSize));
  31. this.#shiftRegister.set(data.subarray(0, segmentSize), 16 - segmentSize);
  32. }
  33. encrypt(plaintext: Uint8Array): Uint8Array {
  34. if (8 * plaintext.length % this.segmentSize) {
  35. throw new TypeError("invalid plaintext size (must be multiple of segmentSize bytes)");
  36. }
  37. const segmentSize = this.segmentSize / 8;
  38. const ciphertext = new Uint8Array(plaintext);
  39. for (let i = 0; i < ciphertext.length; i += segmentSize) {
  40. const xorSegment = this.aes.encrypt(this.#shiftRegister);
  41. for (let j = 0; j < segmentSize; j++) {
  42. ciphertext[i + j] ^= xorSegment[j];
  43. }
  44. this.#shift(ciphertext.subarray(i));
  45. }
  46. return ciphertext;
  47. }
  48. decrypt(ciphertext: Uint8Array): Uint8Array {
  49. if (8 * ciphertext.length % this.segmentSize) {
  50. throw new TypeError("invalid ciphertext size (must be multiple of segmentSize bytes)");
  51. }
  52. const segmentSize = this.segmentSize / 8;
  53. const plaintext = new Uint8Array(ciphertext);
  54. for (let i = 0; i < plaintext.length; i += segmentSize) {
  55. const xorSegment = this.aes.encrypt(this.#shiftRegister);
  56. for (let j = 0; j < segmentSize; j++) {
  57. plaintext[i + j] ^= xorSegment[j];
  58. }
  59. this.#shift(ciphertext.subarray(i));
  60. }
  61. return plaintext;
  62. }
  63. }