Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How encrypt and decrypt #12

Closed
Comraovat opened this issue Apr 21, 2019 · 1 comment
Closed

How encrypt and decrypt #12

Comraovat opened this issue Apr 21, 2019 · 1 comment

Comments

@Comraovat
Copy link

I send text to my friend. How can i encrypt a text from my private key and him public key. And then, how can he decrypt by him private key and my public key ?

@ldudzsim
Copy link
Member

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";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants