doukang7486 2014-09-29 13:35
浏览 78
已采纳

php:如何为同一个字符串生成不同的输出

Is there some way to generate different output for same given string, here is example:

echo md5('test');

That always generates same fb469d7ef430b0baf0cab6c436e70375 for the given input. How do I generate different encrypted text each time and be able to decrypt it later if needed ?

I have seen functions such as md5, base64_encode, crypt, sha1, etc but they generate same output and secondly I cannot decrypt later if needed.

P.S: I know I can go with one way encryption and compare encrypted texts but for a particular scenario, I have requirement to be able to decrypt text completely if needed later however I am not able to figure out if there is some way or function in php for it.

Any help will be greatly appreciated. Thanks

  • 写回答

3条回答 默认 最新

  • dongxianshuai8927 2014-09-29 13:50
    关注

    To encrypt the same plaintext so that it generates different ciphertext you change the key (and/or Initialization Vector (IV) depending on the mode of the algorithm, like CBC).

    Example:

    $string = 'Some Secret thing I want to encrypt'; 
    $iv = '12345678'; 
    $passphrase = '8chrsLng'; 
    
    $encryptedString = encryptString($string, $passphrase, $iv); 
    // Expect: 7DjnpOXG+FrUaOuc8x6vyrkk3atSiAf425ly5KpG7lOYgwouw2UATw== 
    
    function encryptString($unencryptedText, $passphrase, $iv) { 
      $enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $passphrase, $unencryptedText, MCRYPT_MODE_CBC, $iv); 
      return base64_encode($enc); 
    }
    

    Both the same IV and the passphrase must be used when decrypting in CBC mode. The passphrase MUST be kept a secret (from eavesdroppers) while the IV can be transmitted in the clear.

    You CAN (but should not) use the same passphrase for every message/data but you should ALWAYS change the IV for each message/data.

    This is the basics of encryption but depending on you needs you may need to modify your architecture to keep the system secure.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序