php 自定义双向加密、解密方法


/**

 * PHP DES 加密程式 BY openssl

 *

 * @param $key 密鑰(八個字元內)

 * @param $encrypt 要加密的明文

 * @return string 密文

 */

function des_encrypt($key, $encrypt)

{

    return base64_encode(openssl_encrypt($encrypt, "DES-ECB", $key, OPENSSL_RAW_DATA));

}


/**

 * PHP DES 解密程式 BY openssl

 *

 * @param $key 密鑰(八個字元內)

 * @param $decrypt 要解密的密文

 * @return string 明文

 */

function des_decrypt($key, $decrypt)

{

    return openssl_decrypt(base64_decode($decrypt), "DES-ECB", $key, OPENSSL_RAW_DATA);

}




<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext "message to be encrypted";
$ivlen openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw openssl_encrypt($plaintext$cipher$key$options=OPENSSL_RAW_DATA$iv);
$hmac hash_hmac('sha256'$ciphertext_raw$key$as_binary=true);
$ciphertext base64_encode$iv.$hmac.$ciphertext_raw );

//decrypt later....
$c base64_decode($ciphertext);
$ivlen openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv substr($c0$ivlen);
$hmac substr($c$ivlen$sha2len=32);
$ciphertext_raw substr($c$ivlen+$sha2len);
$original_plaintext openssl_decrypt($ciphertext_raw$cipher$key$options=OPENSSL_RAW_DATA$iv);
$calcmac hash_hmac('sha256'$ciphertext_raw$key$as_binary=true);
if (
hash_equals($hmac$calcmac))//PHP 5.6+ timing attack safe comparison
{
    echo 
$original_plaintext."\n";
}
?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值