c# - 不同平台上的NaCL密封盒
问题描述
有tweetnacl-sealedbox-js
node.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#代码的动作不一样?
解决方案
所以我做了一些测试: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());
并在日志中收到我的消息。
所以我发现这些库是相互兼容的。
推荐阅读
- xml - xslt 1.0 每行重复检查
- vba - Vba 代码运行时错误无法打开文件(损坏)
- python-3.x - 使用boto3(python 3.x)将文件上传到aws s3存储桶维护文件结构?
- google-cloud-platform - 未能创建谷歌云函数
- sockets - Octave 中的 pkg 负载插座
- openmdao - 一个组中的半个组不使用相同的输入
- laravel - Laravel:使用队列每小时发送 1000 封电子邮件
- c++ - Array Length,为什么从命令行获取时不能使用?
- google-bigquery - 我可以从 bigquery 导出到使用不同凭据访问的存储桶吗?
- java - BeanUtils:将字符串日期格式的地图字段填充到日期属性