How to generate public and private key for API - php

I want the easy way in order to generate Public / Private key for API, i want a speed class without need of OPENSSL or Any server side installation or third party application.
I tried to look about a Bitcoin Public/Private system generation, but nothing found about it ... and then i tested:
require_once('PHPCoinAddress.php');
$coin = CoinAddress::bitcoin(); coin_info('Bitcoin', $coin);
//////////////////////////////////////////////
function coin_info($name,$coin) {
print 'public (base58): ' . $coin['public'] . "<br>";
print 'private (WIF) : ' . $coin['private'] . "<br>";
}
But this take many times in order to return a result !
Source from here: https://github.com/zamgo/PHPCoinAddress
If u have any easy, speed, secure and unique pair generation solution will be welcome ! Thank's in advance.

Old post, but somebody may find interesting that maybe phpseclib is a solution for such an use case:
From the introduction:
Compatibility
phpseclib is designed to be ultra-compatible. It works on PHP4+ (PHP4,
assuming the use of PHP_Compat) and doesn't require any extensions.
For purposes of speed, mcrypt is used if it's available as is gmp or
bcmath (in that order), but they are not required. Interoperability
phpseclib is designed to be fully interoperable with OpenSSL and other
standardized cryptography programs and protocols.

Related

How to verify public key is on Ed25519 curve in PHP? (verify Solana address)

Building a server-side implementation to do Solana verification for a contract, when we receive a Solana address (Ed25519 public key) from client. They only want me to use native PHP methods, no imports, idk why. Open source libraries are still helpful as I can try my best to pull bits and pieces from it. I do have access to all of the libsodium PHP\Sodium library methods here: https://www.php.net/manual/en/book.sodium.php (which I believe allows us to do Ed25519)
This is the implementation in JS: https://solana-labs.github.io/solana-web3.js/classes/PublicKey.html#isOnCurve
I need this in PHP. In other words:
How can I verify Solana addresses (such as AJXw4EJtRBGswEestiD3gztdbsAh8fe3VSJXs6U33UBv) in PHP? As in, how do I verify a public key is on the Ed25519 curve?
Thanks in advance! I don't usually post on StackOverflow but I'm hoping this answer will be useful as Web3 continues to evolve.
It looks like your best bet is to try sodium_crypto_sign_ed25519_pk_to_curve25519 and catch the exception if it fails, ie:
try {
$_ = sodium_crypto_sign_ed25519_pk_to_curve25519($pubkeyBinaryString);
return true;
} catch (SodiumException $exception) {
return false;
}
Code lifted from https://github.com/verze-app/solana-php-sdk/blob/ab97975d4588fd759c63f7967caee1a5401cb2fe/src/PublicKey.php#L187

Verifying JWT tokens generated with PHP in Node

I'm working on implementing JWT verification in a client-side web-application that's using Webpack5. When a user is created on the backend running PHP, I create a public and private keypair for use in JWT like this and store them:
$keyPair = sodium_crypto_sign_keypair();
$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair));
$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair));
Then with firebase/php-jwt create the request like this:
$jwt = JWT::encode($payload, $privateKey, 'EdDSA');
However, using jose I get the following error when attempting to verify the JWT:
import * as jose from 'jose';
const { payload, protectedHeader } = await jose.jwtVerify(response.token, window.atob(response.key));
console.log(payload);
console.log(protectedHeader);
TypeError: Key must be of type CryptoKey.
I'm not understanding how it wants the key as both the base64 string and base64 presentation of the publicKey is met with the same TypeError in node. What am I doing wrong here?
Edwards-Curve Digital Signature Algorithm (EdDSA in JOSE) is not supported by WebCryptography API, as such you won't succeed with any library that uses native browser crypto. Sadly.
There's a proposal for Ed25519, Ed448, X25519, and X448 to be added in WebCrypto but it'll take a while before adoption and then implementation. When that happens jose will support this action. That being said you'll need to pass a CryptoKey. That's either imported via crypto.subtle.importKey directly, or via jose's import key functions. SubtleCrypto supports raw public key imports, jose supports PEM key imports in its wrappers only.
See Browser Support for the browser algorithm support matrix, as well as Algorithm Key Requirements for algorithm key requirements, and Type alias: KeyLike for how to obtain the right key representation.
As for the other (now deleted) suggestions, they do not take into account the algorithm you use, suggesting to use Uint8Array instead of a CryptoKey is wrong, Uint8Array use is exclusive for symmetric algorithms. Likewise, using transpiled jsonwebtoken is only remotely reliable for HMAC based algorithms.
jose only uses the runtime's native crypto layer which is your best bet at conformance and secure implementation but when running cross-runtimes you need the consider the intersection of supported algorithms on the platform.
I'm not understanding how it wants the key as both the base64 string and base64 presentation of the publicKey is met with the same TypeError in node
It's supposed to be KeyLike (interface) - in Node that's KeyObject (see crypto documentation), in Web-like environments it's CryptoKey (see WebCryptoAPI).

