【问题标题】:PHP data encryption and decryptionPHP数据加解密
【发布时间】:2012-08-31 03:51:30
【问题描述】:

我正在尝试使用 php 加密数据并插入 mysql。加密和插入操作正常工作,但解密不返回实际字符​​串。请参阅下面的加密代码

public function encryptText($text,$customer_id)
    {
        $key = $customer_id;
        $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB);
        return $crypttext;
    }

用于解密

public function decryptText($ctext,$customer_id)
    {
            $key = $customer_id;
            $text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,$key,$ctext,MCRYPT_MODE_ECB);
            return $text;
    }

请帮我解决这个问题

【问题讨论】:

  • "工作正常,但解密不返回实际字符​​串" -- 太好了,那它工作正常吗? ;P
  • 在数据库中加密数据通常没什么意义,如果坏人可以访问数据库,他们可能可以访问用于加密数据的代码。
  • 您能发布您的“测试”代码吗?因为您的代码可以正常工作。我想字符串填充或 $customer_id (key) 参数转换存在一些问题。
  • @Dagon:这完全没有根据。
  • @Jon 在我读过的大部分内容中创立。

标签: php


【解决方案1】:

这些函数将获取任何 PHP 对象并对其进行加密/解密:

加密 JSON 对象 Rijndael ECB base 64 编码

function ejor2eb($object, $key) {
    // Encode the object
    $object = json_encode($object, JSON_FORCE_OBJECT);

    // Add length onto the encoded object so we can remove the excess padding added by AES
    $object = strlen($object) . ':' . $object;

    // Encrypt the string
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $result = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $object, MCRYPT_MODE_ECB, $iv);

    // Return the URL encoded string, with the encryption type attached
    return 'jor2eu:' . base64_encode($result);
}

解密 JSON 对象 Rijndael ECB base 64 解码

function djor2eb($string, $key, $default = false) {
    // Remove the encryption type, and decode the string
    $binary = base64_decode(substr($string, 7));
    if (!$binary) {
        return $default;
    }

    // Decrypt the string
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $result = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $binary, MCRYPT_MODE_ECB, $iv);

    // Remove encrption padding
    $tokens = null;
    preg_match('/^([0-9]+):/i', $result, $tokens);
    if (sizeof($tokens) !== 2) {
        return $default;
    }
    $result = substr($result, strlen($tokens[1]) + 1, $tokens[1]);

    // Decode the ecoded object
    $object = json_decode($result);

    return $object;
}

【讨论】:

    【解决方案2】:

    最可能的问题是您没有使用正确的密钥来解密加密数据。您的代码显示了许多真正需要研究的问题:

    • 理想情况下,密钥应该是二进制字符串。 $customer_id的具体内容是什么?即使这是一个字符串,它也应该是 128、192 或 256 位长。看起来不像。
    • 即使密钥在技术上是可接受的,但使用客户 ID 作为密钥并不能真正提供任何安全性。
    • MCRYPT_RIJNDAEL_256 中的 256 不指定加密强度,而是指定块大小。在几乎所有情况下,您都应该改用MCRYPT_RIJNDAEL_128——实际上这样做与 AES 相同。 MCRYPT_RIJNDAEL_256 不是 AES。

    【讨论】:

    • 我已使用 customer_id(整数)作为键。
    • @Vinay:那行不通。请花一些时间熟悉基本的加密文献,这个错误是如此根本,以至于我无法给出比这更好的建议。即使它确实有效,您的系统也不会比以前更安全。加密是你必须正确做的事情,否则它不起作用。
    猜你喜欢
    • 2011-11-20
    • 2014-11-21
    • 2012-10-14
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多