ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

如何在PHP中没有硬编码密钥的情况下进行对称加密

2019-05-16 13:16:51  阅读:322  来源: 互联网

标签:php encryption mcrypt


我正在使用PHP mcrypt库来使用AES加密和存储(MySQL)数据.

我想知道如果没有在我的代码中使用硬编码加密/解密密钥,是否有一种好方法可以做到这一点.

如果黑客能够访问我的服务器,他将能够在代码上看到文件和我的密钥,从而访问数据库上的所有数据.

谢谢.

最佳答案:

I’m using the PHP mcrypt library to cryptograph and store (MySQL) data using AES.

You may wish to reconsider your choice in cryptography library.

I was wondering if there is a good way to do this without having a hardcoded encryption/decryption key in my code.

将其存储在文档根目录之外的配置文件中?例如,defuse/php-encryption.

If a hacker gets access to my server he will be able to see the files and my key on the code, therefore accessing all the data on the database.

如果黑客可以访问您的服务器,symmetric-key encryption cannot save you.但是,公钥加密可以保护机密性.

使用Halite,这很容易解决:

>您只能在服务器上加密;从不解密.
>您的密钥必须保持脱机状态并由人使用.

在线代码(假设PHP 7.0和Halite 2.1)

<?php
declare(strict_types=1);
use ParagonIE\Halite\{
    Asymmetric\Crypto as Asymmetric,
    KeyFactory
};

$publicKey = KeyFactory::loadEncryptionPublicKey("/path/to/public/key");
$encrypted = Asymmetric::seal("Whatever secret data we want", $publicKey);
// Now do whatever you need with $encrypted

离线代码(假设PHP 7.0和Halite 2.1)

<?php
declare(strict_types=1);
use ParagonIE\Halite\{
    Asymmetric\Crypto as Asymmetric,
    KeyFactory
};

$salt = ""; // Generate from random_bytes(16) once, then persist.
$password = ""; // Create a strong password

$keyPair = KeyFactory::deriveEncryptionKeyPair($password, $salt);
$secretKey = $keyPair->getSecretKey();
$publicKey = $keyPair->getPublicKey();

// To have the public key to a file to upload to the server:
   KeyFactory::save($publicKey, '/path/to/public/key');

$decrypted = Asymmetric::unseal($encrypted, $secretKey);

标签:php,encryption,mcrypt
来源: https://codeday.me/bug/20190516/1115252.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有