[SOLVED!] PHP Native - Hive Signature Validation - and the Hive+WordPress SSO (single sign on)
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!!!
**
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!).
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…
Receive data from the ajax post
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];
}
- Remove the “STM’ from the key (actually just the first 3, not specifically STM).
// Strip 'STM'
$stripKey = substr($hivePublicKey, 3);
- 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.
- 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());
}
- 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' );
- 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";
- 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!!!
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:
- Configurable redirect after login
- Custom login button colors and text
- Custom roles assigned on new account creation
- Replacing gravatar with Hive profile pictures
- 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:
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://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…
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
Congratulations @innerwebbp! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):
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!
Great work! Keep it up! !PGM !LOLZ !PIZZA
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!
Discord
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
lolztoken.com
They eventually fired him.
Credit: reddit
@innerwebbp, I sent you an $LOLZ on behalf of @captaincryptic
Are You Ready for some $FUN? Learn about LOLZ's new FUN tribe!
(1/10)
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!!
!LOLZ
lolztoken.com
Because they know how to multiply.
Credit: theabsolute
@captaincryptic, I sent you an $LOLZ on behalf of @cryptokungfu
Are You Ready for some $FUN? Learn about LOLZ's new FUN tribe!
(1/2)
PIZZA Holders sent $PIZZA tips in this post's comments:
@captaincryptic(1/5) tipped @innerwebbp (x1)
Join us in Discord!
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.
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!!!
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.
Awesome work! And the references you added at the bottom of your post are pure gold.
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!
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.
Yes!! I am working on this. I want users to be able to use whatever browser they want! HiveAuth is perfect for this!
Great news. Feel free to contact me if you need help.
YO ... if Wordpress creators in general catch on to this ... great stuff, friend!
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:
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!
$WINE
Congratulations, @theguruasia You Successfully Shared 0.200 WINEX With @innerwebbp.
You Earned 0.200 WINEX As Curation Reward.
You Utilized 2/3 Successful Calls.
Contact Us : WINEX Token Discord Channel
WINEX Current Market Price : 0.168
Swap Your Hive <=> Swap.Hive With Industry Lowest Fee (0.1%) : Click This Link
Read Latest Updates Or Contact Us
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
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:
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!
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!
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!! 😂
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!
Thank you for saying that! That was one of the things I was specifically shooting for, that anyone interested could understand it!
What other projects do you have in mind?
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!
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!
Awesome work!
Thank you!
You're awesome bro, great to know you
Thank you Hiro! You are a good friend! Thank you for all your support! Your cat project is one of my favorites! 🙏🙏🙏
https://peakd.com/hive-137634/@give-cat-food/happy-catz-a-real-life-cats-on-the-blockchain
Thanks for all your work to make this happen. It is people ;ike yourself that make the Hive the great place it is.
👍 Your comment reminded me of the 'birds of a feather flock together' phenomenon! I think it's a good one! Thank you!
amazing work!
@tipu curate
Upvoted 👌 (Mana: 10/40) Liquid rewards.
Thank you!
Your content has been voted as a part of Encouragement program. Keep up the good work!
Use Ecency daily to boost your growth on platform!
Support Ecency
Vote for new Proposal
Delegate HP and earn more
Congrats! Great work! Hope that this could work with @bambukah's Superhive?
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!!!
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!