Last active
November 22, 2017 13:19
-
-
Save lcherone/e8200485be6ac752f5a7a78c1c5e0914 to your computer and use it in GitHub Desktop.
Asymmetric encryption using PHP (the alice and bob story)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// define an example, our people, messages and their keys | |
$people = [ | |
'alice' => [ | |
'keys' => gen_keys(), | |
'msg' => 'Hi Bob, I\'m sending you a private message' | |
], | |
'bob' => [ | |
'keys' => gen_keys(), | |
'msg' => 'Thanks Alice, message received' | |
] | |
]; | |
// | |
$encrypted = $decrypted = [ | |
'alice' => '', | |
'bob' => '' | |
]; | |
// keys get exchanged | |
// alice encrypts her message to bob | |
$encrypted['bob'] = encrypt( | |
$people['alice']['msg'], // message to encrypt | |
$people['bob']['keys']['public'] // bobs public key, which he sent to alice | |
); | |
// message sent to bob | |
// bob decrypts his message | |
$decrypted['bob'] = decrypt( | |
$encrypted['bob'], // message to decrypt | |
$people['bob']['keys']['private'] // bob's private key, which he uses to decrypt the message | |
); | |
// bob now responds | |
// bob encrypts his message to alice | |
$encrypted['alice'] = encrypt( | |
$people['bob']['msg'], // message to encrypt | |
$people['alice']['keys']['public'] // alice public key, which she sent to bob | |
); | |
// alice decrypts her message | |
$decrypted['alice'] = decrypt( | |
$encrypted['alice'], // message to decrypt | |
$people['alice']['keys']['private'] // alice's private key, which she uses to decrypt the message | |
); | |
// | |
print_r($decrypted); | |
/* | |
Array | |
( | |
[alice] => Thanks Alice, message received | |
[bob] => Hi Bob, I'm sending you a private message | |
) | |
*/ | |
/** | |
* Functions - wraps for openssl operations | |
*/ | |
// generate public and private key pair | |
function gen_keys() { | |
$res = openssl_pkey_new(array('private_key_bits' => 2048)); | |
/* extract the private key */ | |
openssl_pkey_export($res, $privateKey); | |
/* extract the public key */ | |
$publicKey = openssl_pkey_get_details($res); | |
return ['public' => $publicKey["key"], 'private' => $privateKey]; | |
} | |
// encrypt using public key | |
function encrypt($msg, $key) { | |
$ret = ''; | |
openssl_public_encrypt( | |
$msg, // message to encrypt | |
$ret, // &encrypted message | |
$key // public key | |
); | |
return $ret; | |
} | |
// decrypts using private key | |
function decrypt($msg, $key) { | |
$ret = ''; | |
openssl_private_decrypt( | |
$msg, // message to decrypt | |
$ret, // &decrypted message | |
$key // private key | |
); | |
return $ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment