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条)

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写