Created
April 23, 2020 21:34
-
-
Save Nutscracker87/904484b1b36f1d101538157f88ebe3e3 to your computer and use it in GitHub Desktop.
RSA encrypt/decrypt (php to node)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Node code: | |
| ========================================= | |
| var crypto = require('crypto'); | |
| const { generateKeyPair } = require('crypto'); | |
| // generate private/public secret keys if you need | |
| generateKeyPair('rsa', { | |
| modulusLength: 2048, | |
| publicKeyEncoding: { | |
| type: 'spki', | |
| format: 'pem' | |
| }, | |
| privateKeyEncoding: { | |
| type: 'pkcs8', | |
| format: 'pem', | |
| } | |
| }, (err, publicKey, privateKey) => { | |
| console.log(publicKey) | |
| console.log(privateKey) | |
| //save your private and public keys somewhere. | |
| //than you can send your public key to other side(in our case other server with php) | |
| // Handle errors and use the generated key pair. | |
| }); | |
| var publicKey = `-----BEGIN PUBLIC KEY----- | |
| your_publick_sercret_hash | |
| -----END PUBLIC KEY-----`; | |
| var privateKey = `-----BEGIN PRIVATE KEY----- | |
| your_publick_sercret_hash | |
| -----END PRIVATE KEY-----`; | |
| var receivedBase64EncodedEncryptedMsg = 'encrypted_with_publicKey_msg_from_other_site'; | |
| //decrypt received message | |
| var msg = crypto.privateDecrypt({key:privateKey, padding:crypto.constants.RSA_PKCS1_PADDING}, Buffer.from(encryptedMsg, 'base64')); | |
| console.log(msg.toString()); | |
| ========================================= | |
| PHP code(other side): | |
| ========================================= | |
| include_once APPPATH . 'vendor/Crypt/Crypt/Hash.php'; | |
| include_once APPPATH . 'vendor/Crypt/Crypt/RSA.php'; | |
| include_once APPPATH . 'vendor/Crypt/Math/BigInteger.php'; | |
| $public_key_from_node_side = '-----BEGIN PUBLIC KEY----- | |
| public_key | |
| -----END PUBLIC KEY-----'; | |
| $msg_for_encrypt = "PHP is my secret love"; | |
| $pk = openssl_get_publickey($public_key_from_node_side); | |
| openssl_public_encrypt($data, $encrypted, $pk); | |
| $encrypted_msg = chunk_split(base64_encode($encrypted)); | |
| echo 'Encrypted: '. $encrypted.'<br>'; | |
| // send $encrypted_msg to server with node and here decode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment