cbc.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*!
  2. * Crypto-JS v1.1.0
  3. * http://code.google.com/p/crypto-js/
  4. * Copyright (c) 2009, Jeff Mott. All rights reserved.
  5. * http://code.google.com/p/crypto-js/wiki/License
  6. */
  7. Crypto.mode.CBC = {
  8. encrypt: function (cipher, m, iv) {
  9. var blockSizeInBytes = cipher._blocksize * 4;
  10. // Pad
  11. m.push(0x80);
  12. // Encrypt each block
  13. for (var offset = 0; offset < m.length; offset += blockSizeInBytes) {
  14. if (offset == 0) {
  15. // XOR first block using IV
  16. for (var i = 0; i < blockSizeInBytes; i++)
  17. m[i] ^= iv[i];
  18. }
  19. else {
  20. // XOR this block using previous crypted block
  21. for (var i = 0; i < blockSizeInBytes; i++)
  22. m[offset + i] ^= m[offset + i - blockSizeInBytes];
  23. }
  24. // Encrypt block
  25. cipher._encryptblock(m, offset);
  26. }
  27. },
  28. decrypt: function (cipher, c, iv) {
  29. var blockSizeInBytes = cipher._blocksize * 4;
  30. // Decrypt each block
  31. for (var offset = 0; offset < c.length; offset += blockSizeInBytes) {
  32. // Save this crypted block
  33. var thisCryptedBlock = c.slice(offset, offset + blockSizeInBytes);
  34. // Decrypt block
  35. cipher._decryptblock(c, offset);
  36. if (offset == 0) {
  37. // XOR first block using IV
  38. for (var i = 0; i < blockSizeInBytes; i++)
  39. c[i] ^= iv[i];
  40. }
  41. else {
  42. // XOR decrypted block using previous crypted block
  43. for (var i = 0; i < blockSizeInBytes; i++)
  44. c[offset + i] ^= prevCryptedBlock[i];
  45. }
  46. // This crypted block is the new previous crypted block
  47. var prevCryptedBlock = thisCryptedBlock;
  48. }
  49. // Strip padding
  50. while (c.pop() != 0x80) ;
  51. }
  52. };