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
Related
So I have a certificate in pem format (mycert.pem), from which I only need to extract the public key.
openssl x509 -in mycert.pem -pubkey -noout gives me a public key. However, it seems to be the base64 encoded string of the entire subject public key info.
Subject Public Key Info:
Public Key Algorithm: id-ecPublicKey
Public-Key: (256 bit)
pub:
04:6e:af:3c:7d:4c:a3:1a:81:f0:ae:14:45:16:67:
38:5b:09:4d:9e:55:f8:e2:f2:ba:e4:55:28:f6:31:
d8:25:c3:2d:f9:a2:d5:62:ba:eb:17:5f:1d:ad:99:
50:e4:a6:bd:eb:9b:44:18:0f:72:ae:bd:fb:87:1f:
82:dd:98:be:25
ASN1 OID: prime256v1
NIST CURVE: P-256
However, I'm only interested in the "raw" public key part pub:
04:6e:af:3c:7d:4c:a3:1a:81:f0:ae:14:45:16:67:
38:5b:09:4d:9e:55:f8:e2:f2:ba:e4:55:28:f6:31:
d8:25:c3:2d:f9:a2:d5:62:ba:eb:17:5f:1d:ad:99:
50:e4:a6:bd:eb:9b:44:18:0f:72:ae:bd:fb:87:1f:
82:dd:98:be:25
How can I extract (dynamically!) the relevant information? It is important to have an approach that works for any certificate, not just the example presented.
My implementation is in php, so ideally I'll find a solution using phpseclib or openssl functions. But understanding how it works with openssl via the command line, for example, also helps. Thank you.
I´m having a hard time understanding what is my problem here, so i was hopping someone could help me. So, i have a xml file which was build respecting W3C recomendationsand because of this, there are specific tags which were encrypted with my public key, and now i need to decrypt them using my private key, so for example this chunck of code:
<AuthenticatedPrivate Id="ID_AuthenticatedPrivate">
<enc:EncryptedKey xmlns:enc="http://www.w3.org/2001/04/xmlenc#">
<enc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<enc:CipherData>
<enc:CipherValue>lwYdkG5Q5wfW/S7UzZDtnJMcAng3w3ketzkh68y1BeX+okNEj48b5rSWUC/4mNhT
N2QsHxOCkvKDavIGGSAP23tdp0VtdeHTNAszcgK4Xzc8VHGUEiswONCOxTzNWuwj
....
zfHceeHN50b8vzM/Rt/jTUq54eC3nE+lP3eTXbLj/YvpPo8H45Sti9YP9WZixGHz
Uvf6Go31+3JwsXXIUl3O+w==</enc:CipherValue>
</enc:CipherData>
</enc:EncryptedKey>
<enc:EncryptedKey xmlns:enc="http://www.w3.org/2001/04/xmlenc#">
<enc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<enc:CipherData>
<enc:CipherValue>TvC1LCspgTsXqM1b8ClPCtAkAdXXzxe+Av7LMxYtUaqUbd8HeBuaS1cx3WwoVRDr
TWcrBEnv24GbIB5ygcMFW3DlGsXfmWJGnRNx/6xT/U15RQPgoD9AP4WFEHxthzP0
....
1ajG5lDjEu4TqjdL7DPGNu9HfI9boerJ5FUFQ/fMdD4xbDHdc4DgIQdTUgLFGHJz
RwOyfOAcSNoO/fpAkMXoEw==</enc:CipherValue>
</enc:CipherData>
</enc:EncryptedKey>
</AuthenticatedPrivate>
I need to decrypt that, so what i have done was:
Parsed the xml, and got the tag i need (CipherValue).And actually putted that inside a file, cypher.xml
cat cypher.xml| base64 -D > rawFile
openssl rsautl -decrypt -in rawFile -out plaintext -inkey private.pem
and the result was:
4476804716:error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error:rsa_pk1.c:273:
4476804716:error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed:rsa_eay.c:602:
What am i missing here? i´m losing too much time on this, i saw something about using the padding, but i did that directly on my php app using:
openssl_private_decrypt($tag, $decrypted, $privkey, OPENSSL_PKCS1_PADDING);
but with NO! luck at all.
Thanks for your time, regards
EDIT
The code sequence i´m using is this:
$xmlFile = file_get_contents(path_to_my_xml_file);
$privkey = openssl_pkey_get_private(path_to_my_private_key);
$arrCplContent = XmlToArray::convert($xmlFile);
$tag = $arrCplContent['AuthenticatedPrivate']['enc:EncryptedKey'][0]['enc:CipherData']['enc:CipherValue'];
$b64Dec = base64_decode($tag);
$result = openssl_private_decrypt($b64Dec, $decrypted, $privkey, OPENSSL_PKCS1_OAEP_PADDING);
when i log this, the result is:
error:04099079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error
Is this the proper way of doing things, considering this ?.
First of all, it seems you are using PKCS#1 v1.5 padding instead of OAEP padding when performing the decryption. You can see OPENSSL_PKCS1_OAEP_PADDING listed for openssl_private_decrypt.
Note the line in the XML document containing the OAEP padding indication:
<enc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
There are two CipherValue elements in there. Usually that means that the ciphertext was created using two different key pairs and thus two separate private keys. You may just need to decrypt the other EncryptedKey.
To solve this in general: XML encryption or XML enc is a full standard, and you need to either implement the standard or - what's commonly recommended - use a library to decrypt it.
Disclaimer: I'm not affiliated with the shown library, and I don't have any opinion on it's security.
I have this issue where something is encrypted in python using aes 256 cbc encryption as shown in the python codes encrypt method .
I am trying to create a Decrypt method in php to actually decrypt whats encrypted using the python class .
Here is my attempt to convert the python decryption method to php does it look right or am I missing something in my conversion as every time i use the php version to decrypt it says hmac failed ?
anyhelp in converting the python class to php i will appreciate.
public function decrypt(){
$encrypt_method ="AES-256-CBC";
$secret_key =base64_decode('samekeyusedintheencryption');
$encrypted=(string)'some encrypted text to be decrypted';
$data=json_decode(base64_decode($encrypted),true);
$secret_iv =base64_decode($data['iv']);
$output = \openssl_decrypt($data['value'],
$encrypt_method,$secret_key,0,$secret_iv);
return json_encode($output);
}
def decrypt(self, payload):
data = json_c.decode(base64.b64decode(payload))
value = base64.b64decode(data['value'])
iv = base64.b64decode(data['iv'])
crypt_object=AES.new(self.key,AES.MODE_CBC,iv)
plaintext = crypt_object.decrypt(value)
return loads(plaintext)
OK, I got it to work!
function decrypt($encryptedText, $secret_key){
$secret_key = base64_decode($secret_key);
$encrypt_method ="AES-256-CBC";
$data = json_decode(base64_decode($encryptedText),true);
$data['iv'] = base64_decode($data['iv']);
$data['value'] = base64_decode($data['value']);
return openssl_decrypt($data['value'], $encrypt_method, $secret_key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $data['iv']);
}
Some things I learned:
If the options in the openssl function are set to '0' it expects a base64_encoded input for the cipher text. Also, if the default options is set to '0' the padding default is set to PKCS#7. This, I think, is why we were getting the bad block size error.
So, the cipher text needs to be base64_decoded and we need to set both options for the padding.
I was able to decrypt your provided cipher text and see the email addresses.
You are provided the MAC in the Data array so this would allow you to check the MAC in the PHP script. This allows you to make sure the data has not been tampered with.
I recently did an encryption project and started with the open ssl, but ended up changing to the libSodium library. I highly recommend you check it out for any further projects.
Cheers!
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.
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