Examples of AES and RSA encryption operations implemented by PHP7.1

  • 2021-10-16 01:10:30
  • OfStack

This article illustrates the AES and RSA encryption operations implemented by PHP 7.1. Share it for your reference, as follows:

AES:


<?php
header('Content-Type: text/plain;charset=utf-8');
$data = 'phpbest';
$key = 'oScGU3fj8m/tDCyvsbEhwI91M1FcwvQqWuFpPoDHlFk='; //echo base64_encode(openssl_random_pseudo_bytes(32));
$iv = 'w2wJCnctEG09danPPI7SxQ=='; //echo base64_encode(openssl_random_pseudo_bytes(16));
echo ' Content : '.$data."\n";
$encrypted = openssl_encrypt($data, 'aes-256-cbc', base64_decode($key), OPENSSL_RAW_DATA, base64_decode($iv));
echo ' Encryption : '.base64_encode($encrypted)."\n";
$encrypted = base64_decode('To3QFfvGJNm84KbKG1PLzA==');
$decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', base64_decode($key), OPENSSL_RAW_DATA, base64_decode($iv));
echo ' Decryption : '.$decrypted."\n";
?>

Generate rsa key pair (private key/public key) with openssl:


openssl genrsa -out rsa_private_key.pem 2048
openssl rsa -pubout -in rsa_private_key.pem -out rsa_public_key.pem

RSA:


<?php
header('Content-Type: text/plain;charset=utf-8');
$data = 'phpbest';
echo ' Original content : '.$data."\n";
openssl_public_encrypt($data, $encrypted, file_get_contents(dirname(__FILE__).'/rsa_public_key.pem'));
echo ' Public key encryption : '.base64_encode($encrypted)."\n";
$encrypted = base64_decode('nMD7Yrx37U5AZRpXukingESUNYiSUHWThekrmRA0oD0=');
openssl_private_decrypt($encrypted, $decrypted, file_get_contents(dirname(__FILE__).'/rsa_private_key.pem'));
echo ' Private key decryption : '.$decrypted."\n";
?>

PS: Friends who are interested in encryption and decryption can also refer to the online tools of this site:

Online RSA Encryption/Decryption Tool:
http://tools.ofstack.com/password/rsa_encode

Text online encryption and decryption tools (including AES, DES, RC4, etc.):
http://tools.ofstack.com/password/txt_encode

Online hash/hash algorithm encryption tool:
http://tools.ofstack.com/password/hash_encrypt

Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 Encryption Tool:
http://tools.ofstack.com/password/hash_md5_sha

Online sha1/sha224/sha256/sha384/sha512 Encryption Tool:
http://tools.ofstack.com/password/sha_encode

More readers interested in PHP can check the topics of this site: "Summary of php Encryption Methods", "Summary of PHP Encoding and Transcoding Operation Skills", "Summary of PHP Mathematical Operation Skills", "Complete Collection of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Tutorial on PHP Data Structure and Algorithm", "Summary of php Programming Algorithm" and "Summary of php Regular Expression Usage"

I hope this article is helpful to everyone's PHP programming.


Related articles: