how-to-generate-rsa-private-and-public-keys

how-to-generate-php-rsa-encryption-and-decryption

how-to-generate-php-rsa-encryption-and-decryption

**openssl_pkey_new**

**openssl_pkey_new — Generates a new private key**

```
Example #1 Obtain the public key from a private key
```

```
<?php
$private_key = openssl_pkey_new();
$public_key_pem = openssl_pkey_get_details($private_key)['key'];
echo $public_key_pem;
$public_key = openssl_pkey_get_public($public_key_pem);
var_dump($public_key);
?>
```

The above example will output something similar to:

```
echo $public_key_pem;
```

```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArZFsmN2P6rx1Xt7YV95o
gcdlal0k3ryiIhFNzjwtRNNTXfEfBr6lUuaIJYQ8/XqEBX0hpcfuuF6tTRlonA3t
WLME0QFD93YVsAaXcy76YqjjqcRRodIBphAbYyyMI/lXkQAdn7kbAmr7neSOsMYJ
El9Wo4Hl4oG6e52ZnYHyqW9dxh4hX93eupR2TmcCdVf+r9xoHewP0KJYSHt7vDUX
AQlWYcQiWHIadFsmL0orr6mutlXFReoHbesgKY9/3YLOu0JfxflSjIZ2JeL1NTl1
MsmODsUwgAUrwnWKKx+eQUP5g3GnSB3dPkRh9zRVRiLNWbCugyjrf3e6DgQWrW7j
pwIDAQAB
-----END PUBLIC KEY-----
var_dump($public_key);
resource(5) of type (OpenSSL key)
```

Example 1

**Working of openssl_pkey_new()**:

```
<?php
// Generate a new private (and public) key pair
$privkey = openssl_pkey_new(array(
"digest_alg"=>'md5',
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
var_dump($privkey);
?>
```

This will produce the following result:

**Output**

```
resource(2) of type (OpenSSL key)
```

**Example 2**

**Working of openssl_pkey_new() and openssl_pkey_get_details**:

```
<?php
// Generate a new private (and public) key pair
$privkey = openssl_pkey_new(array(
"digest_alg"=>'md5',
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$key_details = openssl_pkey_get_details($privkey);
print_r($key_details);
?>
```

This will produce the following result:

**Output**

