Giter VIP home page Giter VIP logo

Comments (1)

ldudzsim avatar ldudzsim commented on July 28, 2024 1

You should use ECIES. Unfortunately we do not have ECIES support in our library because our lib is strict about elliptic curve. Maybe in future we add ECIES to our lib. Now you can try this code:

<?php

// Utils helper class

class Utils {
    
    public static function hex2bin($str) {
        return hex2bin(strlen($str) % 2 == 1 ? "0" . $str : $str);
    }
    
    public static function substring($str, $start, $end) {
        return substr($str, $start, $end - $start);
    }
    
    public static function arrayValue($array, $key, $default = false) {
        return array_key_exists($key, $array) ? $array[$key] : $default;
    }
}

// Crypto helper class

class Crypto {
    
    public static function hmacSha256($key, $data) {
        return hash_hmac("sha256", $data, $key, true);
    }
    
    public static function aes256CbcPkcs7Encrypt($data, $key, $iv) {
        return openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    }
    
    public static function aes256CbcPkcs7Decrypt($data, $key, $iv) {
        return openssl_decrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    }
}

// ECIES helper class

class ECIES {
    
    private $privateKey;
    private $publicKey;
    private $rBuf;
    private $kEkM;
    private $kE;
    private $kM;
    private $opts;
    
    public function __construct($privateKey, $publicKey, $opts = array("noKey" => true, "shortTag" => true)) {
        $this->privateKey = $privateKey;
        $this->publicKey = $publicKey;
        $this->opts = $opts;
    }

    public function getRbuf() {
        if (is_null($this->rBuf)) {
            $this->rBuf = Utils::hex2bin($this->privateKey->getPublic(true, "hex"));
        }
        return $this->rBuf;
    }

    private function getSharedKey()
    {
        $shared = $this->privateKey->derive($this->publicKey->getPublic());
        $bin = Utils::hex2bin( $shared->toString("hex") );
        return hash("sha512", $bin, true);
    }
    
    public function getkEkM() {
        if (is_null($this->kEkM)) {
            $this->kEkM = $this->getSharedKey();
        }
        return $this->kEkM;
    }
    
    public function getkE() {
        if (is_null($this->kE)) {
            $this->kE = Utils::substring($this->getkEkM(), 0, 32);
        }
        return $this->kE;
    }
    
    public function getkM() {
        if (is_null($this->kM)) {
            $this->kM = Utils::substring($this->getkEkM(), 32, 64);
        }
        return $this->kM;
    }

    private function getPrivateEncKey()
    {
        $hex = $this->privateKey->getPrivate("hex");
        return Utils::hex2bin( $hex );
    }
    
    public function encrypt($message, $ivbuf = null) {
        if (is_null($ivbuf)) {
            $ivbuf = Utils::substring(Crypto::hmacSha256($this->getPrivateEncKey(), $message), 0, 16);
        }
        $c = $ivbuf . Crypto::aes256CbcPkcs7Encrypt($message, $this->getkE(), $ivbuf);
        $d = Crypto::hmacSha256($this->getkM(), $c);
        if (Utils::arrayValue($this->opts, "shortTag")) {
            $d = Utils::substring($d, 0, 4);
        }
        if (Utils::arrayValue($this->opts, "noKey")) {
            $encbuf = $c . $d;
        }
        else {
            $encbuf = $this->getRbuf() . $c . $d;
        }
        return $encbuf;
    }
    
    public function decrypt($encbuf) {
        $offset = 0;
        $tagLength = 32;
        if (Utils::arrayValue($this->opts, "shortTag")) {
            $tagLength = 4;
        }
        if (!Utils::arrayValue($this->opts, "noKey")) {
            $offset = 33;
             $this->publicKey = Utils::substring($encbuf, 0, 33);
        }
        
        $c = Utils::substring($encbuf, $offset, strlen($encbuf) - $tagLength);
        $d = Utils::substring($encbuf, strlen($encbuf) - $tagLength, strlen($encbuf));
        
        $d2 = Crypto::hmacSha256($this->getkM(), $c);
        if (Utils::arrayValue($this->opts, "shortTag")) {
            $d2 = Utils::substring($d2, 0, 4);
        }
        
        $equal = true;
        for ($i = 0; $i < strlen($d); $i++) {
            $equal &= ($d[$i] === $d2[$i]);
        }
        if (!$equal) {
            throw new \Exception("Invalid checksum");
        }
        
        return Crypto::aes256CbcPkcs7Decrypt(Utils::substring($c, 16, strlen($c)), $this->getkE(), Utils::substring($c, 0, 16));
    }
}

and the usage example

<?php

use Elliptic\EC;

$ec = new EC('secp256k1');

// Generate keys
$key1Priv = $ec->genKeyPair();
$key2Priv = $ec->genKeyPair();

// Get public parts from generated keys
$key1Pub = $ec->keyFromPublic($key1Priv->getPublic());
$key2Pub = $ec->keyFromPublic($key2Priv->getPublic());

// Some text to encrypt
$text = "Some text to encrypt";

// Encrypt using private from key1 and public from key2
$ecies1 = new ECIES($key1Priv, $key2Pub);
$cipher = $ecies1->encrypt($text);

// Decrypt using private from key2 and public from key1
$ecies1 = new ECIES($key2Priv, $key1Pub);
$decryptedText = $ecies1->decrypt($cipher);

echo "ECIES example\n";
echo "Source text: " . $text . "\n";
echo "Cipher: " . bin2hex($cipher) . "\n";
echo "Decrypted: " . $decryptedText . "\n";

from elliptic-php.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.