Generating URL safe encrypted ids in Codeigniter

For encryption of parameters in url, I am using codeigniter encrypt class after extending it. The purpose of extending was to remove /+- from encryption. This was working fine. But after upgrading to PHP 7.1 it is showing deprecation error of mcrypt related methods and documentation is also recommending to use openssl provided in Encryption library. So I implemented it
$this->load->library('encryption');
$this->encryption->initialize(
array('driver' => 'openssl')
);
$this->encryption->encrypt($vendor->vid);
But its generating encrypted ids with / in it.
8da179e79fee45aa3c569d6c54653c99626d57b074fa599f8a109cb0c5f2edb6d7def3f1a6daf5b449d467976a8a32de0819b9af6d84b068f9ec903d41c2bcb9H/eQluY5LUANEDwmCh+/trIvaJu2Bemj2p9J2MnEMII=
How to generate url safe encrypted parameters using openssl in CI ?
A simple solution to this problem is to replace the delimiters that you don't want with another url safe delimiters by extending the core encryption library as you did and use something like this:
function encode($string)
{
$encrypted = parent::encrypt($string);
if ( !empty($string) )
{
$encrypted = strtr($encrypted, array('/' => '~'));
}
return $encrypted;
}
function decode($string)
{
$string = strtr($string, array('~' => '/'));
return parent::decrypt($string);
}
maybe not answering your question but can solve in way obfuscating url safe id
for generate encrypt id just like Youtube watch id i use Hashids Spark for CodeIgniter
https://github.com/sekati/codeigniter-hashids
the purpose of this helper is implementing Hashids to generate hashes (like YouTube or Bitly) from numbers to obfuscate database IDs.
installation just like at instruction i modify the hashids_helper.php at line 20
require_once FCPATH . 'sparks/sk-hashids/' . HASHIDS_VERSION . '/vendor/Hashids.php';
to
require_once FCPATH . 'vendor/Hashids.php'; //according to your Hashids path

Does PHP use a FIPS-140 compliant RNG to generate session IDs?

