public void DecodeTest() { IntegerEncoder encoder = new IntegerEncoder(GlobalContext.BFVContext); Plaintext plain = new Plaintext("0x^5 + 1x^4 + 1x^3 + 1x^1 + 0"); Assert.AreEqual(6ul, plain.CoeffCount); ulong resultU64 = encoder.DecodeUInt64(plain); Assert.AreEqual(26UL, resultU64); long resultI64 = encoder.DecodeInt64(plain); Assert.AreEqual(26L, resultI64); uint resultU32 = encoder.DecodeUInt32(plain); Assert.AreEqual(26U, resultU32); int resultI32 = encoder.DecodeInt32(plain); Assert.AreEqual(26, resultI32); BigUInt bui = encoder.DecodeBigUInt(plain); Assert.IsNotNull(bui); Assert.AreEqual(0, bui.CompareTo(26ul)); }
public void CreateWithHexTest() { Plaintext plain = new Plaintext("6x^5 + 5x^4 + 3x^2 + 2x^1 + 1"); Assert.IsNotNull(plain); Assert.AreEqual(6ul, plain.CoeffCount); Assert.AreEqual(5ul, plain.NonZeroCoeffCount); Assert.AreEqual(1ul, plain[0]); Assert.AreEqual(2ul, plain[1]); Assert.AreEqual(3ul, plain[2]); Assert.AreEqual(0ul, plain[3]); Assert.AreEqual(5ul, plain[4]); Assert.AreEqual(6ul, plain[5]); Plaintext plain2 = new Plaintext("6x^5 + 5x^4 + 3x^2 + 2x^1"); Assert.IsNotNull(plain); Assert.AreEqual(6ul, plain2.CoeffCount); Assert.AreEqual(4ul, plain2.NonZeroCoeffCount); Assert.AreEqual(0ul, plain2[0]); Assert.AreEqual(2ul, plain2[1]); Assert.AreEqual(3ul, plain2[2]); Assert.AreEqual(0ul, plain2[3]); Assert.AreEqual(5ul, plain2[4]); Assert.AreEqual(6ul, plain2[5]); }
public void CopyTest() { Plaintext plain = new Plaintext("6x^5 + 5x^4 + 3x^2 + 2x^1 + 1"); Assert.IsFalse(plain.IsNTTForm); Plaintext plain2 = new Plaintext(plain); Assert.AreEqual(plain, plain2); Assert.IsFalse(plain2.IsNTTForm); Assert.AreEqual(plain.ParmsId, plain2.ParmsId); SEALContext context = GlobalContext.BFVContext; Evaluator evaluator = new Evaluator(context); evaluator.TransformToNTTInplace(plain, context.FirstParmsId); Assert.IsTrue(plain.IsNTTForm); Assert.IsFalse(plain2.IsNTTForm); Assert.AreNotEqual(plain.ParmsId, plain2.ParmsId); Assert.AreEqual(plain.ParmsId, context.FirstParmsId); Plaintext plain3 = new Plaintext(plain); Assert.AreEqual(plain3, plain); Assert.IsTrue(plain3.IsNTTForm); Assert.AreEqual(plain3.ParmsId, context.FirstParmsId); }
public static List <Ciphertext> Encrypt( this byte[] data, CKKSEncoder encoder, Encryptor encryptor, double scale, int slots) { return(ComputeInBatches( data, slots, bytes => { using var pt = new Plaintext(); encoder.Encode( bytes.Select(d => Convert.ToDouble(d)), scale, pt); var ct = new Ciphertext(); encryptor.Encrypt(pt, ct); return ct; })); }
/// <summary> /// Convert a Matrix to a twisted Plaintext. Rows in the matrix are laid next to /// each other in a Plaintext. The second batching row is duplicate of the first /// one but rotated by eltSeparation /// </summary> /// <param name="matrix">Matrix to convert to Plaintext</param> /// <param name="encoder">BatchEncoder used to encode the matrix data</param> /// <returns>Encrypted matrix</returns> public static Plaintext MatrixToTwistedPlaintext(int[,] matrix, BatchEncoder encoder) { int batchRowSize = (int)encoder.SlotCount / 2; int rows = matrix.GetLength(dimension: 0); int cols = matrix.GetLength(dimension: 1); int paddedColLength = FindNextPowerOfTwo((ulong)rows); int eltSeparation = batchRowSize / paddedColLength; long[] batchArray = new long[encoder.SlotCount]; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { batchArray[r * eltSeparation + c] = (long)matrix[r, c]; batchArray[batchRowSize + ((batchRowSize + (r - 1) * eltSeparation) % batchRowSize) + c] = (long)matrix[r, c]; } } Plaintext plain = new Plaintext(); encoder.Encode(batchArray, plain); return(plain); }
// private static void SinglePredict(Svc secureSvc, double[] feature, int i, CKKSEncoder encoder, Encryptor encryptor, Decryptor decryptor, Stopwatch innerProductStopwatch, Stopwatch degreeStopwatch, Stopwatch negateStopwatch, Stopwatch serverDecisionStopWatch, double scale, Result[] results) { double finalResult = 0; Console.WriteLine($"start {i} \n"); var plaintexts = new Plaintext(); var featuresCiphertexts = new Ciphertext(); encoder.Encode(feature, scale, plaintexts); encryptor.Encrypt(plaintexts, featuresCiphertexts); // Server side start var cyphetResult = secureSvc.Predict(featuresCiphertexts, true, true, innerProductStopwatch, degreeStopwatch, negateStopwatch, serverDecisionStopWatch); // Server side end //timePredictSum.Stop(); Plaintext plainResult = new Plaintext(); decryptor.Decrypt(cyphetResult, plainResult); List <double> result = new List <double>(); encoder.Decode(plainResult, result); finalResult = result[0]; int estimation = finalResult > 0 ? 0 : 1; Console.WriteLine($"\n ************************************************"); Console.WriteLine($"SVC estimation{i} is : {estimation} , result : {finalResult}"); //file.WriteLine($"{i} , {estimation} , {finalResult} "); Console.WriteLine($"************************************************ \n"); results[i] = new Result(finalResult, estimation); //Console.WriteLine($"SecureSVC estimation{i} is : {estimation} , finalResult = {finalResult} , Time = {timePredictSum.ElapsedMilliseconds}"); }
public void EncryptTest() { SEALContext context = GlobalContext.BFVContext; KeyGenerator keyGen = new KeyGenerator(context); PublicKey publicKey = keyGen.PublicKey; SecretKey secretKey = keyGen.SecretKey; Encryptor encryptor = new Encryptor(context, publicKey, secretKey); Assert.IsNotNull(encryptor); Plaintext plain = new Plaintext("1x^1 + 1"); Ciphertext cipher = new Ciphertext(); Assert.AreEqual(0ul, cipher.Size); encryptor.Encrypt(plain, cipher); Assert.IsNotNull(cipher); Assert.AreEqual(2ul, cipher.Size); cipher = new Ciphertext(); Assert.AreEqual(0ul, cipher.Size); encryptor.Encrypt(plain, cipher); Assert.IsNotNull(cipher); Assert.AreEqual(2ul, cipher.Size); }
public void ExceptionsTest() { EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV) { PlainModulus = new SmallModulus(4ul) }; SEALContext context = SEALContext.Create(parms); SEALContext context_null = null; IntegerEncoder enc = new IntegerEncoder(context); IntegerEncoder copy_null = null; BigUInt bui_null = null; BigUInt bui = new BigUInt(5ul); Plaintext plain = new Plaintext(); Assert.ThrowsException <ArgumentNullException>(() => enc = new IntegerEncoder(context_null)); Assert.ThrowsException <ArgumentNullException>(() => enc = new IntegerEncoder(copy_null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1ul, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1L, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1u, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui_null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui_null, plain)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeUInt32(null)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeUInt64(null)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeInt32(null)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeInt64(null)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeBigUInt(null)); }
/// <summary> /// Convert a Matrix to a Ciphertext. /// Rows in the matrix are laid next to each other in a Plaintext and then encrypted. /// </summary> /// <param name="matrix">Matrix to convert to Ciphertext</param> /// <param name="encryptor">Encryptor used to encrypt Plaintext data</param> /// <param name="encoder">BatchEncoder used to encode the matrix data</param> /// <returns>Encrypted matrix</returns> public static Ciphertext MatrixToCiphertext(int[,] matrix, Encryptor encryptor, BatchEncoder encoder) { int batchRowSize = (int)encoder.SlotCount / 2; int rows = matrix.GetLength(dimension: 0); int cols = matrix.GetLength(dimension: 1); int paddedColLength = FindNextPowerOfTwo((ulong)rows); int eltSeparation = batchRowSize / paddedColLength; long[] batchArray = new long[encoder.SlotCount]; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { batchArray[r * eltSeparation + c] = (long)matrix[r, c]; } } Plaintext plain = new Plaintext(); encoder.Encode(batchArray, plain); Ciphertext result = new Ciphertext(); encryptor.Encrypt(plain, result); return(result); }
private void SetConstants() { //Encodes negative six and stores in variable negativeSix. negativeSix = new Plaintext(); encoder.Encode(-6, scale, negativeSix); }
public void DecodeTest() { EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV) { PlainModulus = new SmallModulus(1024) }; SEALContext context = SEALContext.Create(parms); IntegerEncoder encoder = new IntegerEncoder(context); Plaintext plain = new Plaintext("0x^5 + 1x^4 + 1x^3 + 1x^1 + 0"); Assert.AreEqual(6ul, plain.CoeffCount); ulong resultU64 = encoder.DecodeUInt64(plain); Assert.AreEqual(26UL, resultU64); long resultI64 = encoder.DecodeInt64(plain); Assert.AreEqual(26L, resultI64); uint resultU32 = encoder.DecodeUInt32(plain); Assert.AreEqual(26U, resultU32); int resultI32 = encoder.DecodeInt32(plain); Assert.AreEqual(26, resultI32); BigUInt bui = encoder.DecodeBigUInt(plain); Assert.IsNotNull(bui); Assert.AreEqual(0, bui.CompareTo(26ul)); }
public void PlaintextBasicsNET() { var plain = new Plaintext(2); Assert.AreEqual(2, plain.Capacity); Assert.AreEqual(2, plain.CoeffCount); Assert.AreEqual(0, plain.SignificantCoeffCount()); plain[0] = 1; plain[1] = 2; plain.Reserve(10); Assert.AreEqual(10, plain.Capacity); Assert.AreEqual(2, plain.CoeffCount); Assert.AreEqual(2, plain.SignificantCoeffCount()); Assert.AreEqual(1UL, plain[0]); Assert.AreEqual(2UL, plain[1]); plain.Resize(5); Assert.AreEqual(10, plain.Capacity); Assert.AreEqual(5, plain.CoeffCount); Assert.AreEqual(2, plain.SignificantCoeffCount()); Assert.AreEqual(1UL, plain[0]); Assert.AreEqual(2UL, plain[1]); Assert.AreEqual(0UL, plain[2]); Assert.AreEqual(0UL, plain[3]); Assert.AreEqual(0UL, plain[4]); }
public void SaveLoadPlaintextNET() { var stream = new MemoryStream(); var plain = new Plaintext(); var plain2 = new Plaintext(); plain.Save(stream); stream.Seek(0, SeekOrigin.Begin); plain2.Load(stream); Assert.AreEqual(0, plain2.Capacity); Assert.AreEqual(0, plain2.CoeffCount); plain.Reserve(20); plain.Resize(5); plain[0] = 1; plain[1] = 2; plain[2] = 3; stream.Seek(0, SeekOrigin.Begin); plain.Save(stream); stream.Seek(0, SeekOrigin.Begin); plain2.Load(stream); Assert.AreEqual(5, plain2.Capacity); Assert.AreEqual(5, plain2.CoeffCount); Assert.AreEqual(1UL, plain2[0]); Assert.AreEqual(2UL, plain2[1]); Assert.AreEqual(3UL, plain2[2]); Assert.AreEqual(0UL, plain2[3]); Assert.AreEqual(0UL, plain2[4]); }
public void ExceptionsTest() { SEALContext context = GlobalContext.BFVContext; SEALContext context_null = null; IntegerEncoder enc = new IntegerEncoder(context); BigUInt bui_null = null; BigUInt bui = new BigUInt(5ul); Plaintext plain = new Plaintext(); Assert.ThrowsException <ArgumentNullException>(() => enc = new IntegerEncoder(context_null)); Assert.ThrowsException <ArgumentException>(() => enc = new IntegerEncoder(GlobalContext.CKKSContext)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1ul, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1L, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(1u, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui_null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui, null)); Assert.ThrowsException <ArgumentNullException>(() => enc.Encode(bui_null, plain)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeUInt32(null)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeUInt64(null)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeInt32(null)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeInt64(null)); Assert.ThrowsException <ArgumentNullException>(() => enc.DecodeBigUInt(null)); }
private static async Task GetMetrics() { // Get encrypted metrics var metrics = await FitnessTrackerClient.GetMetrics(); LogUtils.SummaryStatisticInfo("CLIENT", "GetMetrics", metrics); // Decrypt the data var ciphertextTotalRuns = SEALUtils.BuildCiphertextFromBase64String(metrics.TotalRuns, _context); var plaintextTotalRuns = new Plaintext(); _decryptor.Decrypt(ciphertextTotalRuns, plaintextTotalRuns); var ciphertextTotalDistance = SEALUtils.BuildCiphertextFromBase64String(metrics.TotalDistance, _context); var plaintextTotalDistance = new Plaintext(); _decryptor.Decrypt(ciphertextTotalDistance, plaintextTotalDistance); var ciphertextTotalHours = SEALUtils.BuildCiphertextFromBase64String(metrics.TotalHours, _context); var plaintextTotalHours = new Plaintext(); _decryptor.Decrypt(ciphertextTotalHours, plaintextTotalHours); // Print metrics in console PrintMetrics(plaintextTotalRuns.ToString(), plaintextTotalDistance.ToString(), plaintextTotalHours.ToString()); }
public void Create2Test() { SEALContext context = GlobalContext.BFVContext; KeyGenerator keygen1 = new KeyGenerator(context); keygen1.CreatePublicKey(out PublicKey publicKey); Encryptor encryptor1 = new Encryptor(context, publicKey); Decryptor decryptor1 = new Decryptor(context, keygen1.SecretKey); Ciphertext cipher = new Ciphertext(); Plaintext plain = new Plaintext("2x^1 + 5"); Plaintext plain2 = new Plaintext(); encryptor1.Encrypt(plain, cipher); decryptor1.Decrypt(cipher, plain2); Assert.AreNotSame(plain, plain2); Assert.AreEqual(plain, plain2); KeyGenerator keygen2 = new KeyGenerator(context, keygen1.SecretKey); keygen2.CreatePublicKey(out publicKey); Encryptor encryptor2 = new Encryptor(context, publicKey); Decryptor decryptor2 = new Decryptor(context, keygen2.SecretKey); Plaintext plain3 = new Plaintext(); decryptor2.Decrypt(cipher, plain3); Assert.AreNotSame(plain, plain3); Assert.AreEqual(plain, plain3); }
// 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]); } }
public void EncodeDecodeVectorDoubleTest() { EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS) { PolyModulusDegree = 64, CoeffModulus = CoeffModulus.Create(64, new int[] { 30, 30 }) }; SEALContext context = new SEALContext(parms, expandModChain: false, secLevel: SecLevelType.None); CKKSEncoder encoder = new CKKSEncoder(context); Plaintext plain = new Plaintext(); double[] values = new double[] { 0.1, 2.3, 34.4 }; encoder.Encode(values, scale: Math.Pow(2, 20), destination: plain); List <double> result = new List <double>(); encoder.Decode(plain, result); Assert.IsNotNull(result); Assert.AreEqual(0.1, result[0], delta: 0.001); Assert.AreEqual(2.3, result[1], delta: 0.001); Assert.AreEqual(34.4, result[2], delta: 0.001); }
public bool IsIn(Position searchPosition) { var encoded = GetEncodedPosition(searchPosition); var evaluator = new Evaluator(GetContext()); PositionEncrypted positionEncrypted = GetFromIota(); evaluator.SubPlain(positionEncrypted.Lon, encoded.Lon); evaluator.SubPlain(positionEncrypted.Lat, encoded.Lat); var decryptor = new Decryptor(GetContext(), GetSecretKey()); Plaintext plainResultLon = new Plaintext(); Plaintext plainResultLat = new Plaintext(); decryptor.Decrypt(positionEncrypted.Lon, plainResultLon); decryptor.Decrypt(positionEncrypted.Lat, plainResultLat); var encoder = GetEncoder(GetContext()); double resultLon = encoder.Decode(plainResultLon); double resultLat = encoder.Decode(plainResultLat); var diff = Math.Abs(resultLon) + Math.Abs(resultLat); if (diff < 0.007) { return(true); } return(false); }
public void EncodeDecodeDoubleTest() { EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS); parms.PolyModulusDegree = 64; parms.CoeffModulus = CoeffModulus.Create(64, new int[] { 40, 40, 40, 40 }); SEALContext context = new SEALContext(parms, expandModChain: false, secLevel: SecLevelType.None); int slots = 16; Plaintext plain = new Plaintext(); double delta = 1 << 16; List <Complex> result = new List <Complex>(); CKKSEncoder encoder = new CKKSEncoder(context); Assert.AreEqual(32ul, encoder.SlotCount); double value = 10d; encoder.Encode(value, delta, plain); encoder.Decode(plain, result); for (int i = 0; i < slots; i++) { double tmp = Math.Abs(value - result[i].Real); Assert.IsTrue(tmp < 0.5); } }
public void SetConstants() { // Encode the constant 1/52 and store in DivideByFiftyTwo. DivideByFiftyTwo = new Plaintext(); encoder.Encode(0.01923076, scale, DivideByFiftyTwo); }
public void EncodeDecodeUlongTest() { int slots = 32; EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS); parms.PolyModulusDegree = (ulong)slots * 2; parms.CoeffModulus = CoeffModulus.Create(64, new int[] { 40, 40, 40, 40 }); SEALContext context = new SEALContext(parms, expandModChain: false, secLevel: SecLevelType.None); CKKSEncoder encoder = new CKKSEncoder(context); Plaintext plain = new Plaintext(); List <Complex> result = new List <Complex>(); long value = 15; encoder.Encode(value, plain); encoder.Decode(plain, result); for (int i = 0; i < slots; i++) { double tmp = Math.Abs(value - result[i].Real); Assert.IsTrue(tmp < 0.5); } }
/// <summary> /// Set the indicated Matrix row as the coefficients of a Plaintext. /// </summary> /// <param name="matrix">Matrix to get a row from</param> /// <param name="row">Row to encrypt</param> /// <param name="repl">How many times to replicate the row values</param> /// <param name="encoder">BatchEncoder used to encode the matrix data</param> /// <returns>Encrypted matrix row</returns> public static Plaintext RowToPlaintext(int[,] matrix, int row, int repl, BatchEncoder encoder) { int batchRowSize = (int)encoder.SlotCount / 2; int cols = matrix.GetLength(dimension: 1); int paddedLength = FindNextPowerOfTwo((ulong)cols); int eltSeparation = batchRowSize / paddedLength; if (repl < 0 || repl > eltSeparation) { throw new ArgumentException("repl out of bounds"); } long[] rowToEncrypt = new long[batchRowSize]; for (int c = 0; c < cols; c++) { for (int j = 0; j < repl; j++) { rowToEncrypt[eltSeparation * c + j] = matrix[row, c]; } } Plaintext plain = new Plaintext(); encoder.Encode(rowToEncrypt, plain); return(plain); }
public void EncodeDecodeComplexTest() { EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS) { PolyModulusDegree = 64, CoeffModulus = CoeffModulus.Create(64, new int[] { 40, 40, 40, 40 }) }; SEALContext context = new SEALContext(parms, expandModChain: false, secLevel: SecLevelType.None); CKKSEncoder encoder = new CKKSEncoder(context); Plaintext plain = new Plaintext(); Complex value = new Complex(3.1415, 2.71828); encoder.Encode(value, scale: Math.Pow(2, 20), destination: plain); List <Complex> result = new List <Complex>(); encoder.Decode(plain, result); Assert.IsTrue(result.Count > 0); Assert.AreEqual(3.1415, result[0].Real, delta: 0.0001); Assert.AreEqual(2.71828, result[0].Imaginary, delta: 0.0001); }
public void ReserveResizeTest() { Plaintext plain = new Plaintext(); MemoryPoolHandle handle = plain.Pool; Assert.AreEqual(0ul, plain.CoeffCount); Assert.AreEqual(0ul, plain.NonZeroCoeffCount); Assert.AreEqual(0ul, plain.Capacity); plain.Reserve(capacity: 10); ulong alloced = handle.AllocByteCount; Assert.IsTrue(alloced > 0ul); Assert.AreEqual(0ul, plain.CoeffCount); Assert.AreEqual(0ul, plain.NonZeroCoeffCount); Assert.AreEqual(10ul, plain.Capacity); plain.Resize(coeffCount: 11); Assert.AreEqual(11ul, plain.CoeffCount); Assert.AreEqual(11ul, plain.Capacity); Assert.AreEqual(0ul, plain.SignificantCoeffCount); Assert.AreEqual(0ul, plain.NonZeroCoeffCount); Assert.IsTrue(handle.AllocByteCount > 0ul); }
static public List <List <long> > decryptValues(List <List <Ciphertext> > weihtedSums, SecretKey sk, SEALContext context) { List <List <long> > results = new List <List <long> >(); Decryptor decryptor = new Decryptor(context, sk); IntegerEncoder encoder = new IntegerEncoder(context); int sample_ind = 0; foreach (List <Ciphertext> sample in weihtedSums) { List <long> resultsRow = new List <long>(); foreach (Ciphertext encryptedClassScore in sample) { Plaintext plainClassScore = new Plaintext(); if (decryptor.InvariantNoiseBudget(encryptedClassScore) == 0) { throw new Exception("Noise budget depleated in sample " + sample_ind + ". Aborting..."); } decryptor.Decrypt(encryptedClassScore, plainClassScore); long ClassScore = encoder.DecodeInt64(plainClassScore) / (1000 * 1000); resultsRow.Add(ClassScore); } results.Add(resultsRow); sample_ind++; } return(results); }
public void ExceptionsTest() { SEALContext context = GlobalContext.BFVContext; Plaintext plain = new Plaintext(); MemoryPoolHandle pool = MemoryManager.GetPool(MMProfOpt.ForceGlobal); MemoryPoolHandle pool_uninit = new MemoryPoolHandle(); Utilities.AssertThrows <ArgumentException>(() => plain = new Plaintext(pool_uninit)); Utilities.AssertThrows <ArgumentNullException>(() => plain = new Plaintext((string)null, pool)); Utilities.AssertThrows <ArgumentNullException>(() => plain.Set((Plaintext)null)); Utilities.AssertThrows <ArgumentNullException>(() => plain.Set((string)null)); Utilities.AssertThrows <ArgumentOutOfRangeException>(() => plain.SetZero(100000)); Utilities.AssertThrows <ArgumentOutOfRangeException>(() => plain.SetZero(1, 100000)); Utilities.AssertThrows <ArgumentOutOfRangeException>(() => plain.SetZero(100000, 1)); Utilities.AssertThrows <ArgumentNullException>(() => ValCheck.IsValidFor(plain, null)); Utilities.AssertThrows <ArgumentNullException>(() => plain.Save(null)); Utilities.AssertThrows <ArgumentNullException>(() => plain.UnsafeLoad(null, new MemoryStream())); Utilities.AssertThrows <ArgumentNullException>(() => plain.UnsafeLoad(context, null)); Utilities.AssertThrows <EndOfStreamException>(() => plain.UnsafeLoad(context, new MemoryStream())); Utilities.AssertThrows <ArgumentNullException>(() => plain.Load(context, null)); Utilities.AssertThrows <ArgumentNullException>(() => plain.Load(null, new MemoryStream())); }
static public List <List <Ciphertext> > encryptValues(List <List <float> > featureList, PublicKey pk, SEALContext context) { IntegerEncoder encoder = new IntegerEncoder(context); Encryptor encryptor = new Encryptor(context, pk); List <List <Ciphertext> > cList = new List <List <Ciphertext> >(); foreach (List <float> row in featureList) { List <Ciphertext> cRow = new List <Ciphertext>(); for (int i = 0; i < row.Count; i++) { long featureItem = (long)(row[i] * 1000); Plaintext fPlain = encoder.Encode(featureItem); Ciphertext fCipher = new Ciphertext(); encryptor.Encrypt(fPlain, fCipher); cRow.Add(fCipher); } cList.Add(cRow); } return(cList); }
/// <summary> /// Perform a Matrix operation (add / subtract) /// </summary> /// <param name="sid">Session ID</param> /// <param name="operation">Operation to perform</param> /// <param name="code">Azure Function key</param> private async Task PerformMatrixOperation(string sid, string operation, string code) { ClearLog(); Log($"Session ID: {sid}"); MatrixData mda = MatrixA.Matrix.DataContext as MatrixData; MatrixData mdb = MatrixB.Matrix.DataContext as MatrixData; Plaintext plaina = Utilities.MatrixToPlaintext(Utilities.MatrixDataToMatrix(mda), encoder_); Plaintext plainb = Utilities.MatrixToPlaintext(Utilities.MatrixDataToMatrix(mdb), encoder_); Plaintext plain = await PerformOperation(sid, operation, code, plaina, plainb); if (null == plain) { OperationResult.MatrixTitle = $"Error executing {operation}"; OperationResult.ClearMatrix(); return; } int rows = mda.DataView.Table.Rows.Count; int cols = mda.DataView.Table.Columns.Count; int[,] matresult = Utilities.PlaintextToMatrix(plain, rows, cols, encoder_); OperationResult.MatrixTitle = "Result"; OperationResult.InitMatrix(matresult); }
public void EncodeDecodeComplexTest() { EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS) { PolyModulusDegree = 64, CoeffModulus = new List <SmallModulus>() { DefaultParams.SmallMods40Bit(0), DefaultParams.SmallMods40Bit(1), DefaultParams.SmallMods40Bit(2), DefaultParams.SmallMods40Bit(3) } }; SEALContext context = SEALContext.Create(parms); CKKSEncoder encoder = new CKKSEncoder(context); Plaintext plain = new Plaintext(); Complex value = new Complex(3.1415, 2.71828); encoder.Encode(value, scale: Math.Pow(2, 20), destination: plain); List <Complex> result = new List <Complex>(); encoder.Decode(plain, result); Assert.IsTrue(result.Count > 0); Assert.AreEqual(3.1415, result[0].Real, delta: 0.0001); Assert.AreEqual(2.71828, result[0].Imaginary, delta: 0.0001); }