Here is the string I am submitting as text file (csr.txt) with command line
https://pastebin.com/qBLJcKQB
openssl command I am passing is:
openssl req -noout -modulus -in csr.txt | openssl md5
e199562f2e9f6a29826745d09faec3a6
Here is the php script version for getting the md5 hash
<?php
$csr = '-----BEGIN CERTIFICATE REQUEST-----
MIIBxzCCATACAQAwgYYxCzAJBgNVBAYTAlVLMQ8wDQYDVQQIDAZMb25kb24xDTAL
BgNVBAcMBEJsYWgxDjAMBgNVBAoMBUJsYWgxMQ4wDAYDVQQLDAVCbGFoMjETMBEG
A1UEAwwKSm9lIEJsb2dnczEiMCAGCSqGSIb3DQEJARYTb3BlbnNzbEBleGFtcGxl
LmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAsfzWjyj7zlVFlXCaGMH6
Gj3jsWV2tC6rLnRKK4x7hUaI0JriqXUQTNYKTgVhDslR1K0zrJYcaqpmwb4PrUJ/
2RY5si7QvHnndwJ3NOdHFOK8ggn1QqRvFFo4ssPpYWGY63Abj0Df9O6igEHQRQtn
5/9WkkM8evLLmS2ZYf9v6W8CAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4GBADLYvFDq
IfxN81ZkcAIuRJY/aKZRcxSsGWwnuu9yvlAisFSp7xN3IhipnPwU2nfCf71iTe/l
SZifofNpqrnamKP90X/t/mjAgXbg4822Nda1HhbPOMx3zsO1hBieOmTQ9u03OkIZ
hkuQmljK8609PGUGcX5KeGBupZPVWJRf9ly7
-----END CERTIFICATE REQUEST-----';
$csrDetails = openssl_pkey_get_details(openssl_csr_get_public_key($csr));
echo md5($csrDetails['rsa']['n']);
?>
php script produces:
718926bb97aabc0fd1116fa25c295612
I have seen other threads which talk about excluding new line but in my case I am not using echo but rather using openssl. Why PHP's md5 is different from OpenSSL's md5?
Appreciate some assistance.
NOTE: If I drop from the command line "| openssl md5" & in the php script remove md5() then the results are identical
php script produces:
echo strtoupper(bin2hex($csrDetails['rsa']['n']));
B1FCD68F28FBCE554595709A18C1FA1A3DE3B16576B42EAB2E744A2B8C7B854688D09AE2A975104CD60A4E05610EC951D4AD33AC961C6AAA66C1BE0FAD427FD91639B22ED0BC79E777027734E74714E2BC8209F542A46F145A38B2C3E9616198EB701B8F40DFF4EEA28041D0450B67E7FF5692433C7AF2CB992D9961FF6FE96F
In the php version you are hashing the binary representation of the modulus, i.e. the binary data 0xB1FCD68F28.... With the command line version you are hashing a printable text string representation of the modulus, i.e. the string "Modulus=B1FCD68F28...". Assuming you are on a machine using an ASCII based character set, this translates to the binary data 0x4D6F64756C... Therefore you are hashing different data in each case and so you are going to get a different result.
Also it looks like openssl is adding a "\n" to the end of the output from the "openssl req ..." command. From php try running md5("Modulus=B1FCD68F28...\n"), i.e. note using " instead of ' and the \n on the end. I tried that and got "e199562f2e9f6a29826745d09faec3a6" - the same as the OpenSSL command line
Related
I'm attempting to run a bash command in a php script. Unfortunately, because the command contains a pipe to another command, it doesn't seem to work as simple as writing the actual bash command into proc_open, popen, or shell_exec. I'm trying to use openssl to decrypt an encrypted password. I have the encrypted password in a database and after I retrieve it I need to echo the encrypted pw and pipe it to openssl. This is the exact command I need to run in its basic bash format:
echo $encryptedPassword | openssl enc -base64 -d -aes-256-cbc -salt -pass pass: password -pbkdf2
Where password is the password I have chosen to use as a salt to encrypt it in the beginning which I'm obviously not going to put in the forum. I've tried to use proc_open, popen, and shell_exec and none of the info I've found online seems to work. There's very little information online for chaining commands within php which leads me to believe this may not be possible and I may have to take another approach. It seems there is a php openssl plugin, however my company is trying to keep things as basic as possible without installing additional components. I also feel like this would be good information to know for other command chaining as there won't always be a plugin to use.
Any help would be greatly appreciated.
With the following command:
note: please notice the use of printf %s instead of echo (which adds a newline at the end).
printf %s 'stringPassword' |
openssl enc -base64 -aes-256-cbc -salt -pass pass:'password' -pbkdf2
You get:
U2FsdGVkX1/PdBwO5rCJrbn5dZ5cHb9w1lH2E1LECBw=
For deciphering it you have to:
base64-decode the output of openssl.
Get the salt, which is bytes 9-16 of the base64-decoded string.
Derive a 48 bytes key using PBKDF2 with the given password, the salt and 10000 iterations of sha256 hashing (default of openssl -pbkdf2).
Get the encryption key (which is bytes 1-32) and the iv (which is bytes 33-48) from the derived key.
Get the ciphered text, which is bytes 17 through the end of the base64-decoded string.
Decrypt the ciphered text using aes-256-cbc, the encryption key and the iv.
Now, let's try to decipher it with php:
function decrypt($data, $passphrase) {
$d = unpack(
'x8/a8salt/a*data',
base64_decode( $data, true )
);
$k = unpack(
'a32key/a16iv',
openssl_pbkdf2( $passphrase, $d['salt'], 48, 10000, 'sha256' )
);
return openssl_decrypt(
$d['data'],
'aes-256-cbc',
$k['key'],
OPENSSL_RAW_DATA,
$k['iv']
);
}
var_dump( decrypt('U2FsdGVkX1/PdBwO5rCJrbn5dZ5cHb9w1lH2E1LECBw=', 'password') );
string(14) "stringPassword"
ASIDE: answering OP's initial question.
For calling the openssl command in a pipe inside php you can use shell_exec, but you SHALL prevent any potential code injection:
$cypher = 'U2FsdGVkX1/PdBwO5rCJrbn5dZ5cHb9w1lH2E1LECBw=';
$secret = 'password';
$text = shell_exec(
'echo ' . escapeshellarg($cypher) . ' | ' .
'openssl enc -d -base64 -aes-256-cbc -salt -pbkdf2 -pass pass:' . escapeshellarg($secret)
);
################
var_dump($text);
string(14) "stringPassword"
It turns out the digest algorithm for openssl changed between versions. 1.0.2 and older used md5 as the digest. Anything newer than that uses sha256. Since I was encrypting with newer openssl but decrypting with an older openssl, on the decryption side with openssl I had to specify to use sha256 with the option -md sha256. Otherwise it would try to use the older md5 digest. A very helpful link that led me to this conclusion: https://bbs.archlinux.org/viewtopic.php?id=225863
i have line of command
echo -n 2bRePass1234 | openssl dgst -sha1 -binary | openssl enc -base64
output : 3O3bhZbGKheK+g/M4pp18AwGqq8= (28 char)
i need to convert it php
what i tried. openssl_encrypt need $iv and $key. i just use random_bytes because dont know whats is the default value like the command above
return base64_encode(
openssl_encrypt(
sha1('testPass1234'),
'AES-128-CBC',
random_bytes(16),
OPENSSL_RAW_DATA,
random_bytes(16)
)
);
But its doest return same result as the command did.. is there any way just use default key and cipher to generate it?
Note: i put random_bytes(16) because i dont know what to fill it based on the command.
Two things ...
You are doing a dgst (digest) in your first call of openssl therefore you cannot call openssl_encrypt in your php.
By doing a digest you does not need random bytes.
There are at least 2 ways to do it in php
1) Using sha1 function
php -r "var_dump(base64_encode(pack('H*', sha1('testPass1234'))));"
string(28) "wW+fqYWyUoXq+c76j0j2mnD5Oyc="
2) Using openssl_digest function
php -r "var_dump(base64_encode(pack('H*', openssl_digest('testPass1234', 'SHA1'))));"
string(28) "wW+fqYWyUoXq+c76j0j2mnD5Oyc="
They will both return the same. The string returned from sha1 will be packed into a string of real bits and not treated as string.
PS: I saw you passed a different string in the command line sample and the php sample, but whenever passing the same string the results will be the same.
echo -n testPass1234 | openssl dgst -sha1 -binary | openssl enc -base64
wW+fqYWyUoXq+c76j0j2mnD5Oyc=
Hope it's what you whore looking for. Cheers!
I need to make a simple very basic encryption with AES 128 ECB mode.
The idea is to generate a cryptogram, code it in base64 and then decipher that text from a web service in php to process its content. Later we will increase the robustness of the encryption with a 256 key and CBC mode.
The problem is that the encrypted text generated from the openssl tool (installed by default in MacOX) generates a completely different result than the one generated by the openssl_encrypt function in php 7.
echo -n 'Sergio Sánchez' | openssl12n enc -aes-128-ecb -a
Result
U2FsdGVkX1+wrLjaCTSM9T3WMV1YcD9Cwzj0mKBoa7M=
No Salt
echo -n 'Sergio Sánchez' | openssl12n enc -aes-128-ecb -nosalt -a
Result
stpJKCaUQ/Q1GLzDvqaYRg==
PHP 7
echo base64_encode(openssl_encrypt('Sergio Sánchez', 'AES-128-ECB', 'password', OPENSSL_RAW_DATA));
Result
dum7MBJOzIi9jvMTvEYnug==
How can I generate a compatible cryptogram between both tools?
Here is an example of Command Line OpenSSL and web based encryption with the same encrypted example:
Changing the test data and key in order to reduce length issues:
key: 'testkey1testkey1 hex: 746573746b657931746573746b657931
data: '54657374446174615465737444617461' hex: 746573746b657931746573746b657931
Test OpenSSL encryption:
echo -n 'TestDataTestData' | openssl enc -aes-128-ecb -a -K 746573746b657931746573746b657931
Output: 'AdLbg3zhQ2/hei0QxAdvnVZaYCTUjgmjheMmWi8Js5A='
hex: 01D2DB837CE1436FE17A2D10C4076F9D565A6024D48E09A385E3265A2F09B390
The first 16 bytes are the encrypted data, the last 16 bytes are padding, see note.
Test web based encryption (yes it is ECB mode):
http://extranet.cryptomathic.com/aescalc?key=746573746b657931746573746b657931&iv=00000000000000000000000000000000&input=54657374446174615465737444617461&mode=ecb&action=Encrypt&output=
output: 01D2DB837CE1436FE17A2D10C4076F9D
Comparing the two outputs (dropping the padding):
AESCalc : 01D2DB837CE1436FE17A2D10C4076F9D
OpenSSL: 01D2DB837CE1436FE17A2D10C4076F9D
From here you can make changes as necessary one by one.
Helpful links:
OpenSSL enc man page
AES Calculator
Base64 to hex decoder
Text to Hex Converter
PKCS#7 padding
Note 1: PKCS#7 padding always adds padding so when used with data that is a multiple of the block size a full block of padding is (must be) added. If padding were not added, even in this case, it would not be possible in all cases to determine that no padding were added.
Note 2: AESCalc with padding explicitly added:
http://extranet.cryptomathic.com/aescalc?key=746573746B657931746573746B657931&iv=00000000000000000000000000000000&input=5465737444617461546573744461746110101010101010101010101010101010&mode=ecb&action=Encrypt&output=01D2DB837CE1436FE17A2D10C4076F9D
Output: 01D2DB837CE1436FE17A2D10C4076F9D565A6024D48E09A385E3265A2F09B390
I have come accross other threads with similar questions but due to recent changes in PHP (ie. mcrypt removal), I am seeking some advice as to how I'd best go about this using OpenSSL in 2017/18.
Using echo 'this string will be encrypted' | openssl enc -aes-256-cbc -a -pass pass:123 in the Mac Terminal, I was able to password encrypt the string and would now like to pass this (as a parameter) into a server-side PHP function to decrypt.
Having studied this question, I can see that it is possible but it uses the now removed mcrypt function. Further reading in the PHP manual, I am no closer to figuring out how to reverse this encryption command into its PHP decryption equivalent.
This recent answer is what I have implemented so far, yet again, it just won't work with a Terminal generated encryption, only one which was created in PHP (not shown here).
<?php
$encrypted_string = $_GET['data'];
$password = '123';
$decrypted_data = openssl_decrypt($encrypted_string, "AES-256-CBC", $password);
print "Decrypted Data: <$decrypted_data>\n";
?>
The OpenSSL PHP manual states that either plain text or base64 encoded strings can be passed in and be decrypted. As I have used the -a flag during encryption, I would expect base64 to be passed in, thus eliminating the source as a potential reason why no decrypted data is returned.
I have taken care of URL encoding such that any + symbols produced by the encryption algorithm are replaced with their - %2B - URL-Safe equivalent as they would otherwise be turned into a space character, thus breaking the parameter string. This further ensures that the encoded input string is correctly addressed by the decryption algorithm.
Questions: Why won't my PHP function decrypt the string generated by the terminal command, although both use the same method and password? What is missing from my PHP code that would enable this to work?
Cheers everyone.
UPDATE
I am now using Terminal command:
echo 'blah' | openssl enc -aes-256-cbc -a -K B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF -iv 64299685b2cc8da5
which encrypts to: Y4xelTtEJPUHytB5ARwUHQ==
I pass this to PHP using www.example.com/?data=Y4xelTtEJPUHytB5ARwUHQ==
PHP should take data param and decrypt. Currently, that function looks like this:
<?php
$encrypted_string = base64_decode($_GET['data']);
$key = 'B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF';
$iv = '64299685b2cc8da5';
$output = openssl_decrypt($encrypted_string, 'AES-256-CBC', hex2bin($key), OPENSSL_RAW_DATA, hex2bin($iv));
print "Decrypted Data: <$output>\n";
?>
OpenSSL uses a proprietary KDF that you probably don't want to put the effort in to reproduce in PHP code. However, you can pass your key as pure hex instead, avoiding the KDF, by using the -K flag:
echo 'blah' | openssl enc -aes-256-cbc -K 0000000000000000000000000000000000000000000000000000000000000000
Here, the large hex string is your 256-bit key, hex encoded. This encryption operation will be compatible with your PHP.
In PHP, I want to sign some documents with a padding of PSS, and a digest of SHA512.
According to the docs, at http://www.php.net/manual/en/function.openssl-sign.php, I can set the digest however I need, by using a string, such as
openssl_sign($text-to-sign,$binary_signature,$privkey,"sha512");
I don't see any way to set the padding, however.
Can anyone please help me understand how I can sign text, using the RSA-PSS padding style, as seen in version 2.1 of PKCS #1?
I had the same needs as you, but in 2019 (I assume we got better libraries now ;)
As you already discovered, the way is using phpseclib, which is now at version 2.0 in Debian Stretch.
Signature Generation
This is the code I used to sign some binary data, using a 8192 RSA key, with PSS padding and a SHA512 hash function:
require "/usr/share/php/phpseclib/autoload.php";
use phpseclib\Crypt\RSA;
// INPUT DATA
$privkey = "..."; // I used a RSA private key in PEM format, generated by openssl, but phpseclib supports many formats...
$mydata = "..."; // I generated some binary bytes here...
// SIGNING
$rsa = new RSA();
if ($rsa->loadKey($privkey) != TRUE) {
echo "Error loading private key";
return;
}
$rsa->setHash("sha512");
$rsa->setMGFHash("sha512"); // This NEEDS to be set, or the default will be used
$rsa->setSignatureMode(RSA::SIGNATURE_PSS); // This doesn't need to be set, as it is already the default value
$signatureBytes = $rsa->sign($mydata);
$signatureBytes is a binary string (or an array of bytes, as you call it in C/C++/C#). It doesn't have any encoding, and may contain NULL bytes. This is your wanted signature.
Side note: it's nearly required to insall php-gmp, or you'll get painfully slow signing times. Here there are some benchmarks.
Signature Verification with OpenSSL
openssl dgst -sha512 -sigopt rsa_padding_mode:pss -sigopt
rsa_pss_saltlen:-1 -verify pubkey.pem -signature signature.bin
plaintextdata.dat
In detail, the -sigopt rsa_pss_saltlen:-1 tells openssl to use a salt length that matches the hashing algorithm size. (this is what the Microsoft APIs do, and there's no way to change that behavior)
Signature Verification with C++/CLI (.NET)
In order to be able to use the RSA public key in the .NET world, without using any other library, you need first to export it in BLOB format using openssl:
openssl rsa -pubin -inform PEM -in pubkey.pem -outform "MS PUBLICKEYBLOB" -out pubkey.blob
Then, you need .NET 4.6, with the new RSACng CryptoProvider.
And that's the code:
// Import the public key (as BLOBDATA)
RSACryptoServiceProvider^ rsaCsp = gcnew RSACryptoServiceProvider();
rsaCsp->ImportCspBlob(pubkey);
RSAParameters rsaParams = rsaCsp->ExportParameters(false);
RSA^ rsa = gcnew RSACng();
rsa->ImportParameters(rsaParams);
array<Byte>^ dataBytes = ...;
array<Byte>^ signatureBytes = ...;
bool signIsValid = rsa->VerifyData(dataBytes, signatureBytes, HashAlgorithmName::SHA512, RSASignaturePadding::Pss);
In order not to be "That Guy", I thought I'd leave an answer to the question, given how this does show up in Google and all ;)
I am able to get the PSS padding via http://phpseclib.sourceforge.net/
So far, I haven't gotten it to interop with OpenSSL or LibTomCrypt, but..
I'm probably just configuring it wrong.
I'm sure you'll have better luck, future person!
-CPD