A requirement for the deployment of a PHP application I am working on is that is uses FIPS-140 validated cryptographic modules.
The customer has specifically flagged up that "PHP utilizes a cryptographically weak random number generator to produce session ID information" and cited this report: http://berlin.ccc.de/~andreas/php-entropy-advisory.txt
I have advised them on how to set session.entropy_length and session.hash_function to increase entropy, but they have not accepted this, specifically requiring that we use a FIPS-140 compliant RNG.
I'm not certain on the difference between the hash function and the RNG, so am struggling to respond. Can anyone suggest a way of using a FIPS-140 compliant function to generate session ids within php?
We're running PHP 5.4.16 on Windows + SQL Server, in case it matters.
Thanks
A requirement for the deployment of a PHP application I am working on is that is uses FIPS-140 validated cryptographic modules.
My condolences. A headache is to FIPS-140 what a drop of morning dew is to the ocean.
I'm not certain on the difference between the hash function and the RNG, so am struggling to respond. Can anyone suggest a way of using a FIPS-140 compliant function to generate session ids within php?
If you're using ext/mcrypt, mcrypt_create_iv() uses Windows' CryptGenRandom API which should be FIPS-140 compliant. (Or, at minumum, it should be possible to setup that way.) That function is the only good thing about mcrypt, and exists separatef from libmcrypt.
If you're using OpenSSL, and compiled OpenSSL in FIPS mode, you can similarly use openssl_random_pseudo_bytes() and it should use a FIPS-compliant generator.
Finally, if you upgrade to PHP 7+ and use random_bytes(), so long as Windows is FIPS-140 compliant, you're golden.
The hash function really doesn't matter here. You want to use a secure source and that's it. Hashing it doesn't buy you anything. If you're forced to use a hash function, use one of the SHA2 family hash functions (SHA256, SHA384, or SHA512) approved for use in FIPS-140 compliant software.
Session Generator that should pass FIPS-140 audits
<?php
/**
* #return string
*/
function session_id_fips140()
{
if (is_callable('random_bytes')) {
return session_id(bin2hex(random_bytes(32)));
}
if (is_callable('mcrypt_create_iv')) {
return session_id(bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)));
}
if (is_callable('openssl_random_pseudo_bytes')) {
return session_id(bin2hex(openssl_random_pseudo_bytes(32)));
}
// Fail closed. Maybe install random_compat?
throw new Exception("No suitable PRNG is available on the current system!");
}
Usage:
<?php
ini_set('session.
if (!isset($_COOKIE['PHPSESSID'])) {
session_id_fips140();
}
session_start();

Creating a web service in PHP

I would like to create a web service in PHP which can be consumed by different consumers (Web page, Android device, iOS device).
I come from a Microsoft background so am confortable in how I would do it in C# etc. Ideally I would like to be able to provide a REST service which can send JSON.
Can you let me know how I can achieve this in PHP?
Thanks
Tariq
I developed a class that is the PHP native SoapServer class' REST equivalent.
You just include the RestServer.php file and then use it as follows.
class Hello
{
public static function sayHello($name)
{
return "Hello, " . $name;
}
}
$rest = new RestServer(Hello);
$rest->handle();
Then you can make calls from another language like this:
http://myserver.com/path/to/api?method=sayHello&name=World
(Note that it doesn't matter what order the params are provided in the query string. Also, the param key names as well as the method name are case-insensitive.)
Get it here.
I would suggest you go for Yii it is worth of learning. You can easily establish it in this.
Web Service. Yii provides CWebService and CWebServiceAction to simplify the work of implementing Web service in a Web application. Web service relies on SOAP as its foundation layer of the communication protocol stack.
Easiest way in PHP is to use GET/POST as data-in and echo as data-out.
Here's a sample:
<?php if(empty($_GET['method'])) die('no method specified');
switch($_GET['method']){
case 'add': {
if(empty($_GET['a']) || empty($_GET['b'])) die("Please provide two numbers. ");
if(!is_numeric($_GET['a']) || !is_numeric($_GET['b'])) die("Those aren't numbers, please provide numbers. ");
die(''.($_GET['a']+$_GET['b']));
break;
}
}
Save this as test.php and go to http://localhost/test.php?method=add&a=2&b=3 (or wherever your webserver is) and it should say 5.
PHP does have native support for a SOAP server ( The SoapServer class manual shows it) and I've found it pretty simple to use.
Creating a REST style API is pretty easy if you use a framework. I don't want to get into a debate about which framework is better but CakePHP also supports output as XML and I'm pretty sure others will as well.
If you're coming from a Microsoft background just be careful about thinking about "datasets". They are a very specific Microsoft thing and have been a curse of mine in the past. It's probably not going to be an issue for you, but you may want to just see the differences between Microsoft and open implementations.
And of course PHP has a native json_encode() function.
You can check out this nice RESTful server written for Codeigniter, RESTful server.
It does support XML, JSON, etc. responses, so I think this is your library.
There is even a nice tutorial for this on the Tutsplus network -
Working with RESTful Services in CodeIgniter
You can also try PHP REST Data Services https://github.com/chaturadilan/PHP-Data-Services
You can use any existing PHP framework like CodeIgniter or Symfony or CakePHP to build the webservices.
You can also use plain PHP like disscussed in this example

Categories