This question already has answers here:
How do you Encrypt and Decrypt a PHP String?
(10 answers)
Closed 8 years ago.
I'm looking for some functions to encrypt and decrypt strings in php using a key specified.
Thanks!
A basic openssl implementation I've used before:
class MyEncryption
{
public $pubkey = '...public key here...';
public $privkey = '...private key here...';
public function encrypt($data)
{
if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
$data = base64_encode($encrypted);
else
throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');
return $data;
}
public function decrypt($data)
{
if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
$data = $decrypted;
else
$data = '';
return $data;
}
}
You would need to generate the RSA key pair. See here for information on how to do that. Storing the private key in the file itself is a bad idea. This is just an example. Ideally you would want the user to supply the private key at decryption time
Start with this: http://www.ibm.com/developerworks/opensource/library/os-php-encrypt/
After that, have a look at Pascal MARTIN's answer in How do I encrypt a string in PHP?
have you tried mcrypt?
I assume you meant symmetric key encryption. mcrypt does support several algorithms (Like AES, Tripel DES). There is one catch though, it doesn't support any padding algorithm so you wouldn't be able to get the original length back. You have 2 options to get around this issue,
Add a length field in front of your clear-text. Say use first 4 bytes as length.
Do PKCS#5 padding yourself. There are code examples on this page: http://www.php.net/manual/en/function.mcrypt-encrypt.php
Related
I am trying to encrypt a string using a public key but each time I get a new string. Any workarounds to getting a static string?
Here is my code
$publicKey = openssl_pkey_get_public(file_get_contents("file://C:/Users/nick/Dropbox/wamp/www/samples/mycert.cer"));
$plaintext = "Matr!x12";
openssl_public_encrypt($plaintext, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);
echo base64_encode($encrypted);
Well, obviously SSL encryption generates different results each time it's involved for security reasons. If you for whatever reason you need to have identical results multiple times you cannot use "real encryption". Maybe just use MD5 or some other hash function but be aware that you cannot get secrets that cannot be decrypted (with enough effort).
I want to encrypt large strings using public key and store in file. And after that read the contents of file and decrypt it using private key.
How can I do that.
Is there any default function or code available in php.
How large is the text you're wanting to encrypt? You can't have plaintext larger than the key length (ie. modulo) in RSA. What's most often done in these instances is that a symmetric cipher key is encrypted and the plaintext is then encrypted with that key.
PHP's openssl_seal() and openssl_open() functions (assuming you have the openssl extension installed) do this using the RC4 cipher.
Checkout OPENSSL documentation for PHP as you need to know how to handle PKI. You will find every information you need there.
Here is the link
You can do this using Zend Framework 2 (Zend\Crypt\PublicKey)
ZF2 : Public key cryptography
Example (from the docs from above link!)
use Zend\Crypt\PublicKey\Rsa;
$rsa = Rsa::factory(array(
'public_key' => 'public_key.pub',
'private_key' => 'private_key.pem',
'pass_phrase' => 'test',
'binary_output' => false
));
$text = 'This is the message to encrypt';
$encrypt = $rsa->encrypt($text);
printf("Encrypted message:\n%s\n", $encrypt);
$decrypt = $rsa->decrypt($encrypt);
if ($text !== $decrypt) {
echo "ERROR\n";
} else {
echo "Encryption and decryption performed successfully!\n";
}
(edit: whitespace added to code)
This question already has answers here:
Two-way encryption: I need to store passwords that can be retrieved
(8 answers)
Closed 9 years ago.
Possible Duplicate:
Best way to use PHP to encrypt and decrypt passwords?
I've been doing a lot with PHP recently and want to make my first login/registration system. As such I've been doing a lot of reading online to figure out the best method(s) for doing this. I've come across a couple of guides and I'm confused on a few instances and I'd like to be sure before I start down this road.
My question is how exactly do I use blowfish? I've read that crypt() will auto select blowfish if an appropriate salt is provided. If that is the case, What makes a salt blowfish appropriate?
Right now, I have a script that makes a salt out of the date and time, a random number, then hash that for the salt. Is that something I can use with blowfish or not?
In short: don't build it yourself. Use a library.
In PHP 5.5, there will be a new API available to make this process easier on you. Here's the RFC for it.
I've also created a backwards-compatibility library for it here: password-compat:
$hash = password_hash($password, PASSWORD_BCRYPT);
And then to verify:
if (password_verify($password, $hash)) {
/* Valid */
} else {
/* Invalid */
}
And if you want another library, check out phpass
In short, don't do it yourself. There's no need. Just import the library and be done with it...
Take a look at http://php.net/manual/en/function.crypt.php
If you scroll down about 1/3, you should see the heading: Example #3 Using crypt() with different hash types. Hopefully this will help! and your salt should be fine!
Try this - its untested, I just whipped it up to show how to use the BLOWFISH algo with PHP
<?php
class cipher {
private static $mode = 'MCRYPT_BLOWFISH';
private static $key = 'q!2wsd#45^532dfgTgf56njUhfrthu&^&ygsrwsRRsf';
public static function encrypt($buffer){
$iv = mcrypt_create_iv(mcrypt_get_iv_size(constant(self::$mode), MCRYPT_MODE_ECB), MCRYPT_RAND);
$passcrypt = mcrypt_encrypt(constant(self::$mode), self::$key, $buffer, MCRYPT_MODE_ECB, $iv);
$encode = base64_encode($passcrypt);
return $encode;
}
public static function decrypt($buffer){
$decoded = base64_decode($buffer);
$iv = mcrypt_create_iv(mcrypt_get_iv_size(constant(self::$mode), MCRYPT_MODE_ECB), MCRYPT_RAND);
$decrypted = mcrypt_decrypt(constant(self::$mode), self::$key, $decoded, MCRYPT_MODE_ECB, $iv);
return $decrypted;
}
}
?>
IMPORTANT!! CHANGE THE $key VALUE TO ANOTHER RANDOM STRING!
Usage:
To Encrypt:
$mystring = 'a quick brown fox jumped over the lazy llama';
$mystring = cipher::encrypt($mystring);
To Decrypt:
$mystring = cipher::decrypt($myencryptedstring);
I'm working on a project(PHP Based) in which I need to compute SHA1, I'm using this line of code to generate SHA1 in PHP.
$da = file_get_contents("payload.txt");
echo sha1($da);
and this is the code for the .Net
private static string GetSHA1(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA1Managed hashString = new SHA1Managed();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
But I'm confused because both of languages generate different results, I'm not provide any salt in both of them(as I don't know what to use in salt b/c the api didn't defined that)
I also need to work on RSA after that(I've a key for the encryption)
Also Can anyone tell, does these algorithms differ due to languages or any thing I'm missing???
Need some experts opinion on this
this is the whole Algorithm to generate SHA1 and RSA encryption
<?php
class MyEncryption
{
public $pubkey = '...public key here...';
public $privkey = '...private key here...';
public function encrypt($data)
{
if (openssl_private_encrypt($data, $encrypted, $this->pubkey))
$data = base64_encode($encrypted);
else
throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');
return $data;
}
public function decrypt($data)
{
if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
$data = $decrypted;
else
$data = '';
return $data;
}
}
$enc = new MyEncryption();
$enc->pubkey = file_get_contents("server.key");
$payload = file_get_contents("payload1.txt");//payload1.txt contain xml data
$hashRes = sha1($payload,true);
echo $enc->encrypt($hashRes);
?>
Thanks alot
It's your UnicodeEncoding. PHP doesn't know anything about encodings, so your string simply contains all the bytes that the file does, 1:1. In .NET however, if you read the file as text, it will assume some encoding (typically UTF-8, if you don't specify otherwise) and then converts it to the internal representation, and in the end you convert it to UTF-16 and hash those bytes - which are probably nothing like the original at bytes all, unless the original also was UTF-16. And even if it was UTF-16, it might have included the Byte-Order-Mark, which UnicodeEncoding.GetBytes() doesn't. And even if it didn't, the original string might not have been normalized, and you might have normalized it somewhere along the way (you don't show us the code where you read it), and the bytes will be different again. Etc.
The correct approach would be to read the whole file as a binary block of bytes (for example, with System.IO.File.ReadAllBytes()), and then hash those bytes directly. There's no need to involve any text encodings and conversions. And then the hashes should match.
Have you tried sha1(data, true)? Otherwise it will generate hexadecimals. You can also use hex2bin(sha1(data)) if it is not available on your platform. Also, UnicodeEncoding may use 2 bytes as encoding instead of one (for characters that are also in ASCII). Try UTF8Encoding instead.
I'm trying to secure communication between a JS front-end and a PHP backend by using symmetric and asymmetric encryption. I'm creating a symmetric key on the client and encrypting it with the server's public key with JSEncrypt and sending it to the server for future use. However, I'm getting stuck when I get the data on the server side. openssl_open requires an envelope to decrypt the symmetric key and I'm not even positive what data is supposed to be in the envelope. I was under the impression that the envelope is the symmetric key that was encrypted with the public key, but using that has not worked. I've also tried different combinations of decoding as I've read that JSEncrypt encodes the message in base 64 and the key in hex, but those attempts are fruitless as well.
JS encryption code:
let pub = "-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----";
//I have a function that just creates a random string of characters
let key = generateKey(32);
let aesData = CryptoJS.AES.encrypt( "test", key );
let symKey = aesData.key + ":::" + aesData.iv;
let msg = aesData.toString();
let rsa = new JSEncrypt();
rsa.setPublicKey( pub );
let cryptKey = rsa.encrypt( symKey );
//I'm passing the data through a hidden form field
$("#key").val(cryptKey + ":::" + msg);
PHP decryption code:
$key = openssl_get_privatekey( file_get_contents( $_SERVER["PRIV_KEY"]) );
$encryptedKey = explode( ":::", $msg )[0];
$realMsg = base64_decode(explode( ":::", $msg )[1]);
openssl_open($realMsg, $decrypted, $encryptedKey, $key);
return $decrypted;
The code above outputs nothing because the openssl_open call fails (returns false). When I base 64 decode the $encryptedKey variable, I get:
�vEi���pΕ��d_���#����욲JE��
but the symmetric key changes every time, so the output changes every time as well. Like I said, I've tried different encoding combinations, but they all return similar nonsense. As the JS code shows, I've encrypted the message "test".
I've never implemented encryption before, so I might be way off the mark here, but after staring at this code for days, any insight would be appreciated.
Edit: I'm having problems decrypting with my private key in PHP, not with the symmetric key
Figured it out!!! So, I found out that PHP has a function to decrypt without needing an envelope called openssl_private_decrypt that uses a private key to decrypt a message. By using that function and base 64 decoding the encrypted key, I am able to decrypt the symmetric key on the server side and will hopefully be able to decrypt the message symmetrically now. For those interested, my code on the server side is:
$key = openssl_get_privatekey( file_get_contents( $_SERVER['PRIV_KEY'] ) );
$encryptedKey = base64_decode(explode( ":::", $msg )[0]);
if( openssl_private_decrypt($encryptedKey, $decrypted, $key) )
{
return $decrypted;
}
return $encryptedKey;
And on the client side, my code is the same as it was above. Hope this helps someone!