1

I need generate a public key and secret key.

Is the following code would be enough?

<?php

function genToken($salt) {
    $secret = openssl_random_pseudo_bytes(16);

    $apiKey = hash_hmac('sha256', $salt, $secret);
    $apiKey = base64_encode($apiKey);
    $apiKey = str_replace('=', '', $apiKey);

    return $apiKey;
}

$salt = 'UsernameEmail@gmail.com';
echo 'pk_' . genToken($salt);
echo "\n";
echo 'sk_' . genToken($salt);
echo "\n";
iBet7o
  • 758
  • 8
  • 9
  • Why base64 encoding? Just for decoration? – fusion3k Mar 15 '16 at 23:31
  • Yep for decoration XD – iBet7o Mar 15 '16 at 23:32
  • 3
    When all else fails [Try using the manual](http://php.net/manual/en/function.openssl-pkey-new.php) Read all examples – RiggsFolly Mar 15 '16 at 23:36
  • 1
    What the purpose of this code? If you need to have a pair crypto keys for asymmetric encryption, this algorithm is totally wrong. Both keys must be mathematically correlated between themselves. – Wizard Mar 16 '16 at 02:44
  • I need to implement this https://websec.io/2013/02/14/API-Authentication-Public-Private-Hashes.html so I need the public key that is unique for each user and the private key to generate the hash json – iBet7o Mar 17 '16 at 00:06

1 Answers1

1

Do not use as salt the user email because it can be guessed.Instead of doing it yourself with a risk of error use a library instead.

I suggest you to use this PHP library https://github.com/IcyApril/CryptoLib (like proposed in this post :Generating cryptographically secure tokens). This library enables you to generate a random string then to hash it using a salt by exposing very practical methods :

This example (provided by the documentation that you can find here : https://cryptolib.ju.je/#intro) generate a salt to hash a token, that you can provide to your user as a key :

<?php
// Require the library
require_once('path/to/cryptolib.php');
// Generate a token of 16 char with the library by calling the randomString method.
$token = CryptoLib::randomString(16);
// Generate a salt with the library by calling the generateSalt method
$salt = CryptoLib::generateSalt();
// Hash the token with the salt that was generated
$hash = CryptoLib::hash($token, $salt);

// Salt and hash are then stored in the database.

// $hash and $salt are gotten later from the database, and the token is provided via a POST variable by the user
$isHashCorrect = CryptoLib::validateHash($hash, $_POST['token']);

// If isHashCorrect is true, the user has provided the correct token.
?>

I hope it will help you.

Community
  • 1
  • 1