【发布时间】:2020-01-29 16:27:41
【问题描述】:
我在 php 中有一个代码 sn-p,我想将其移入 node.js,但我似乎找不到正确的方法。
class EncryptService
{
const PUBLIC_CERT_PATH = 'cert/public.cer';
const PRIVATE_CERT_PATH = 'cert/private.key';
const ERROR_LOAD_X509_CERTIFICATE = 0x10000001;
const ERROR_ENCRYPT_DATA = 0x10000002;
public $outEncData = null;
public $outEnvKey = null;
public $srcData;
public function encrypt()
{
$publicKey = openssl_pkey_get_public(self::PUBLIC_CERT_PATH);
if ($publicKey === false) {
$publicKey = openssl_pkey_get_public("file://".self::PUBLIC_CERT_PATH);
}
if ($publicKey === false) {
$errorMessage = "Error while loading X509 public key certificate! Reason:";
while (($errorString = openssl_error_string())) {
$errorMessage .= $errorString . "\n";
}
throw new Exception($errorMessage, self::ERROR_LOAD_X509_CERTIFICATE);
}
$publicKeys = array($publicKey);
$encData = null;
$envKeys = null;
$result = openssl_seal($this->srcData, $encData, $envKeys, $publicKeys);
if ($result === false)
{
$this->outEncData = null;
$this->outEnvKey = null;
$errorMessage = "Error while encrypting data! Reason:";
while (($errorString = openssl_error_string()))
{
$errorMessage .= $errorString . "\n";
}
throw new Exception($errorMessage, self::ERROR_ENCRYPT_DATA);
}
$this->outEncData = base64_encode($encData);
$this->outEnvKey = base64_encode($envKeys[0]);
}
};
问题是我无法在任何地方的 Javascript 中找到 openssl_sign 的实现。我确实需要保留这个结构,因为我同时使用了outEncData 和outEnvKey。
我设法用crypto 包找到openssl_sign 的等效实现,但openssl_seal 没有。
LE 添加了工作解决方案作为答案
【问题讨论】:
-
默认情况下,
openssl_seal似乎使用RC4密码,该密码已被弃用,因此您可能需要进行各种恶作剧才能使其正常工作。 -
但是如果操作系统有 RC4 看起来你应该可以用
crypto.createCipheriv("RC4", myGeneratedKey, null)方法 nodejs.org/api/… 替换这段代码 -
感谢@Aivaras 的回复。我像你说的那样尝试了,结果如下。
const cypher = crypto.createCipheriv("RC4", public_key, null);let encrypted = cypher.update(message, 'utf8', 'base64');encrypted += cypher.final('base64');但它返回的哈希值始终保持不变,我错过了env_key。在php中,hash 和 env 总是为相同的值而变化。我在代码中做错了什么吗? -
我认为在
php中env_key是在幕后生成的,而在 Node 中你需要自己创建它,然后使用它而不是你的public_key。 -
@Aivaras 你能用一些代码回复一下吗?
标签: javascript node.js openssl cryptojs