2

sodium-plus.js我想在 Web 浏览器中使用PHP 钠生成的密钥来实现匿名公钥加密,如下所示:

$keyPair = sodium_crypto_box_keypair();

$privateKey = sodium_crypto_box_secretkey($keyPair);
$publicKey = sodium_crypto_box_publickey($keyPair);

使用此方法生成的密钥在 PHP 中使用sodium_crypto_box_sealandsodium_crypto_box_seal_open方法可以正常工作,但是,我无法使其在前端工作。我的做法:

<script type='text/javascript' src='js/sodium-plus.min.js?v=0.4.2'></script>
<script>
async function getPublicKey() {

    return X25519PublicKey.from(
        '<?php echo sodium_bin2hex($publicKey); ?>', // 6a00b1550ccdeff3886a469b9cd4e5dc9aecd30f5deb3dd3e29fd01f8a32103f
        'hex'
    );

}

async function encryptString(clearText, publicKey) {

    if (!window.sodium) window.sodium = await SodiumPlus.auto();

    let cipherText = await sodium.crypto_box_seal(clearText, publicKey);

    return cipherText.toString('hex');

}

(async function () {

    let clearText = "String that contains secret.";
    let publicKey = await getPublicKey();

    console.log(await encryptString(clearText,publicKey));

})();
</script>

这将返回TypeError: Argument 2 must be an instance of X25519PublicKey in the console。

笔记:

  1. sodium.crypto_box_keypair()从前端派生的公钥有效。
  2. 尝试使用CryptographyKey.from()而不是X25519PublicKey.from()- 没有用。
  3. getPublicKey()函数返回一个对象 wit buffer: Uint8Array(32) [ … ],而从 派生的公钥sodium.crypto_box_keypair()返回一个带有 的对象buffer: Uint8Array(32) [ … ], keyType: "x25519", publicKey: true

概念基于:

  1. https://github.com/paragonie/sodium-plus/blob/master/docs/SodiumPlus/sealed-boxes.md
  2. https://dev.to/paragonie/message-encryption-in-javascript-and-php-cg9
  3. https://stackoverflow.com/a/34058638
4

2 回答 2

1

简短的回答是:升级到 0.5.0 或更高版本。

长答案是:等到版本 0.6.0 出来,然后升级到那个版本,因为它也放宽了你遇到的一些类型迂腐的限制。

于 2019-12-13T07:53:14.047 回答
0

我使用https://github.com/jedisct1/libsodium.js/效果很好,在 javascript 中加密并在 PHP 中解密

于 2019-12-10T00:35:48.773 回答