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.
A PHP class that uses RSA algorithm for encryption and decryption.
License
IhadPHP/php-rsa
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
A PHP class that uses RSA algorithm for encryption and decryption.
Before looking at the example, you need to generate the public and private keys of the RSA.
You can install the package using composer.
composer require sy-records/php-rsa -vvv
If you want to use the instantiation method, please check the following.
use syrecords\Rsa; $privateKey = './key/private_key.pem'; // Private key path $publicKey = './key/rsa_public_key.pem'; // Public key path $rsa = new Rsa($privateKey, $publicKey); $originData = 'https://qq52o.me'; # Encryption with a private key requires public key decryption, called "signature". $ecryptionData = $rsa->privEncrypt($originData); $decryptionData = $rsa->publicDecrypt($ecryptionData); echo 'The data encrypted by the private key is:' . $ecryptionData.PHP_EOL; echo 'The data after the public key is decrypted is: ' . $decryptionData; echo '
'; # Encryption with a public key requires private key decryption, called "encryption". $ecryptionData = $rsa->publicEncrypt($originData); $decryptionData = $rsa->privDecrypt($ecryptionData); echo 'The data after public key encryption is:' . $ecryptionData.PHP_EOL; echo 'The data after the private key is decrypted is:' . $decryptionData;
If you want to call a static method, then look at this one!
use syrecords\staticRsa; $privateKey = file_get_contents('./key/private_key.pem'); // Private key path $publicKey = file_get_contents('./key/rsa_public_key.pem'); // Public key path $originData = 'https://qq52o.me'; $ecryptionData = staticRsa::privEncrypt($originData,$privateKey); $decryptionData = staticRsa::publicDecrypt($ecryptionData,$publicKey); echo 'The data encrypted by the private key is:' . $ecryptionData.PHP_EOL; echo 'The data after the public key is decrypted is: ' . $decryptionData; echo '
'; $ecryptionData = staticRsa::publicEncrypt($originData,$publicKey); $decryptionData = staticRsa::privDecrypt($ecryptionData,$privateKey); echo 'The data after public key encryption is:' . $ecryptionData.PHP_EOL; echo 'The data after the private key is decrypted is:' . $decryptionData;
Реализация алгоритма RSA (PHP)
Во вчерашней публикации пользователи runcore и pixxxel попросили поделиться еще информацией о простых и надежных обратимых алгоритмах и конкретно RSA соответственно. Т.к. я в свое время интересовался этим вопросом и реализовывал подобные алгоритмы, то один из них, пример класса для осуществления шифрования методом RSA я вам предлагаю .
Собственно теоретическую часть можно найти тут, в более менее доступной форме тут. Я же в свое время использовал книгу Брюса Шнайера «Прикладная криптография».
Для приготовления кода на понадобятся:
Т.к. подготовительная часть более или менее пройдена можно перейти к реализации.
Далее идет код реализации алгоритма, с моими комментариями:
- class CRSA
- // Два простых числа p и q
- private $p =0x0;
- private $q =0x0;
- // соответственно значение функции n(p,q), ph(p,q) этих простых чисел
- private $ph =0x0;
- private $n =0x0;
- // Ключи шифрования и дешифровки
- private $e =0x0;
- private $d =0x0;
- // Расшифрованая строка и вектор с зашифрованными символами
- private $decriptedData = «» ;
- private $encriptedData = array ();
- function __construct( $p =0x0, $q =0x0)
- $this ->initPQParams( $p , $q );
- >
- // Инициация функций n и ph
- function initPQParams( $p =0x0, $q =0x0)
- $this ->p= $p ;
- $this ->q= $q ;
- if ( $this ->p && $this ->q && ( $this ->q!= $this ->p))
- $this ->n= $this ->p* $this ->q;
- $this ->ph=( $this ->p- 1 )*( $this ->q- 1 );
- >
- >
- // Инициирование подходящего ключа шифрования
- function initEncryptingKey( $e =0x0)
- if (! $this ->ph || ! $e )
- return false ;
- $this ->e= $e ;
- while (! $this ->isMutuallyDistinct( $this ->e, $this ->ph))
- $this ->e+= 2 ;
- return true ;
- >
- // Проверка на чисел на взаимную простоту
- private function isMutuallyDistinct( $a , $b )
- while (( $a !=0x0) && ( $b !=0x0))
- if ( $a >= $b ) $a = $a % $b ;
- else $b = $b % $a ;
- return (( $a + $b )== 1 )? true : false ;
- >
- // Реализация расширеного алгоритма Эвклида для поиска
- // ключа дешифрования
- function generateDecripringKey()
- $u1 = 1 ;
- $u2 =0x0;
- $u3 = $this ->ph;
- $r1 =0x0;
- $r2 = 1 ;
- $r3 = $this ->e;
- while ( $r3 )
- if (! $r3 )
- break ;
- $q =(int)(((int) $u3 )/((int) $r3 ));
- $t1 =( $u1 — $r1 * $q );
- $t2 =( $u2 — $r2 * $q );
- $t3 =( $u3 — $r3 * $q );
- $u1 = $r1 ;
- $u2 = $r2 ;
- $u3 = $r3 ;
- $r1 = $t1 ;
- $r2 = $t2 ;
- $r3 = $t3 ;
- >
- $this ->d= $u2 ;
- >
- // Ну тут даже пояснить ничего не надо
- function getEncripringKey()
- return $this ->e;
- >
- // Тут тоже
- function getDecriptingKey( $forced = false )
- if ((! $this ->d) || ( $forced ))
- $this ->d=0x0;
- $this ->generateDecripringKey();
- >
- return $this ->d;
- >
- // Ф-я шифрования, может работать опираясь как на ранее
- // ининциированные свойства, так и напрямую от параметров —
- // ключа шифрации и занчения n(p,q);
- function EncriptX( $data , $e =0x0, $n =0x0)
- if ( $e >0x0 && $n >0x0)
- $this ->n= $n ;
- $this ->e= $e ;
- >
- for ( $j =0x0; $j
- $b =ord( $data [ $j ]);
- $result = 1 ;
- for ( $i =0x0; $i < $this ->e; $i ++)
- $result = ( $result * $b ) % $this ->n;
- >
- $this ->encriptedData[ $j ]= $result ;
- >
- >
- // Аналогично ф-ии шифрования
- function DecriptX( $d =0x0, $n =0x0)
- if ( $d >0x0 && $n >0x0)
- $this ->d= $d ;
- $this ->n= $n ;
- >
- $result = 1 ;
- for ( $j =0x0; $j
encriptedData); $j ++) - $b =( $this ->encriptedData[ $j ]);
- $result = 1 ;
- for ( $i =0x0; $i < $this ->d; $i ++)
- $result = ( $result * $b ) % $this ->n;
- >
- $this ->decriptedData .= chr( $result );
- >
- return $this ->decriptedData;
- >
- >
Вот собственно релизация класса, применять можно двумя способами
- $rsa = new CRSA( 47 , 71 );
- if ( $rsa ->initEncryptingKey( 79 ))
- $rsa ->EncriptX(«Блин, как все сложно»);
- echo «\n» ;
- $rsa ->getDecriptingKey( true );
- echo $rsa ->DecriptX();
- echo «\n» ;
- >
- $rsa = new CRSA();
- $rsa ->EncriptX( «Блин, как все сложно» , 79 , 3337 );
- echo «\n» ;
- echo $rsa ->DecriptX( 1019 , 3337 );
- echo «\n» ;
Благодарности:
Отдельное спасибо пользователям за предоставленную возможность опубликовать статью.
Прочее:
Еще одну реализацию данного алгоритма можно найти здесь.
Нули записаны в шестнадцатиричной форме чтобы парсер не кушал.
Как справедливо отмечено в комментариях, реализация болше ради академического интереса, т.к. существующие в PHP ограничения типов данных не позволяют шифровать сколь-либо серъезной длиной ключа.
Но для шифрации краткосрочных сессионных данных вполне может подойти.
Так же реализацию можно найти и здесь (спс. пользователю galaxy)