Алгоритм шифрования rsa javascript

Реализация RSA шифрования на языке JavaScript

В следующем листинге размещён HTML и JavsScript демонстрирующий работу процесса шифрования и дешифрования алогритма RSA на JavaScript библиотеке jsencrypt.js(приведена ссылка на библиотеку на данном сервере а не на сайте разработчика). Для того чтобы проверить работу сохраните код из листинга ниже на своём компьютере с расширением .html и в кодировке UTF-8 затем запустите в браузере. Библиотека jsencrypt.js будет загружена с этого сайта, при этом для дальнейшего использования возможно Вам стоит сохранить её на своём сервере и загружать с него.

Дешифрация секретного сообщения по алгоритму RSA на языке PHP

Для того чтобы действительно убедиться что RSA это стандарт который должен работать(если код программы корректно написан) на любом языке программирования в следующем листинге рассмотрим пример дешифрации полученного с помощью JavaScript и RSA секретного сообщения на языке PHP.

Вы так же можете прочитать следующие статьи:

  • Важно ли для продвижения сайта устанавливать редирект(устранять дубли страниц) с www домена или без(с зеркала).
  • Как разделить коммунальные платежи в частном доме
  • SQL запросы и php файлы загружаемые перед их выполнением в CMS Joomla при генерации страницы главного пункта меню административной панели Joomla 3.9.14
  • Реализация лайков в Интернет магазине на bitrix
  • Бесплатное обслуживание сайта
  • Реализация JSON stringify и parse для старых версий браузеров
  • Функция получения Id секции инфоблока bitrix по Id товара или торгового предложения
  • Заявление в прокуратуру Ивановской области по вопросу отопления в Фурмановской межрайонной прокуратуре.
  • Авторизация и регистрация пользователя bitrix через социальную сеть Одноклассники
  • Функция на PHP для преобразования массива в формат для POST запроса.
  • Захват изображения с Web камеры на Delphi 6
  • Функция вычисления CRC64 в PHP
Читайте также:  Collapsing toolbar android kotlin

В YouTube есть достаточно популярный канал, а ещё он есть по другой ссылке — Danatar. Вернее В YouTube есть несколько каналов данного автора, Вы можете перейти по ссылке и посмотреть какие классные видео снимает Danatar. Как с использованием Bitrix ORM связать несколько(три или более) таблиц.

Источник

A simple implementation of the RSA algorithm in JavaScript

In the RSA cryptosystem, the receiver of messages has a public key, which is publicly shared, and a secret key, which is kept private.

The sender of a message uses the public key to encrypt the message. Then, the receiver is able to decrypt the message using the private key.

Could someone explain how this works in more detail and provide a simple JavaScript implementation?

1 Answer

Let’s go through the three phases of RSA: key generation, encryption, and decryption.

I will also show a JavaScript implementation of each step.

Note: since we will be working with very large numbers, we will be using the new JavaScript BigInt type instead of the simple number type. This means that all integers will be written with an n suffix, e.g., 191n .

Key generation

Let’s first see how the receiver creates a public key and a secret key.

First, two distinct primes numbers p p p and q q q are chosen. These are generally very large, but for the purposes of this explanation, let’s keep them small.

const p = 191n; const q = 223n;

Then, we compute the integer n n n as the product of p p p and q q q .

Next, we compute the value of the Euler’s totient function for n n n , denoted as ϕ ( n ) \phi(n) ϕ ( n ) , which represents the number of integers that are relatively prime to n n n in the range 1 to n n n .

Since n n n is equal to the product of two distinct primes, it can be proven that:

Let’s refer to this value using the phi variable.

const phi = (p - 1n) * (q - 1n); // 42180n

We can pick a prime number for e e e and then check that it does not divide ϕ ( n ) \phi(n) ϕ ( n ) . The number 47 is prime and does not divide 42180, so let’s go with e = 47 e=47 e = 4 7 .

More generally, we can write a generateEncryptionExponent function that generates e e e by starting with 47 and checking if it is relatively prime to ϕ ( n ) \phi(n) ϕ ( n ) and incrementing it by 2 if it is not relatively prime until we get a number that is relatively prime to ϕ ( n ) \phi(n) ϕ ( n ) :

function generateEncryptionExponent(phi)  let e = 47n; while (gcd(e, phi) !== 1n)  e += 2n; > return e; >

Now, let’s compute the decryption exponent d d d , which is the multiplicative inverse of e e e modulo ϕ ( n ) \phi(n) ϕ ( n ) . That is,

It can be proven that d d d is the coefficient of e e e in the linear combination of e e e and ϕ ( n ) \phi(n) ϕ ( n ) that expresses the gcd ⁡ ( e , ϕ ( n ) ) \gcd(e, \phi(n)) g cd ( e , ϕ ( n ) ) , which we can compute using the Extended Euclidean Algorithm.

So, let’s assume that we have an extendedGcd function that implements the Extended Euclidean Algorithm.

This function takes two integers a and b for which we want to compute the GCD, and it returns an object that has the value of the GCD as well as the coefficients s and t in the linear combination of a and b that is equal to the GCD. That is,

gcd ⁡ ( a , b ) = s a + t b for some s , t \gcd(a, b) = sa + tb \ \text < for some >s,t g cd ( a , b ) = s a + t b for some s , t

So, if we compute the GCD of e e e and ϕ ( n ) \phi(n) ϕ ( n ) , d d d will correspond to the coefficient of e e e , which will be the first one, i.e., s s s .

Furthermore, we want the decryption exponent d d d to be positive. So, if we get a negative value for d d d , we can make it positive by adding ϕ ( n ) \phi(n) ϕ ( n ) to it as many times as needed to make it positive.

Here’s the computeDecryptionExponent function which computes d d d :

function computeDecryptionExponent(e, phi)  let d = extendedGcd(e, phi).s; while (d  1n)  d += phi; > return d; >

The public key will be a pair that consists of the encryption exponent e e e and the integer n n n .

The secret key will be a pair that consists of the decryption exponent d d d and the integer n n n .

Encryption

Let’s say that the resulting message expressed as an integer is m m m . It is required that:

The sender should also check that gcd ⁡ ( m , n ) = 1 \gcd(m, n) = 1 g cd ( m , n ) = 1 , since we don’t want the GCD to equal p p p or q q q , which in practice almost never happens.

Next, the message m m m is encrypted into the ciphertext c c c using the public key by computing the remainder of m e m^e m e divided by n n n .

Here’s the encrypt function that does the encryption:

function encrypt(m, publicKey)  const  e, n > = publicKey; if (m  0n || m >= n)  throw new Error(`Condition 0  $m>`); > if (gcd(m, n) !== 1n)  throw new Error("Condition gcd(m, n) = 1 not met."); > const c = m ** e % n; return c; >

Decryption

The receiver can decrypt the ciphertext c c c back to the original message m m m using the secret key by computing the remainder of c d c^d c d divided by n n n .

Here’s the decrypt function that does the decryption:

function decrypt(c, secretKey)  const  d, n > = secretKey; const m = c ** d % n; return m; >

Finally, here’s the rsaExample function that puts all of this together:

function rsaExample()  const p = 191n; const q = 223n; const n = p * q; const phi = (p - 1n) * (q - 1n); const e = generateEncryptionExponent(phi); const d = computeDecryptionExponent(e, phi); const publicKey =  e, n >; const secretKey =  d, n >; const m = textToNumber("Hi"); const c = encrypt(m, publicKey); const m2 = decrypt(c, secretKey); console.log(numberToText(m2)); // Hi >

Note that this is just a simple JavaScript implementation of the RSA algorithm shown for learning purposes.

If we try it with big prime numbers and long messages, we will end up with extremely large numbers that cannot even fit inside the JavaScript BigInt , and so we will get the RangeError: Maximum BigInt size exceeded error.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Browser dedicated RSA encryption tool.

benjaminBrownlee/RSA.js

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

RSA.js is a javascript RSA algorithim encryption tool, complete with key generation and functions to encrypt, decrypt, encode, and decode strings.

This library is built primarily for browser applications. Simply download it here or just hotlink to it:

Also, RSA.js relies on bigInt.js to generate, compute, and manage massive values for encryption. Keys, encoded strings, and encrypted strings will be represented as Big Integer objects. Download bigInt.js here or use the hotlink below:

You can generate an encryption key of a given keysize (in bits), using RSA.generate() . This function will return an object with «n», «e», and «d» properties, standing for the publc key, public exponet, and private key respectively, where the public key is the number of bits given in the argument.

Convert a string of alphanumerical characters to standard utf-8 decimal encoding. Only numbers can be encrypted, so an encoding is necessary to encrypt any non-numerical data.

RSA.encrypt(data, public_key, public_exponet)

Encrypt numerical data using public parts of a generated or transmitted key. These will be the «n» and «e» properties in the object returned by the RSA.generate() function. Function will throw an error if any of the arguments are not Big Integer objects.

RSA.decrypt(cipher_text, private_key, public_key)

Using the private part of the encryption key (which should not be transfered via network), decrypt a cipher-text string of numerals. Will return an encoded string or simply a number, depending on intent of data transmission

Revert data back to string form if it was originally encoded in utf-8 code.

Here is a worked example of how to use RSA.js to encrypt and decrypt a JS string:

var keys = RSA.generate(250); var message = RSA.encode("Successful RSA process!"); var encrypted_message = RSA.encrypt(message, keys.n, keys.e); var decrypted_message = RSA.decrypt(encrypted_message, keys.d, keys.n); var decoded_message = RSA.decode(decrypted_message); message === decoded_message ? alert("Success!") : alert("Error!"); 

About

Browser dedicated RSA encryption tool.

Источник

Оцените статью