pisya

simple rsa

Dec 12th, 2021 (edited)
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const alphabet = (() => {
  2.   const letters = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
  3.   const chars = ['.', ',', '!', '?', '-', ' ']
  4.   return [...letters, ...letters.toLowerCase(), ...chars].reduce(
  5.     (acc, char) => ({ ...acc, [char]: Object.keys(acc).length + 2 }),
  6.     {}
  7.   )
  8. })()
  9.  
  10. class RSA {
  11.   #encodedChars
  12.   #decodedChars
  13.   #p
  14.   #q
  15.   #N
  16.   #d
  17.   #e
  18.  
  19.   constructor(message) {
  20.     this.message = message
  21.     this.#computeEnv()
  22.   }
  23.  
  24.   encodeChars() {
  25.     this.#encodedChars = [...this.message].map(char => {
  26.       const largeInteger =
  27.         BigInt(alphabet[char]) ** BigInt(this.#e) %
  28.         BigInt(this.#N)
  29.       return largeInteger.valueOf()
  30.     })
  31.     return this.#encodedChars
  32.   }
  33.  
  34.   decodeChars() {
  35.     if (!this.#encodedChars)
  36.       throw Error('Вначале необходимо закодировать символы')
  37.     this.#decodedChars = this.#encodedChars.map((encodedChar) => {
  38.       const num = BigInt(encodedChar) ** BigInt(this.#d) % BigInt(this.#N)
  39.       return num.valueOf()
  40.     })
  41.     return this.#decodedChars
  42.   }
  43.  
  44.   decodeMessage() {
  45.     if (!this.#decodedChars)
  46.       throw Error('Вначале необходимо декодировать символы')
  47.     return this.#decodedChars.reduce((word, decodedChar) => {
  48.       const [char] = Object.entries(alphabet).find(
  49.         ([, digit]) => digit === +decodedChar.toString()
  50.       )
  51.       return word + char
  52.     }, '')
  53.   }
  54.  
  55.   #computeEnv() {
  56.     ;[this.#p, this.#q] = this.#generatePandQ()
  57.     this.#N = this.#p * this.#q
  58.     const fiN = (this.#p - 1) * (this.#q - 1)
  59.     this.#e = this.#generateE(fiN)
  60.     this.#d = this.#gcdex(fiN, this.#e)[2]
  61.   }
  62.  
  63.   #generatePandQ() {
  64.     const [p, q] = [this.#randomInt(1, 100), this.#randomInt(1, 100)]
  65.     if (this.#isPrime(p) && this.#isPrime(q) && 100 <= p * q && p * q < 1000) {
  66.       return [p, q]
  67.     }
  68.     return this.#generatePandQ()
  69.   }
  70.  
  71.   #generateE(fiN) {
  72.     const e = this.#randomInt(100, 1000)
  73.     if (this.#gcd(fiN, e) !== 1 || this.#gcdex(fiN, e)[2] < 0) {
  74.       return this.#generateE(fiN)
  75.     }
  76.     return e
  77.   }
  78.  
  79.   #gcd(a, b) {
  80.     let r = a % b
  81.     while (r) {
  82.       ;[a, b] = [b, r]
  83.       r = a % b
  84.     }
  85.     return b
  86.   }
  87.  
  88.   #gcdex(a, b) {
  89.     if (!b) return [a, 1, 0]
  90.     const [nod, x, y] = this.#gcdex(b, a % b)
  91.     return [nod, y, x - y * Math.floor(a / b)]
  92.   }
  93.  
  94.   #isPrime(num) {
  95.     for (let i = 2; i < num; i++) {
  96.       if (!(num % i)) return false
  97.     }
  98.     return num > 1
  99.   }
  100.  
  101.   #randomInt(min, max) {
  102.     const rand = min + Math.random() * (max + 1 - min)
  103.     return Math.floor(rand)
  104.   }
  105. }
  106.  
  107. const message =
  108.   'пук-пук-ппривет, а у тебя сколько отчимов? мать найдешь - напишешь'
  109. console.log({ message })
  110. const rsa = new RSA(message)
  111.  
  112. const encodedChars = rsa.encodeChars()
  113. console.log({ encodedChars })
  114.  
  115. const decodedChars = rsa.decodeChars()
  116. console.log({ decodedChars })
  117.  
  118. const decodedWord = rsa.decodeMessage()
  119. console.log({ decodedWord })
  120.  
  121. // Number.prototype.isPrime = function () {
  122. //   for (let i = 2; i < this; i++) {
  123. //     if (this % i === 0) return false
  124. //   }
  125. //   return this > 1
  126. // }
  127.  
  128. // function randomInt(min, max) {
  129. //   const rand = min + Math.random() * (max + 1 - min)
  130. //   return Math.floor(rand)
  131. // }
  132.  
  133. // function gcd(a, b) {
  134. //   let r = a % b
  135. //   while (r) {
  136. //     ;[a, b] = [b, r]
  137. //     r = a % b
  138. //   }
  139. //   return b
  140. // }
  141.  
  142. // function gcdex(a, b) {
  143. //   if (b === 0) return [a, 1, 0]
  144. //   const [nod, x, y] = gcdex(b, a % b)
  145. //   return [nod, y, x - y * Math.floor(a / b)]
  146. // }
  147.  
  148. // function generatePandQ() {
  149. //   const [p, q] = [randomInt(1, 100), randomInt(1, 100)]
  150. //   if (p.isPrime() && q.isPrime() && 100 <= p * q && p * q < 1000) {
  151. //     return [p, q]
  152. //   }
  153. //   return generatePandQ()
  154. // }
  155.  
  156. // function generateE() {
  157. //   const e = randomInt(100, 1000)
  158. //   if (gcd(fiN, e) !== 1 || gcdex(fiN, e)[2] < 0) {
  159. //     return generateE()
  160. //   }
  161. //   return e
  162. // }
  163.  
  164. // let [code, decode] = [[], []]
  165.  
  166. // const [p, q] = generatePandQ()
  167. // const N = p * q
  168. // const fiN = (p - 1) * (q - 1)
  169. // const e = generateE()
  170. // const d = gcdex(fiN, e)[2]
  171.  
  172. // ;[...message].forEach((_, index) => {
  173. //   // const largeInteger = BigInteger(alphabet[message[index]]).pow(e).mod(N)
  174. //   const largeInteger = BigInt(alphabet[message[index]]) ** BigInt(e) % BigInt(N)
  175. //   code[index] = largeInteger.valueOf()
  176. // })
  177. // console.log('зашифрованный код:', code)
  178. //
  179. // ;[...code].forEach((_, index) => {
  180. //   const char = BigInt(code[index]) ** BigInt(d) % BigInt(N)
  181. //   decode[index] = char.valueOf()
  182. //   // decode[index] = code[index] ** d % N
  183. // })
  184. // console.log('расшифрованный код:', decode)
  185.  
  186. // let word = ''
  187. // decode.forEach((decodedChar) => {
  188. //   const [char] = Object.entries(alphabet).find(
  189. //     ([, digit]) => digit === +decodedChar.toString()
  190. //   )
  191. //   word += char
  192. // })
  193.  
  194. // console.log('исходное слово:', word)
  195.  
Advertisement
Add Comment
Please, Sign In to add comment