php encrypt and decrypt - php

can anyone tell me how to encrypt and decrypt a URL string ?
I want to encrypt a hyperlink ...

If you can use database,you could create a table to map a file to an id.
Create a 'mapping_table'
id - integer
file_location - string
Your URL would look something like localhost/waterwell/e_book.php?id=12 .

make links that return to your server with querystring GET params identifying the file. the server can then do echo file_get_contents() after you figure out which file from the inputs
In your example it's trivial. simply omit the portion of the url you don't want shown and fill it back in on the server.

$confirmpassword = $_POST['confirmpassword'];
$value_check = true;
$ciphering = "AES-128-CTR";
$options = 0;
$encryption_iv = '1234567891011121';
$encryption_key = "GeeksforGeeks";
$confirmpasswordencryption = openssl_encrypt($confirmpassword, $ciphering,$encryption_key, $options, $encryption_iv);
$encryption = "pABqPJhobIMHzqai"
$ciphering = "AES-128-CTR";
$options = 0;
$decryption_iv = '1234567891011121';
// Store the decryption key
$decryption_key = "GeeksforGeeks";
// Use openssl_decrypt() function to decrypt the data
$decryption=openssl_decrypt ($encryption, $ciphering,
$decryption_key, $options, $decryption_iv);
// Display the decrypted string
echo "Decrypted String: " . $decryption;

Related

Encrypting data in url

l have some data in json format e.g {"utm_source":"","utm_medium":"","utm_campaign":"","utm_term":"","utm_content":""} and l want to send them encrypted as uri to another domain (example.com/$encrypted_data) and then decrypt them. How can l do that (with PHP) so the encrypted string contains only those chars: [A-Z, a-z, 0-9, -, /] and decryption is possible using the specific key? I am using PHP 8.1
<?php
// Store a string into the variable which
// need to be Encrypted
$simple_string = "Welcome to GeeksforGeeks\n";
// Display the original string
echo "Original String: " . $simple_string;
// Store the cipher method
$ciphering = "AES-128-CTR";
// Use OpenSSl Encryption method
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
// Non-NULL Initialization Vector for encryption
$encryption_iv = '1234567891011121';
// Store the encryption key
$encryption_key = "GeeksforGeeks";
// Use openssl_encrypt() function to encrypt the data
$encryption = openssl_encrypt($simple_string, $ciphering,
$encryption_key, $options, $encryption_iv);
// Display the encrypted string
echo "Encrypted String: " . $encryption . "\n";
// Non-NULL Initialization Vector for decryption
$decryption_iv = '1234567891011121';
// Store the decryption key
$decryption_key = "GeeksforGeeks";
// Use openssl_decrypt() function to decrypt the data
$decryption=openssl_decrypt ($encryption, $ciphering,
$decryption_key, $options, $decryption_iv);
// Display the decrypted string
echo "Decrypted String: " . $decryption;
?>
output
Original String: Welcome to GeeksforGeeks
Encrypted String: hwB1K5NkfcIzkLTWQeQfHLNg5FlyX3PNUA==
Decrypted String: Welcome to GeeksforGeeks
You can use openssl_decrypt() for decrypting data in PHP. you can read more about openssl_decrypt(); to know more how handle decrypt and encrypt string

PHP RSA Enryption Always Returns "AAAAAAA"

I'm trying to encrypt a message using phpseclib. Below is the method that encrypts it:
function RSAEncrypt($data, $publicKey)
{
$rsa = new \Crypt_RSA();
$rsa->loadKey($publicKey);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$encryptedData = $rsa->encrypt($data);
$encodedData = base64_encode($encryptedData);
return $encodedData;
}
the code that encrypt message
$client_key = 123456789;
$random_str = rand();
$aes_password = $client_key.'-'.$random_str;
$public_key = file_get_contents('keys/public.xml');
$ecrypted_password = RSAEncrypt($aes_password, $public_key);
but no matter the message the $aes_password that i passed , the $ecrypted_password output is always
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE= ◀"
I tried to decrypt it using the private key to see if its valid anyways but i always gets Decryption Error so i figured maybe the error is with the encryption

Sending encrypted message from php to a C++ App and decrypting then with CryptoPP

