没有什么比代码故事更能解释这个概念了;p
这是一个示例,其中 alice 仅使用 bobs 公钥向 bob 发送加密消息,然后 bob 使用仅使用 alices 公钥的加密消息进行响应。
在这两种情况下,他们自己的私钥都用于解密消息。
<?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' => ''
];
// public keys get exchanged, not private
// 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;
}