【问题标题】:NaCL sealed box on different platforms不同平台上的NaCL密封盒
【发布时间】:2020-09-18 04:21:36
【问题描述】:

node.js 有tweetnacl-sealedbox-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.js encryption public-key-encryption


    【解决方案1】:

    所以我做了一些测试: 在 node.js 上运行 var keyPair = tweetnacl.box.keyPair() 并转换为 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());
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2012-06-12
      • 2012-03-07
      • 2019-02-23
      • 1970-01-01
      相关资源
      最近更新 更多