```
Array (
[bits] => 2048
[key] => -----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1IGWxnWzICSkjrOVrYkw
9EKpIhcAYbhaymiwQY/ii9d7hnuGhpjjitDxzFftGafL6XOFKOhgbO2yrcpFxRKu
AY3t5wyUcqUJV6CNwV2Hipk90psUcTmK3+pcCzcqCKr7sLWlHI48lse92xane8Sf
CATNNbr9vmqUaTZ9FQqWihm3o/rNGuZTwMSKvcKsVguFpwrEDJaSLP1nt7RSHGc+
PixQSXp3PtQCH+S0CM9jt1jD9NkYXuuAlNbrsPm1fl2zAGR5Vh15evz5765lZ2mH
LIZScfsO/qgai3R6foaBlJM5tiSeiVZgnnQDKFBi5XK2GhzDnKggJe4tdY7awTFm
CQIDAQAB
-----END PUBLIC KEY-----
[rsa] => Array (
[n] => ԁ��u� $��0�B�"a�Z�h�A��{�{��W���s�(�`l��E�����r� W��]��=қq9��\7*���<�ǽ��{ğ�5��j�i6}
�����S�Ċ�¬V��
���,�g��Rg>>,PIzw>���c�X��^뀔��~]�dyVyz��egi�,�Rq����tz~��9�$��V`�t(Pb�r�Ü� %�-u��1f
[e] =>
[d] => F"��3��4��!K�yF��R�lY�9�]Ξ��A��@�f��~�<�YPєG��=��TkTP�rl�Mԓ{�lŮ^��!��q�˂�7�|�f��lE+#�@.�GIH�tS�R.mbc�U~��7&w�ݥ�P.Fe�ϨU�@��m��X�ECsemjI$@/�$l��)�8�@���c�w�NRo��+!'�.��fvT7�=n")LQ�sd�%zZ��G��{�{�1A^��v��E
[p] => �>u)��1bǰK�r��pHE��k���LBE��y�'�3-�/��Pd��jeFV1����?�.O���:�bl2�z�U�{��{��*��A���<�}m4��J�Y�'�f@���
[q] => ߦz\��96�=��V]"k��2w��>�r�袤�6�/�-Z�_��8!Y��I��L���_3Ym���.p�֏^��>�I:��oZ��"��=��8���뻢1��:�
[dmp1] => z"�TW*��Ƴm�$�HQ�$0��sa��j� #�
P�*�P��Q�G\42�a�26(�5�K�7zj��xj7��@e�$.6��b�Dq]]I}�L�m�d��54)@:���#
[dmq1] => +��4}��\dc�R�K�Bw�\�E6�����%_�m$3蚞9�Fh�D�uz��$�8HPK�ˇԁ^�K�k�]e�g�>ºX�"<ƌ�`ė��&,9E��MS"��¥�)
[iqmp] => !��߷�=�z�=ܰ7��V�6q�~���3V��t�P�$��O�kgv��3=W\ѝm��� �J���5^�K��a�t��~��U�.��!�l�v�#��z*��� ���r
)
[type] => 0
)
```

**Example 3**

**To read public key from openssl_pkey_new()**:

```
<?php
echo "The hash of Welcome to Tutorialspoint is - ". hash('crc32b', 'Welcome to Tutorialspoint');
?>
```

This will produce following result:

**Output**

```
-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArAWYwKIaf3uN1bwww4R8 51ifDPGsreqr9cV3J1gSKC8kaAEsAQaZ/6gQlDBsUGs4nE8zKgOlcdOV/JApgAdz +CwoLJUgmEUkLDxOcWaCIUVuHAiyBGJaRKZ+MASy7wRG8hb+INd0/zoQRGXk3+jf Fj6rvSinVg49C4RAkRtkEdNnH0G5s6cedV6ec30DouRTuEQ/Fgizf0qaVtQbAURP n+/LT9V8c4LMaCyID7caTQOXAEjQqD4ooXGkOzmcsp03j2/F+T2mSIQRtI1gGJkZ oCMGX/xRxh5uemCcC4jcshn45Ikmb/S7WFqTCOC0e8l8CiTZ5Rr8EKFgtwliMds8 pQIDAQAB -----END PUBLIC KEY-----
```

**Example 4**

**To store public key from openssl_pkey_new() in a file**:

```
<?php
// Generate a new private (and public) key pair
$privkey = openssl_pkey_new(array(
"digest_alg"=>'md5',
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$keydetails = openssl_pkey_get_details($privkey);
// To save the public key to a file
file_put_contents('mypublic.key', $keydetails['key']);
?>
```

The contents of file mypublic.key is:

```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3QxA7vWIz+F5t12/fl0H
vyavVy/ZNZFWGK6BID/koYeVA2wKdXx9De3gn0hs4sSrN3aV58ctuxDVx36rKvYd
AjKHfnfh7NmXnCEeUE4SgUUe0UUleoEMtsPP2Q8BC1HUjcC6SyJQKZG0bQqQlnAb
HL7ou2TNsjA/SiJbPD+0OpsLAcW1c/DeoM+TAkZo0JIlgxjcJ5ZlEbJ0Mxv6m9XK
k3bbMYHtKmZl+fzfPNcxCuK8Djnm5mYVR9KX1L86m1jz2kUQT/+wW84QRnZ7G+z8
4rQ77sZvWiIwwO2JmUvIsYeUxEP6/keZbDRuyO/2tWk/VxqQry4+Ktix/M2/iKWo
QQIDAQAB
-----END PUBLIC KEY-----
```

## How to generate RSA private and public keys in your PC

In this article, you will learn what data encryption is, what RSA data encryption algorithm is, how it works and how to generate a pair of RSA private and public keys in your PC using the OpenSSL library in your Linux terminal or Windows command prompt.

**What is encryption**?

Encryption is the process of securing data by encoding it mathematically into an unreadable format known as ciphertext.

It is a data security practice for protecting sensitive information from being read by unauthorized parties.

An encrypted data will appear scrambled and meaningless to anyone who tries to view read it and must be decrypted to be read and make sense.

There exist various cryptographic algorithms for doing data encryption such as the DES (Data Encryption Standard), 3DES (Triple Data Encryption Standard), AES (Advanced Encryption Standard), RC4, and RSA (Rivest, Shamir, and Adleman) encryption among others. In this article, we put our focus on the RSA algorithm.

**What is RSA**?

RSA is the most popular and widely used asymmetric encryption algorithm available to the public. It also happens to be the very first asymmetric encryption algorithm.

Its name is derived from the surnames of the three mathematicians (Rivest, Shamir, and Adleman) who invented it.

RSA is considered an asymmetric algorithm due to its use of a pair of keys. Asymmetric encryption uses a key pair (private and public keys) that is mathematically linked to encrypt and decrypt data.

As their names suggest, a public key is shared publicly, while a private key is secret and known only by the key pair creator (it must not be shared with anyone).

**How the RSA algorithm works**

In RSA, either of the keys can encrypt the data, while the other key decrypts it. If for instance the public key is used for encryption, the private key must be used to decrypt the data.

**Encrypting data with the public key**

This is very applicable especially when sending sensitive data across a network such as the Internet. In such a case, the recipient of the data shares their public key with the sender.

The sender then encrypts the data using the public key and sends it to the recipient. Since the data was encrypted with the public key, it can only be decrypted using the private key.

Since the private key is kept secret by the data recipient, only him/her can decrypt that data. Even if a hacker accesses the data while in transit, they can read it, and thus it is secure.

**Encrypting data with the private key**

Alternatively, the data can be encrypted using the private key. Using the above example, the sender of the data encrypts it using their private key and sends the ciphertext (encrypted data) together with the public key to the recipient.

The recipient can then decrypt the data using the shared public key. The data can be read in transit using this method. The purpose of this method is not to prevent data from being read, but to verify the identity of the sender.

Since only the sender has the private key in this case, if a person accessed, decrypted, and modified the data in transit, they won't be able to encrypt the data in a way that the recipient public key can decrypt it (since they don't have the encrypting private key). Hence the recipient would know the data had been modified in transit.

The RSA algorithm is based on the fact that it is easy to generate a number by multiplying two large numbers, but extremely difficult to factorize that number back into the original prime numbers. The two keys are derived from two numbers, one of which is a multiplication of two large prime numbers. They both use the same two prime numbers to compute their value.

**RSA private key size consideration**

If somebody can factorize the large number, the private key is compromised. The encryption strength in RSA, therefore, relies on the key size. The larger the key size, the stronger the encryption.

You can therefore specify the private key size from the four options when creating it.

```
Key size Key strength
512 bits Low-strength key
1024 bits Medium-strength key
2048 bits High-strength key
4096 bits Very high-strength key
```

Though keys from 1024 bits in length are considered strong, experts believe that 1024 bit keys could be broken in the near future. I recommend you use from 2048 bits length.

**How to create RSA private and public keys**

We will focus on creating the keys using the OpenSSL library.

OpenSSL is a robust open-source software library/toolkit for general-purpose cryptography and secure communication.

OpenSSL allows users to perform various SSL related tasks, such as CSR (Certificate Signing Request) and private keys generation and SSL certificate installation.

It is available for Linux, Windows, macOS, and BSD systems. It comes pre-compiled in most Linux distributions. If you are on Windows, you will need to first install it.

**Here is how to install OpenSSL in Windows**.

How to generate private and public keys on Linux

Open the terminal of your Linux distribution.

Navigate to the directory where you want to generate the RSA keys using the cd command. Alternatively, you can right-click on the folder in which you want to create the keys and select the "Open in terminal" option to open the terminal on that directory.

## Generates RSA using php

```
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//Generates a new private key
$res = openssl_pkey_new();
if($res)
{
echo "openssl_pkey_new: " . $res;
}
$openssl_pkey_export=openssl_pkey_export($res, $privkey, "PassPhrase number 1"); {
// Get details of public key
if($openssl_pkey_export)
{
echo "openssl_pkey_export: " . $openssl_pkey_export;
}
$pubkey = openssl_pkey_get_details($res);
$pubkey = $pubkey["key"];
if($pubkey)
{
echo "openssl_pkey_get_details: " . $pubkey;
}
$rsaKey = openssl_pkey_new(array(
'private_key_bits' => 4096,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
if($rsaKey)
{
echo "openssl_pkey_new: " . $rsaKey;
}
$privKey = openssl_pkey_get_private($rsaKey);
if($privKey)
{
echo "openssl_pkey_get_private: " . $privKey;
}
openssl_pkey_export($privKey, $pem);
//download in privatekey.pem file
file_put_contents('publickey.pem', $pubkey);
file_put_contents('privatekey.pem', $pem);
// download function start here
ob_clean();
header('Content-Description: File Transfer');
header('Content-Type: application/x-pem-file');
header("Content-Disposition: attachment; filename=public.pem");
exit(readfile('privatekey.pem'));
// var_export($pubkey, $return)
// var_dump($privkey);
// var_dump($pubkey);
}
}
?>
```

## Top comments (0)