RSA.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // RSA, a suite of routines for performing RSA public-key computations in
  2. // JavaScript.
  3. //
  4. // Requires BigInt.js and Barrett.js.
  5. //
  6. // Copyright 1998-2005 David Shapiro.
  7. //
  8. // You may use, re-use, abuse, copy, and modify this code to your liking, but
  9. // please keep this header.
  10. //
  11. // Thanks!
  12. //
  13. // Dave Shapiro
  14. // dave@ohdave.com
  15. function RSAKeyPair(encryptionExponent, decryptionExponent, modulus)
  16. {
  17. this.e = biFromHex(encryptionExponent);
  18. this.d = biFromHex(decryptionExponent);
  19. this.m = biFromHex(modulus);
  20. // We can do two bytes per digit, so
  21. // chunkSize = 2 * (number of digits in modulus - 1).
  22. // Since biHighIndex returns the high index, not the number of digits, 1 has
  23. // already been subtracted.
  24. this.chunkSize = 2 * biHighIndex(this.m);
  25. this.radix = 16;
  26. this.barrett = new BarrettMu(this.m);
  27. }
  28. function twoDigit(n)
  29. {
  30. return (n < 10 ? "0" : "") + String(n);
  31. }
  32. function encryptedString(key, s)
  33. // Altered by Rob Saunders (rob@robsaunders.net). New routine pads the
  34. // string after it has been converted to an array. This fixes an
  35. // incompatibility with Flash MX's ActionScript.
  36. {
  37. var a = new Array();
  38. var sl = s.length;
  39. var i = 0;
  40. while (i < sl) {
  41. a[i] = s.charCodeAt(i);
  42. i++;
  43. }
  44. while (a.length % key.chunkSize != 0) {
  45. a[i++] = 0;
  46. }
  47. var al = a.length;
  48. var result = "";
  49. var j, k, block;
  50. for (i = 0; i < al; i += key.chunkSize) {
  51. block = new BigInt();
  52. j = 0;
  53. for (k = i; k < i + key.chunkSize; ++j) {
  54. block.digits[j] = a[k++];
  55. block.digits[j] += a[k++] << 8;
  56. }
  57. var crypt = key.barrett.powMod(block, key.e);
  58. var text = key.radix == 16 ? biToHex(crypt) : biToString(crypt, key.radix);
  59. result += text + " ";
  60. }
  61. return result.substring(0, result.length - 1); // Remove last space.
  62. }
  63. function decryptedString(key, s)
  64. {
  65. var blocks = s.split(" ");
  66. var result = "";
  67. var i, j, block;
  68. for (i = 0; i < blocks.length; ++i) {
  69. var bi;
  70. if (key.radix == 16) {
  71. bi = biFromHex(blocks[i]);
  72. }
  73. else {
  74. bi = biFromString(blocks[i], key.radix);
  75. }
  76. block = key.barrett.powMod(bi, key.d);
  77. for (j = 0; j <= biHighIndex(block); ++j) {
  78. result += String.fromCharCode(block.digits[j] & 255,
  79. block.digits[j] >> 8);
  80. }
  81. }
  82. // Remove trailing null, if any.
  83. if (result.charCodeAt(result.length - 1) == 0) {
  84. result = result.substring(0, result.length - 1);
  85. }
  86. return result;
  87. }