我想构建一个消息加密系统,用户将以加密格式发送消息。我正在使用GnUPG。我从http://www.php.net/manual/en/gnupg.installation.php获得了帮助来安装GnUPG。在服务器中安装后,我通过以下代码
创建公钥和私钥$GeneratedKey = $gpg->GenKey($name, $comment, $email, $passphrase,$ExpireDate, $KeyType, $KeyLength,$SubkeyType, $SubkeyLength );
function GenKey($RealName, $Comment, $Email, $Passphrase = '', $ExpireDate = 0, $KeyType = 'DSA', $KeyLength = 1024, $SubkeyType = 'ELG-E', $SubkeyLength = 1024)
{
// validates the keytype
if (($KeyType != 'DSA') && ($KeyType != 'RSA')) {
$this->error = 'Invalid Key-Type, the allowed are DSA and RSA';
return false;
}
// validates the subkey
if ((!empty($SubkeyType)) && ($SubkeyType != 'ELG-E')) {
$this->error = 'Invalid Subkey-Type, the allowed is ELG-E';
return false;
}
// validate the expiration date
if (!preg_match('/^(([0-9]+[dwmy]?)|([0-9]{4}-[0-9]{2}-[0-9]{2}))$/', $ExpireDate)) {
$this->error = 'Invalid Expire Date, the allowed values are <iso-date>|(<number>[d|w|m|y])';
return false;
}
// generates the batch configuration script
$batch_script = "Key-Type: $KeyType\n" .
"Key-Length: $KeyLength\n";
if (($KeyType == 'DSA') && ($SubkeyType == 'ELG-E'))
$batch_script .= "Subkey-Type: $SubkeyType\n" .
"Subkey-Length: $SubkeyLength\n";
$batch_script .= "Name-Real: $RealName\n" .
"Name-Comment: $Comment\n" .
"Name-Email: $Email\n" .
"Expire-Date: $ExpireDate\n" .
"Passphrase: $Passphrase\n" .
"%commit\n" .
"%echo done with success\n";
// initialize the output
$contents = '';
// execute the GPG command
if ( $this->_fork_process($this->program_path . ' --homedir ' . $this->home_directory .
' --batch --status-fd 1 --gen-key',
$batch_script, $contents) ) {
$matches = false;
if ( preg_match('/\[GNUPG:\]\sKEY_CREATED\s(\w+)\s(\w+)/', $contents, $matches) )
return $matches[2];
else
return true;
} else
return false;
}
我通过以下代码进行加密
$gpg = new gnupg();
$gpg->addencryptkey($recipient);
$ciphertext = $gpg->encrypt($plaintext);
通过以下代码解密
$gpg = new gnupg();
$gpg->adddecryptkey($recipient, $receiver_passphrase);
$plain = $gpg->decrypt($encrypted_text, $plaintext);
通过这个我成功创建了一个用户名文件夹,然后在那里生成私钥和公钥,然后以加密方式发送消息并由接收方解密。但我主要担心的是我不想在服务器中生成用户公钥和私钥,而是想在用户本地计算机上生成公钥和私钥。
是否可以在本地计算机中生成公钥和私钥?因为我不希望用户依赖服务器安全性。只有接收者才能解密消息..其他人无法解密..
感谢,
答案 0 :(得分:3)
您可以使用在客户端浏览器中运行的OpenPGP.js创建密钥,将私钥存储在客户端的某处,并将公共密钥发送给服务器。
// Create new key with RSA encryption (1), 4k length for
// John Doe with password "foobar"
var keys = openpgp.generate_key_pair(1, 4096,
"John Doe john.doe@example.org", "foobar");
keys.privateKeyArmored; // Access private key
keys.publicKeyArmored; // Access public key