繁体   English   中英

在PHP 7中加密在Node JS中解密

[英]Encrypt in PHP 7 decrypt in Node JS

在PHP 5.6中,有许多基于http://php.net/manual/en/function.mcrypt-decrypt.php的完美解决方案

例如

public function encrypt($data)
{
    //don't use default php padding which is '\0'
    $pad = $this->blocksize - (strlen($data) % $this->blocksize);
    $data = $data . str_repeat(chr($pad), $pad);
    return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,
        $this->encryptKey,
        $data, MCRYPT_MODE_CBC, $this->iv));
}

但是PHP7有一个警告 ,建议不要使用此功能。

“此功能从PHP 7.1.0开始已被弃用。强烈建议不要依赖此功能。”

关于在两端使用关键字进行安全加密的任何想法; PHP + Node.js?

LibMcrypt在2007年被废弃。更多信息https://wiki.php.net/rfc/mcrypt-viking-funeral

您必须使用openssl加密http://php.net/manual/en/function.openssl-encrypt.php

PHP

<?php
$textToEncrypt = "Secret Text to Encrypt";
$encryptionMethod = 'aes-256-cbc';
$secretHash = "315a5504d921f8327f73a356d2bbcbf1"; // <---- you have to use some persistent key.

$iv_size = openssl_cipher_iv_length($encryptionMethod);
$iv = openssl_random_pseudo_bytes($iv_size);

//To encrypt
$encryptedMessage = openssl_encrypt($textToEncrypt, $encryptionMethod, $secretHash, 0, $iv);

//Concatenate iv with data
$encryptedMessageWithIv = bin2hex($iv) . $encryptedMessage;

//To Decrypt
$iv_size = openssl_cipher_iv_length($encryptionMethod);
$iv = hex2bin(substr($encryptedMessageWithIv, 0, $iv_size * 2));

$decryptedMessage = openssl_decrypt(substr($encryptedMessageWithIv, $iv_size * 2), $encryptionMethod, $secretHash, 0, $iv);

echo "Encrypted: $encryptedMessageWithIv <br>Decrypted: $decryptedMessage";

在这里尝试https://3v4l.org/r9pYv

Node.JS (我真的不是node.js程序员,可以有更有效的方法)

var data = "ad699a2537ec2a7f699acbf97ca0080eh3z5EgvnTAvlc76YeR6HdWPmkDDt+pHiG//qo7xnqyQ=";
var key = "315a5504d921f8327f73a356d2bbcbf1";
var iv = new Buffer(data.substring(0,32), 'hex');
var dec = crypto.createDecipheriv('aes-256-cbc',key,iv);
var decrypted = Buffer.concat([dec.update(new Buffer(data.substring(32),'base64')), dec.final()]);
console.log('DECRYPTED TEXT: '+decrypted.toString());

在这里尝试: https : //repl.it/FQyo/2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM