[SOLVED!] PHP Native - Hive Signature Validation - and the Hive+WordPress SSO (single sign on)

avatar
(Edited)

Verifying a Hive signature in PHP = Adding WordPress magic to your Hive account! I’m excited to say, it’s working!! With the help of a slimmed down ECC library, and about two + weeks of my own private ‘cryptographic google bootcamp’... which was required in order to understand what in the world was actually happening, and how to do it… It’s finally working!!!

**update!!! @mahdiyari just posted a new PHP library that is totally awesome! Check it out here: Hive-PHP - A real PHP library for Hive !!! THANK YOU THANK YOU!!! This is SO GREAT!!!
**

Screen Shot 2022-07-25 at 2.43.31 PM.jpg

Screen Shot 2022-07-22 at 3.11.06 PM.jpg

Untitled.jpg

Screen Shot 2022-07-22 at 3.11.04 PM.jpg

Screen Shot 2022-07-22 at 3.11.23 PM.jpg

Screen Shot 2022-07-22 at 3.11.34 PM.jpg

Screen Shot 2022-07-22 at 3.11.53 PM.jpg

More importantly, it’s working with the same version requirements of a standard WordPress install!!! So, now any WordPress installation can use this plugin! Links at the bottom!

I’m also working with @bambukah to get this added to the Hive PHP libraries he’s maintaining so anyone can use this in any php application! Link to his post about his new Hive-Engine library at the bottom.

If you have no idea what I’m talking about, In my last post, I was asking for some help figuring out how to validate a Hive signed message in PHP. I also talked a little bit about why I want to do that (verify a Hive signature in php), it’s for this WordPress plugin I am working on.

The plugin is a Single Sign On (SSO) plugin for WordPress that allows any user to login to a WordPress site with just their Hive account. Obviously a site needs to be running this plugin, but if they are… anyone with a Hive account can login!!

This plugin is more aimed at ‘Wordpress Creators’ than just the average user… I’m actually making it because I want to use it!!! But it’s something the average user can use too, because it allows them to login to a WordPress site! Ultimately the more creators, the more users, and so on, which is good for Hive. I’m pretty excited about it!

This is part of my 'pinky and the brain' plan, to make just having a Hive account a super power!! Even more than it is now! More about my pinky and the brain plan and IWB (InnerWebBlueprint.com) soon, lots of work still to do.



I’m working to get into a ‘Monday’ IWB DEV - post an update schedule! So… wish me luck on that! I have a tendency to write novela's! LOL!

So, the update is... the first version of the plugin was working great, but it was verifying a Hive signed message on the backend using Python, and the beempy library. Thanks again @brianoflondon for sharing your work!!!

Now, in this case, while it’s working just great, using Python is not ideal, as installing Python libraries can get complicated if you're not hosting your own environment. So I wanted to do it ‘natively’ in PHP so it would be easier for an average WordPress site admin to use it…. Cause if it’s easy, then everyone will do it, right?!?!



Below is some example code, and an explanation of what’s going on behind the ‘easy’ button. Github links with full code at the bottom. (please forgive my ‘code newbness’ too, I’m just picking up coding again after a long time and still have lots to learn, all feedback (good and bad - especially better ways to do things) welcome!).

Screen Shot 2022-07-23 at 9.04.21 AM.jpg

So just to go over the whole process…

When a user clicks the ‘login with your hive account’ button, a unique message is sent to Hive Keychain for the user to sign with their Hive account.

After a successful signing, the signature, the original unique message, and the Hive username, are all sent through an ajax call (without reloading the page) back to WordPress (PHP) where the Hive users public key is first looked up from the blockchain, then the message signature is cryptographically verified to have been signed by that same user.

If it is verified, the user is logged in! If they don’t already have a WordPress account with that username, one is created automatically for them... now they do!

Your Hive username becomes your WordPress username, one and the same!

Some details from where the backend starts…

  1. Receive data from the ajax post

  2. Using the provided username, we grab the user's key from the blockchain, so we know it’s not a fake. (this code is not included in the test file, but it’s part of the actual plugin. Eventually I will get this included into one of the PHP libraries as I learn more about classes, something like $account->get_public_key($hiveUname,$keyType))

function iwb_sso_get_publickey ($iwb_sso_HiveUsername) {
 /**
  * For now I am just going to use an API call to get the info I need
  * I'm using a hard coded api node for now
  * For API calls I will want to ensure I have a working API
  * see: https://hive.blog/full-nodes/@fullnodeupdate/full-api-node-update---2762022-20220627t203029z
  */
 $iwb_sso_HiveNode = 'https://api.hive.blog';
  
 // Use Curl to make an API call.   
 // Build out the json data for the call
 $iwb_sso_CallData = json_encode(array(
   "jsonrpc" => "2.0",
   "method" => "condenser_api.lookup_account_names",
   "params" => array(
     ["$iwb_sso_HiveUsername"]
     ),
   "id" => 1
   ));
 
 // Let's do the curl call
 $ch = curl_init( $iwb_sso_HiveNode );   
 curl_setopt( $ch, CURLOPT_POSTFIELDS, $iwb_sso_CallData );
 curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
 # Return response
 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
 # Send request.
 $result = curl_exec($ch);
 curl_close($ch);
 $data = json_decode($result, true);
 return $data["result"][0]["active"]["key_auths"][0][0];
}
 
  1. Remove the “STM’ from the key (actually just the first 3, not specifically STM).
// Strip 'STM'
   $stripKey = substr($hivePublicKey, 3);
  1. Like Bitcoin, Hive public keys are Base58 encoded, so below we will decode the key. I am using the Tuupola\Base58 library, which I’ve included in the plugin with composer. I’ve also got some links at the bottom I found helpful in explaining Base58 encoding, it’s kinda interesting.
  $base58 = new Base58(["characters" => Base58::BITCOIN]);
  $decoded = $base58->decode($stripKey);
  $hexDecoded = bin2hex($decoded);

Now, we have it decoded, but Hive keys are still ‘compressed’, which I’m pretty sure means it’s got the x coordinate, and some information on how to derive the correct y coordinate. That’s an ECC thing, as there are 2 points on the curve that match possible keys.

  1. So here we check if the key is in fact compressed, and then grab the ‘x’ coordinate from the decoded key, and then using the ECC library get the x,y coordinates that we will test against the signed message.
   // Check if key is compressed
   // Hive's keys are pretty much always compressed,
   // See here for reference: https://github.com/holgern/beem/blob/master/beemgraphenebase/account.py
   // note:: By default, graphene-based networks deal with **compressed**
   // public keys.
 
   // if so, decompress and send to EC to derive y
   if (substr($hexDecoded,0,2)== '04') {
       color_red("not compressed");
       return $hexDecoded;
       // do something different here
       // Hive's keys are pretty much always compressed
   } elseif (substr($hexDecoded,0,2) == '02'|'03') {
       color_red("compressed, let's uncompress \n");
       $hexDecoded = substr($hexDecoded,0,66);
       $key = $ec->keyFromPublic($hexDecoded, 'hex');
       //print_r($key);
       $test = $key->getPublic();
       print_r($test);
       // var_dump($test->getX());
       // var_dump($test->getY());
   }
  
  1. Now, before we can make sure it’s the same as the signature, first we have to hash the original message that was signed (using sha256). We will use this in a minute.
// let's hash the message - that is what is actually signed
   $msgHash = openssl_digest($message, 'SHA256' );
  1. Now let’s grab the r, and s, from the signature. We will be using these in the last step. Links at the bottom about r and s.
// now lets extract 'r' and 's' from the provided signature into an array
   $sig   = [
       "r" => substr($signature, 2, 64),
       "s" => substr($signature, 66, 64)
   ];
   color_red("Signature r, and s: \n");
   var_dump($sig);
   echo "\n";
 
  1. And now… drum roll please… we send the hashed original message, and our $sig in DER format to the verify method of the ECC library.
   // very the message signature key against the formatted public key pair using the ECC library's verify method.
   color_red("Is the signature verified: ");
   echo "Verified: " . (($key->verify($msgHash, $sig) == TRUE) ? "true" : "false") . "\n";

But wait?? What is that $key thing? LOL?? Well, that’s where I learned that I needed to learn something about OOP (object oriented programming)... That $key is an object, defined in the ECC library I keep referencing.

use Elliptic\EC;
//
$ec = new EC('secp256k1');
//
$key = $ec->keyFromPublic($hexDecoded, 'hex');

So after all of that… signature verified natively in PHP!!!

Screen Shot 2022-07-25 at 2.10.50 PM.jpg

Now, I am no expert, that is for certain, so if you have a better way, faster way, or see any errors, please let me know!

Please also note, this is working well, but it’s still early beta, and I plan to add a bunch of settings and stuff like:

  1. Configurable redirect after login
  2. Custom login button colors and text
  3. Custom roles assigned on new account creation
  4. Replacing gravatar with Hive profile pictures
  5. And please comment with any other ideas so I can add them to my list!

I hope you found this valuable in some way, even if the code and ECC stuff doesn’t make any sense to you. It didn’t make sense to me at first either, but it’s starting to seep in!!!

But without all the other people posting all the stuff they have, I would have never been able to figure this out. I hope posting this helps someone else out somewhere along the way like others has helped me.

Links at the bottom:

IWB Github link to the working plugin, which includes test.php in ./includes (all the code mentioned above all together in one file)

Hive Engine Tools PHP Library announcement from @bambukah

My last post asking for help:
https://peakd.com/stem/@innerwebbp/hey-looking-for-help-validating-a-hive-signature-in-php

@brianoflondon ‘s post -> thank you for sharing your work!
https://stemgeeks.net/@brianoflondon/looking-for-help-how-to-verify-if-a-hive-message-is-signed-correctly-in-python-beem

r, s, x and y, curves (secp256k1), inverses, loops, and loopy!

What is the relation between x y and r s in an ECDSA signature?
ECDSA r, s encoding as a signature

Why Did Satoshi Decide To Use Secp256k1 Instead Of Secp256r1?

A Bluffer’s Guide to secp256k1

Guidance for Choosing an Elliptic Curve Signature Algorithm in 2022

Another PHP library that I never got around to trying out

A comparison between the secp256r1 and the koblitz secp256k1 bitcoin curves

EC Private Key Example - secp256k1

Base58/encoding/decoding:
https://blog.boot.dev/bitcoin/base64-vs-base58-encoding/

https://blog.boot.dev/cryptography/encoding-vs-encryption/

https://github.com/tuupola/base58

https://www.darklaunch.com/base58-encode-and-decode-using-php-with-example-base58-encode-base58-decode.html

https://stackoverflow.com/questions/8970715/how-do-i-base58-encode-a-string

https://medium.com/concerning-pharo/understanding-base58-encoding-23e673e37ff6
https://en.bitcoinwiki.org/wiki/Base58#Base58_converters

Oh, and if you made it this far, this link about hive intelligence is absolutely remarkable…

The Secret Life of Bees
The world’s leading expert on bee behavior discovers the secrets of decision-making in a swarm

It’s a ‘core design element’ of the IWB project I am working on… I’ll write a lot more about this later in a ‘regular’ non dev update post. v+v=vm2

(Unsupported https://www.youtube.com/watch?v=GBkT19uH2RQ)


0
0
0.000
43 comments
avatar

Congratulations @innerwebbp! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You distributed more than 10 upvotes.
Your next target is to reach 50 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Support the HiveBuzz project. Vote for our proposal!
0
0
0.000
avatar

Great work! Keep it up! !PGM !LOLZ !PIZZA

0
0
0.000
avatar

Sent 0.1 PGM - 0.1 LVL- 1 STARBITS - 0.05 DEC - 15 SBT tokens to @innerwebbp

remaining commands 0

BUY AND STAKE THE PGM TO SEND A LOT OF TOKENS!

The tokens that the command sends are: 0.1 PGM-0.1 LVL-2.5 BUDS-0.01 MOTA-0.05 DEC-15 SBT-1 STARBITS-[0.00000001 BTC (SWAP.BTC) only if you have 2500 PGM in stake or more ]

5000 PGM IN STAKE = 2x rewards!

image.png
Discord image.png

Support the curation account @ pgm-curator with a delegation 10 HP - 50 HP - 100 HP - 500 HP - 1000 HP

Get potential votes from @ pgm-curator by paying in PGM, here is a guide

I'm a bot, if you want a hand ask @ zottone444


0
0
0.000
avatar

Thank you master of the !LOLZ... oops I don't think I have any lolz here! I hope you got a laugh out of my pinky and the brain reference though!!

0
0
0.000
avatar

This is excellent. I wish I knew more about the coding, but I'm so rusty these days.

As for feature/ settings, I would love to see a way to set beneficiaries.

This is sincerely very exciting. I can imagine so many ways that Hive could be integrated into WP for publishing, but imagine commerce! Oh, what a great time to be around.

0
0
0.000
avatar

Yes!!! I will for sure add that, setting beneficiaries! I have that planned for a separate plugin that will allow posting to hive, and also integrate comments on hive too! This signature verification is, of course, the first step to that, so I'm hoping my progress will speed up a little now that that's working...

I am rusty too, like an old creaky motor!!! This took me what seems like FOREVER!!! I've been dreaming about elliptic curves for almost 3 weeks now!!!

I'm so excited about all the possibilities too!!! My 'garage sale' site is on my list of sites to make where everything will be for sale exclusively in HIVE, HBD, or Hive-Engine tokens!!!

0
0
0.000
avatar

That makes sense. The sign on feature is big in it own right. I can see where that is the foundation for pretty much anything else.

0
0
0.000
avatar

Awesome work! And the references you added at the bottom of your post are pure gold.

0
0
0.000
avatar

WOW, Thank you! I have great respect for your work! To wake up to your compliment and support is quite wonderful! I love the tools you've created, and your attention to detail is remarkable! It's an honor to receive such a compliment! (even better than gold!) Thanks for making things like https://engage.hivechain.app/ and all your other projects! More than just being valuable, they are inspirational!

0
0
0.000
avatar

Thank you for your kind words @innerwebbp. ❤️
Do you think you could add support for HiveAuth to your plugin? It would be awesome to log into WordPress by providing its Hive account name but any password or private key.

0
0
0.000
avatar

Yes!! I am working on this. I want users to be able to use whatever browser they want! HiveAuth is perfect for this!

0
0
0.000
avatar

Great news. Feel free to contact me if you need help.

0
0
0.000
avatar

YO ... if Wordpress creators in general catch on to this ... great stuff, friend!

0
0
0.000
avatar

I'm hoping that's exactly what happens!!! 😄 Still lots more work to do to get to that point... but the reception has been great so far! WordPress people (as odd as they are sometimes LOL...) are some pretty industrious people! As you mentioned, if they 'catch' on to something it's like... well here's an example:

0
0
0.000
avatar

Exactly right! Hive on WordPress -- people plugging into a decentralized arena and a little crypto for their blogs? Keep going and THANK YOU for the work thus far and to come!

0
0
0.000
avatar
(Edited)

Absolutely amazing work. I've got to go over this a few times because, whilst I managed to get my thing working, I never actually got into understanding the cryptography and that is super interesting.

P.S. I just tipped you 5000 sats as Hive via @v4vapp

Send sats to @innerwebbp

0
0
0.000
avatar

Brian!!! Thank you!!! You have no idea how much inspiration you have been to me! I really enjoyed watching you with @jongolson and @taskmaster445083 here:

(Really good talk!) and I share https://lnd.v4v.app/hive with everyone I know!

V4V is a magic formula and you put it into motion! So impressive! ❤️ Really inspired me!, thank you.

Oh, I forgot to include this in the links above... but this video was great for helping me start understand this EC stuff. I still only understand half of what this guy is saying, but it helped a lot!

0
0
0.000
avatar

Very well done. I've been in that bootcamp myself for a while, but didn't get much out of it except a phenomenal headache. I salute you!

0
0
0.000
avatar

Thank you!! Yes, the headache is part of it all for sure!! I like to think of it as the brain growing LOL! I'm not sure that's true, but it makes feel better!! 😂

0
0
0.000
avatar

Such an amazing article and explained in so much detail for anyone interested to understand. I hope this is just one of many more to come!

Voted on ListNerds!

0
0
0.000
avatar

Thank you for saying that! That was one of the things I was specifically shooting for, that anyone interested could understand it!

0
0
0.000
avatar

What other projects do you have in mind?

0
0
0.000
avatar

So many projects in mind LOL!! I wrote you a little novella here LOL… But my main objective is literally to make it so easy to setup a website, link it to Hive, and have whatever you want (like a webstore, your own digital garage sale, just a blog, the stories of your life, whatever you like), that my 78 year old mother could do it. Literally! I know that might sound a little corny, or overly sentimental, but I mean it, I'm serious. 🧐

To me, mix all that with Hive, and that’s web3.0!!! At least the 3.0 that I’m dreaming of!!

I might indeed be dreaming, and I am a dreamer for sure!!!… I don't know if she ever 'will' do it, but that's not really the point... I want to make it so easy that she could if she wanted to… and do it without breaking the bank, or having to constantly bug someone for help, or be constantly nagged with updates and sales offers. She doesn't like bugging people, doesn’t much like being ‘bugged’, she's very 'old school', do it yourself, learn how, or figure out how to make do without!

But she has lots and lots of knowledge and wisdom from her many years and experience, and though it's not computer technical, she makes an Orange Marmelade that is like no other!!! She is a master seamstress too! I want that recipe on Hive stored forever!!! It's soo good!! Her experience and knowledge is literally priceless! She loves sharing it too, she loves making things for other people, it makes her smile!

She could share all that stuff on Facebook, and she has a little, but she’s grown to hate Facebook. It makes her grumpy! They keep changing it, she can’t find anything, it drives her crazy! It kinda made her dislike computers and the internet, and that made me sad. I love the internet, and I love computers. She used to too. (I very much dislike facebook because of what they have done to it!).

But as you might imagine, my mom is not likely learning how to install Python libraries or PHP dependencies, or host her own website, or anything like that, anytime soon… She probably could if she wanted to, but it would take her a long time, and she doesn't really want to LOL! Can you blame her?!?!

But she is really good at following instructions, she’s smart as a wip, and she can click a button like nobody's business!! She can use WordPress already, if I remove all the nag’s, and get her menu items down to 3 or 4 at a time… AND I don’t keep changing things on her! (that drives her crazy!!! Her sewing machine just works, and if it doesn’t, she knows how to fix it, it's SOLID STATE LOL!)

If I make it easy enough, she just might do it too! I know she would have a blast doing it, and if she could, she just might.

With the pandemic, all the isolation, inflation… well that’s all hit pretty hard too… and if she could earn a couple hundred extra dollars a month selling sewing patterns, or jam recipes, or even a couple jars of her marmalade here and there… it would make a world of difference for her. I know she would have a lot of fun doing it too, once she got started! She won’t take my money (not that I have all that much anyway LOL), it’s just not something she does.

But if I can make it easy enough for her, If she can do it, I bet she will… and then I will have achieved my goal! It will put a big huge smile on my face! 😄 I really love making things for other people, I learned it from her, it makes me smile, both on the inside, and the outside 🌈;)
I hope that gives you a general idea of my plans for this project! Thanks for asking!

0
0
0.000
avatar

Ohh man, you should have put all this into a proper article to get more exposure and let more people know about your plans. Maybe more devs can help or get involved with your plans.
Your idea sounds great and I'm sure it would bring more people to Hive but there's a huge amount of work involved.

You mother must be a very cool oldie 😁 I would love to read some articles written by her on Hive!

0
0
0.000
avatar

Thanks for all your work to make this happen. It is people ;ike yourself that make the Hive the great place it is.

0
0
0.000
avatar

👍 Your comment reminded me of the 'birds of a feather flock together' phenomenon! I think it's a good one! Thank you!

0
0
0.000
avatar

Congrats! Great work! Hope that this could work with @bambukah's Superhive?

0
0
0.000
avatar
(Edited)

Well yes, sort of... but more indirectly. @bambukah 's SuperHive is much more flexible than WordPress... It's custom hosted so there is a lot more flexibility with libraries and extensions. The ECC signing and verifying stuff in PHP is great for SuperHive... and that's what's been missing for PHP and Hive I think. @mahdiyari just (like hours ago!!!) released a new PHP library that does so much great stuff: https://peakd.com/hive-139531/@mahdiyari/hive-php-a-real-php-library-for-hive , including signing, verifying, and pretty much all the Hive API operations: and that is AWESOME in so many ways!! It should make work go much faster for any PHP project using Hive!!

So much good stuff!!!

0
0
0.000
avatar

this is amazing. i work with WP and was thinking in something that all this can help out.
how is your project?
following you now!

0
0
0.000