本文介绍了用多个密钥进行PHP加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法产生两个相互依赖的字符串格式的键?
Is there a way to produce two keys in string format, that are dependent on each other?
- 主密钥(用于解密数据)
- 从密钥(取决于主密钥,只能解密数据)
推荐答案
没有什么比代码故事更能说明概念了; p
Nothing like a code story to explain the concept ;p
这里是一个示例,其中alice仅使用bobs公钥向bob发送加密的消息,然后bob仅使用alices公钥以加密的消息进行响应.
Here is an example where alice sends an encrypted message to bob using only bobs public key, bob then responds with an encrypted message using only alices public key.
在两种情况下,它们自己的私钥都用于解密消息.
In both cases their own private keys are used to decrypt the messages.
<?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;
}
这篇关于用多个密钥进行PHP加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!