这里有几个问题。让我们按顺序来。
首先,Microsoft.Research.SEAL.Ciphertext类型既没有无参数构造函数也没有单参数构造函数,从reference source可以看出:
public class Ciphertext : NativeObject
{
public Ciphertext(MemoryPoolHandle pool = null)
{
// Contents omitted
}
public Ciphertext(SEALContext context, MemoryPoolHandle pool = null)
{
// Contents omitted
}
// Additional constructors, methods and members omitted.
第一个构造函数的参数是可选的,但这并不意味着它是无参数的,它只是意味着编译器在代码中不存在该值时提供该值。但是当通过反射(Json.NET 就是这样做的)调用构造函数时,仍然需要提供一个值;请参阅 Reflection - Call constructor with parameters 了解详情。此类型缺少真正的无参数构造函数是导致 Newtonsoft.Json: Unable to find a constructor to use for type Microsoft.Research.SEAL.Ciphertext. 异常的原因。
(在 cmets 中指出您的问题是 sampleClass 缺少默认构造函数,但该注释是错误的。)
由于您无法修改Ciphertext,因此提供自己的构造方法的标准方法是使用CustomCreationConverter<T>,如下所示:
public class CiphertextConverter : CustomCreationConverter<Ciphertext>
{
public override Ciphertext Create(Type objectType)
{
return new Ciphertext(); // Use the default value for the optional parameter
}
}
然后做:
var settings = new JsonSerializerSettings
{
Converters = { new CiphertextConverter() },
};
var array = JsonConvert.DeserializeObject<sampleClass []>(requestBody, settings);
但是,这不起作用,这是您的下一个问题。由于Ciphertext 的大部分公共属性都是只读的,因此无法从它们中反序列化类型。
演示小提琴 #1 here 失败。
那么,该怎么办?事实证明,Ciphertext 有两种方法
这些似乎允许我们将 Ciphertext 序列化为 MemoryStream,然后使用如下转换器将内容作为 Base64 字符串插入 JSON:
public class CiphertextConverter : JsonConverter<Ciphertext>
{
readonly SEALContext context;
public CiphertextConverter(SEALContext context) => this.context = context ?? throw new ArgumentNullException(nameof(context));
public override Ciphertext ReadJson(JsonReader reader, Type objectType, Ciphertext existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var data = serializer.Deserialize<byte []>(reader);
if (data == null)
return null;
var cipherText = new Ciphertext();
using (var stream = new MemoryStream(data))
cipherText.Load(context, stream);
return cipherText;
}
public override void WriteJson(JsonWriter writer, Ciphertext value, JsonSerializer serializer)
{
using (var stream = new MemoryStream())
{
value.Save(stream, ComprModeType.Deflate); // TODO: test to see whether Deflate gives better size vs speed performance in practice.
writer.WriteValue(stream.ToArray());
}
}
}
然后在序列化和反序列化时使用转换器如下:
var settings = new JsonSerializerSettings
{
Converters = { new CiphertextConverter(GlobalContext.Context) },
};
var array = JsonConvert.DeserializeObject<sampleClass []>(requestBody, settings);
但是等等——GlobalContext.Context 这个对象是什么?这给我们带来了第三个问题,即您需要在客户端和服务器端兼容 SEALContext 对象,然后通过序列化在两者之间传递 Ciphertext。现在,查看Cloud Functions Demo 演示应用程序,这似乎是一个正确的假设,因为该应用程序在客户端和服务器端确实具有兼容的上下文:
所以我假设你也会这样做。既然你这样做了,上面的转换器应该同时用于序列化和反序列化。
出于测试目的,我调整了测试方法 CiphertextTests.SaveLoadTest() 和来自 https://github.com/microsoft/SEAL/tree/master/dotnet/tests 的类 GlobalContext 以创建以下测试工具:
public class TestClass
{
[TestMethod]
public void JsonNetSaveLoadTest()
{
Debug.WriteLine("Testing Json.NET");
Func<Ciphertext, SEALContext, Ciphertext> roundtrip = (cipher, context) =>
{
var clientArray = new [] { new sampleClass { ciphertext = cipher } };
var settings = new JsonSerializerSettings
{
Converters = { new CiphertextConverter(GlobalContext.Context) },
};
var requestBody = JsonConvert.SerializeObject(clientArray, settings);
Debug.Write(" ");
Debug.WriteLine(requestBody);
Debug.WriteLine(" requestBody.Length={0}", requestBody.Length);
var array = JsonConvert.DeserializeObject<sampleClass []>(requestBody, settings);
Assert.IsTrue(array.Length == clientArray.Length);
var reserializedJson = JsonConvert.SerializeObject(array, settings);
Debug.Write(" ");
Debug.WriteLine(reserializedJson);
Assert.IsTrue(requestBody == reserializedJson);
return array[0].ciphertext;
};
SaveLoadTest(roundtrip);
Console.WriteLine(" passed.");
}
// Adapted from https://github.com/microsoft/SEAL/blob/master/dotnet/tests/CiphertextTests.cs#L113
[TestMethod]
public void DirectSaveLoadTest()
{
Debug.WriteLine("Testing direct save and load:");
Func<Ciphertext, SEALContext, Ciphertext> roundtrip = (cipher, context) =>
{
Ciphertext loaded = new Ciphertext();
Assert.AreEqual(0ul, loaded.Size);
Assert.AreEqual(0ul, loaded.PolyModulusDegree);
Assert.AreEqual(0ul, loaded.CoeffModCount);
using (MemoryStream mem = new MemoryStream())
{
cipher.Save(mem);
mem.Seek(offset: 0, loc: SeekOrigin.Begin);
loaded.Load(context, mem);
}
return loaded;
};
SaveLoadTest(roundtrip);
Debug.WriteLine(" passed.");
}
// Adapted from https://github.com/microsoft/SEAL/blob/master/dotnet/tests/CiphertextTests.cs#L113
static void SaveLoadTest(Func<Ciphertext, SEALContext, Ciphertext> roundtrip)
{
SEALContext context = GlobalContext.Context;
KeyGenerator keygen = new KeyGenerator(context);
Encryptor encryptor = new Encryptor(context, keygen.PublicKey);
Plaintext plain = new Plaintext("2x^3 + 4x^2 + 5x^1 + 6");
Ciphertext cipher = new Ciphertext();
encryptor.Encrypt(plain, cipher);
Assert.AreEqual(2ul, cipher.Size);
Assert.AreEqual(8192ul, cipher.PolyModulusDegree);
Assert.AreEqual(4ul, cipher.CoeffModCount);
var loaded = roundtrip(cipher, context);
Assert.AreEqual(2ul, loaded.Size);
Assert.AreEqual(8192ul, loaded.PolyModulusDegree);
Assert.AreEqual(4ul, loaded.CoeffModCount);
Assert.IsTrue(ValCheck.IsValidFor(loaded, context));
ulong ulongCount = cipher.Size * cipher.PolyModulusDegree * cipher.CoeffModCount;
for (ulong i = 0; i < ulongCount; i++)
{
Assert.AreEqual(cipher[i], loaded[i]);
}
}
}
static class GlobalContext
{
// Copied from https://github.com/microsoft/SEAL/blob/master/dotnet/tests/GlobalContext.cs
static GlobalContext()
{
EncryptionParameters encParams = new EncryptionParameters(SchemeType.BFV)
{
PolyModulusDegree = 8192,
CoeffModulus = CoeffModulus.BFVDefault(polyModulusDegree: 8192)
};
encParams.SetPlainModulus(65537ul);
BFVContext = new SEALContext(encParams);
encParams = new EncryptionParameters(SchemeType.CKKS)
{
PolyModulusDegree = 8192,
CoeffModulus = CoeffModulus.BFVDefault(polyModulusDegree: 8192)
};
CKKSContext = new SEALContext(encParams);
}
public static SEALContext BFVContext { get; private set; } = null;
public static SEALContext CKKSContext { get; private set; } = null;
public static SEALContext Context => BFVContext;
}
工作演示小提琴 #2 here.
注意事项:
免责声明
我不是安全专家。我无法告诉您通过网络发送序列化的Ciphertext 是否会泄漏信息。我也不能就如何为您的应用程序选择合适的SEALContext 提供建议——甚至在客户端和服务器端具有兼容的上下文是否可能会泄漏信息。此答案仅说明如何通过 Json.NET 序列化特定的 SEAL 对象。