首页 > 解决方案 > 不同平台上的NaCL密封盒

问题描述

tweetnacl-sealedbox-jsnode.js

例如我们可以加密一些数据

const key = crypto.pseudoRandomBytes(32);
const publicKey = 'ed9f2af89336b2ff5960634fafb401ca36644cad61cb6a1daafdda0c74ef4636';
const encryptedKey = seal(key, Buffer.from(publicKey, 'hex'));

但是 C# 有类似的库吗?我正在尝试使用 libsodium-net 但不完全确定这是正确的

例如

byte[] randKey = new byte[32];
Random.NextBytes(randKey);
string publicKey = "ed9f2af89336b2ff5960634fafb401ca36644cad61cb6a1daafdda0c74ef4636";
byte[] encryptedKey = SealedPublicKeyBox.Create(randKey, HexToByte(publicKey));
public static byte [] HexToByte(string hexStr)
        {
            byte[] bArray = new byte[hexStr.Length / 2];
            for (int i = 0; i < (hexStr.Length / 2); i++)
            {
                byte firstNibble = Byte.Parse(hexStr.Substring((2 * i), 1), 
                                   System.Globalization.NumberStyles.HexNumber); // [x,y)
                byte secondNibble = Byte.Parse(hexStr.Substring((2 * i) + 1, 1), 
                                    System.Globalization.NumberStyles.HexNumber);
                int finalByte = (secondNibble) | (firstNibble << 4);
                bArray[i] = (byte)finalByte;
            }
            return bArray;
        }

有人知道私钥的所有者可以解密这两条消息吗?还是c#代码的动作不一样?

标签: c#node.jsencryptionpublic-key-encryption

解决方案


所以我做了一些测试:var keyPair = tweetnacl.box.keyPair()在 node.js 上运行并转换为 base64 字符串公钥和密钥。

var pubKey = Buffer.from('Uv4bICdcUlIO+Z9YsLLg9EGaLPy/M7oTBVZJn2B7XhU=', 'base64');
var secKey = Buffer.from('fEAUUQ+axuD3NkOr+a59ZtsVurZPTa4Ee8ULoNr3WS0=', 'base64');

尝试通过 c# 加密消息,libsodium-net就像这样:

string mes = "i want to believe";
string pKey = "Uv4bICdcUlIO+Z9YsLLg9EGaLPy/M7oTBVZJn2B7XhU=";

byte [] enc = Sodium.SealedPublicKeyBox.Create(mes, Convert.FromBase64String(pKey));

return Convert.ToBase64String(enc);

并尝试通过 node.js 解密消息

var msg = Buffer.from('uW+5ecQhzKKx++uRYcbCu2nUVNIqToWTSjVB7UmdDCeJn9Buf3UWFu5kRfIGIxMJYdVeTFijdvJhlHR0VBd5HnE=', 'base64');
var result = sealedbox.open(msg, pubKey, secKey);
console.log(Buffer.from(result).toString());

并在日志中收到我的消息。

所以我发现这些库是相互兼容的。


推荐阅读