search
HomeBackend DevelopmentPHP TutorialHow to use PHP and GMP to perform RSA encryption and decryption algorithms for large integers

How to use PHP and GMP to perform RSA encryption and decryption algorithm for large integers

RSA encryption algorithm is an asymmetric encryption algorithm that is widely used in the field of data security. It implements the process of public key encryption and private key decryption based on two particularly large prime numbers and some simple mathematical operations. In the PHP language, the calculation of large integers can be realized through the GMP (GNU Multiple Precision) library, and the encryption and decryption functions can be realized by combining the RSA algorithm. This article will introduce how to use PHP and GMP libraries to implement RSA encryption and decryption algorithms for large integers, and give corresponding code examples.

1. Generate RSA public and private key pairs

In the RSA algorithm, both the public key and the private key are generated from a pair of large prime numbers. First, we need to generate two large prime numbers $p$ and $q$.

function generatePrime($bits) {
    do {
        $num = gmp_strval(gmp_random_bits($bits));
    } while (!gmp_prob_prime($num));
    return gmp_init($num);
}

$bits = 1024; // 生成的素数位数
$p = generatePrime($bits);
$q = generatePrime($bits);

Next, we need to calculate $n$ and $phi(n)$, where $n=pq$, $phi(n)=(p-1)(q-1)$.

$n = gmp_mul($p, $q);
$phi_n = gmp_mul(gmp_sub($p, 1), gmp_sub($q, 1));

Then, we choose an integer $e$ as the public key index, satisfying $1

$e = gmp_init(65537); // 公钥指数(一般固定为65537)

Using the extended Euclidean algorithm, we can calculate the private key index $d$, which satisfies $dequiv e^{-1}pmod{phi(n)}$.

function extendedEuclidean($a, $b) {
    if (gmp_cmp($b, 0) === 0) {
        return ['x' => gmp_init(1), 'y' => gmp_init(0)];
    }
    $result = extendedEuclidean($b, gmp_mod($a, $b));
    return [
        'x' => $result['y'],
        'y' => gmp_sub($result['x'], gmp_mul(gmp_div_q($a, $b), $result['y']))
    ];
}

$d = extendedEuclidean($e, $phi_n)['x'];

Finally, we got the RSA public key $(n, e)$ and private key $(n, d)$.

2. Encryption and decryption process

Using the generated public key and private key, we can perform the RSA encryption and decryption process.

function rsaEncrypt($msg, $n, $e) {
    $msg = gmp_init($msg);
    $result = gmp_powm($msg, $e, $n);
    return gmp_strval($result);
}

function rsaDecrypt($cipher, $n, $d) {
    $cipher = gmp_init($cipher);
    $result = gmp_powm($cipher, $d, $n);
    return gmp_strval($result);
}

During the encryption process, we convert the plaintext message into a large integer $msg$, and then use the public key exponent $e$ and the modulus $n$ to calculate to obtain the ciphertext $cipher$. During the decryption process, we convert the ciphertext $cipher$ into a large integer, and then use the private key exponent $d$ and the modulus $n$ to perform calculations to obtain the decrypted plaintext message.

3. Sample code

The following is a complete sample code, including the generation of RSA public and private key pairs and the encryption and decryption process.

function generatePrime($bits) {
    do {
        $num = gmp_strval(gmp_random_bits($bits));
    } while (!gmp_prob_prime($num));
    return gmp_init($num);
}

function extendedEuclidean($a, $b) {
    if (gmp_cmp($b, 0) === 0) {
        return ['x' => gmp_init(1), 'y' => gmp_init(0)];
    }
    $result = extendedEuclidean($b, gmp_mod($a, $b));
    return [
        'x' => $result['y'],
        'y' => gmp_sub($result['x'], gmp_mul(gmp_div_q($a, $b), $result['y']))
    ];
}

function rsaEncrypt($msg, $n, $e) {
    $msg = gmp_init($msg);
    $result = gmp_powm($msg, $e, $n);
    return gmp_strval($result);
}

function rsaDecrypt($cipher, $n, $d) {
    $cipher = gmp_init($cipher);
    $result = gmp_powm($cipher, $d, $n);
    return gmp_strval($result);
}

$bits = 1024; // 生成的素数位数
$p = generatePrime($bits);
$q = generatePrime($bits);

$n = gmp_mul($p, $q);
$phi_n = gmp_mul(gmp_sub($p, 1), gmp_sub($q, 1));

$e = gmp_init(65537); // 公钥指数(一般固定为65537)

$d = extendedEuclidean($e, $phi_n)['x'];

$msg = 'Hello, RSA!';
$cipher = rsaEncrypt($msg, $n, $e);
$decryptedMsg = rsaDecrypt($cipher, $n, $d);

echo "明文消息:" . $msg . "
";
echo "加密后的密文:" . $cipher . "
";
echo "解密后的明文消息:" . $decryptedMsg . "
";

The above code implements the RSA encryption and decryption algorithm for large integers using PHP through the GMP library. You can modify the parameters and logic in the code according to your specific needs. Through understanding and practice, I believe everyone can master and flexibly apply this basic cryptographic algorithm.

The above is the detailed content of How to use PHP and GMP to perform RSA encryption and decryption algorithms for large integers. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool