How signature file data with RSA 2048 & digest sha256? - php

I am generating a RSA signature in PHP By PHPSECLIB library. According to the instructions, the signature digest must be sha256. Should the digest be set when the key is generated?
I generated Pub/Pri key by blow code: (It should be 2048 and .perm)
$new_key_pair = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
openssl_pkey_export($new_key_pair, $private_key_pem);
$details = openssl_pkey_get_details($new_key_pair);
$public_key_pem = $details['key'];
file_put_contents('private.pem', $private_key_pem);
file_put_contents('public.pem', $public_key_pem);
I sign data by blow code:
$file_name = "x.json";
$sign_file = "signed/" . $file_name . ".sign";
$data = file_get_contents('files/' . $file_name);
$privatekey = file_get_contents('private.pem');
$rsa = new Crypt_RSA();
$rsa->loadKey($privatekey);
$rsa->setHash('sha256');
$signature = $rsa->sign($data);
file_put_contents($sign_file, $signature);
exit("signed.");
and verify it by
$file_name = "x.json";
$sign_file = "signed/" . $file_name . ".sign";
$publickey = file_get_contents('public.pem');
$data = file_get_contents('files/' . $file_name);
$signature = file_get_contents($sign_file);
$rsa = new Crypt_RSA();
$rsa->setHash('sha256');
$rsa->loadKey($publickey);
$verify = false;
try {
$verify = $rsa->verify($data, $signature);
} catch (Exception $ex) {
$verify = false;
}
echo "verify: " . (($verify) ? "true" : "false") . "<br>";
exit("finished.");
How to set up a digest? Is the signing process correct?

Related

How to generate a correct JWT without using Firebase

I am trying to generate a JWT for the DocuSign Embed API and I can't seem to figure out the private/public key part.
When I generate the JWT, the signature part is very short. Pasting it in jwt.io, it turns out both the header and payload are correct, but the signature part is wrong (and way too short when I compare it to what I get when I copy paste my public and rsa private keys.
Here is the relevant code:
$args = [
'envelope_id' => $_GET['envelope_id'],
'ds_return_url' => 'https://www.returnurl.be',
'starting_view' => 'envelope',
'base_path' => 'https://baseurl.be'
];
$args['integration_key'] = 'abc123';
if(isset($_GET['user_id'])) {
$args['user_id'] = $_GET['user_id'];
}
//generate jwt:
$headers = array('alg'=>'RS256','typ'=>'JWT');
$payload = array(
'iss'=>$args['integration_key'],
'sub'=>$args['user_id'],
'aud'=>'account-d.docusign.com', //prod: account.docusign.com
'iat'=>time(),
'exp'=>(time() + 6000),
'scope'=>'signature impersonation'
);
$secret = '-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAj...
-----END RSA PRIVATE KEY-----';
$jwt = generate_jwt($headers, $payload, $secret);
echo $jwt;
function generate_jwt($headers, $payload, $secret = 'secret') {
$headers_encoded = base64url_encode(json_encode($headers));
$payload_encoded = base64url_encode(json_encode($payload));
$signature = hash_hmac('SHA256', "$headers_encoded.$payload_encoded", $secret, true);
$signature_encoded = base64url_encode($signature);
$jwt = "$headers_encoded.$payload_encoded.$signature_encoded";
return $jwt;
}
function base64url_encode($str) {
return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
}

Etsy PHP Oauth: Cant get access token

I have followed etsy guide to authenticate my app and connect to a user, and I was able to get through the first process to get a oauth_token, token secret and verifier. But after setting token for the oauth it fails the getAccessToken function with this message
Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)bad
this is my code, as you can tell i tried many options, my ultimate goal is to have all credentials stored in file then in a database but first i want to learn whats wrong with my app
<?php
header('Content-type: text/plain');
ini_set('max_execution_time', 600);
$ksecrFile = fopen("key_secret.txt", "r") or die("Unable to open file!");
$key = trim(fgets($ksecrFile),"\n");
$secret = trim(fgets($ksecrFile),"\n");
$verifier = "";
fclose($ksecrFile);
$lines = file("key_secret.txt");
$oauth = new OAuth($key, $secret);
//$oauth->setAuthType(OAUTH_AUTH_TYPE_URI);
$oauth->disableSSLChecks();
function getToken($oauth, $verifier){
$req_token = $oauth->getRequestToken("https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r", "http://localhost/ksec.php");
if (!empty($_GET))
{
print_r($req_token);
$verifier = $_GET["oauth_verifier"];
$token = $req_token['oauth_token'];
$token_secret = $req_token['oauth_token_secret'];
//$tokenFile = fopen("token.txt", "w");
//fwrite($tokenFile, $verifier . "\r\n");
//fwrite($tokenFile, $token . "\r\n");
//fwrite($tokenFile, $token_secret);
//fclose($tokenFile);
//header("Location: http://localhost/ksec.php");
echo $verifier . " " . $token . " " . $token_secret . "\n";
$ksecrFile = fopen("key_secret.txt", "r") or die("Unable to open file!");
$key = trim(fgets($ksecrFile),"\n");
$secret = trim(fgets($ksecrFile),"\n");
$oauth1 = new OAuth($key, $secret);
$oauth1->disableSSLChecks();
$oauth1->setToken($req_token['oauth_token'], $req_token['oauth_token_secret']);
try {
// set the verifier and request Etsy's token credentials url
$acc_token = $oauth1->getAccessToken("https://openapi.etsy.com/v2/oauth/access_token", null, $_GET["oauth_verifier"]);
echo "good";
} catch (OAuthException $e) {
print_r($e->getMessage());
echo "bad";
}
}
else
{
$login_url = sprintf(
"%s?oauth_consumer_key=%s&oauth_token=%s",
$req_token['login_url'],
$req_token['oauth_consumer_key'],
$req_token['oauth_token']
);
header("Location: " . $login_url);
}
}
$tokenFile = fopen("token.txt", "r") or die(getToken($oauth, $verifier));
//$verifier = trim(fgets($tokenFile),"\n");
//$token = trim(fgets($tokenFile),"\n");
//$tokenSecret = trim(fgets($tokenFile),"\n");
//fclose($tokenFile);
//echo $verifier . " " . $token . " " . $tokenSecret . "\n";
//echo $verifier . " " . $token;
?>
Ok i figured it out, i just dont know how to explain but having the code
<?php
header('Content-type: text/plain');
ini_set('max_execution_time', 600);
$ksecrFile = fopen("key_secret.txt", "r") or die("Unable to open file!");
$key = trim(fgets($ksecrFile),"\n");
$secret = trim(fgets($ksecrFile),"\n");
fclose($ksecrFile);
$oauth = new OAuth($key, $secret);
$oauth->disableSSLChecks();
$tokenFile = fopen("token.txt", "r") or die(getToken($oauth, $key, $secret));
function getToken($oauth, $key, $secret){
$req_token = $oauth->getRequestToken("https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r", "http://localhost/ksec.php");
$tokenFile = fopen("token.txt", "w") or die("Unable to open file!");
fwrite($tokenFile, $req_token['oauth_token'] . "\n");
fwrite($tokenFile, $req_token['oauth_token_secret'] . "\n");
$login_url = sprintf(
"%s?oauth_consumer_key=%s&oauth_token=%s",
$req_token['login_url'],
$req_token['oauth_consumer_key'],
$req_token['oauth_token']
);
header("Location: " . $login_url);
}
if (empty($_GET))
{
getToken($oauth, $key, $secret);
}
else
{
$tokenFile = fopen("token.txt", "r") or die("Unable to open file!");
$token = trim(fgets($tokenFile),"\n");
$tokenSecret = trim(fgets($tokenFile),"\n");
fclose($tokenFile);
$oauth1 = new OAuth($key, $secret);
$oauth1->disableSSLChecks();
$oauth1->setToken($token, $tokenSecret);
try {
// set the verifier and request Etsy's token credentials url
$acc_token = $oauth1->getAccessToken("https://openapi.etsy.com/v2/oauth/access_token", null, $_GET["oauth_verifier"]);
echo "good";
} catch (OAuthException $e) {
print_r($e->getMessage());
echo "bad";
}
}
?>

phpseclib: Validating signed data using certificate

I do have a private.pem and public.crt. my goal is to signed using private.pem and to verify its signature using public.crt. How do I achieve this by using phpseclib ?
$data = 'test';
$rsa = new RSA();
$privatekey = file_get_contents(storage_path('app/private.pem'));
$rsa->loadKey($privatekey);
$signed = $rsa->sign($data);
$publickey = file_get_contents(storage_path('app/public.crt'));
$rsa->loadKey($publickey);
return $rsa->verify($data, $signed) ? 'verified' : 'unverified';
got my answer here:
<?php
$data = 'test';
$rsa = new RSA();
$x509 = new X509();
$privatekey = file_get_contents(storage_path('app/private.pem'));
$rsa->loadKey($privatekey);
$signed = $rsa->sign($data);
$publickey = file_get_contents(storage_path('app/public.crt'));
$x509->loadX509($publickey);
$rsa = $x509->getPublicKey();
return $rsa->verify($data, $signed) ? 'verified' : 'unverified';

Can't verify openssl public key

I'm trying to use openssl_verify() to verify $payload with $publicKey.
Here's my code:
$publicKey = openssl_pkey_get_public($_POST['publicKeyURL']);
$playerID = $_POST['playerID'];
$timestamp = intval($_POST['timestamp']);
$signature = base64_decode($_POST['signature']);
$salt = base64_decode($_POST['salt']);
$payload = $playerID . $bundleID . $timestamp . $salt;
$status = openssl_verify($payload, $signature, $publicKey);
openssl_free_key($publicKey);
if ($status == 1) { /* */ }
I'm getting the following error:
openssl_verify() supplied key param cannot be coerced into a public key
The POST information is coming from an iOS app using this Game Center method.

Using openssl in PHP 5.3

How can I use openssl when accessing data using PHP 5.3?
I hope I can get how to use it. Please give me an example as how to access data using OpenSSL.
Do you want to generate a pair of keys with php?
$NEW_KEY = openssl_pkey_new(array(
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
openssl_pkey_export_to_file($NEW_KEY, 'private.key');
$NEW_KEY_DETAILS = openssl_pkey_get_details($NEW_KEY);
file_put_contents('public.key', $NEW_KEY_DETAILS['key']);
openssl_free_key($NEW_KEY);
Do you already have the keys ?
$public = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfmlc2EgrdhvakQApmLCDOgP0n
NERInBheMh7J/r5aU8PUAIpGXET/8+kOGI1dSYjoux80AuHvkWp1EeHfMwC/SZ9t
6rF4sYqV5Lj9t32ELbh2VNbE/7QEVZnXRi5GdhozBZtS1gJHM2/Q+iToyh5dfTaA
U8bTnLEPMNC1h3qcUQIDAQAB
-----END PUBLIC KEY-----";
$private = "-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDfmlc2EgrdhvakQApmLCDOgP0nNERInBheMh7J/r5aU8PUAIpG
XET/8+kOGI1dSYjoux80AuHvkWp1EeHfMwC/SZ9t6rF4sYqV5Lj9t32ELbh2VNbE
/7QEVZnXRi5GdhozBZtS1gJHM2/Q+iToyh5dfTaAU8bTnLEPMNC1h3qcUQIDAQAB
AoGAcbh6UFqewgnpGKIlZ89bpAsANVckv1T8I7QT6qGvyBrABut7Z8t3oEE5r1yX
UPGcOtkoRniM1h276ex9VtoGr09sUn7duoLiEsp8aip7p7SB3X6XXWJ9K733co6C
dpXotfO0zMnv8l3O9h4pHrrBkmWDBEKbUeuE9Zz7uy6mFAECQQDygylLjzX+2rvm
FYd5ejSaLEeK17AiuT29LNPRHWLu6a0zl923299FCyHLasFgbeuLRCW0LMCs2SKE
Y+cIWMSRAkEA7AnzWjby8j8efjvUwIWh/L5YJyWlSgYKlR0zdgKxxUy9+i1MGRkn
m81NLYza4JLvb8/qjUtvw92Zcppxb7E7wQJAIuQWC+X12c30nLzaOfMIIGpgfKxd
jhFivZX2f66frkn2fmbKIorCy7c3TIH2gn4uFmJenlaV/ghbe/q3oa7L0QJAFP19
ipRAXpKGX6tqbAR2N0emBzUt0btfzYrfPKtYq7b7XfgRQFogT5aeOmLARCBM8qCG
tzHyKnTWZH6ff9M/AQJBAIToUPachXPhDyOpDBcBliRNsowZcw4Yln8CnLqgS9H5
Ya8iBJilFm2UlcXfpUOk9bhBTbgFp+Bv6BZ2Alag7pY=
-----END RSA PRIVATE KEY-----";
if (!$privateKey = openssl_pkey_get_private($private)) die('Loading Private Key failed');
if (!$publicKey = openssl_pkey_get_public($public)) die('Loading Public Key failed');
$encrypted = '';
$decrypted = '';
$plaintext = 'This is just some text to encrypt';
echo '<p>$plaintext = ' . $plaintext . '<p>';
if (!openssl_public_encrypt($plaintext, $encrypted, $publicKey)) die('Failed to encrypt data');
echo '<p>$encrypted = ' . $encrypted . '<p>';
if (!openssl_private_decrypt($encrypted, $decrypted, $privateKey)) die('Failed to decrypt data');
echo '<p>$decrypted = ' . $decrypted . '<p>';
There you go, Enjoy!

Categories