i am trying to send an encrypted message with AES-256-CRT that need to be encoded with a base16 hex cause CryptoPP HexDecoder does it in that way, but i can't decrypt the encrypted text in my C++ application how i can solve this?
PS: I am using libcurl to make the requests from c++.
Here is the code's:
PHP File:
<?php
function EncryptThis($ClearTextData)
{
$ENCRYPTION_KEY = '7D9BB722DA2DC8674E08C3D44AAE976F';
$ENCRYPTION_IV = '37C6D22FADE22B2D924598BEE2455EFC';
return openssl_encrypt($ClearTextData, "AES-256-CTR", $ENCRYPTION_KEY, OPENSSL_RAW_DATA, $ENCRYPTION_IV);
}
$code = 'test';
$encryptedBytes = EncryptThis($code);
echo($encryptedBytes);
PHP echo Output: `]$Q
This is fixed right now, and the answer is the above code. (At least for my problem). I have been trying with a CBC mode but it doens't worked so i tried CRT.
I changed the file reading method and added a decryption function just to check that encryption is working properly.
Please keep in mind that this method of reading is not good for large file encryption (it reads the complete file into memory) - in this situation you may need another solution.
This is a very basic example that does not do any vanity checks...
<?php
$ENCRYPTION_KEY = 'ThisIsNotMine';
$ENCRYPTION_ALGORITHM = 'AES-256-CBC';
function EncryptThis($ClearTextData)
{
// This function encrypts the data passed into it and returns the cipher data with the IV embedded within it.
// The initialization vector (IV) is appended to the cipher data with
// the use of two colons serve to delimited between the two.
global $ENCRYPTION_KEY;
global $ENCRYPTION_ALGORITHM;
$EncryptionKey = base64_decode($ENCRYPTION_KEY);
$InitializationVector = openssl_random_pseudo_bytes(openssl_cipher_iv_length($ENCRYPTION_ALGORITHM));
$EncryptedText = openssl_encrypt($ClearTextData, $ENCRYPTION_ALGORITHM, $EncryptionKey, 0, $InitializationVector);
return base64_encode($EncryptedText . '::' . $InitializationVector);
}
function DecryptThis($CryptedTextData)
{
// This function decrypts the data passed into it and returns the clear data
// The initialization vector (IV) is appended to the cipher data with
// the use of two colons serve to delimited between the two.
global $ENCRYPTION_KEY;
global $ENCRYPTION_ALGORITHM;
$EncryptionKey = base64_decode($ENCRYPTION_KEY);
list($EncryptedTextData, $InitializationVector) = explode('::', base64_decode($CryptedTextData), 2);
$DecryptedText = openssl_decrypt($EncryptedTextData, $ENCRYPTION_ALGORITHM, $EncryptionKey, 0, $InitializationVector);
return ($DecryptedText);
}
$path = 'file.txt';//file to send can be .exe, .dll, .txt whatever i am just trying with it.
if (file_exists($path)) {
$code = file_get_contents($path); //Get the code to be encypted.
$encryptedBytes = EncryptThis($code);
echo 'encryptedBytes:' . ($encryptedBytes) . '<br>';//send the encrypted bytes to my client.
// decryption for a simple check
$decryptedData = DecryptThis($encryptedBytes);
echo 'decryptedData:' . $decryptedData . '<br>';
}
?>

Decrypting PHP openssl_ecrypt with NodeJS crypto errors

We have a legacy PHP system that encrypted some data via openssl_encrypt. The PHP code is pretty straight forward. (All values are randomly generated for this example, but are the same format and lengths as the real values and reproduce the same errors).
$in = '12345';
$method = 'AES-256-CBC';
$key = '5fjfwc7kp84z5yet358t';
$options = 0;
$iv = '8x69nt6qnptg3x4j';
openssl_encrypt($in, $method, $key, $options, $iv);
Decrypting via PHP is also pretty straight forward.
$in = 'yy03+cUpsq5uGWclBLtwIA==';
$method = 'AES-256-CBC';
$key = '5fjfwc7kp84z5yet358t';
$options = 0;
$iv = '8x69nt6qnptg3x4j';
openssl_decrypt($in, $method, $key, $options, $iv);
However, when trying to port it over to Node crypto I keep getting errors on key length, iv length, and numerous other errors as I try different approaches.
const input = Buffer.from('yy03+cUpsq5uGWclBLtwIA==');
const iv = Buffer.from('8x69nt6qnptg3x4j');
const key = Buffer.from('5fjfwc7kp84z5yet358t');
let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv, 0);
let clearText = decipher.update(input, 'base64', 'utf8');
clearText += decipher.final('utf8');
I've probably tried half a dozen or more examples in NodeJS and all produce errors and fail to decrypt entirely.
Current error is "Invalid key length" which remains the error even if I restrict it to 16 characters.
Padding and base64 processing was the solution. Working code looks closer to this:
const keyStr = '5fjfwc7kp84z5yet358t';
const diff = Math.abs(keyStr.length - 32);
const padding = Buffer.alloc(diff, 0x00);
const input = Buffer.from('yy03+cUpsq5uGWclBLtwIA==', 'base64');
const iv = Buffer.from('8x69nt6qnptg3x4j');
let key = Buffer.from('5fjfwc7kp84z5yet358t');
key = Buffer.concat([key, padding]);
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv, 0);
let clearText = decipher.update(input, 'base64', 'utf8');
clearText += decipher.final('utf8');

Encrypt file with PHP OpenSSL

Usually, I use openssl_encrypt to encrypt simple string with AES in PHP, and it works pretty well.
Now I need to encrypt files with AES-256-CTR mode, but the only way to do this is to file_get_contents the entire content of the file and then send it to the openssl_encrypt function to encrypt the actual file data. The problem is this method is very "poor" because of the critical waste of memory.
1) Is there a way to work with chunked data with PHP OpenSSL ?
For example:
<?php
// ...
$f = fopen('large.iso','r');
while(feof($f)){
$chunk = fread($f,16);
$cipher = openssl_encrypt(...$chunk...);
// ... code ...
}
// ... more code ...
?>
2) openssl_encrypt official documentation is not published yet. Does someone could clarify the meaning of the parameters of the function for use with AES-CTR mode? Does the counter is handled automatically? Is it necessary to apply a manual XOR the data returned by the function?
Note: It is a professional project so I don't want to use phpseclib or others' "anonymous" libraries, nor do I don't want to use the command line as well.
Looks like for php it's not possible to use aes-256-ctr without temporary file.
But for next chiper types:
OPENSSL_CIPHER_RC2_40
OPENSSL_CIPHER_RC2_128
OPENSSL_CIPHER_RC2_64
OPENSSL_CIPHER_DES
OPENSSL_CIPHER_3DES
OPENSSL_CIPHER_AES_128_CBC
OPENSSL_CIPHER_AES_192_CBC
OPENSSL_CIPHER_AES_256_CBC
you can use generating key on the fly:
$res = openssl_pkey_new('chiper args here');
openssl_pkey_export($res, $private_key);
$public_key = openssl_pkey_get_details($res);
$public_key = $public_key["key"];
Then encrypt:
$crypted_text = openssl_get_privatekey($private_key,'your data');
And decrypt:
openssl_public_decrypt($crypted_text,$decrypted_text,$public_key);
So if you don't want to use files, may be switching to OPENSSL_CIPHER_AES_256_CBC will help you?
1) It should be something like this:
function strtohex($x) {
$s = '';
foreach (str_split($x) as $c){
$s.=sprintf("%02X", ord($c));
}
return($s);
}
$method = "aes-256-ctr"; //aes-256-cbc
echo "Selected method: ".$method."<br /><br />";
$textToEncrypt = "My chunk of data";
$iv = "1234567890123456";
$pass = 'some_pass';
$dec_iv = strtohex($iv);
$key = strtohex($pass);
$enc_data = openssl_encrypt($textToEncrypt, $method, $pass, true, $iv);
echo "Encrypted message (openssl): ".$enc_data."<br />";
$dec_data = openssl_decrypt($enc_data, $method, $pass, OPENSSL_RAW_DATA, $iv);
echo "Decrypted message (openssl): ".$dec_data."<br />";
For CTR $iv should be unique for each chunk or your data can be broken.
2) I know only abot difference betwen CBC and CTR:
For CBC, the IV must be random, but not unique. It also must not be known.
For CTR, the IV must be unique and not known, but does not need to be random.

Categories