I use the library "JSEncrypt" for JS
HTML & JS & AJAX to PHP (send encrypted text to php file for decryted)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>RSA js - php</title>
<script type="text/javascript" src="https://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<script>
var encrypt = new JSEncrypt();
const servPubKeyPem = '-----BEGIN PUBLIC KEY-----\
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEApa35WYXLyAIoIikbTU7J\
qQyltZX+zj8ea2bwCcs0rVcpSqMsYYWElQhvGXwSG1Dnd1jY3kNoqOvxb0oRToPj\
wLtx4xLh/RrH5eb9Xhssmo+KYhHFPu/FDBeAy4RQyP/Rv4CIIjWscj3aCiBDPrrM\
S6olwPtCRPsszG4TuUe29pW60JNCnU/1o+7rfjOCecdJpvVvqRW2vN4yxgkjAsf6\
UYyrnd9NXCaElG7X3jYKX84PSBTfttIHUthu+u37FLFUoKOZwqO4Lv0OfacevFCJ\
T4OoMnibeiygSVu8y94MtODp2SMCJ2OteKz8/11uzU27T4x9odS/DrevBebY2V5I\
94cpjyHVzJvNxqrwQ7nNOk0Y7rPvLvKfIGXXD708LRqMNpYZwj9Wu4aOXaxC6myW\
lguGT+OX3TfFzQ1dLyslGTiuy9f41AOJiK+PUnTZh84UALtnSnS62bM39+OaWHZc\
xlI7lHDK8mYxgzp9Us6WvLRBH15j3sSNV+GWCLOIk8Y6UIV/RYMCUNdVahiVqOH8\
0vevhdGZQHTLKmNdaiqCOI9R0hZLbFLzkph/kNnFKRlI0MoYn8Tqg2BRIPFYizPf\
eK+y4nmvJhmiMq3ZzUmVApt2deufZIJmNfqmnDyMKOICnYxcH0zJCrKmBmlM9u1i\
PMIXYCIshW2D3E1ACCPOw3ECAwEAAQ==\
-----END PUBLIC KEY-----'
encrypt.setPublicKey(servPubKeyPem);
var encryptedText = encrypt.encrypt('Hello my friend!');
$.ajax({
type: "POST",
url: 'test.php',
data: {'encryptedText' : encryptedText},
success: function(data) {
}
});
</script>
</body>
</html>
PHP:
<?php
$encryptedText = $_POST['encryptedText'];
$priKeyPem = file_get_contents('../php/priKey.pem');
$priKey = openssl_pkey_get_private($priKeyPem); //PriKey - PrivateKey - (he is work)
openssl_private_decrypt($encryptedText, $decryptedText, $priKey);
# but $decryptedText == null ...
?>
I need to encrypt the text in JS pass the encrypted text in PHP and in PHP decrypt it, but in PHP I get "null"... Please help :/
My Answer:
CryptoJS for encryption in JavaScript and the library phpseclib for decryption in PHP using RSA encryption.
Here is an example of how you can encrypt a message in JavaScript using CryptoJS:
javascript
const message = 'Hello, world!';
const publicKey = '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz8z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z2z3z
Rate this post
3 of 5 based on 6143 votesComments